"use strict";

const $ = (s, root = document) => root.querySelector(s);
const $$ = (s, root = document) => Array.from(root.querySelectorAll(s));

document.addEventListener("DOMContentLoaded", () => {
    initMobileMenu();
    initHeroSlider();
    initReveal();
    initCounters();
    initParallax();
    initSmoothScroll();
    initLiveSearch();
    initForms();
    initInteractiveCaption();
});

function initMobileMenu() {
    const toggle = $(".mobile-toggle");
    const nav = $(".nav");
    if (!toggle || !nav) return;
    toggle.addEventListener("click", () => nav.classList.toggle("open"));
}

function initHeroSlider() {
    const slides = $$(".hero-slide");
    if (!slides.length) return;
    let idx = 0;
    setInterval(() => {
        slides[idx].classList.remove("active");
        idx = (idx + 1) % slides.length;
        slides[idx].classList.add("active");
    }, 5500);
}

function initReveal() {
    const items = $$("[data-reveal]");
    if (!items.length) return;
    const obs = new IntersectionObserver((entries) => {
        entries.forEach((entry) => {
            if (entry.isIntersecting) entry.target.classList.add("revealed");
        });
    }, {
        threshold: 0.2
    });
    items.forEach((item) => obs.observe(item));
}

function initCounters() {
    const nums = $$(".counter-num");
    nums.forEach((el) => {
        const target = Number(el.dataset.target || "0");
        let v = 0;
        const step = Math.max(1, Math.floor(target / 80));
        const timer = setInterval(() => {
            v += step;
            if (v >= target) {
                v = target;
                clearInterval(timer);
            }
            el.textContent = toFaNum(v.toLocaleString("en-US"));
        }, 16);
    });
}

function initParallax() {
    const hero = $(".hero");
    if (!hero) return;
    window.addEventListener("scroll", () => {
        const y = window.scrollY * 0.25;
        hero.style.backgroundPosition = `center ${y}px`;
    }, {
        passive: true
    });
}

function initSmoothScroll() {
    $$('a[href^="#"]').forEach((a) => {
        a.addEventListener("click", (e) => {
            const id = a.getAttribute("href");
            const target = id ? document.querySelector(id) : null;
            if (!target) return;
            e.preventDefault();
            target.scrollIntoView({
                behavior: "smooth",
                block: "start"
            });
        });
    });
}

function initLiveSearch() {
    const input = $("#liveSearch");
    const box = $("#searchResults");
    if (!input || !box) return;

    let debounce = null;
    input.addEventListener("input", () => {
        clearTimeout(debounce);
        debounce = setTimeout(async () => {
            const q = input.value.trim();
            if (q.length < 2) {
                box.textContent = "";
                return;
            }
            try {
                const base = (window.ZYLON_BASE_URL || "").replace(/\/$/, "");
                const res = await fetch(`${base}/public/search.php?q=${encodeURIComponent(q)}`);
                if (!res.ok) {
                    throw new Error("Search request failed");
                }
                const data = await res.json();
                box.textContent = "";
                data.forEach((item) => {
                    const el = document.createElement("div");
                    el.className = "search-item";
                    el.textContent = item.title || "";
                    box.appendChild(el);
                });
            } catch {
                box.textContent = "";
                const el = document.createElement("div");
                el.className = "search-item";
                el.textContent = "خطا در دریافت نتایج";
                box.appendChild(el);
            }
        }, 260);
    });
}

function initForms() {
    const contact = $("#contactForm");
    if (contact) {
        contact.addEventListener("submit", (e) => {
            e.preventDefault();
            alert("پیام شما ثبت شد. به زودی تماس می‌گیریم.");
            contact.reset();
        });
    }
    const newsletter = $("#newsletterForm");
    if (newsletter) {
        newsletter.addEventListener("submit", (e) => {
            e.preventDefault();
            alert("عضویت در خبرنامه انجام شد.");
            newsletter.reset();
        });
    }
}

function initInteractiveCaption() {
    const box = $("#interactiveCaption");
    if (!box) return;

    const textColor = box.dataset.textColor || "#fff";
    const bgColor = box.dataset.bgColor || "rgba(34,34,34,0.45)";
    const borderColor = box.dataset.borderColor || "#ef4056";
    box.style.color = textColor;
    box.style.backgroundColor = bgColor;
    box.style.borderColor = borderColor;

    const move = (clientX, clientY) => {
        const rect = box.getBoundingClientRect();
        const x = ((clientX - rect.left) / rect.width - 0.5) * 12;
        const y = ((clientY - rect.top) / rect.height - 0.5) * -12;
        box.style.transform = `perspective(700px) rotateX(${y}deg) rotateY(${x}deg)`;
    };

    box.addEventListener("mousemove", (e) => move(e.clientX, e.clientY));
    box.addEventListener("touchmove", (e) => {
        const touch = e.touches && e.touches[0];
        if (touch) move(touch.clientX, touch.clientY);
    }, {
        passive: true
    });
    box.addEventListener("mouseleave", () => {
        box.style.transform = "perspective(700px) rotateX(0deg) rotateY(0deg)";
    });

    const subtitle = box.querySelector("[data-typing]");
    if (subtitle) {
        const fullText = (subtitle.textContent || "").trim();
        const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
        if (!reducedMotion && fullText.length > 2) {
            subtitle.textContent = "";
            let index = 0;
            const write = () => {
                subtitle.textContent = fullText.slice(0, index);
                index += 1;
                if (index <= fullText.length) {
                    window.setTimeout(write, 42);
                }
            };
            write();
        }
    }
}

function toFaNum(s) {
    return String(s).replace(/\d/g, (d) => "۰۱۲۳۴۵۶۷۸۹" [Number(d)]);
}