const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
const siteHeader = document.querySelector(".site-header");

const syncHeaderMetrics = () => {
    const headerOffset = siteHeader ? siteHeader.offsetHeight + 10 : 96;
    document.documentElement.style.setProperty("--header-offset", `${headerOffset}px`);
};

const updateHeaderState = () => {
    if (!siteHeader) {
        return;
    }

    siteHeader.classList.toggle("is-scrolled", window.scrollY > 18);
    syncHeaderMetrics();
};

let headerTicking = false;

const requestHeaderUpdate = () => {
    if (headerTicking) {
        return;
    }

    headerTicking = true;
    window.requestAnimationFrame(() => {
        updateHeaderState();
        headerTicking = false;
    });
};

const resolveSectionTarget = (hash) => {
    if (!hash || hash === "#") {
        return null;
    }

    if (hash === "#sectors") {
        return document.querySelector("#organization");
    }

    return document.querySelector(hash);
};

const getHeaderOffset = () => {
    return siteHeader ? siteHeader.offsetHeight + 10 : 96;
};

updateHeaderState();
window.addEventListener("scroll", requestHeaderUpdate, { passive: true });
window.addEventListener("resize", requestHeaderUpdate);

Array.from(document.querySelectorAll('a[href^="#"]')).forEach((link) => {
    link.addEventListener("click", (event) => {
        const href = link.getAttribute("href") || "";
        const targetSection = resolveSectionTarget(href);

        if (!targetSection) {
            return;
        }

        event.preventDefault();
        const targetTop = targetSection.getBoundingClientRect().top + window.scrollY - getHeaderOffset();

        window.scrollTo({
            top: Math.max(targetTop, 0),
            behavior: "smooth",
        });
    });
});

const autoRevealGroups = [
    { selector: "#hero .page-title, #manifesto .page-title", animation: "fade-up", step: 80 },
    { selector: "#hero .body-copy, #manifesto .body-copy, #about .body-copy", animation: "fade-up", step: 120 },
    { selector: "#about .page-title, .leadership-header, #career .career-copy-panel, #news .news-aside__inner, #contact .contact-copy-panel", animation: "fade-right", step: 120 },
    { selector: ".organization-brand-panel, #career .career-form-panel, #contact .contact-map-panel", animation: "fade-left", step: 120 },
    { selector: ".organization-item, .news-item, .contact-card", animation: "fade-up", step: 70 },
    { selector: ".leadership-card", animation: "zoom-in", step: 90 },
    { selector: ".news-filter", animation: "fade-up", step: 45 },
];

autoRevealGroups.forEach(({ selector, animation, step }) => {
    const elements = Array.from(document.querySelectorAll(selector));

    elements.forEach((element, index) => {
        if (element.closest(".news-modal, .contact-modal")) {
            return;
        }

        if (!element.dataset.aos) {
            element.dataset.aos = animation;
        }

        element.style.setProperty("--aos-delay", `${Math.min(index * step, 280)}ms`);
    });
});

const revealElements = Array.from(document.querySelectorAll("[data-aos]"));

if (revealElements.length) {
    const revealObserver = new IntersectionObserver((entries) => {
        entries.forEach((entry) => {
            entry.target.classList.toggle("aos-animate", entry.isIntersecting);
        });
    }, {
        threshold: 0.16,
        rootMargin: "0px 0px -12% 0px",
    });

    revealElements.forEach((element) => {
        revealObserver.observe(element);
    });
}

const founderSection = document.querySelector("#founder");

if (founderSection) {
    const founderQuote = founderSection.querySelector(".founder-quote");
    const founderIcon = founderSection.querySelector(".founder-icon");
    const founderTitle = founderSection.querySelector(".founder-credit-title");
    const founderSubtitle = founderSection.querySelector(".founder-credit-subtitle");
    const founderDivider = founderSection.querySelector(".founder-divider");
    const founderPortrait = founderSection.querySelector(".founder-portrait");
    const founderQuoteText = founderQuote ? founderQuote.textContent.replace(/\s+/g, " ").trim() : "";
    const founderChars = [];

    if (founderQuote && founderQuoteText) {
        const fragment = document.createDocumentFragment();

        Array.from(founderQuoteText).forEach((character) => {
            const span = document.createElement("span");
            span.setAttribute("aria-hidden", "true");

            if (character === " ") {
                span.className = "founder-quote-space";
                span.textContent = " ";
            } else {
                span.className = "founder-quote-char";
                span.textContent = character;
                founderChars.push(span);
            }

            fragment.appendChild(span);
        });

        founderQuote.textContent = "";
        founderQuote.appendChild(fragment);
        founderQuote.setAttribute("aria-label", founderQuoteText);
    }

    let previousVisibleCount = -1;

    const updateFounderProgress = () => {
        const rect = founderSection.getBoundingClientRect();
        const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
        const progress = clamp((viewportHeight * 0.82 - rect.top) / (rect.height * 0.92), 0, 1);
        const visibleCount = Math.floor(progress * founderChars.length);

        if (visibleCount !== previousVisibleCount) {
            founderChars.forEach((char, index) => {
                char.classList.toggle("is-revealed", index < visibleCount);
            });
            previousVisibleCount = visibleCount;
        }

        if (founderIcon) {
            founderIcon.style.color = `rgba(255, 255, 255, ${0.18 + progress * 0.82})`;
        }

        if (founderTitle) {
            founderTitle.style.color = `rgba(255, 255, 255, ${0.56 + progress * 0.44})`;
        }

        if (founderSubtitle) {
            founderSubtitle.style.color = `rgba(255, 255, 255, ${0.32 + progress * 0.68})`;
        }

        if (founderDivider) {
            founderDivider.style.backgroundColor = `rgba(255, 255, 255, ${0.16 + progress * 0.84})`;
        }

        if (founderPortrait) {
            founderPortrait.style.transform = `translate3d(0, ${3 - progress * 2}%, 0) scale(${1.02 + progress * 0.03})`;
            founderPortrait.style.opacity = `${0.14 + progress * 0.09}`;
        }
    };

    let ticking = false;

    const requestFounderUpdate = () => {
        if (ticking) {
            return;
        }

        ticking = true;
        window.requestAnimationFrame(() => {
            updateFounderProgress();
            ticking = false;
        });
    };

    updateFounderProgress();
    window.addEventListener("scroll", requestFounderUpdate, { passive: true });
    window.addEventListener("resize", requestFounderUpdate);
}

const manifestoSection = document.querySelector("#manifesto");

if (manifestoSection) {
    const manifestoImage = manifestoSection.querySelector(".manifesto-image");
    const manifestoContent = manifestoSection.querySelector(".manifesto-content__inner");
    const manifestoTitleLines = Array.from(manifestoSection.querySelectorAll(".manifesto-title span"));

    const updateManifestoParallax = () => {
        const rect = manifestoSection.getBoundingClientRect();
        const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
        const progress = clamp((viewportHeight - rect.top) / (rect.height + viewportHeight * 0.2), 0, 1);

        if (manifestoImage) {
            const translateY = (0.5 - progress) * 120;
            const scale = 1.08 + progress * 0.08;
            manifestoImage.style.transform = `translate3d(0, ${translateY}px, 0) scale(${scale})`;
        }

        if (manifestoContent) {
            manifestoContent.style.transform = `translate3d(0, ${42 - progress * 42}px, 0)`;
        }

        manifestoTitleLines.forEach((line, index) => {
            const offset = (1 - progress) * (20 + index * 16);
            line.style.transform = `translate3d(0, ${offset}px, 0)`;
            line.style.opacity = `${0.34 + progress * 0.66}`;
        });
    };

    let manifestoTicking = false;

    const requestManifestoUpdate = () => {
        if (manifestoTicking) {
            return;
        }

        manifestoTicking = true;
        window.requestAnimationFrame(() => {
            updateManifestoParallax();
            manifestoTicking = false;
        });
    };

    updateManifestoParallax();
    window.addEventListener("scroll", requestManifestoUpdate, { passive: true });
    window.addEventListener("resize", requestManifestoUpdate);
}

const companySelector = document.querySelector("[data-company-select]");

if (companySelector) {
    const trigger = companySelector.querySelector("[data-company-trigger]");
    const menu = companySelector.querySelector("[data-company-menu]");
    const hiddenInput = companySelector.querySelector("[data-company-input]");
    const selectedLabel = companySelector.querySelector("[data-company-selected-label]");
    const selectedLogo = companySelector.querySelector("[data-company-selected-logo]");
    const options = Array.from(companySelector.querySelectorAll("[data-company-option]"));

    const closeCompanyMenu = () => {
        if (!trigger || !menu) {
            return;
        }

        trigger.setAttribute("aria-expanded", "false");
        menu.hidden = true;
    };

    const openCompanyMenu = () => {
        if (!trigger || !menu) {
            return;
        }

        trigger.setAttribute("aria-expanded", "true");
        menu.hidden = false;
    };

    if (trigger && menu) {
        trigger.addEventListener("click", () => {
            const isExpanded = trigger.getAttribute("aria-expanded") === "true";

            if (isExpanded) {
                closeCompanyMenu();
            } else {
                openCompanyMenu();
            }
        });
    }

    options.forEach((option) => {
        option.addEventListener("click", () => {
            const value = option.dataset.companyValue || option.textContent.trim();
            const logo = option.dataset.companyLogo || "";

            options.forEach((item) => item.classList.remove("is-selected"));
            option.classList.add("is-selected");

            if (hiddenInput) {
                hiddenInput.value = value;
            }

            if (selectedLabel) {
                selectedLabel.textContent = value;
            }

            if (selectedLogo && logo) {
                selectedLogo.src = logo;
            }

            closeCompanyMenu();
        });
    });

    document.addEventListener("click", (event) => {
        if (!companySelector.contains(event.target)) {
            closeCompanyMenu();
        }
    });
}

const careerFileInput = document.querySelector(".career-upload__input");

if (careerFileInput) {
    const uploadSurfaceText = careerFileInput.parentElement?.querySelector(".career-upload__surface span:last-child");

    careerFileInput.addEventListener("change", () => {
        if (!uploadSurfaceText) {
            return;
        }

        const fileName = careerFileInput.files && careerFileInput.files[0]
            ? careerFileInput.files[0].name
            : "PDF veya DOC formatında CV ekleyin";

        uploadSurfaceText.textContent = fileName;
    });
}

const newsFilters = Array.from(document.querySelectorAll("[data-news-filter]"));
const newsItems = Array.from(document.querySelectorAll("[data-news-category]"));
const newsModal = document.querySelector("[data-news-modal]");
const newsModalImage = document.querySelector("[data-news-modal-image]");
const newsModalDate = document.querySelector("[data-news-modal-date]");
const newsModalCompany = document.querySelector("[data-news-modal-company]");
const newsModalTitle = document.querySelector("[data-news-modal-title]");
const newsModalDescription = document.querySelector("[data-news-modal-description]");
const newsModalCloseControls = Array.from(document.querySelectorAll("[data-news-modal-close]"));
const contactModal = document.querySelector("[data-contact-modal]");
const contactModalOpen = document.querySelector("[data-contact-open]");
const contactModalCloseControls = Array.from(document.querySelectorAll("[data-contact-close]"));

if (newsFilters.length && newsItems.length) {
    const updateNewsFilter = (category) => {
        newsFilters.forEach((filter) => {
            filter.classList.toggle("is-active", filter.dataset.newsFilter === category);
        });

        newsItems.forEach((item) => {
            const itemCategory = item.dataset.newsCategory;
            const isVisible = category === "all" || itemCategory === category;
            item.classList.toggle("is-hidden", !isVisible);
        });
    };

    const closeNewsModal = () => {
        if (!newsModal) {
            return;
        }

        newsModal.hidden = true;
        document.body.classList.remove("news-modal-open");
    };

    const openNewsModal = (item) => {
        if (!newsModal || !newsModalImage || !newsModalDate || !newsModalCompany || !newsModalTitle || !newsModalDescription) {
            return;
        }

        const image = item.dataset.newsImage || "";
        const imageWrapper = newsModalImage.parentElement;

        if (image) {
            newsModalImage.src = image;
            newsModalImage.alt = item.dataset.newsTitle || "";

            if (imageWrapper) {
                imageWrapper.hidden = false;
            }
        } else {
            newsModalImage.removeAttribute("src");
            newsModalImage.alt = "";

            if (imageWrapper) {
                imageWrapper.hidden = true;
            }
        }

        newsModalDate.textContent = item.dataset.newsDate || "";
        newsModalCompany.textContent = item.dataset.newsCompany || "";
        newsModalTitle.textContent = item.dataset.newsTitle || "";
        newsModalDescription.textContent = item.dataset.newsDescription || "";
        newsModal.hidden = false;
        document.body.classList.add("news-modal-open");
    };

    newsFilters.forEach((filter) => {
        filter.addEventListener("click", () => {
            updateNewsFilter(filter.dataset.newsFilter || "all");
        });
    });

    newsItems.forEach((item) => {
        item.addEventListener("click", () => {
            openNewsModal(item);
        });
    });

    newsModalCloseControls.forEach((control) => {
        control.addEventListener("click", closeNewsModal);
    });

    document.addEventListener("keydown", (event) => {
        if (event.key === "Escape") {
            closeNewsModal();
        }
    });

    updateNewsFilter("all");
}

if (contactModal && contactModalOpen) {
    const closeContactModal = () => {
        contactModal.hidden = true;
        document.body.classList.remove("contact-modal-open");
    };

    const openContactModal = () => {
        contactModal.hidden = false;
        document.body.classList.add("contact-modal-open");
    };

    contactModalOpen.addEventListener("click", openContactModal);

    contactModalCloseControls.forEach((control) => {
        control.addEventListener("click", closeContactModal);
    });

    document.addEventListener("keydown", (event) => {
        if (event.key === "Escape") {
            closeContactModal();
        }
    });
}
