<?php
/**
 * Header Template — Updated Navigation + Marquee + Products Mega Menu
 * + Global scroll effects: Fade Up, Stagger, Count-Up, Smooth Scroll
 * Menu order: About → Services → Products → Reviews → FAQs → News → Contact
 */
require_once 'function.php';

$site_logo     = get_site_logo();
$site_name     = get_site_setting('site_name');
$site_subtitle = get_site_setting('site_subtitle');
$site_phone    = get_site_setting('site_phone');
$marquee       = get_marquee();
$current_page  = basename($_SERVER['PHP_SELF']);

$menu_tree = get_product_menu_tree();
$menu_json = json_encode($menu_tree, JSON_UNESCAPED_UNICODE);

$about_pages = ['about.php', 'mission.php', 'vision.php', 'privacy-policy.php'];
$about_links = [
    ['href' => 'about.php',           'label' => 'Company Profile', 'icon' => 'fa-building'],
    ['href' => 'mission.php',         'label' => 'Mission',         'icon' => 'fa-bullseye'],
    ['href' => 'vision.php',          'label' => 'Vision',          'icon' => 'fa-eye'],
    ['href' => 'privacy-policy.php',  'label' => 'Privacy Policy',  'icon' => 'fa-shield-halved'],
];

$nav_links = [
    ['href' => 'about.php',       'label' => 'About Us',      'file' => 'about.php', 'about' => true],
    ['href' => 'services.php',    'label' => 'Services',      'file' => 'services.php'],
    ['href' => 'products.php',    'label' => 'Products',      'file' => 'products.php', 'mega' => true],
    ['href' => 'projects.php',    'label' => 'Projects',      'file' => 'projects.php'],
    ['href' => 'reviews.php',     'label' => 'Reviews',       'file' => 'reviews.php'],
    ['href' => 'faqs.php',        'label' => 'FAQs',          'file' => 'faqs.php'],
    ['href' => 'news.php',        'label' => 'News & Updates','file' => 'news.php'],
    ['href' => 'contact.php',     'label' => 'Contact',       'file' => 'contact.php'],
];

function nav_link_class($file, $current, $extra_active = []) {
    $active_files = array_merge([$file], $extra_active);
    $active = in_array($current, $active_files, true) ? 'text-primary font-semibold' : 'text-gray-600 hover:text-primary';
    return $active . ' transition-colors py-2';
}

$speed_map = ['slow' => '35s', 'normal' => '22s', 'fast' => '14s'];
$marquee_speed = $speed_map[$marquee['speed'] ?? 'normal'] ?? '22s';
?>
<!DOCTYPE html>
<html lang="bn" class="scroll-smooth">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($site_name); ?><?php echo !empty($site_subtitle) ? ' ' . htmlspecialchars($site_subtitle) : ''; ?> — Elevator, Generator, Transformer & Solar Solutions</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#1e3a8a',
                        secondary: '#0284c7',
                        accent: '#f59e0b',
                        darkBg: '#1f2937'
                    }
                }
            }
        }
    </script>
    <style>
        html { scroll-behavior: smooth; }
        #mobile-menu { transition: all 0.3s ease-in-out; }
        @keyframes siteMarquee {
            0%   { transform: translateX(0); }
            100% { transform: translateX(-50%); }
        }
        .marquee-track { animation: siteMarquee <?php echo $marquee_speed; ?> linear infinite; }
        .marquee-track:hover { animation-play-state: paused; }
        .products-mega, .about-dropdown { display: none; }
        .group:hover > .products-mega,
        .group:hover > .about-dropdown { display: block; }
        .mega-col-item.active { background-color: #eff6ff; color: #1e3a8a; font-weight: 600; }

        /* ── Scroll Effects ── */
        .reveal-fade {
            opacity: 0;
            transform: translateY(36px);
            transition: opacity 0.7s ease, transform 0.7s ease;
            will-change: opacity, transform;
        }
        .reveal-fade.is-visible {
            opacity: 1;
            transform: translateY(0);
        }
        .reveal-stagger {
            opacity: 0;
            transform: translateY(28px);
            transition: opacity 0.55s ease, transform 0.55s ease;
            will-change: opacity, transform;
        }
        .reveal-stagger.is-visible {
            opacity: 1;
            transform: translateY(0);
        }
        @media (prefers-reduced-motion: reduce) {
            html { scroll-behavior: auto; }
            .reveal-fade, .reveal-stagger {
                opacity: 1 !important;
                transform: none !important;
                transition: none !important;
            }
        }
    </style>
</head>
<body class="bg-gray-50 text-gray-800 flex flex-col min-h-screen">

    <!-- Header -->
    <header class="bg-white/95 backdrop-blur-md shadow-md sticky top-0 z-50">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex items-center justify-between h-20">
                <div class="flex-shrink-0 flex items-center">
                    <a href="index.php" class="flex items-center space-x-3 group">
                        <img class="w-16 h-16 rounded-full object-cover border-2 border-primary/25 shadow-sm transition-transform group-hover:scale-105"
                             src="<?php echo htmlspecialchars($site_logo); ?>" alt="<?php echo htmlspecialchars($site_name); ?>">
                        <div class="flex flex-col justify-center">
                            <span class="text-lg md:text-xl font-black text-primary tracking-tight group-hover:text-secondary transition-colors leading-none">
                                <?php echo htmlspecialchars($site_name); ?>
                            </span>
                            <?php if (!empty($site_subtitle)): ?>
                            <span class="text-[10px] md:text-[11px] font-bold text-gray-500 uppercase tracking-wider mt-1 group-hover:text-secondary transition-colors leading-tight">
                                <?php echo htmlspecialchars($site_subtitle); ?>
                            </span>
                            <?php endif; ?>
                        </div>
                    </a>
                </div>

                <!-- Desktop Nav -->
                <nav class="hidden lg:flex space-x-5 xl:space-x-6 text-sm font-medium items-center">
                    <?php foreach ($nav_links as $link): ?>
                        <?php if (!empty($link['about'])): ?>
                        <div class="relative group">
                            <a href="about.php" class="<?php echo nav_link_class($link['file'], $current_page, $about_pages); ?> inline-flex items-center gap-1">
                                <?php echo $link['label']; ?>
                                <i class="fa-solid fa-chevron-down text-[10px] opacity-60"></i>
                            </a>
                            <div class="about-dropdown absolute left-0 top-full pt-2 z-[60]">
                                <div class="bg-white rounded-xl shadow-2xl border border-gray-100 min-w-[220px] py-2 overflow-hidden">
                                    <?php foreach ($about_links as $al): ?>
                                    <a href="<?php echo $al['href']; ?>"
                                       class="flex items-center gap-2.5 px-4 py-2.5 text-sm text-gray-700 hover:bg-blue-50 hover:text-primary transition-colors <?php echo ($current_page === $al['href']) ? 'bg-blue-50 text-primary font-semibold' : ''; ?>">
                                        <i class="fa-solid <?php echo $al['icon']; ?> text-secondary text-xs w-4"></i>
                                        <?php echo $al['label']; ?>
                                    </a>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                        <?php elseif (!empty($link['mega'])): ?>
                        <div class="relative group">
                            <a href="products.php" class="<?php echo nav_link_class($link['file'], $current_page); ?> inline-flex items-center gap-1">
                                <?php echo $link['label']; ?>
                                <i class="fa-solid fa-chevron-down text-[10px] opacity-60"></i>
                            </a>
                            <div class="products-mega absolute left-0 top-full pt-2 z-[60]">
                                <div class="bg-white rounded-xl shadow-2xl border border-gray-100 min-w-[720px] overflow-hidden">
                                    <div class="grid divide-x divide-gray-100" id="mega-menu-grid" style="grid-template-columns: 1fr 1fr 1.5fr;">
                                        <!-- Col 1: Categories -->
                                        <div class="py-2 max-h-[380px] overflow-y-auto" id="mega-cats">
                                            <p class="px-4 py-2 text-[10px] font-black uppercase text-gray-400 tracking-wider">Categories</p>
                                            <?php foreach ($menu_tree as $i => $cat): ?>
                                            <a href="products.php?cat=<?php echo $cat['id']; ?>"
                                               class="mega-cat-item mega-col-item block px-4 py-2.5 text-sm text-gray-700 hover:bg-blue-50 hover:text-primary transition-colors <?php echo $i === 0 ? 'active' : ''; ?>"
                                               data-cat-idx="<?php echo $i; ?>">
                                                <i class="fa-solid <?php echo htmlspecialchars($cat['icon']); ?> mr-2 text-secondary text-xs"></i>
                                                <?php echo htmlspecialchars($cat['name']); ?>
                                            </a>
                                            <?php endforeach; ?>
                                            <a href="products.php" class="block px-4 py-2.5 text-xs font-bold text-secondary hover:underline border-t border-gray-100 mt-1">
                                                View All Products →
                                            </a>
                                        </div>
                                        <!-- Col 2: Sub-categories -->
                                        <div class="py-2 max-h-[380px] overflow-y-auto" id="mega-subs"></div>
                                        <!-- Col 3: Image OR Brands (swap) — fixed 4:3 -->
                                        <div class="relative aspect-[4/3] w-full" id="mega-slot">
                                            <div class="absolute inset-0 bg-slate-50" id="mega-preview">
                                                <div class="absolute inset-0 flex flex-col items-center justify-center p-4 text-center text-gray-400 text-xs" id="mega-preview-empty">
                                                    <i class="fa-solid fa-images text-2xl mb-2 opacity-40"></i>
                                                    Hover a category
                                                </div>
                                                <div class="hidden absolute inset-0" id="mega-preview-image-wrap">
                                                    <img id="mega-preview-image" src="" alt="" class="w-full h-full object-cover">
                                                    <div class="absolute inset-0 bg-gradient-to-t from-slate-900/70 via-transparent to-transparent"></div>
                                                    <p id="mega-preview-label" class="absolute bottom-3 left-3 right-3 text-white font-black text-sm uppercase drop-shadow"></p>
                                                </div>
                                            </div>
                                            <div class="hidden absolute inset-0 py-2 overflow-y-auto bg-white" id="mega-brands"></div>
                                        </div>
                                        <!-- Col 4: Brand actions (only when brand hovered) -->
                                        <div class="hidden relative aspect-[4/3] w-full" id="mega-actions">
                                            <div class="absolute inset-0 flex flex-col items-center justify-center gap-3 p-5 bg-gradient-to-br from-primary to-blue-900 text-white" id="mega-preview-brand">
                                                <p id="mega-brand-label" class="font-black text-sm uppercase text-center"></p>
                                                <a id="mega-btn-catalog" href="#" target="_blank" rel="noopener"
                                                   class="hidden w-full text-center bg-white text-primary hover:bg-secondary hover:text-white font-bold text-xs uppercase px-4 py-3 rounded-xl transition-all">
                                                    <i class="fa-solid fa-book-open mr-2"></i> Show Catalog
                                                </a>
                                                <a id="mega-btn-products" href="#"
                                                   class="w-full text-center bg-white/15 hover:bg-white/25 border border-white/30 font-bold text-xs uppercase px-4 py-3 rounded-xl transition-all">
                                                    <i class="fa-solid fa-boxes-stacked mr-2"></i> Show Products
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php else: ?>
                        <a href="<?php echo $link['href']; ?>" class="<?php echo nav_link_class($link['file'], $current_page); ?>">
                            <?php echo $link['label']; ?>
                        </a>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </nav>

                <div class="hidden md:flex items-center space-x-3">
                    <a href="tel:<?php echo htmlspecialchars($site_phone); ?>" class="hidden xl:flex text-primary hover:text-secondary font-semibold text-sm items-center">
                        <i class="fa-solid fa-phone mr-2"></i><?php echo htmlspecialchars($site_phone); ?>
                    </a>
                    <a href="contact.php" class="bg-primary hover:bg-secondary text-white px-4 py-2.5 rounded-lg font-semibold shadow-sm text-sm transition-all">
                        Request a Quote
                    </a>
                    <button type="button" id="mobile-menu-button" class="lg:hidden text-gray-600 hover:text-primary focus:outline-none ml-1" aria-label="Menu">
                        <i class="fa-solid fa-bars text-2xl" id="menu-icon"></i>
                    </button>
                </div>

                <div class="flex md:hidden">
                    <button type="button" id="mobile-menu-button-sm" class="text-gray-600 hover:text-primary focus:outline-none" aria-label="Menu">
                        <i class="fa-solid fa-bars text-2xl" id="menu-icon-sm"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- Mobile Menu -->
        <div class="hidden lg:hidden bg-white border-t border-gray-100 shadow-inner" id="mobile-menu">
            <div class="px-4 pt-3 pb-6 space-y-1 font-medium">
                <?php foreach ($nav_links as $link): ?>
                    <?php if (!empty($link['about'])): ?>
                    <button type="button" id="mobile-about-toggle"
                        class="w-full text-left text-gray-700 hover:bg-gray-50 hover:text-primary px-3 py-2.5 rounded-lg transition-all flex items-center justify-between <?php echo in_array($current_page, $about_pages, true) ? 'text-primary bg-blue-50' : ''; ?>">
                        <span><?php echo $link['label']; ?></span>
                        <i class="fa-solid fa-chevron-down text-xs text-gray-400"></i>
                    </button>
                    <div id="mobile-about-panel" class="hidden bg-gray-50 rounded-xl border border-gray-100 mb-2 overflow-hidden py-1">
                        <?php foreach ($about_links as $al): ?>
                        <a href="<?php echo $al['href']; ?>"
                           class="flex items-center gap-2 px-4 py-2.5 text-sm text-gray-700 hover:bg-white <?php echo ($current_page === $al['href']) ? 'text-primary font-semibold bg-white' : ''; ?>">
                            <i class="fa-solid <?php echo $al['icon']; ?> text-secondary text-xs w-4"></i>
                            <?php echo $al['label']; ?>
                        </a>
                        <?php endforeach; ?>
                    </div>
                    <?php elseif (!empty($link['mega'])): ?>
                    <button type="button" id="mobile-products-toggle"
                        class="w-full text-left text-gray-700 hover:bg-gray-50 hover:text-primary px-3 py-2.5 rounded-lg transition-all flex items-center justify-between <?php echo ($link['file'] === $current_page) ? 'text-primary bg-blue-50' : ''; ?>">
                        <span><?php echo $link['label']; ?></span>
                        <i class="fa-solid fa-chevron-right text-xs text-gray-400"></i>
                    </button>
                    <div id="mobile-products-panel" class="hidden bg-gray-50 rounded-xl border border-gray-100 mb-2 overflow-hidden">
                        <div id="mobile-step-cats" class="p-2 space-y-0.5">
                            <p class="px-3 py-2 text-[10px] font-black uppercase text-gray-400">Select Category</p>
                            <?php foreach ($menu_tree as $cat): ?>
                            <button type="button" class="mobile-cat-btn w-full text-left px-3 py-2.5 text-sm text-gray-700 hover:bg-white rounded-lg flex items-center gap-2"
                                data-cat-id="<?php echo $cat['id']; ?>">
                                <i class="fa-solid <?php echo htmlspecialchars($cat['icon']); ?> text-secondary text-xs"></i>
                                <?php echo htmlspecialchars($cat['name']); ?>
                                <i class="fa-solid fa-chevron-right text-[10px] text-gray-300 ml-auto"></i>
                            </button>
                            <?php endforeach; ?>
                            <a href="products.php" class="block px-3 py-2.5 text-xs font-bold text-secondary">View All Products →</a>
                        </div>
                        <div id="mobile-step-subs" class="hidden p-2 space-y-0.5">
                            <button type="button" id="mobile-back-subs" class="px-3 py-2 text-xs font-bold text-gray-500 hover:text-primary flex items-center gap-1">
                                <i class="fa-solid fa-arrow-left"></i> Back
                            </button>
                            <p class="px-3 py-1 text-[10px] font-black uppercase text-gray-400" id="mobile-subs-title">Sub-categories</p>
                            <div id="mobile-subs-list"></div>
                        </div>
                        <div id="mobile-step-brands" class="hidden p-2 space-y-0.5">
                            <button type="button" id="mobile-back-brands" class="px-3 py-2 text-xs font-bold text-gray-500 hover:text-primary flex items-center gap-1">
                                <i class="fa-solid fa-arrow-left"></i> Back
                            </button>
                            <p class="px-3 py-1 text-[10px] font-black uppercase text-gray-400" id="mobile-brands-title">Brands</p>
                            <div id="mobile-brands-list"></div>
                        </div>
                    </div>
                    <?php else: ?>
                    <a href="<?php echo $link['href']; ?>" class="block text-gray-700 hover:bg-gray-50 hover:text-primary px-3 py-2.5 rounded-lg transition-all <?php echo ($link['file'] === $current_page) ? 'text-primary bg-blue-50' : ''; ?>">
                        <?php echo $link['label']; ?>
                    </a>
                    <?php endif; ?>
                <?php endforeach; ?>
                <div class="pt-4 border-t border-gray-100 space-y-3">
                    <a href="tel:<?php echo htmlspecialchars($site_phone); ?>" class="text-primary font-semibold flex items-center px-3 py-2 text-sm">
                        <i class="fa-solid fa-phone mr-3"></i><?php echo htmlspecialchars($site_phone); ?>
                    </a>
                    <a href="contact.php" class="bg-primary text-white text-center px-5 py-3 rounded-lg font-semibold block text-sm">Request a Quote</a>
                </div>
            </div>
        </div>
    </header>

    <!-- Marquee Text -->
    <?php if (!empty($marquee['text']) && ($marquee['is_active'] ?? 1)): ?>
    <div class="bg-gradient-to-r from-blue-950 via-primary to-blue-950 text-white py-2 overflow-hidden relative z-40 border-b border-blue-800/30">
        <div class="marquee-track flex whitespace-nowrap will-change-transform">
            <span class="text-xs md:text-sm font-semibold tracking-wide px-8 text-sky-100">
                <?php echo htmlspecialchars($marquee['text']); ?>
            </span>
            <span class="text-xs md:text-sm font-semibold tracking-wide px-8 text-sky-100" aria-hidden="true">
                <?php echo htmlspecialchars($marquee['text']); ?>
            </span>
        </div>
    </div>
    <?php endif; ?>

    <script>
        const menuTree = <?php echo $menu_json; ?>;

        /* ── Desktop Mega Menu ── */
        (function() {
            const megaGrid    = document.getElementById('mega-menu-grid');
            const megaSubs    = document.getElementById('mega-subs');
            const megaBrands  = document.getElementById('mega-brands');
            const megaPreview = document.getElementById('mega-preview');
            const megaActions = document.getElementById('mega-actions');
            const catItems    = document.querySelectorAll('.mega-cat-item');
            const prevEmpty   = document.getElementById('mega-preview-empty');
            const prevImgWrap = document.getElementById('mega-preview-image-wrap');
            const prevImg     = document.getElementById('mega-preview-image');
            const prevLabel   = document.getElementById('mega-preview-label');
            const brandLabel  = document.getElementById('mega-brand-label');
            const btnCatalog  = document.getElementById('mega-btn-catalog');
            const btnProducts = document.getElementById('mega-btn-products');
            if (!megaSubs || !menuTree.length) return;

            /** Category/Sub view: Cats | Subs | Image */
            function setImageMode() {
                if (megaGrid) megaGrid.style.gridTemplateColumns = '1fr 1fr 1.5fr';
                if (megaPreview) megaPreview.classList.remove('hidden');
                if (megaBrands) megaBrands.classList.add('hidden');
                if (megaActions) megaActions.classList.add('hidden');
            }

            /** Sub hovered: Cats | Subs | Brands */
            function setBrandsMode() {
                if (megaGrid) megaGrid.style.gridTemplateColumns = '1fr 1fr 1.5fr';
                if (megaPreview) megaPreview.classList.add('hidden');
                if (megaBrands) megaBrands.classList.remove('hidden');
                if (megaActions) megaActions.classList.add('hidden');
            }

            /** Brand hovered: Cats | Subs | Brands | Actions */
            function setActionsMode() {
                if (megaGrid) megaGrid.style.gridTemplateColumns = '1fr 1fr 1.2fr 1.2fr';
                if (megaPreview) megaPreview.classList.add('hidden');
                if (megaBrands) megaBrands.classList.remove('hidden');
                if (megaActions) megaActions.classList.remove('hidden');
            }

            function showCatImage(cat) {
                setImageMode();
                if (!cat || !cat.image_url) {
                    if (prevImgWrap) prevImgWrap.classList.add('hidden');
                    if (prevEmpty) prevEmpty.classList.remove('hidden');
                    return;
                }
                if (prevEmpty) prevEmpty.classList.add('hidden');
                if (prevImgWrap) prevImgWrap.classList.remove('hidden');
                if (prevImg) prevImg.src = cat.image_url;
                if (prevLabel) prevLabel.textContent = cat.name || '';
            }

            function showBrandActions(cat, sub, brand) {
                setActionsMode();
                if (brandLabel) brandLabel.textContent = brand.name;
                if (btnProducts) {
                    btnProducts.href = `products.php?cat=${cat.id}&sub=${sub.id}&comp=${brand.id}`;
                }
                if (btnCatalog) {
                    if (brand.catalog_url) {
                        btnCatalog.classList.remove('hidden');
                        btnCatalog.href = `catalog.php?comp=${brand.id}`;
                    } else {
                        btnCatalog.classList.add('hidden');
                        btnCatalog.href = '#';
                    }
                }
            }

            function renderSubs(catIdx) {
                const cat = menuTree[catIdx];
                if (!cat) return;
                showCatImage(cat);
                let html = '<p class="px-4 py-2 text-[10px] font-black uppercase text-gray-400 tracking-wider">Sub-categories</p>';
                html += `<a href="products.php?cat=${cat.id}" class="block px-4 py-2 text-xs font-bold text-secondary hover:underline">All in ${cat.name}</a>`;
                if (!cat.subcategories || !cat.subcategories.length) {
                    html += '<p class="px-4 py-3 text-xs text-gray-400">No sub-categories</p>';
                } else {
                    cat.subcategories.forEach((sub, i) => {
                        html += `<a href="products.php?cat=${cat.id}&sub=${sub.id}"
                            class="mega-sub-item mega-col-item block px-4 py-2.5 text-sm text-gray-700 hover:bg-blue-50 hover:text-primary transition-colors"
                            data-cat-idx="${catIdx}" data-sub-idx="${i}">${sub.name}</a>`;
                    });
                }
                megaSubs.innerHTML = html;
                megaSubs.querySelectorAll('.mega-sub-item').forEach(el => {
                    el.addEventListener('mouseenter', () => {
                        megaSubs.querySelectorAll('.mega-sub-item').forEach(x => x.classList.remove('active'));
                        el.classList.add('active');
                        renderBrands(catIdx, parseInt(el.dataset.subIdx));
                    });
                });
                // Don't auto-show brands — wait for sub hover (image stays)
                if (megaBrands) megaBrands.innerHTML = '';
            }

            function renderBrands(catIdx, subIdx) {
                const cat = menuTree[catIdx];
                const sub = cat?.subcategories?.[subIdx];
                setBrandsMode();
                let html = '<p class="px-4 py-2 text-[10px] font-black uppercase text-gray-400 tracking-wider">Brands</p>';
                if (!sub) {
                    html += '<p class="px-4 py-3 text-xs text-gray-400">—</p>';
                } else {
                    html += `<a href="products.php?cat=${cat.id}&sub=${sub.id}" class="block px-4 py-2 text-xs font-bold text-secondary hover:underline">All in ${sub.name}</a>`;
                    if (!sub.brands || !sub.brands.length) {
                        html += '<p class="px-4 py-3 text-xs text-gray-400">No brands listed</p>';
                    } else {
                        sub.brands.forEach((b, bi) => {
                            html += `<button type="button"
                                class="mega-brand-item mega-col-item w-full text-left block px-4 py-2.5 text-sm text-gray-700 hover:bg-blue-50 hover:text-primary transition-colors"
                                data-cat-idx="${catIdx}" data-sub-idx="${subIdx}" data-brand-idx="${bi}">${b.name}</button>`;
                        });
                    }
                }
                megaBrands.innerHTML = html;
                megaBrands.querySelectorAll('.mega-brand-item').forEach(el => {
                    el.addEventListener('mouseenter', () => {
                        megaBrands.querySelectorAll('.mega-brand-item').forEach(x => x.classList.remove('active'));
                        el.classList.add('active');
                        const c = menuTree[parseInt(el.dataset.catIdx)];
                        const s = c?.subcategories?.[parseInt(el.dataset.subIdx)];
                        const b = s?.brands?.[parseInt(el.dataset.brandIdx)];
                        if (c && s && b) showBrandActions(c, s, b);
                    });
                });
            }

            catItems.forEach(el => {
                el.addEventListener('mouseenter', () => {
                    catItems.forEach(x => x.classList.remove('active'));
                    el.classList.add('active');
                    renderSubs(parseInt(el.dataset.catIdx));
                });
            });
            renderSubs(0);
        })();

        /* ── Mobile Menu Toggle ── */
        function setupMobileMenu(btnId, iconId) {
            const btn  = document.getElementById(btnId);
            const menu = document.getElementById('mobile-menu');
            const icon = document.getElementById(iconId);
            if (!btn) return;
            btn.addEventListener('click', () => {
                menu.classList.toggle('hidden');
                const open = !menu.classList.contains('hidden');
                const cls = open ? 'fa-solid fa-xmark text-2xl' : 'fa-solid fa-bars text-2xl';
                if (icon) icon.className = cls;
                document.getElementById('menu-icon') && (document.getElementById('menu-icon').className = cls);
                document.getElementById('menu-icon-sm') && (document.getElementById('menu-icon-sm').className = cls);
            });
        }
        setupMobileMenu('mobile-menu-button', 'menu-icon');
        setupMobileMenu('mobile-menu-button-sm', 'menu-icon-sm');

        document.getElementById('mobile-menu')?.querySelectorAll('a').forEach(link => {
            link.addEventListener('click', () => {
                document.getElementById('mobile-menu').classList.add('hidden');
            });
        });

        /* ── Mobile About Panel ── */
        document.getElementById('mobile-about-toggle')?.addEventListener('click', () => {
            document.getElementById('mobile-about-panel')?.classList.toggle('hidden');
        });

        /* ── Mobile Products Panel ── */
        (function() {
            const toggle   = document.getElementById('mobile-products-toggle');
            const panel    = document.getElementById('mobile-products-panel');
            const stepCats = document.getElementById('mobile-step-cats');
            const stepSubs = document.getElementById('mobile-step-subs');
            const stepBrands = document.getElementById('mobile-step-brands');
            const subsList = document.getElementById('mobile-subs-list');
            const brandsList = document.getElementById('mobile-brands-list');
            if (!toggle || !panel) return;

            let currentCat = null, currentSub = null;

            function showStep(step) {
                stepCats.classList.add('hidden');
                stepSubs.classList.add('hidden');
                stepBrands.classList.add('hidden');
                step.classList.remove('hidden');
            }

            toggle.addEventListener('click', () => {
                panel.classList.toggle('hidden');
                if (!panel.classList.contains('hidden')) showStep(stepCats);
            });

            document.querySelectorAll('.mobile-cat-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    const catId = parseInt(btn.dataset.catId);
                    currentCat = menuTree.find(c => c.id === catId);
                    if (!currentCat) return;
                    document.getElementById('mobile-subs-title').textContent = currentCat.name;
                    let html = `<a href="products.php?cat=${currentCat.id}" class="block px-3 py-2.5 text-xs font-bold text-secondary rounded-lg">All in ${currentCat.name}</a>`;
                    if (currentCat.subcategories && currentCat.subcategories.length) {
                        currentCat.subcategories.forEach(sub => {
                            html += `<button type="button" class="mobile-sub-btn w-full text-left px-3 py-2.5 text-sm text-gray-700 hover:bg-white rounded-lg flex items-center justify-between"
                                data-sub-id="${sub.id}">
                                ${sub.name}
                                <i class="fa-solid fa-chevron-right text-[10px] text-gray-300"></i>
                            </button>`;
                        });
                    } else {
                        html += '<p class="px-3 py-2 text-xs text-gray-400">No sub-categories</p>';
                    }
                    subsList.innerHTML = html;
                    subsList.querySelectorAll('.mobile-sub-btn').forEach(sbtn => {
                        sbtn.addEventListener('click', () => {
                            const subId = parseInt(sbtn.dataset.subId);
                            currentSub = currentCat.subcategories.find(s => s.id === subId);
                            if (!currentSub) return;
                            document.getElementById('mobile-brands-title').textContent = currentSub.name;
                            let bhtml = `<a href="products.php?cat=${currentCat.id}&sub=${currentSub.id}" class="block px-3 py-2.5 text-xs font-bold text-secondary rounded-lg">All in ${currentSub.name}</a>`;
                            if (currentSub.brands && currentSub.brands.length) {
                                currentSub.brands.forEach(b => {
                                    bhtml += `<div class="px-2 py-2 border-b border-gray-100 last:border-0">
                                        <p class="px-1 text-sm font-semibold text-gray-800 mb-1.5">${b.name}</p>
                                        <div class="flex gap-2">
                                            ${b.catalog_url ? `<a href="catalog.php?comp=${b.id}" target="_blank" rel="noopener"
                                                class="flex-1 text-center text-[10px] font-bold uppercase bg-primary text-white px-2 py-2 rounded-lg">Catalog</a>` : ''}
                                            <a href="products.php?cat=${currentCat.id}&sub=${currentSub.id}&comp=${b.id}"
                                                class="flex-1 text-center text-[10px] font-bold uppercase bg-secondary text-white px-2 py-2 rounded-lg">Products</a>
                                        </div>
                                    </div>`;
                                });
                            } else {
                                bhtml += '<p class="px-3 py-2 text-xs text-gray-400">No brands listed</p>';
                            }
                            brandsList.innerHTML = bhtml;
                            showStep(stepBrands);
                        });
                    });
                    showStep(stepSubs);
                });
            });

            document.getElementById('mobile-back-subs')?.addEventListener('click', () => showStep(stepCats));
            document.getElementById('mobile-back-brands')?.addEventListener('click', () => showStep(stepSubs));
        })();

        /* ═══════════════════════════════════════════════
           GLOBAL SCROLL EFFECTS (all pages via header)
           Fade Up | Stagger | Count-Up | Smooth Scroll
           ═══════════════════════════════════════════════ */
        document.addEventListener('DOMContentLoaded', function () {
            const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

            /* Smooth Scroll — # anchors */
            document.querySelectorAll('a[href^="#"]').forEach(function (a) {
                a.addEventListener('click', function (e) {
                    const id = a.getAttribute('href');
                    if (!id || id === '#') return;
                    const target = document.querySelector(id);
                    if (!target) return;
                    e.preventDefault();
                    target.scrollIntoView({ behavior: reduceMotion ? 'auto' : 'smooth', block: 'start' });
                });
            });

            if (reduceMotion) return;

            /* Fade Up — all main sections */
            document.querySelectorAll('body > section, body > div.bg-primary').forEach(function (el) {
                if (el.closest('header')) return;
                el.classList.add('reveal-fade');
            });

            /* Stagger — cards inside section grids */
            document.querySelectorAll('section .grid').forEach(function (grid) {
                const kids = Array.from(grid.children).filter(function (c) {
                    return c.matches('div, a, article');
                });
                if (kids.length < 2) return;
                kids.forEach(function (card, i) {
                    card.classList.add('reveal-stagger');
                    card.style.transitionDelay = (i * 0.08) + 's';
                });
            });

            const observer = new IntersectionObserver(function (entries) {
                entries.forEach(function (entry) {
                    if (!entry.isIntersecting) return;
                    entry.target.classList.add('is-visible');
                    observer.unobserve(entry.target);
                });
            }, { threshold: 0.12, rootMargin: '0px 0px -40px 0px' });

            document.querySelectorAll('.reveal-fade, .reveal-stagger').forEach(function (el) {
                observer.observe(el);
            });

            /* Count-Up — home stats (20+ Years, 2,700+, etc.) */
            function animateCount(el, target, original, duration) {
                const start = performance.now();
                const plusMatch = original.match(/^([\d,.]+)\+(.*)$/);
                const spaceMatch = original.match(/^([\d,.]+)\s+(.+)$/);
                let endNum, prefixMode, rest;

                if (plusMatch) {
                    endNum = parseFloat(plusMatch[1].replace(/,/g, ''));
                    prefixMode = 'plus';
                    rest = plusMatch[2] || '';
                } else if (spaceMatch) {
                    endNum = parseFloat(spaceMatch[1].replace(/,/g, ''));
                    prefixMode = 'space';
                    rest = spaceMatch[2];
                } else {
                    const m = original.match(/^([\d,.]+)/);
                    if (!m) return;
                    endNum = parseFloat(m[1].replace(/,/g, ''));
                    prefixMode = 'plain';
                    rest = '';
                }
                if (isNaN(endNum) || endNum <= 0) return;
                if ((original.match(/\//g) || []).length >= 2) return;

                const useComma = original.indexOf(',') !== -1;
                const isFloat = endNum % 1 !== 0;

                function fmt(n) {
                    let s = isFloat ? n.toFixed(1) : Math.round(n).toString();
                    if (useComma) s = s.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                    if (prefixMode === 'plus') return s + '+' + rest;
                    if (prefixMode === 'space') return s + ' ' + rest;
                    return s;
                }

                function frame(now) {
                    const t = Math.min(1, (now - start) / duration);
                    const eased = 1 - Math.pow(1 - t, 3);
                    el.textContent = fmt(endNum * eased);
                    if (t < 1) requestAnimationFrame(frame);
                    else el.textContent = original;
                }
                requestAnimationFrame(frame);
            }

            const countObserver = new IntersectionObserver(function (entries) {
                entries.forEach(function (entry) {
                    if (!entry.isIntersecting) return;
                    const el = entry.target;
                    if (el.dataset.countDone) return;
                    const original = el.textContent.trim();
                    if (!/^[\d,.]+/.test(original)) return;
                    if ((original.match(/\//g) || []).length >= 2) return;
                    el.dataset.countDone = '1';
                    animateCount(el, 0, original, 1500);
                    countObserver.unobserve(el);
                });
            }, { threshold: 0.35 });

            document.querySelectorAll('.bg-primary .font-black.text-secondary, .bg-primary span.font-black').forEach(function (el) {
                countObserver.observe(el);
            });
        });
    </script>
