const body = document.body;
const variantButtons = document.querySelectorAll("[data-switch-variant]");
const conceptPages = document.querySelectorAll(".concept-homepage");
const tabGroups = document.querySelectorAll("[data-tabs]");
const homepageHeader = document.querySelector(".homepage-header");
const mobileNavToggle = document.querySelector("[data-mobile-nav-toggle]");
const homepageNavShell = document.querySelector(".homepage-nav-shell");
const homepageNavLinks = document.querySelectorAll(".homepage-nav a");
const homepageNavSections = Array.from(homepageNavLinks)
    .map((link) => {
        const targetId = link.getAttribute("href");
        if (!targetId || !targetId.startsWith("#")) {
            return null;
        }

        const section = document.querySelector(targetId);
        return section ? { link, section } : null;
    })
    .filter(Boolean);
const desktopNavMediaQuery = window.matchMedia("(min-width: 72rem)");
const scrollTopButton = document.querySelector("[data-scroll-top]");
const contactForms = document.querySelectorAll("[data-contact-form]");
const cookieBar = document.querySelector("[data-cookie-bar]");
const cookieAcceptButton = document.querySelector("[data-cookie-accept]");
const cookieDetailsToggle = document.querySelector("[data-cookie-details-toggle]");
const COOKIE_CONSENT_KEY = "iliedragan-cookie-consent";

const lightbox = document.querySelector(".media-lightbox");
const lightboxContent = document.querySelector("[data-lightbox-content]");
const lightboxCaption = document.querySelector("[data-lightbox-caption]");
const lightboxTitle = document.getElementById("lightbox-title");
const lightboxCloseButtons = document.querySelectorAll("[data-close-lightbox]");
let activeVideoJumpTimeout = null;

function setTabGroupState(group, target, options = {}) {
    if (!group || !target) {
        return null;
    }

    const { scrollButton = true, behavior = "smooth" } = options;
    const tabList = group.querySelector(".tabs__list");
    const buttons = Array.from(group.querySelectorAll("[data-tab-button]"));
    const panels = Array.from(group.querySelectorAll("[data-tab-panel]"));
    const activeButton = buttons.find((button) => button.dataset.tabButton === target);

    if (!activeButton) {
        return null;
    }

    buttons.forEach((button) => button.classList.toggle("is-active", button === activeButton));
    panels.forEach((panel) => {
        const isActive = panel.dataset.tabPanel === target;
        panel.hidden = !isActive;
        panel.classList.toggle("is-active", isActive);
    });

    if (scrollButton && tabList) {
        activeButton.scrollIntoView({
            behavior,
            block: "nearest",
            inline: "center",
        });
    }

    group.__syncScrollControls?.();

    return activeButton;
}

function setActiveVariant(variant) {
    body.dataset.activeVariant = variant;

    variantButtons.forEach((button) => {
        const isActive = button.dataset.switchVariant === variant;
        button.classList.toggle("is-active", isActive);
        button.setAttribute("aria-pressed", String(isActive));
    });

    conceptPages.forEach((page) => {
        const isActive = page.dataset.variant === variant;
        page.hidden = !isActive;
        page.setAttribute("aria-hidden", String(!isActive));
        page.classList.toggle("is-active", isActive);
    });
}

function initTabs() {
    tabGroups.forEach((group) => {
        const tabList = group.querySelector(".tabs__list");
        const buttons = group.querySelectorAll("[data-tab-button]");
        const previousButton = group.querySelector('[data-tabs-scroll="prev"]');
        const nextButton = group.querySelector('[data-tabs-scroll="next"]');
        const syncScrollControls = () => {
            if (!tabList || !previousButton || !nextButton) {
                return;
            }

            const maxScrollLeft = Math.max(tabList.scrollWidth - tabList.clientWidth, 0);
            const currentScrollLeft = Math.round(tabList.scrollLeft);

            previousButton.disabled = currentScrollLeft <= 4;
            nextButton.disabled = currentScrollLeft >= maxScrollLeft - 4;
        };

        group.__syncScrollControls = syncScrollControls;
        group.__setActiveTab = (target, options = {}) => setTabGroupState(group, target, options);

        buttons.forEach((button) => {
            button.addEventListener("click", () => {
                group.__setActiveTab?.(button.dataset.tabButton, { scrollButton: true, behavior: "smooth" });
            });
        });

        if (tabList && previousButton && nextButton) {
            const scrollAmount = () => Math.max(tabList.clientWidth * 0.72, 180);

            previousButton.addEventListener("click", () => {
                tabList.scrollBy({
                    left: -scrollAmount(),
                    behavior: "smooth",
                });
            });

            nextButton.addEventListener("click", () => {
                tabList.scrollBy({
                    left: scrollAmount(),
                    behavior: "smooth",
                });
            });

            tabList.addEventListener("scroll", syncScrollControls, { passive: true });
            window.addEventListener("resize", syncScrollControls);
            requestAnimationFrame(() => {
                group.__setActiveTab?.(group.querySelector(".tabs__button.is-active")?.dataset.tabButton, {
                    scrollButton: true,
                    behavior: "auto",
                });
                syncScrollControls();
            });
        }
    });
}

function initVideoJumpLinks() {
    const jumpLinks = document.querySelectorAll("[data-video-jump]");
    const videoTabsGroup = document.querySelector('[data-tabs="editorial-video"]');
    const videoSection = document.getElementById("institutional-media-video");

    if (!jumpLinks.length || !videoTabsGroup || !videoSection) {
        return;
    }

    jumpLinks.forEach((link) => {
        link.addEventListener("click", (event) => {
            const targetKey = link.dataset.videoJump;
            const targetTab = link.dataset.videoTab || "editorial-video-1";
            const targetCard = targetKey ? document.querySelector(`[data-video-target="${targetKey}"]`) : null;

            event.preventDefault();

            videoTabsGroup.__setActiveTab?.(targetTab, { scrollButton: true, behavior: "smooth" });
            videoSection.scrollIntoView({
                behavior: "smooth",
                block: "start",
            });

            if (history.replaceState) {
                history.replaceState(null, "", link.getAttribute("href"));
            }

            if (!targetCard) {
                return;
            }

            window.clearTimeout(activeVideoJumpTimeout);
            targetCard.classList.remove("is-video-jump-highlight");

            activeVideoJumpTimeout = window.setTimeout(() => {
                targetCard.classList.remove("is-video-jump-highlight");
                void targetCard.offsetWidth;
                targetCard.classList.add("is-video-jump-highlight");
                targetCard.scrollIntoView({
                    behavior: "smooth",
                    block: "nearest",
                    inline: "nearest",
                });

                activeVideoJumpTimeout = window.setTimeout(() => {
                    targetCard.classList.remove("is-video-jump-highlight");
                }, 1800);
            }, 480);
        });
    });
}

function setMobileNavOpen(isOpen) {
    if (!homepageHeader || !mobileNavToggle || !homepageNavShell) {
        return;
    }

    homepageHeader.classList.toggle("is-menu-open", isOpen);
    mobileNavToggle.setAttribute("aria-expanded", String(isOpen));
    homepageNavShell.hidden = !isOpen && !desktopNavMediaQuery.matches;
}

function syncMobileNavState() {
    if (!homepageHeader || !mobileNavToggle || !homepageNavShell) {
        return;
    }

    if (desktopNavMediaQuery.matches) {
        homepageHeader.classList.remove("is-menu-open");
        mobileNavToggle.setAttribute("aria-expanded", "false");
        homepageNavShell.hidden = false;
        return;
    }

    homepageNavShell.hidden = !homepageHeader.classList.contains("is-menu-open");

    if (!homepageHeader.classList.contains("is-menu-open")) {
        mobileNavToggle.setAttribute("aria-expanded", "false");
    }
}

function initMobileNav() {
    if (!homepageHeader || !mobileNavToggle || !homepageNavShell) {
        return;
    }

    mobileNavToggle.addEventListener("click", () => {
        const isOpen = homepageHeader.classList.contains("is-menu-open");
        setMobileNavOpen(!isOpen);
    });

    homepageNavLinks.forEach((link) => {
        link.addEventListener("click", () => {
            if (!desktopNavMediaQuery.matches) {
                setMobileNavOpen(false);
            }
        });
    });

    document.addEventListener("click", (event) => {
        if (
            !desktopNavMediaQuery.matches &&
            homepageHeader.classList.contains("is-menu-open") &&
            !homepageHeader.contains(event.target)
        ) {
            setMobileNavOpen(false);
        }
    });

    if (typeof desktopNavMediaQuery.addEventListener === "function") {
        desktopNavMediaQuery.addEventListener("change", syncMobileNavState);
    } else if (typeof desktopNavMediaQuery.addListener === "function") {
        desktopNavMediaQuery.addListener(syncMobileNavState);
    }

    syncMobileNavState();
}

function setActiveNavLink(activeId) {
    homepageNavLinks.forEach((link) => {
        const isActive = link.getAttribute("href") === activeId;
        link.classList.toggle("is-active", isActive);

        if (isActive) {
            link.setAttribute("aria-current", "location");
        } else {
            link.removeAttribute("aria-current");
        }
    });
}

function updateActiveNavLinkOnScroll() {
    if (!homepageNavSections.length) {
        return;
    }

    const readingLine = window.scrollY + Math.max(homepageHeader?.offsetHeight || 0, 120) + 56;
    let currentSection = homepageNavSections[0];

    homepageNavSections.forEach((entry) => {
        const sectionTop = entry.section.getBoundingClientRect().top + window.scrollY;

        if (sectionTop <= readingLine) {
            currentSection = entry;
        }
    });

    setActiveNavLink(`#${currentSection.section.id}`);
}

function initScrollSpy() {
    if (!homepageNavSections.length) {
        return;
    }

    homepageNavLinks.forEach((link) => {
        link.addEventListener("click", () => {
            setActiveNavLink(link.getAttribute("href"));
        });
    });

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

function updateScrollTopButtonVisibility() {
    if (!scrollTopButton) {
        return;
    }

    const shouldShow = window.scrollY > 260;
    scrollTopButton.hidden = false;
    scrollTopButton.classList.toggle("is-visible", shouldShow);
    scrollTopButton.setAttribute("aria-hidden", String(!shouldShow));
    scrollTopButton.style.opacity = shouldShow ? "1" : "0";
    scrollTopButton.style.visibility = shouldShow ? "visible" : "hidden";
    scrollTopButton.style.transform = shouldShow ? "translateY(0) scale(1)" : "translateY(12px) scale(0.96)";
    scrollTopButton.style.pointerEvents = shouldShow ? "auto" : "none";
}

function initScrollTopButton() {
    if (!scrollTopButton) {
        return;
    }

    const scrollTopIcon = scrollTopButton.querySelector(".scroll-top-button__icon");
    const scrollTopText = scrollTopButton.querySelector(".scroll-top-button__text");

    // Apply critical layout inline so the control stays bottom-right even if cached CSS lags behind.
    Object.assign(scrollTopButton.style, {
        position: "fixed",
        right: "20px",
        bottom: "calc(max(1rem, env(safe-area-inset-bottom)) + var(--cookie-bar-offset))",
        left: "auto",
        top: "auto",
        zIndex: "90",
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        gap: "10px",
        minWidth: "90px",
        height: "56px",
        margin: "0",
        padding: "6px 10px 6px 8px",
        border: "1px solid rgba(35, 71, 109, 0.16)",
        borderRadius: "9999px",
        background: "linear-gradient(180deg, rgba(255, 255, 255, 0.98), rgba(248, 246, 242, 0.94))",
        color: "#23476d",
        boxShadow: "0 18px 44px rgba(20, 34, 51, 0.18), inset 0 1px 0 rgba(255, 255, 255, 0.88)",
        backdropFilter: "blur(16px) saturate(140%)",
        WebkitBackdropFilter: "blur(16px) saturate(140%)",
        whiteSpace: "nowrap",
        opacity: "0",
        visibility: "hidden",
        transform: "translateY(12px) scale(0.96)",
        transition: "opacity 180ms ease, transform 180ms ease, visibility 180ms ease, box-shadow 180ms ease, border-color 180ms ease",
        pointerEvents: "none",
    });

    if (scrollTopIcon) {
        Object.assign(scrollTopIcon.style, {
            display: "inline-flex",
            alignItems: "center",
            justifyContent: "center",
            width: "40px",
            height: "40px",
            borderRadius: "9999px",
            background: "rgba(49, 90, 133, 0.12)",
            boxShadow: "inset 0 0 0 1px rgba(35, 71, 109, 0.08)",
            fontSize: "18px",
            lineHeight: "1",
            fontWeight: "700",
        });
    }

    if (scrollTopText) {
        Object.assign(scrollTopText.style, {
            paddingRight: "4px",
            fontSize: "15px",
            lineHeight: "1",
            fontWeight: "600",
            letterSpacing: "0.01em",
        });
    }

    scrollTopButton.addEventListener("mouseenter", () => {
        scrollTopButton.style.borderColor = "rgba(35, 71, 109, 0.28)";
        scrollTopButton.style.boxShadow = "0 22px 48px rgba(20, 34, 51, 0.22), inset 0 1px 0 rgba(255, 255, 255, 0.92)";
    });

    scrollTopButton.addEventListener("mouseleave", () => {
        scrollTopButton.style.borderColor = "rgba(35, 71, 109, 0.16)";
        scrollTopButton.style.boxShadow = "0 18px 44px rgba(20, 34, 51, 0.18), inset 0 1px 0 rgba(255, 255, 255, 0.88)";
    });

    scrollTopButton.addEventListener("click", () => {
        window.scrollTo({
            top: 0,
            behavior: "smooth",
        });
    });

    window.addEventListener("scroll", updateScrollTopButtonVisibility, { passive: true });
    updateScrollTopButtonVisibility();
}

function updateContactFormState(form) {
    const selectedType = form.querySelector('input[name="requestType"]:checked')?.value || "";
    const pressFields = form.querySelectorAll("[data-contact-press-only]");
    const isPressRequest = selectedType === "Presa / interviu";

    pressFields.forEach((field) => {
        field.hidden = !isPressRequest;

        field.querySelectorAll("input, select, textarea").forEach((input) => {
            if (!isPressRequest) {
                input.value = "";
            }
        });
    });
}

function initContactForms() {
    if (!contactForms.length) {
        return;
    }

    contactForms.forEach((form) => {
        const requestTypeInputs = form.querySelectorAll('input[name="requestType"]');
        const successMessage = form.querySelector("[data-contact-success]");
        const errorMessage = form.querySelector("[data-contact-error]");
        const submitButton = form.querySelector('button[type="submit"]');
        const defaultSubmitLabel = submitButton?.textContent || "Trimite solicitarea";

        requestTypeInputs.forEach((input) => {
            input.addEventListener("change", () => updateContactFormState(form));
        });

        form.addEventListener("input", () => {
            successMessage.hidden = true;
            if (errorMessage) {
                errorMessage.hidden = true;
            }
        });

        form.addEventListener("change", () => {
            successMessage.hidden = true;
            if (errorMessage) {
                errorMessage.hidden = true;
            }
        });

        form.addEventListener("submit", async (event) => {
            event.preventDefault();

            if (!form.reportValidity()) {
                return;
            }

            successMessage.hidden = true;
            if (errorMessage) {
                errorMessage.hidden = true;
            }

            if (submitButton) {
                submitButton.disabled = true;
                submitButton.textContent = "Se trimite...";
            }

            try {
                const response = await fetch(form.action, {
                    method: "POST",
                    body: new FormData(form),
                    headers: {
                        Accept: "application/json",
                    },
                });

                const payload = await response.json().catch(() => ({}));

                if (!response.ok || !payload.success) {
                    throw new Error(payload.message || "Transmiterea a eșuat.");
                }

                successMessage.textContent = payload.message || successMessage.textContent;
                successMessage.hidden = false;
                form.reset();
                const defaultRequestType = form.querySelector('input[name="requestType"][value="Presa / interviu"]');
                if (defaultRequestType) {
                    defaultRequestType.checked = true;
                }
                updateContactFormState(form);
            } catch (error) {
                if (errorMessage) {
                    errorMessage.textContent = error.message || "Mesajul nu a putut fi trimis momentan.";
                    errorMessage.hidden = false;
                }
            } finally {
                if (submitButton) {
                    submitButton.disabled = false;
                    submitButton.textContent = defaultSubmitLabel;
                }
            }
        });

        updateContactFormState(form);
    });
}

function syncFloatingUiOffset() {
    const cookieBarOffset = cookieBar && !cookieBar.hidden ? cookieBar.offsetHeight + 24 : 0;
    document.documentElement.style.setProperty("--cookie-bar-offset", `${cookieBarOffset}px`);
}

function hideCookieBar() {
    if (!cookieBar) {
        return;
    }

    cookieBar.hidden = true;
    syncFloatingUiOffset();
}

function initCookieBar() {
    if (!cookieBar || !cookieAcceptButton || !cookieDetailsToggle) {
        syncFloatingUiOffset();
        return;
    }

    const detailsPanel = document.getElementById(cookieDetailsToggle.getAttribute("aria-controls"));
    const hasConsent = window.localStorage.getItem(COOKIE_CONSENT_KEY) === "accepted";

    if (hasConsent) {
        hideCookieBar();
        return;
    }

    cookieBar.hidden = false;
    syncFloatingUiOffset();

    cookieDetailsToggle.addEventListener("click", () => {
        if (!detailsPanel) {
            return;
        }

        const isExpanded = cookieDetailsToggle.getAttribute("aria-expanded") === "true";
        cookieDetailsToggle.setAttribute("aria-expanded", String(!isExpanded));
        detailsPanel.hidden = isExpanded;
        syncFloatingUiOffset();
    });

    cookieAcceptButton.addEventListener("click", () => {
        window.localStorage.setItem(COOKIE_CONSENT_KEY, "accepted");
        hideCookieBar();
    });

    window.addEventListener("resize", syncFloatingUiOffset);
}

function initLoadMoreButtons() {
    const loadMoreButtons = document.querySelectorAll("[data-load-more-target]");

    loadMoreButtons.forEach((button) => {
        const targetId = button.dataset.loadMoreTarget;
        const target = targetId ? document.getElementById(targetId) : null;
        const actions = button.closest(".press-context-actions");
        const endNote = actions?.querySelector(".press-context-actions__end") || null;

        if (!target) {
            button.hidden = true;
            return;
        }

        const getCollapsedItems = () => Array.from(target.querySelectorAll("[data-load-more-item].is-collapsed, [data-load-more-item][hidden]"));
        const showEndNote = () => {
            if (!endNote) {
                return;
            }

            endNote.hidden = false;
            requestAnimationFrame(() => {
                endNote.classList.add("is-visible");
            });
        };
        const hideEndNote = () => {
            if (!endNote) {
                return;
            }

            endNote.classList.remove("is-visible");
            endNote.hidden = true;
        };
        const updateButtonState = ({ animate = false } = {}) => {
            const hasMoreItems = getCollapsedItems().length > 0;

            if (hasMoreItems) {
                button.hidden = false;
                button.classList.remove("is-exhausted");
                hideEndNote();
                return;
            }

            if (animate) {
                button.classList.add("is-exhausted");
                window.setTimeout(() => {
                    button.hidden = true;
                    showEndNote();
                }, 180);
                return;
            }

            button.hidden = true;
            showEndNote();
        };

        button.addEventListener("click", () => {
            const batchSize = Number.parseInt(button.dataset.loadMoreBatch || "2", 10) || 2;
            const revealedItems = getCollapsedItems().slice(0, batchSize);

            revealedItems.forEach((item) => {
                item.hidden = false;
                item.classList.remove("is-collapsed");
            });

            if (revealedItems[0]) {
                requestAnimationFrame(() => {
                    const headerOffset = Math.max(homepageHeader?.offsetHeight || 0, 96);
                    const targetTop = revealedItems[0].getBoundingClientRect().top + window.scrollY - headerOffset - 20;

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

            updateButtonState({ animate: true });
        });

        updateButtonState();
    });
}

function initCurrentYear() {
    const yearNodes = document.querySelectorAll("[data-current-year]");
    const currentYear = new Date().getFullYear();

    yearNodes.forEach((node) => {
        node.textContent = String(currentYear);
    });
}

function getEmbedUrl(rawUrl) {
    if (!rawUrl || rawUrl.startsWith("replace-") || rawUrl === "#") {
        return null;
    }

    if (rawUrl.includes("youtube.com/embed/")) {
        return rawUrl;
    }

    if (rawUrl.includes("youtube.com/watch?v=")) {
        const id = new URL(rawUrl).searchParams.get("v");
        return id ? `https://www.youtube.com/embed/${id}` : null;
    }

    if (rawUrl.includes("youtu.be/")) {
        const id = rawUrl.split("youtu.be/")[1]?.split(/[?&]/)[0];
        return id ? `https://www.youtube.com/embed/${id}` : null;
    }

    return rawUrl;
}

function openLightbox(contentNode, titleText, captionText) {
    lightboxContent.replaceChildren(contentNode);
    lightboxTitle.textContent = titleText || "Media";
    lightboxCaption.textContent = captionText || "";
    lightbox.hidden = false;
    lightbox.setAttribute("aria-hidden", "false");
    body.style.overflow = "hidden";
}

function openImageLightbox(source, caption) {
    const image = document.createElement("img");
    image.src = source;
    image.alt = caption || "Imagine din galerie";

    openLightbox(image, "Galerie foto", caption);
}

function openVideoLightbox(source, title) {
    const embedUrl = getEmbedUrl(source);

    if (embedUrl) {
        const iframe = document.createElement("iframe");
        iframe.src = `${embedUrl}${embedUrl.includes("?") ? "&" : "?"}autoplay=1&rel=0`;
        iframe.allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share";
        iframe.allowFullscreen = true;
        iframe.title = title || "Video";

        openLightbox(iframe, title || "Video", "Material video disponibil în player.");
        return;
    }

    const placeholder = document.createElement("div");
    placeholder.className = "media-lightbox__placeholder";
    placeholder.innerHTML = `
        <strong>${title || "Video"}</strong>
        <p>Acest material video va fi publicat în această secțiune imediat ce este disponibil linkul final.</p>
        <p>Pentru publicare, atașează în atributul <code>data-lightbox-video</code> un URL YouTube embed, watch sau youtu.be.</p>
    `;

    openLightbox(placeholder, title || "Video", "Clipul nu este încă publicat.");
}

function closeLightbox() {
    lightboxContent.replaceChildren();
    lightbox.hidden = true;
    lightbox.setAttribute("aria-hidden", "true");
    body.style.overflow = "";
}

variantButtons.forEach((button) => {
    button.addEventListener("click", () => {
        setActiveVariant(button.dataset.switchVariant);
    });
});

document.addEventListener("click", (event) => {
    const imageTrigger = event.target.closest("[data-lightbox-image]");
    if (imageTrigger) {
        openImageLightbox(imageTrigger.dataset.lightboxImage, imageTrigger.dataset.lightboxCaption);
        return;
    }

    const videoTrigger = event.target.closest("[data-lightbox-video]");
    if (videoTrigger) {
        openVideoLightbox(videoTrigger.dataset.lightboxVideo, videoTrigger.dataset.videoTitle);
    }
});

lightboxCloseButtons.forEach((button) => {
    button.addEventListener("click", closeLightbox);
});

document.addEventListener("keydown", (event) => {
    if (event.key === "Escape" && homepageHeader?.classList.contains("is-menu-open")) {
        setMobileNavOpen(false);
    }

    if (event.key === "Escape" && !lightbox.hidden) {
        closeLightbox();
    }
});

setActiveVariant(body.dataset.activeVariant || conceptPages[0]?.dataset.variant || "institutional");
initTabs();
initMobileNav();
initScrollSpy();
initScrollTopButton();
initContactForms();
initCookieBar();
initLoadMoreButtons();
initCurrentYear();
initVideoJumpLinks();
