<?php
// navbar.php - Persistent Navigation Component
// Assumes session_start() has been called and user authentication is set

$is_logged_in = isset($_SESSION['user_id']);
$is_admin = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin';
$user_email = $_SESSION['user_email'] ?? 'Guest';
$user_name = explode('@', $user_email)[0];
$cart_count = 0;
if ($is_logged_in && isset($_SESSION['cart'])) {
    if (!empty($_SESSION['cart']['package']))
        $cart_count++;
    if (!empty($_SESSION['cart']['topup']))
        $cart_count++;
}

// Active page detection
$_nav_current = basename($_SERVER['PHP_SELF'] ?? '');
function nav_active($pages) {
    global $_nav_current;
    $list = is_array($pages) ? $pages : [$pages];
    return in_array($_nav_current, $list)
        ? 'text-blue-900 font-bold border-b-2 border-blue-600 pb-0.5'
        : 'text-slate-600';
}
function nav_active_mobile($pages) {
    global $_nav_current;
    $list = is_array($pages) ? $pages : [$pages];
    return in_array($_nav_current, $list) ? 'bg-blue-50 text-blue-900 font-bold' : 'text-slate-700';
}
?>

<style>
    .nav-search-input {
        width: 140px;
        transition: width 0.3s ease;
    }

    .nav-search-input:focus {
        width: 220px;
    }

    #navSearchResults {
        position: absolute;
        top: calc(100% + 8px);
        left: 0;
        min-width: 360px;
        background: #fff;
        border-radius: 14px;
        box-shadow: 0 16px 48px rgba(15, 23, 42, 0.16);
        border: 1px solid #e2e8f0;
        max-height: 440px;
        overflow-y: auto;
        z-index: 9999;
        scrollbar-width: thin;
    }
    #navSearchResults .sr-group-label {
        font-size: 0.6rem;
        font-weight: 800;
        letter-spacing: 0.1em;
        color: #94a3b8;
        text-transform: uppercase;
        padding: 10px 16px 4px;
    }
    #navSearchResults a.sr-item {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 8px 14px;
        transition: background 0.15s;
        text-decoration: none;
        border-bottom: 1px solid #f8fafc;
    }
    #navSearchResults a.sr-item:last-of-type { border-bottom: none; }
    #navSearchResults a.sr-item:hover { background: #eff6ff; }
    #navSearchResults .sr-icon-wrap {
        width: 32px; height: 32px;
        border-radius: 8px;
        display: flex; align-items: center; justify-content: center;
        flex-shrink: 0;
        font-size: 0.75rem;
    }
    #navSearchResults .sr-badge {
        font-size: 0.6rem;
        font-weight: 700;
        padding: 1px 6px;
        border-radius: 999px;
        white-space: nowrap;
        flex-shrink: 0;
    }
</style>

<nav class="sticky top-0 z-50 bg-white/90 backdrop-blur-md border-b border-slate-200 shadow-sm">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between items-center h-16">
            <!-- Logo/Brand -->
            <div class="flex items-center">
                <a href="/index.php" class="flex items-center gap-2">
                    <img src="/images/saniBook%20logo.png" alt="SaniBook Logo" class="h-10 w-auto rounded-lg">
                    <span class="text-xl font-bold text-blue-900">SaniBook</span>
                </a>
            </div>

            <!-- Desktop Navigation -->
            <div class="hidden md:flex items-center gap-3">

                <!-- Home -->
                <a href="/index.php"
                    class="flex items-center gap-1.5 text-sm font-medium <?= nav_active('index.php') ?> hover:text-blue-700 transition-colors whitespace-nowrap">
                    <i class="fa-solid fa-house text-blue-500 text-xs"></i>Home
                </a>

                <!-- Explore Dropdown (now includes Service Chain & Enabling Pillars) -->
                <div class="relative group">
                    <button
                        class="flex items-center gap-1 text-sm font-medium <?= nav_active(['service-chain.php','enabling-pillars.php','submitted.php','sanitation-reality.php','thematic-repositories.php','explore.php','pricing.php']) ?> hover:text-blue-900 transition-colors whitespace-nowrap">
                        <i class="fa-solid fa-compass text-blue-500 text-xs"></i>
                        <span>Explore</span>
                        <i class="fa-solid fa-chevron-down text-xs"></i>
                    </button>
                    <div
                        class="absolute left-0 mt-2 w-60 bg-white rounded-lg shadow-lg border border-slate-200 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200">
                        <a href="/service-chain.php"
                            class="block px-4 py-3 text-slate-700 hover:bg-teal-50 hover:text-teal-900 transition-colors rounded-t-lg">
                            <i class="fa-solid fa-link mr-2 text-teal-500"></i>Service Chain
                        </a>
                        <a href="/enabling-pillars.php"
                            class="block px-4 py-3 text-slate-700 hover:bg-orange-50 hover:text-orange-900 transition-colors">
                            <i class="fa-solid fa-columns mr-2 text-orange-500"></i>Enabling Pillars
                        </a>
                        <div class="border-t border-slate-100 my-0.5"></div>
                        <a href="/submitted.php"
                            class="block px-4 py-3 text-slate-700 hover:bg-blue-50 hover:text-blue-900 transition-colors">
                            <i class="fa-solid fa-file-lines mr-2 text-slate-400"></i>Submitted Works
                        </a>
                        <a href="/sanitation-reality.php"
                            class="block px-4 py-3 text-slate-700 hover:bg-blue-50 hover:text-blue-900 transition-colors">
                            <i class="fa-solid fa-chart-bar mr-2 text-slate-400"></i>Sanitation Status
                        </a>
                        <a href="/thematic-repositories.php"
                            class="block px-4 py-3 text-slate-700 hover:bg-blue-50 hover:text-blue-900 transition-colors">
                            <i class="fa-solid fa-shield mr-2 text-slate-400"></i>Barriers
                        </a>
                        <a href="/explore.php"
                            class="block px-4 py-3 text-slate-700 hover:bg-blue-50 hover:text-blue-900 transition-colors">
                            <i class="fa-solid fa-users mr-2 text-blue-500"></i>Public Directory
                        </a>
                        <div class="border-t border-slate-100 my-0.5"></div>
                        <a href="/pricing.php"
                            class="block px-4 py-3 text-slate-700 hover:bg-blue-50 hover:text-blue-900 transition-colors rounded-b-lg">
                            <i class="fa-solid fa-tag mr-2 text-blue-400"></i>Pricing
                        </a>
                    </div>
                </div>

                <!-- About Dropdown -->
                <div class="relative group">
                    <button
                        class="flex items-center gap-1 text-sm font-medium <?= nav_active(['why-sanibook.php','grand-unveiling.php']) ?> hover:text-blue-900 transition-colors whitespace-nowrap">
                        <i class="fa-solid fa-circle-info text-slate-400 text-xs"></i>
                        <span>About</span>
                        <i class="fa-solid fa-chevron-down text-xs"></i>
                    </button>
                    <div
                        class="absolute left-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-slate-200 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200">
                        <a href="/why-sanibook.php"
                            class="block px-4 py-3 text-slate-700 hover:bg-blue-50 hover:text-blue-900 transition-colors rounded-t-lg">
                            Why SaniBook?
                        </a>
                        <a href="/grand-unveiling.php"
                            class="block px-4 py-3 text-slate-700 hover:bg-blue-50 hover:text-blue-900 transition-colors rounded-b-lg">
                            Grand Unveiling
                        </a>
                    </div>
                </div>

                <!-- AJAX Search Bar -->
                <div class="relative nav-search-form">
                    <input type="text" id="navSearch" placeholder="Search..." autocomplete="off"
                        class="nav-search-input pl-8 pr-3 py-1.5 text-sm bg-slate-100 border border-slate-200 rounded-full focus:outline-none focus:ring-2 focus:ring-blue-400 focus:bg-white transition-all">
                    <i class="fa-solid fa-search absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
                    <div id="navSearchResults" class="hidden"></div>
                </div>

                <?php if ($is_logged_in): ?>
                    <!-- Cart Icon -->
                    <div class="relative" id="cart-wrapper">
                        <button id="cart-toggle-btn" class="relative p-2 rounded-lg hover:bg-slate-100 transition-colors">
                            <i class="fa-solid fa-shopping-cart text-slate-600 text-lg"></i>
                            <span id="cart-badge"
                                class="absolute -top-1 -right-1 w-5 h-5 bg-red-500 text-white text-xs font-bold rounded-full flex items-center justify-center <?= $cart_count > 0 ? '' : 'hidden' ?>"><?= $cart_count ?></span>
                        </button>
                        <!-- Cart Dropdown -->
                        <div id="cart-dropdown"
                            class="hidden absolute right-0 mt-2 w-80 bg-white rounded-xl shadow-2xl border border-slate-200 z-50">
                            <div class="p-4 border-b border-slate-100">
                                <h4 class="font-bold text-slate-800"><i
                                        class="fa-solid fa-shopping-cart mr-2 text-blue-600"></i>Your Cart</h4>
                            </div>
                            <div id="cart-items" class="p-4 space-y-3 max-h-64 overflow-y-auto">
                                <p class="text-sm text-slate-500 text-center py-4">Cart is empty</p>
                            </div>
                            <div id="cart-footer" class="hidden p-4 border-t border-slate-100 bg-slate-50 rounded-b-xl">
                                <div class="flex justify-between items-center mb-3">
                                    <span class="font-bold text-slate-700">Total</span>
                                    <span id="cart-total" class="font-extrabold text-lg text-green-700">KES 0</span>
                                </div>
                                <a href="/cart.php"
                                    class="block w-full text-center py-2.5 bg-blue-600 text-white rounded-lg font-bold hover:bg-blue-700 transition-colors text-sm">
                                    <i class="fa-solid fa-credit-card mr-1"></i> Checkout
                                </a>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <?php if ($is_logged_in): ?>
                    <!-- User Menu Dropdown -->
                    <div class="relative group">
                        <button class="flex items-center gap-2 px-4 py-2 rounded-lg hover:bg-slate-100 transition-colors">
                            <i class="fa-solid fa-user-circle text-blue-900"></i>
                            <span class="font-medium text-slate-700">
                                <?php echo htmlspecialchars($user_name); ?>
                            </span>
                            <i class="fa-solid fa-chevron-down text-xs text-slate-500"></i>
                        </button>
                        <div
                            class="absolute right-0 mt-2 w-52 bg-white rounded-lg shadow-lg border border-slate-200 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200">
                            <a href="/user_dashboard.php"
                                class="block px-4 py-3 text-slate-700 hover:bg-blue-50 hover:text-blue-900 transition-colors rounded-t-lg">
                                <i class="fa-solid fa-dashboard mr-2"></i>Dashboard
                            </a>
                            <a href="/profile.php"
                                class="block px-4 py-3 text-slate-700 hover:bg-blue-50 hover:text-blue-900 transition-colors">
                                <i class="fa-solid fa-user mr-2"></i>My Profile
                            </a>
                            <a href="/pricing.php"
                                class="block px-4 py-3 text-slate-700 hover:bg-blue-50 hover:text-blue-900 transition-colors">
                                <i class="fa-solid fa-tag mr-2"></i>Pricing
                            </a>
                            <div class="border-t border-slate-200"></div>
                            <a href="/logout.php"
                                class="block px-4 py-3 text-red-600 hover:bg-red-50 transition-colors rounded-b-lg">
                                <i class="fa-solid fa-right-from-bracket mr-2"></i>Logout
                            </a>
                        </div>
                    </div>

                    <?php if ($is_admin): ?>
                        <!-- Admin Menu Dropdown -->
                        <div class="relative group">
                            <button
                                class="flex items-center gap-2 px-4 py-2 rounded-lg bg-blue-900 text-white hover:bg-blue-800 transition-colors">
                                <i class="fa-solid fa-shield-halved"></i>
                                <span class="font-medium">Admin</span>
                                <i class="fa-solid fa-chevron-down text-xs"></i>
                            </button>
                            <div
                                class="absolute right-0 mt-2 w-56 bg-white rounded-lg shadow-lg border border-slate-200 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200">
                                <a href="/admin/index.php"
                                    class="block px-4 py-3 text-slate-700 hover:bg-blue-50 hover:text-blue-900 transition-colors rounded-t-lg">
                                    <i class="fa-solid fa-file-invoice mr-2"></i>Content Moderation
                                </a>
                                <a href="/admin/submissions.php"
                                    class="block px-4 py-3 text-slate-700 hover:bg-blue-50 hover:text-blue-900 transition-colors">
                                    <i class="fa-solid fa-inbox mr-2"></i>All Submissions
                                </a>
                                <a href="/admin/users.php"
                                    class="block px-4 py-3 text-slate-700 hover:bg-blue-50 hover:text-blue-900 transition-colors rounded-b-lg">
                                    <i class="fa-solid fa-users mr-2"></i>User Management
                                </a>
                            </div>
                        </div>
                    <?php endif; ?>
                <?php else: ?>
                    <!-- Guest CTAs -->
                    <button onclick="openAuthModal('login')"
                        class="px-4 py-2 bg-blue-900 text-white rounded-lg hover:bg-blue-800 transition-colors font-medium text-sm">
                        Login
                    </button>
                    <a href="/signup.php"
                        class="text-xs text-slate-500 hover:text-blue-700 underline underline-offset-2 ml-1">New here? Register</a>
                <?php endif; ?>
            </div>

            <!-- Mobile Menu Button -->
            <div class="md:hidden flex items-center gap-2">
                <?php if ($is_logged_in): ?>
                    <a href="/cart.php" class="relative p-2">
                        <i class="fa-solid fa-shopping-cart text-slate-600"></i>
                        <span id="cart-badge-mobile"
                            class="absolute -top-1 -right-1 w-5 h-5 bg-red-500 text-white text-xs font-bold rounded-full flex items-center justify-center <?= $cart_count > 0 ? '' : 'hidden' ?>"><?= $cart_count ?></span>
                    </a>
                <?php endif; ?>
                <button id="mobile-menu-btn" class="p-2 rounded-lg hover:bg-slate-100 transition-colors">
                    <i class="fa-solid fa-bars text-xl text-slate-700"></i>
                </button>
            </div>
        </div>
    </div>

    <!-- Mobile Menu -->
    <div id="mobile-menu" class="hidden md:hidden bg-white border-t border-slate-200">
        <div class="px-4 py-4 space-y-2">
            <!-- Mobile Search -->
            <form action="/search.php" method="GET" class="mb-3">
                <div class="relative">
                    <input type="text" name="q" placeholder="Search SaniBook..." autocomplete="off"
                        class="w-full pl-9 pr-3 py-2.5 text-sm bg-slate-100 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400 focus:bg-white transition-all">
                    <i class="fa-solid fa-search absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-sm"></i>
                </div>
            </form>

            <!-- Mobile Site Navigation -->
            <a href="/index.php"
                class="block px-4 py-3 <?= nav_active_mobile('index.php') ?> hover:bg-blue-50 rounded-lg transition-colors font-medium">Home</a>

            <div class="border-t border-slate-100 my-1"></div>
            <p class="px-4 py-2 text-[10px] font-bold text-slate-400 uppercase tracking-widest">Explore</p>
            <a href="/service-chain.php"
                class="block px-4 py-3 text-slate-700 hover:bg-teal-50 rounded-lg transition-colors">
                <i class="fa-solid fa-link mr-2 text-teal-500 text-xs"></i>Service Chain</a>
            <a href="/enabling-pillars.php"
                class="block px-4 py-3 text-slate-700 hover:bg-orange-50 rounded-lg transition-colors">
                <i class="fa-solid fa-columns mr-2 text-orange-500 text-xs"></i>Enabling Pillars</a>
            <a href="/submitted.php"
                class="block px-4 py-3 text-slate-700 hover:bg-blue-50 rounded-lg transition-colors">Submitted Works</a>
            <a href="/sanitation-reality.php"
                class="block px-4 py-3 text-slate-700 hover:bg-blue-50 rounded-lg transition-colors">Sanitation
                Reality</a>
            <a href="/thematic-repositories.php"
                class="block px-4 py-3 text-slate-700 hover:bg-blue-50 rounded-lg transition-colors">Barriers</a>
            <a href="/explore.php" class="block px-4 py-3 text-slate-700 hover:bg-blue-50 rounded-lg transition-colors">
                <i class="fa-solid fa-users w-5 mr-2 text-blue-500"></i>Public Directory</a>

            <div class="border-t border-slate-100 my-1"></div>
            <p class="px-4 py-2 text-[10px] font-bold text-slate-400 uppercase tracking-widest">About</p>
            <a href="/why-sanibook.php"
                class="block px-4 py-3 text-slate-700 hover:bg-blue-50 rounded-lg transition-colors">Why SaniBook?</a>
            <a href="/grand-unveiling.php"
                class="block px-4 py-3 text-slate-700 hover:bg-blue-50 rounded-lg transition-colors">Grand Unveiling</a>

            <div class="border-t border-slate-200 my-2 pt-2"></div>

            <?php if ($is_logged_in): ?>
                <div class="px-4 py-2 bg-slate-50 rounded-lg mb-2">
                    <p class="text-sm text-slate-500">Signed in as</p>
                    <p class="font-medium text-slate-900"><?php echo htmlspecialchars($user_email); ?></p>
                </div>
                <a href="/user_dashboard.php"
                    class="block px-4 py-3 text-slate-700 hover:bg-blue-50 rounded-lg transition-colors">
                    <i class="fa-solid fa-dashboard mr-2"></i>Dashboard
                </a>
                <a href="/profile.php" class="block px-4 py-3 text-slate-700 hover:bg-blue-50 rounded-lg transition-colors">
                    <i class="fa-solid fa-user mr-2"></i>My Profile
                </a>
                <a href="/submit-data.php"
                    class="block px-4 py-3 text-slate-700 hover:bg-blue-50 rounded-lg transition-colors font-bold text-blue-800">
                    <i class="fa-solid fa-pen mr-2"></i>Submit Data
                </a>

                <?php if ($is_admin): ?>
                    <div class="mt-2 pt-2 border-t border-slate-100">
                        <p class="px-4 py-1 text-[10px] font-bold text-slate-400 uppercase tracking-widest">Admin Control</p>
                        <a href="/admin/index.php"
                            class="block px-4 py-3 text-slate-700 hover:bg-blue-50 rounded-lg transition-colors">
                            <i class="fa-solid fa-shield-halved mr-2"></i>Admin Dashboard
                        </a>
                    </div>
                <?php endif; ?>

                <a href="/logout.php"
                    class="block px-4 py-3 text-red-600 hover:bg-red-50 rounded-lg transition-colors mt-2">
                    <i class="fa-solid fa-right-from-bracket mr-2"></i>Logout
                </a>
            <?php else: ?>
                <a href="/pricing.php"
                    class="block px-4 py-3 text-slate-700 hover:bg-blue-50 rounded-lg transition-colors font-medium">
                    <i class="fa-solid fa-tag mr-2 text-blue-500"></i>Pricing
                </a>
                <button onclick="openAuthModal('login')"
                    class="w-full mt-2 px-4 py-3 bg-blue-900 text-white rounded-lg hover:bg-blue-800 transition-colors font-bold text-center">
                    Login
                </button>
                <p class="text-center text-xs text-slate-500 mt-2">New here? <a href="/signup.php" class="text-blue-700 underline">Create an account</a></p>
            <?php endif; ?>
        </div>
    </div>
</nav>

<script>
    // Mobile menu toggle
    document.getElementById('mobile-menu-btn')?.addEventListener('click', function () {
        const menu = document.getElementById('mobile-menu');
        menu.classList.toggle('hidden');
    });

    // --- Navbar AJAX Search ---
    (function () {
        const navInput = document.getElementById('navSearch');
        const navResults = document.getElementById('navSearchResults');
        if (!navInput || !navResults) return;

        let navTimeout;

        // Type labels for group headings
        const typeLabels = {
            submission: 'Submissions',
            user: 'Organizations',
            category: 'Categories',
            content: 'Content',
            page: 'Pages',
            county: 'Counties'
        };
        const typeOrder = ['submission', 'user', 'category', 'content', 'page', 'county'];

        navInput.addEventListener('input', function () {
            clearTimeout(navTimeout);
            const q = this.value.trim();
            if (q.length < 2) { navResults.classList.add('hidden'); navResults.innerHTML = ''; return; }
            navTimeout = setTimeout(() => {
                // Show loading shimmer
                navResults.innerHTML = `<div style="padding:12px 16px;display:flex;flex-direction:column;gap:10px">
                    ${[1,2,3].map(() => `<div style="display:flex;align-items:center;gap:10px">
                        <div style="width:32px;height:32px;border-radius:8px;background:#f1f5f9;flex-shrink:0"></div>
                        <div style="flex:1">
                            <div style="height:10px;border-radius:4px;background:#f1f5f9;width:60%;margin-bottom:5px"></div>
                            <div style="height:8px;border-radius:4px;background:#f8fafc;width:40%"></div>
                        </div></div>`).join('')}
                </div>`;
                navResults.classList.remove('hidden');
                fetch(`/api/search.php?q=${encodeURIComponent(q)}`)
                    .then(r => r.json())
                    .then(data => {
                        const items = data.results || [];
                        if (items.length === 0) {
                            navResults.innerHTML = `<div style="padding:20px 16px;text-align:center">
                                <i class="fa-regular fa-face-frown" style="font-size:1.4rem;color:#cbd5e1;margin-bottom:6px;display:block"></i>
                                <p style="font-size:0.8rem;color:#94a3b8">No results for <strong style="color:#475569">&ldquo;${q}&rdquo;</strong></p>
                                <a href="/search.php?q=${encodeURIComponent(q)}" style="display:inline-block;margin-top:8px;font-size:0.75rem;color:#2563eb;font-weight:600">Try full search</a>
                            </div>`;
                            navResults.classList.remove('hidden');
                            return;
                        }

                        // Group by type
                        const grouped = {};
                        items.forEach(item => {
                            if (!grouped[item.type]) grouped[item.type] = [];
                            grouped[item.type].push(item);
                        });

                        // Icon bg/color per type
                        const typeMeta = {
                            submission: { bg: '#f0fdf4', fg: '#0d9488' },
                            user:       { bg: '#eff6ff', fg: '#2563eb' },
                            category:   { bg: '#faf5ff', fg: '#7c3aed' },
                            content:    { bg: '#eef2ff', fg: '#4338ca' },
                            page:       { bg: '#f8fafc', fg: '#475569' },
                            county:     { bg: '#f0fdf4', fg: '#16a34a' },
                        };
                        // Badge colors
                        const badgeMeta = {
                            submission: { bg: '#ccfbf1', txt: '#0f766e', lbl: 'Data' },
                            user:       { bg: '#dbeafe', txt: '#1d4ed8', lbl: 'Org'  },
                            category:   { bg: '#ede9fe', txt: '#5b21b6', lbl: 'Topic'},
                            content:    { bg: '#e0e7ff', txt: '#3730a3', lbl: 'Article'},
                            page:       { bg: '#f1f5f9', txt: '#475569', lbl: 'Page' },
                            county:     { bg: '#dcfce7', txt: '#166534', lbl: 'County'},
                        };

                        let html = '';
                        typeOrder.forEach(type => {
                            if (!grouped[type]) return;
                            html += `<div class="sr-group-label">${typeLabels[type] || type}</div>`;
                            grouped[type].forEach(item => {
                                const meta  = typeMeta[item.type]  || { bg: '#f8fafc', fg: '#64748b' };
                                const badge = badgeMeta[item.type] || { bg: '#f1f5f9', txt: '#475569', lbl: item.type };
                                html += `<a href="${item.url}" class="sr-item">
                                    <span class="sr-icon-wrap" style="background:${meta.bg}">
                                        <i class="fa-solid ${item.icon}" style="color:${meta.fg}"></i>
                                    </span>
                                    <div class="min-w-0 flex-1">
                                        <p style="font-size:0.825rem;font-weight:600;color:#1e293b;line-height:1.2;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:220px">${item.title}</p>
                                        ${item.sub ? `<p style="font-size:0.7rem;color:#94a3b8;margin-top:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:200px">${item.sub}</p>` : ''}
                                    </div>
                                    <span class="sr-badge" style="background:${badge.bg};color:${badge.txt}">${badge.lbl}</span>
                                </a>`;
                            });
                        });

                        // "View all" footer
                        html += `<a href="/search.php?q=${encodeURIComponent(q)}" style="display:flex;align-items:center;justify-content:center;gap:6px;padding:10px 16px;border-top:1px solid #e2e8f0;font-size:0.75rem;font-weight:700;color:#2563eb;text-decoration:none;border-radius:0 0 14px 14px;background:#f8fafc;transition:background .15s" onmouseover="this.style.background='#eff6ff'" onmouseout="this.style.background='#f8fafc'">
                            <i class="fa-solid fa-magnifying-glass" style="font-size:0.65rem"></i> View all results for &ldquo;${q}&rdquo;
                        </a>`;

                        navResults.innerHTML = html;
                        navResults.classList.remove('hidden');
                    })
                    .catch(() => { navResults.classList.add('hidden'); });
            }, 300);
        });

        // Submit on Enter — go to full search page
        navInput.addEventListener('keydown', function (e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                const q = this.value.trim();
                if (q.length >= 2) window.location.href = '/search.php?q=' + encodeURIComponent(q);
            }
        });

        document.addEventListener('click', function (e) {
            if (!navInput.contains(e.target) && !navResults.contains(e.target)) {
                navResults.classList.add('hidden');
            }
        });
    })();

    // --- Cart dropdown toggle ---
    (function () {
        const btn = document.getElementById('cart-toggle-btn');
        const dd = document.getElementById('cart-dropdown');
        if (!btn || !dd) return;

        btn.addEventListener('click', function (e) {
            e.stopPropagation();
            dd.classList.toggle('hidden');
            if (!dd.classList.contains('hidden')) refreshCartDropdown();
        });
        document.addEventListener('click', function (e) {
            if (!dd.contains(e.target) && !btn.contains(e.target)) dd.classList.add('hidden');
        });
    })();

    // --- Cart helpers (global so pricing.php can call them) ---
    function refreshCartDropdown() {
        fetch('/cart-api.php?action=get_cart')
            .then(r => r.json())
            .then(d => {
                if (!d.ok) return;
                updateCartBadge(d.count);
                renderCartItems(d.cart, d.total);
            });
    }

    function updateCartBadge(count) {
        document.querySelectorAll('#cart-badge, #cart-badge-mobile').forEach(b => {
            b.textContent = count;
            b.classList.toggle('hidden', count < 1);
        });
    }

    function renderCartItems(cart, total) {
        const container = document.getElementById('cart-items');
        const footer = document.getElementById('cart-footer');
        if (!container) return;

        let html = '';
        let hasItems = false;

        if (cart.package) {
            hasItems = true;
            const label = cart.package.upgrade_from
                ? `Upgrade: ${cart.package.upgrade_from} → ${cart.package.name}`
                : cart.package.name;
            html += `<div class="flex justify-between items-start bg-blue-50 rounded-lg p-3">
                <div>
                    <div class="font-bold text-sm text-blue-900">${label}</div>
                    <div class="text-xs text-slate-500">${Number(cart.package.adjusted_tokens).toLocaleString()} tokens</div>
                </div>
                <div class="text-right">
                    <div class="font-bold text-sm text-blue-900">KES ${Number(cart.package.adjusted_price).toLocaleString()}</div>
                    <button onclick="removeCartItem('package')" class="text-xs text-red-500 hover:underline">Remove</button>
                </div>
            </div>`;
        }

        if (cart.topup) {
            hasItems = true;
            html += `<div class="flex justify-between items-start bg-green-50 rounded-lg p-3">
                <div>
                    <div class="font-bold text-sm text-green-900">Token Top-Up</div>
                    <div class="text-xs text-slate-500">${Number(cart.topup.tokens).toLocaleString()} tokens</div>
                </div>
                <div class="text-right">
                    <div class="font-bold text-sm text-green-900">KES ${Number(cart.topup.price).toLocaleString()}</div>
                    <button onclick="removeCartItem('topup')" class="text-xs text-red-500 hover:underline">Remove</button>
                </div>
            </div>`;
        }

        if (!hasItems) {
            html = '<p class="text-sm text-slate-500 text-center py-4">Cart is empty</p>';
        }

        container.innerHTML = html;
        if (footer) {
            footer.classList.toggle('hidden', !hasItems);
            document.getElementById('cart-total').textContent = 'KES ' + Number(total).toLocaleString();
        }
    }

    function removeCartItem(type) {
        const action = type === 'package' ? 'remove_package' : 'remove_topup';
        fetch('/cart-api.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'action=' + action
        })
            .then(r => r.json())
            .then(d => {
                if (d.ok) {
                    updateCartBadge(d.count);
                    refreshCartDropdown();
                }
            });
    }
</script>