---
// Header component with scroll-based background and enhanced mobile animations

// --- TypeScript Interfaces (from payload-types.ts Header global) ---
interface NavLink {
    type?: ("reference" | "custom") | null;
    newTab?: boolean | null;
    reference?:
        | ({ relationTo: "pages"; value: string | { slug: string } } | null)
        | ({ relationTo: "posts"; value: string | { slug: string } } | null);
    url?: string | null;
    label: string;
}

interface NavItem {
    link: NavLink;
    id?: string | null;
}

// --- Hardcoded fallback nav (used when CMS is unavailable) ---
const FALLBACK_NAV: NavItem[] = [
    { link: { type: "custom", url: "/about-enchun", label: "關於恩群" } },
    {
        link: {
            type: "custom",
            url: "/marketing-solutions",
            label: "行銷方案",
        },
    },
    { link: { type: "custom", url: "/marketing-lens", label: "行銷放大鏡" } },
    { link: { type: "custom", url: "/enchun-basecamp", label: "恩群大本營" } },
    { link: { type: "custom", url: "/website-portfolio", label: "網站設計" } },
    { link: { type: "custom", url: "/contact", label: "聯絡我們" } },
];

// Use local backend in development, production URL from dev.vars/wrangler
const isDev = import.meta.env.DEV;
const PAYLOAD_CMS_URL = isDev
    ? "http://localhost:3000"
    : import.meta.env.PAYLOAD_CMS_URL || "https://enchun-admin.anlstudio.cc";

// Fetch navigation data from Payload CMS server-side
let navItems: NavItem[] = [];
try {
    const response = await fetch(
        `${PAYLOAD_CMS_URL}/api/globals/header?depth=2&draft=false&trash=false`,
    );
    if (response.ok) {
        const data = await response.json();
        navItems = data?.navItems || [];
    }
} catch (error) {
    console.error("[Header SSR] Failed to fetch navigation:", error);
}

// Use fallback when CMS returns empty
if (!navItems.length) {
    navItems = FALLBACK_NAV;
}

// Helper to get link URL
function getLinkUrl(link: NavLink): string {
    if (!link) return "#";

    if (link.type === "custom" && link.url) {
        return link.url;
    }

    if (link.type === "reference" && link.reference?.value) {
        if (typeof link.reference.value === "string") {
            return `/${link.reference.relationTo || "pages"}/${link.reference.value}`;
        } else if (link.reference.value.slug) {
            return `/${link.reference.value.slug}`;
        }
    }

    return "#";
}

// Return badge type for label (data-driven, no HTML strings)
function getBadgeType(label: string): "hot" | "new" | null {
    if (label.includes("行銷方案")) return "hot";
    if (label.includes("行銷放大鏡")) return "new";
    return null;
}

// Check if link is active
function isLinkActive(url: string): boolean {
    return Astro.url.pathname === url;
}
---

<header
    class="fixed top-0 left-0 right-0 z-50 transition-all duration-300 ease-in-out will-change-transform"
    id="main-header"
>
    <nav
        class="max-w-5xl mx-auto px-4 py-4 transition-all duration-300 ease-in-out"
        id="main-nav"
    >
        <ul class="flex items-center justify-between list-none">
            <li class="shrink-0">
                <a href="/" class="block">
                    <img
                        src="/enchun-logo.svg"
                        alt="Enchun Digital Marketing"
                        class="w-32 h-auto transition-transform duration-300 drop-shadow-md"
                        width="919"
                        height="201"
                        loading="eager"
                        decoding="async"
                    />
                </a>
            </li>
            {
                navItems.map((item) => {
                    const link = item.link;
                    const href = getLinkUrl(link);
                    const label = link.label || "未命名";
                    const badge = getBadgeType(label);
                    const active = isLinkActive(href);

                    return (
                        <li class="hidden md:block">
                            <a
                                href={href}
                                class:list={[
                                    "nav-link text-base font-medium transition-all duration-200 px-3 py-2 rounded hover:bg-white/10",
                                    { "relative inline-block": badge },
                                    { "nav-active": active },
                                ]}
                                {...(link.newTab && {
                                    target: "_blank",
                                    rel: "noopener noreferrer",
                                })}
                            >
                                {label}
                                {badge === "hot" && (
                                    <span class="badge-nav badge-hot">Hot</span>
                                )}
                                {badge === "new" && (
                                    <span class="badge-nav badge-new">New</span>
                                )}
                            </a>
                        </li>
                    );
                })
            }
            <!-- Mobile menu button with animated hamburger/X icon -->
            <li class="md:hidden">
                <button
                    class="text-(--color-enchunblue) hover:text-(--color-enchunblue)/80 focus:outline-none relative w-10 h-10 flex items-center justify-center"
                    id="mobile-menu-button"
                    aria-label="Toggle mobile menu"
                    aria-expanded="false"
                >
                    <span class="sr-only text-(--color-enchunblue-dark)"
                        >Toggle menu</span
                    >
                    <svg
                        width="28"
                        height="28"
                        viewBox="0 0 36 36"
                        fill="none"
                        xmlns="http://www.w3.org/2000/svg"
                        class="w-7 h-7 hamburger-icon transition-transform duration-300"
                        id="hamburger-icon"
                    >
                        <path
                            d="M6 27H22.5C23.325 27 24 26.325 24 25.5C24 24.675 23.325 24 22.5 24H6C5.175 24 4.5 24.675 4.5 25.5C4.5 26.325 5.175 27 6 27ZM6 19.5H18C18.825 19.5 19.5 18.825 19.5 18C19.5 17.175 18.825 16.5 18 16.5H6C5.175 16.5 4.5 17.175 4.5 18C4.5 18.825 5.175 19.5 6 19.5ZM4.5 10.5C4.5 11.325 5.175 12 6 12H22.5C23.325 12 24 11.325 24 10.5C24 9.675 23.325 9 22.5 9H6C5.175 9 4.5 9.675 4.5 10.5ZM30.45 22.32L26.13 18L30.45 13.68C30.5889 13.5411 30.699 13.3763 30.7742 13.1948C30.8493 13.0134 30.888 12.8189 30.888 12.6225C30.888 12.4261 30.8493 12.2316 30.7742 12.0502C30.699 11.8687 30.5889 11.7039 30.45 11.565C30.3111 11.4261 30.1463 11.316 29.9648 11.2408C29.7834 11.1657 29.5889 11.127 29.3925 11.127C29.1961 11.127 29.0016 11.1657 28.8202 11.2408C28.6387 11.316 28.4739 11.4261 28.335 11.565L22.95 16.95C22.8109 17.0888 22.7006 17.2536 22.6254 17.4351C22.5501 17.6165 22.5113 17.811 22.5113 18.0075C22.5113 18.204 22.5501 18.3985 22.6254 18.5799C22.7006 18.7614 22.8109 18.9262 22.95 19.065L28.335 24.45C28.92 25.035 29.865 25.035 30.45 24.45C31.02 23.865 31.035 22.905 30.45 22.32V22.32Z"
                            fill="currentColor"
                            class="transition-opacity duration-300"></path>
                    </svg>
                    <!-- X icon for close state -->
                    <svg
                        width="28"
                        height="28"
                        viewBox="0 0 36 36"
                        fill="none"
                        xmlns="http://www.w3.org/2000/svg"
                        class="w-7 h-7 close-icon absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 opacity-0 transition-opacity duration-300 pointer-events-none"
                        id="close-icon"
                    >
                        <path
                            d="M28.5 9.6L26.4 7.5L18 15.9L9.6 7.5L7.5 9.6L15.9 18L7.5 26.4L9.6 28.5L18 20.1L26.4 28.5L28.5 26.4L20.1 18L28.5 9.6Z"
                            fill="currentColor"></path>
                    </svg>
                </button>
            </li>
        </ul>
    </nav>
    <!-- Mobile menu with full-screen overlay (separate nav for semantics) -->
    <nav
        class="md:hidden fixed left-0 right-0 mobile-menu-top mobile-menu-height bg-white/20 backdrop-blur-xl opacity-0 invisible transition-[opacity,visibility,top] duration-300 ease-in-out"
        id="mobile-menu"
        aria-label="Mobile navigation"
    >
        <ul
            class="flex flex-col items-center justify-center h-full space-y-6 px-4"
            id="mobile-nav"
        >
            {
                navItems.map((item, index) => {
                    const link = item.link;
                    const href = getLinkUrl(link);
                    const label = link.label || "未命名";

                    return (
                        <li
                            class="mobile-nav-item"
                            style={`animation-delay: ${index * 50}ms`}
                        >
                            <a
                                href={href}
                                class="text-2xl text-gray-700 font-medium transition-all duration-200 hover:scale-105 p-3 min-h-12 flex items-center"
                                {...(link.newTab && {
                                    target: "_blank",
                                    rel: "noopener noreferrer",
                                })}
                            >
                                {label}
                            </a>
                        </li>
                    );
                })
            }
        </ul>
    </nav>
</header>

<script>
    // Scroll-based header with smooth hide/show animation
    // Uses AbortController for cleanup on re-mount (View Transitions)
    let lastScrollY = 0;
    let ticking = false;
    let isHeaderHidden = false;
    let abortController: AbortController | null = null;

    function initScrollEffect() {
        const header = document.getElementById("main-header");
        const nav = document.getElementById("main-nav");
        if (!header || !nav) return;

        const handleScroll = () => {
            const scrollY = window.scrollY;
            const scrollDelta = scrollY - lastScrollY;
            const scrollDirection = scrollDelta > 0 ? "down" : "up";

            if (Math.abs(scrollDelta) > 1) {
                lastScrollY = scrollY;
            }

            // Toggle single class for scrolled state (CSS handles all visuals)
            if (scrollY > 10) {
                header.classList.add("header-scrolled");
            } else {
                header.classList.remove("header-scrolled");
            }

            // Hide/show header based on scroll direction
            const hideThreshold = 150;
            const showThreshold = 50;

            if (
                scrollY > hideThreshold &&
                scrollDirection === "down" &&
                !isHeaderHidden
            ) {
                if (scrollDelta > 5) {
                    header.classList.remove("translate-in");
                    header.classList.add("translate-out");
                    isHeaderHidden = true;
                }
            } else if (scrollDirection === "up" && isHeaderHidden) {
                header.classList.remove("translate-out");
                header.classList.add("translate-in");
                isHeaderHidden = false;
            } else if (scrollY < showThreshold) {
                header.classList.remove("translate-out");
                header.classList.add("translate-in");
                isHeaderHidden = false;
            }

            ticking = false;
        };

        const signal = abortController!.signal;

        window.addEventListener(
            "scroll",
            () => {
                if (!ticking) {
                    window.requestAnimationFrame(handleScroll);
                    ticking = true;
                }
            },
            { passive: true, signal },
        );

        handleScroll();
    }

    function initMobileMenu() {
        const button = document.getElementById("mobile-menu-button");
        const menu = document.getElementById("mobile-menu");
        const hamburgerIcon = document.getElementById("hamburger-icon");
        const closeIcon = document.getElementById("close-icon");
        const mobileNavItems = document
            .getElementById("mobile-nav")
            ?.querySelectorAll("li");

        if (!button || !menu || !hamburgerIcon || !closeIcon) return;

        const signal = abortController!.signal;

        button.addEventListener(
            "click",
            () => {
                const isMenuOpen = menu.classList.contains("opacity-100");

                if (isMenuOpen) {
                    menu.classList.remove("opacity-100", "visible");
                    menu.classList.add("opacity-0", "invisible");
                    hamburgerIcon.classList.remove("opacity-0", "rotate-90");
                    hamburgerIcon.classList.add("opacity-100");
                    closeIcon.classList.remove("opacity-100");
                    closeIcon.classList.add("opacity-0");
                    button.setAttribute("aria-expanded", "false");

                    mobileNavItems?.forEach((item) => {
                        item.classList.remove("mobile-nav-visible");
                        item.classList.add("mobile-nav-hidden");
                    });

                    document.documentElement.classList.remove(
                        "mobile-menu-open",
                    );
                } else {
                    menu.classList.remove("opacity-0", "invisible");
                    menu.classList.add("opacity-100", "visible");
                    hamburgerIcon.classList.remove("opacity-100");
                    hamburgerIcon.classList.add("opacity-0", "rotate-90");
                    closeIcon.classList.remove("opacity-0");
                    closeIcon.classList.add("opacity-100");
                    button.setAttribute("aria-expanded", "true");

                    mobileNavItems?.forEach((item, index) => {
                        setTimeout(() => {
                            item.classList.remove("mobile-nav-hidden");
                            item.classList.add("mobile-nav-visible");
                        }, index * 50);
                    });

                    document.documentElement.classList.add("mobile-menu-open");
                }
            },
            { signal },
        );

        menu.addEventListener(
            "click",
            (e) => {
                if (e.target === menu) {
                    button.click();
                }
            },
            { signal },
        );

        document.addEventListener(
            "keydown",
            (e) => {
                if (
                    e.key === "Escape" &&
                    menu.classList.contains("opacity-100")
                ) {
                    button.click();
                }
            },
            { signal },
        );
    }

    function init() {
        // Cleanup previous listeners (View Transitions re-mount safety)
        abortController?.abort();
        abortController = new AbortController();

        // Reset state
        lastScrollY = 0;
        ticking = false;
        isHeaderHidden = false;

        initScrollEffect();
        initMobileMenu();
    }

    document.addEventListener("DOMContentLoaded", init);
    document.addEventListener("astro:after-swap", init);
</script>

<style>
    /* JS-controlled animation states */
    #main-header.translate-out {
        transform: translateY(-100%);
    }

    #main-header.translate-in {
        transform: translateY(0);
    }

    /* --- Scrolled state (all visual changes via single CSS class) --- */
    #main-header.header-scrolled {
        background: rgba(255, 255, 255, 0.15);
        backdrop-filter: blur(24px);
        -webkit-backdrop-filter: blur(24px);
        box-shadow: var(--shadow-md, 0 4px 6px -1px rgb(0 0 0 / 0.1));
    }

    #main-header:not(.header-scrolled) {
        background: transparent;
    }

    #main-header.header-scrolled #main-nav {
        padding-top: 0.5rem;
        padding-bottom: 0.5rem;
    }

    /* Logo shrinks when header is scrolled */
    #main-header.header-scrolled img {
        transform: scale(0.85);
    }

    /* Mobile menu positioning: adjusts based on header scroll state */
    .mobile-menu-top {
        top: 5rem; /* = py-4 header height */
    }

    .mobile-menu-height {
        height: calc(100dvh - 5rem);
    }

    #main-header.header-scrolled ~ #mobile-menu,
    #main-header.header-scrolled #mobile-menu {
        top: 4rem; /* = py-2 header height */
        height: calc(100dvh - 4rem);
    }

    /* Navigation links */
    #main-nav a {
        color: var(--color-nav-link);
        text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.3);
    }

    #main-nav a:hover {
        color: var(--color-primary);
    }

    /* Nav link underline animation */
    .nav-link {
        position: relative;
    }

    /* Active state */
    .nav-active {
        position: relative;
        color: var(--color-enchunblue) !important;
        font-weight: 600;
    }

    /* Badge positioning for nav */
    .badge-nav {
        position: absolute;
        top: -4px;
        right: -8px;
        font-size: 6px;
        font-weight: 700;
        padding: 2px 6px;
        border-radius: 9999px;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: white;
        box-shadow: var(--shadow-sm);
    }

    .badge-nav.badge-hot {
        background-color: var(--color-badge-hot, #ea384c);
        animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
    }

    .badge-nav.badge-new {
        background-color: var(--color-badge-hot, #ea384c);
    }

    @keyframes pulse {
        0%,
        100% {
            opacity: 1;
        }
        50% {
            opacity: 0.5;
        }
    }

    /* Mobile menu */
    @media (max-width: 767px) {
        #mobile-menu {
            overflow-y: auto;
            -webkit-overflow-scrolling: touch;
        }

        #mobile-nav a {
            padding: 0.75rem 1rem;
            min-height: 48px;
            display: flex;
            align-items: center;
            color: var(--color-nav-link);
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
        }

        #mobile-nav a:hover {
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
    }

    /* Mobile nav item animation states (CSS-driven) */
    .mobile-nav-item {
        opacity: 0;
        transform: translateY(1rem);
        transition:
            opacity 0.3s ease-out,
            transform 0.3s ease-out;
    }

    .mobile-nav-item.mobile-nav-visible {
        opacity: 1;
        transform: translateY(0);
    }

    .mobile-nav-item.mobile-nav-hidden {
        opacity: 0;
        transform: translateY(1rem);
    }

    /* iOS scroll lock */
    :global(html.mobile-menu-open) {
        overflow: hidden;
        position: fixed;
        width: 100%;
        height: 100%;
    }
</style>
