// GLOBAL VARIABLES
console.log("GHADGET APP JS v1.17 Loaded - NO MOCK - FIXED");
// GLOBAL VARIABLES
// alert("Ghadget System Active - v3.0"); // Legacy
// console.log("GHADGET SYSTEM ACTIVE");
// We can use a subtle toast or just log it. User said remove or modern.
// Let's remove the pervasive alert and just log, or show a welcome toast later.
console.log("Ghadget System Active - v3.0");
console.log("GHADGET SYSTEM ACTIVE");

// --- CLEAN SLATE PROTOCOL ---
const AUTH_VERSION = 'auth_v2';
if (localStorage.getItem('ghadget_auth_version') !== AUTH_VERSION) {
    localStorage.clear();
    localStorage.setItem('ghadget_auth_version', AUTH_VERSION);
}

let currentUser = null;
let products = [];

// INITIALIZATION
window.addEventListener('DOMContentLoaded', async () => {
    // AUTH CHECK
    await checkSession();

    // DYNAMIC PRODUCT LOADING
    const storedProducts = localStorage.getItem('ghadget_products');
    if (storedProducts) {
        products = JSON.parse(storedProducts);
    }

    if (typeof window.productsData !== 'undefined' && Array.isArray(window.productsData)) {
        const productMap = new Map(products.map(p => [p.id, p]));
        window.productsData.forEach(p => {
            productMap.set(p.id, { ...productMap.get(p.id), ...p });
        });
        products = Array.from(productMap.values());
        localStorage.setItem('ghadget_products', JSON.stringify(products));
    }

    if (products.length === 0) console.error("Products data failed to load.");

    // Initial Render
    filterProducts('all');
    renderHomeCategories();
    renderDesktopCategories();
    updateWalletUI();
    updateProfileUI();
});

// AUTHENTICATION & SESSION
async function checkSession() {
    const token = localStorage.getItem('ghadget_token');
    if (!token) {
        currentUser = null;
        updateProfileUI();
        return;
    }

    try {
        const res = await fetch('server/auth.php', {
            method: 'POST',
            body: JSON.stringify({ action: 'check_session', token: token })
        });
        const data = await res.json();
        if (data.success) {
            currentUser = data.user;
            updateProfileUI();
            updateWalletUI();
        } else {
            console.warn("Session Invalid:", data.error);
            userLogout(false);
        }
    } catch (e) {
        console.error("Session Check Failed:", e);
        // Fallback for Local/Network Error
        if (token === 'mock_token_123' || window.location.protocol === 'file:') {
            console.warn("Using Mock Session (Local Mode)");
            currentUser = {
                id: 'mock-user-1',
                username: 'DemoUser',
                email: 'demo@ghadget.com',
                balance: 50000,
                verified: true,
                avatar: 'https://i.pravatar.cc/150?u=demo'
            };
            updateProfileUI();
            updateWalletUI();
        } else {
            currentUser = null;
        }
    }
}

function updateProfileUI() {
    const headerAvatar = document.getElementById('header-avatar');
    const headerName = document.getElementById('header-username');
    const deskAvatar = document.getElementById('desk-avatar');
    const deskName = document.getElementById('desk-username');
    const dashAvatar = document.getElementById('dash-avatar');
    const dashName = document.getElementById('dash-username');
    const statusDot = document.getElementById('header-status-dot');

    if (currentUser) {
        const name = currentUser.username || 'User';
        const avatarSrc = currentUser.avatar || `https://ui-avatars.com/api/?name=${name}&background=1C1917&color=fff`;

        if (headerName) headerName.innerText = name;
        if (headerAvatar) headerAvatar.src = avatarSrc;
        if (deskName) deskName.innerText = name;
        if (deskAvatar) deskAvatar.src = avatarSrc;
        if (dashName) dashName.innerText = name;
        if (dashAvatar) dashAvatar.src = avatarSrc;
        if (statusDot) statusDot.className = "absolute bottom-0 right-0 w-3 h-3 bg-green-500 rounded-full border-2 border-white";
    } else {
        // Guest State
        const guestName = 'GUEST';
        const guestAvatar = 'https://ui-avatars.com/api/?name=Guest&background=1C1917&color=fff';
        if (headerName) headerName.innerText = guestName;
        if (headerAvatar) headerAvatar.src = guestAvatar;
        if (deskName) deskName.innerText = guestName;
        if (deskAvatar) deskAvatar.src = guestAvatar;
        if (statusDot) statusDot.className = "absolute bottom-0 right-0 w-3 h-3 bg-gray-300 rounded-full border-2 border-white";
    }
}

function saveUser(user) {
    // We rely on SERVER state mainly, but can update local cache if needed.
    // Here we just update memory variable `currentUser`
    currentUser = user;
    updateWalletUI();
    updateProfileUI();
}

function handleProfileClick() {
    if (currentUser) {
        openDashboard();
    } else {
        document.getElementById('auth-modal').classList.remove('hidden');
    }
}

// TRIGGER AVATAR UPLOAD (Placeholder for now, implementation requires server endpoint update)
function triggerAvatarUpload() {
    alert("Avatar upload requires server implementation enhancement.");
    // document.getElementById('avatar-input').click();
}

function handleAvatarUpload(event) {
    // ... (Existing logic requires PHP upload handler similar to p2p)
}


// LOGOUT LOGIC
async function userLogout(confirmAction = true) {
    if (confirmAction && !confirm('Are you sure you want to log out?')) return;

    const token = localStorage.getItem('ghadget_token');
    if (token) {
        try {
            await fetch('server/auth.php', {
                method: 'POST',
                body: JSON.stringify({ action: 'logout', token: token })
            });
        } catch (e) { console.error("Logout API failed", e); }
    }

    localStorage.removeItem('ghadget_token');
    localStorage.removeItem('ghadget_user');
    currentUser = null;
    window.location.reload();
}

window.userLogout = userLogout;

function switchAuth(tab) {
    const loginForm = document.getElementById('form-login');
    const signupForm = document.getElementById('form-signup');
    const tabLogin = document.getElementById('tab-login');
    const tabSignup = document.getElementById('tab-signup');

    if (tab === 'login') {
        loginForm.classList.remove('hidden');
        signupForm.classList.add('hidden');
        tabLogin.classList.add('bg-white', 'shadow-sm', 'text-brand-dark');
        tabLogin.classList.remove('text-gray-500');
        tabSignup.classList.remove('bg-white', 'shadow-sm', 'text-brand-dark');
        tabSignup.classList.add('text-gray-500');
    } else {
        loginForm.classList.add('hidden');
        signupForm.classList.remove('hidden');
        tabSignup.classList.add('bg-white', 'shadow-sm', 'text-brand-dark');
        tabSignup.classList.remove('text-gray-500');
        tabLogin.classList.remove('bg-white', 'shadow-sm', 'text-brand-dark');
        tabLogin.classList.add('text-gray-500');
    }
}

// TOAST NOTIFICATIONS (Moved up for usage)
function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    // Added style z-index to ensure it sits on top of everything
    toast.className = `fixed bottom-20 left-1/2 transform -translate-x-1/2 px-6 py-3 rounded-xl shadow-2xl flex items-center gap-3 animate-bounce-in transition duration-300 ${type === 'success' ? 'bg-brand-dark text-white' : 'bg-red-500 text-white'}`;
    toast.style.zIndex = "99999";
    toast.innerHTML = `
        <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i>
        <span class="text-xs font-bold">${message}</span>
    `;
    document.body.appendChild(toast);

    setTimeout(() => {
        toast.className += ' opacity-0 translate-y-10';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// PASSWORD STRENGTH
function checkPasswordStrength(password) {
    const meter = document.getElementById('pass-strength-meter');
    const text = document.getElementById('pass-strength-text');
    const bars = [1, 2, 3, 4].map(i => document.getElementById(`meter-${i}`));

    if (!password) {
        meter.classList.add('hidden');
        return;
    }
    meter.classList.remove('hidden');

    let strength = 0;
    if (password.length >= 8) strength++;
    if (/[A-Z]/.test(password)) strength++;
    if (/[0-9]/.test(password)) strength++;
    // Use permissive special char check matching the new validation regex
    if (/[\W_]/.test(password)) strength++;

    // Colors
    const colors = ['bg-red-500', 'bg-orange-500', 'bg-yellow-500', 'bg-green-500'];

    bars.forEach((bar, idx) => {
        bar.className = `flex-1 rounded-full transition-colors duration-300 h-1 ${idx < strength ? colors[strength - 1] : 'bg-gray-200'}`;
    });

    if (strength < 4) {
        text.innerText = "Too Weak. Need: 8+ chars, Uppercase, Number, Special.";
        text.className = "text-[10px] text-red-500 text-right font-bold";
    } else {
        text.innerText = "Strong Password!";
        text.className = "text-[10px] text-green-500 text-right font-bold";
    }
}

let tempSignupData = {}; // Cache for resend/change flow

async function handleSignup(e) {
    e.preventDefault();
    const username = e.target.querySelector('input[placeholder="Username"]').value.trim();
    const email = e.target.querySelector('input[type="email"]').value.trim();
    const countryCode = document.getElementById('signup-country').value;
    const whatsappLocal = e.target.querySelector('input[type="tel"]').value.trim();
    const password = document.getElementById('index-reg-pass').value;
    const confirmPass = document.getElementById('index-reg-pass-confirm').value;

    // VALIDATION
    if (!username || !email || !whatsappLocal || !password) {
        showToast("All fields are required", "error");
        return;
    }

    // Password Match
    if (password !== confirmPass) {
        showToast("Passwords do not match", "error");
        return;
    }

    // Strict Password Policy (Updated to be permissive of ALL special chars)
    // Regex: At least 8 chars, 1 Upper, 1 Number, 1 Special (Symbol or Underscore)
    const strongRegex = /^(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/;
    if (!strongRegex.test(password)) {
        showToast("Password too weak. Ensure you have Uppercase, Number & Symbol.", "error");
        return;
    }

    // Format WhatsApp (remove leading 0 if present)
    const cleanPhone = whatsappLocal.replace(/^0+/, '');
    const fullWhatsapp = countryCode + cleanPhone;

    tempSignupData = { username, email, password, whatsapp: fullWhatsapp };

    await executeRegister(tempSignupData);
}

async function executeRegister(dataPayload) {
    try {
        const res = await fetch('server/auth.php', {
            method: 'POST',
            body: JSON.stringify({
                action: 'register',
                email: dataPayload.email,
                password: dataPayload.password,
                whatsapp: dataPayload.whatsapp,
                username: dataPayload.username
            })
        });
        const data = await res.json();

        if (data.success) {
            // SUCCESS FLOW
            document.getElementById('auth-modal').classList.add('hidden');

            // Show Verification Modal
            document.getElementById('verify-email-display').innerText = dataPayload.email;
            document.getElementById('verification-modal').classList.remove('hidden');

            // Save pending state just in case
            localStorage.setItem('pending_email', dataPayload.email);
        } else {
            showToast(data.error || "Signup Failed", "error");
        }
    } catch (err) {
        console.error(err);
        showToast("Network Error during Signup", "error");
    }
}

async function resendVerification() {
    if (!tempSignupData.email) {
        showToast("Session lost. Please restart signup.", "error");
        return;
    }
    showToast("Resending email...", "success"); // Feedback
    await executeRegister(tempSignupData); // Re-triggers register logic which handles resend
}

function openChangeEmail() {
    document.getElementById('new-verify-email').value = tempSignupData.email || '';
    document.getElementById('change-email-modal').classList.remove('hidden');
}

function submitNewEmail() {
    const newEmail = document.getElementById('new-verify-email').value.trim();
    if (!newEmail || !newEmail.includes('@')) {
        showToast("Invalid Email", "error");
        return;
    }

    // Update Data
    tempSignupData.email = newEmail;

    document.getElementById('change-email-modal').classList.add('hidden');
    document.getElementById('verify-email-display').innerText = newEmail;

    // Resend to new email
    executeRegister(tempSignupData);
}

// Removed duplicate function - see below for the correct one

// WALLET &// VISUAL UPDATES
function updateWalletUI() {
    let rawBalance = currentUser ? currentUser.balance : (parseFloat(localStorage.getItem('guest_balance')) || 0);

    // Virtual Deduction Logic (Display Only)
    let cartTotal = cart.reduce((sum, item) => sum + item.price, 0);
    let effectiveBalance = rawBalance - cartTotal;
    let bonusBalance = currentUser ? (currentUser.bonus || 0) : (parseFloat(localStorage.getItem('guest_bonus')) || 0);

    // Formatter
    const fmt = new Intl.NumberFormat('en-NG', { style: 'currency', currency: 'NGN' });

    // Update Elements
    const ids = ['wallet-balance', 'dash-balance', 'hero-balance'];
    ids.forEach(id => {
        const el = document.getElementById(id);
        if (el) {
            el.innerText = fmt.format(effectiveBalance);
            if (effectiveBalance < 0) el.classList.add('text-red-500');
            else el.classList.remove('text-red-500');
        }
    });

    // Debit Sub-text AND Bonus Text
    // We repurpose the 'debit' line to show Debit AND Bonus? Or separate? 
    // Let's show Bonus if Debit is 0, or both.
    const debitIds = ['wallet-debit', 'dash-wallet-debit'];
    debitIds.forEach(id => {
        const el = document.getElementById(id);
        if (el) {
            let text = '';
            let escrow = currentUser ? (currentUser.escrowBalance || 0) : 0;

            if (cartTotal > 0) text += `<span class="text-red-400">-${fmt.format(cartTotal)}</span> `;
            if (bonusBalance > 0) text += `<span class="text-brand-accent ml-2">+${fmt.format(bonusBalance)} (Bonus)</span>`;

            if (text) {
                el.innerHTML = text; // Use innerHTML for spans
                el.classList.remove('hidden');
            } else {
                el.classList.add('hidden');
            }
        }
    });

    // Guest Dashboard / Login State

    // Guest Dashboard / Login State
    if (!currentUser) {
        // Ensure guest element doesn't look broken
        const userTitle = document.getElementById('dash-balance-title');
        if (userTitle) userTitle.innerText = "Guest Wallet";
    }

    // Saved Items Badge
    const savedIds = ['footer-saved-badge', 'desk-saved-badge'];
    savedIds.forEach(id => {
        const badge = document.getElementById(id);
        if (badge) {
            let count = savedItems.length;
            badge.innerText = count;
            if (count > 0) badge.classList.remove('hidden');
            else badge.classList.add('hidden');
        }
    });

    // Cart Badge
    const cartIds = ['mobile-cart-badge', 'desk-cart-badge'];
    cartIds.forEach(id => {
        const badge = document.getElementById(id);
        if (badge) {
            let count = cart.length;
            badge.innerText = count;
            if (count > 0) badge.classList.remove('hidden');
            else badge.classList.add('hidden');
        }
    });
}

// PAYSTACK INTEGRATION
function fundWithPaystack() {
    // Get amount
    const amountStr = prompt("Enter amount to fund (NGN):", "5000");
    if (!amountStr) return;
    const amount = parseFloat(amountStr);
    if (isNaN(amount) || amount <= 0) {
        showToast("Invalid amount", "error");
        return;
    }

    const email = currentUser ? (currentUser.email || 'user@ghadget.com') : 'guest@ghadget.com';

    let handler = PaystackPop.setup({
        key: 'pk_test_xxxxxxxxxxxxxxxxxxxxxxxx', // Replace with valid Key if User provides, or use generic mockup
        email: email,
        amount: amount * 100, // Kobo
        currency: 'NGN',
        ref: '' + Math.floor((Math.random() * 1000000000) + 1),
        onClose: function () {
            showToast("Funding cancelled", "error");
        },
        callback: function (response) {
            // Credit Wallet
            if (currentUser) {
                currentUser.balance = (currentUser.balance || 0) + amount;
                saveUser(currentUser);
            } else {
                let bal = parseFloat(localStorage.getItem('guest_balance')) || 0;
                localStorage.setItem('guest_balance', (bal + amount).toString());
            }
            updateWalletUI();
            showToast(`Success! Funded ₦${amount}`);

            // Close modal if open
            document.getElementById('funding-modal').classList.add('hidden');
        }
    });
    handler.openIframe();
}

// TOAST NOTIFICATIONS
function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    toast.className = `fixed bottom-20 left-1/2 transform -translate-x-1/2 px-6 py-3 rounded-xl shadow-2xl flex items-center gap-3 z-[200] animate-bounce-in transition duration-300 ${type === 'success' ? 'bg-brand-dark text-white' : 'bg-red-500 text-white'}`;
    toast.innerHTML = `
        <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i>
        <span class="text-xs font-bold">${message}</span>
    `;
    document.body.appendChild(toast);

    // Remove after 3s
    setTimeout(() => {
        toast.className += ' opacity-0 translate-y-10';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// CART LOGIC
let cart = [];
let savedItems = JSON.parse(localStorage.getItem('ghadget_saved')) || []; // Saved/Loved Items

function addToCart(e, pid) {
    if (e) e.stopPropagation();

    let product;
    if (typeof pid === 'string') {
        product = products.find(p => p.id === pid);
    } else {
        product = pid;
    }

    if (product) {
        cart.push(product);
        showToast("Added to Bundle!");
    } else {
        showToast("Error adding product", "error");
    }

    updateWalletUI(); // Updates ALL badges and wallet
}

function removeFromCart(index) {
    cart.splice(index, 1);
    updateWalletUI();
    renderCart();
}

function toggleSaved(e, pid) {
    if (e) e.stopPropagation();

    // Find product
    const product = products.find(p => p.id === pid);
    if (!product) return;

    // Check if in saved
    const idx = savedItems.findIndex(i => i.id === pid);
    if (idx > -1) {
        savedItems.splice(idx, 1);
        showToast("Removed from Saved");
    } else {
        savedItems.push(product);
        showToast("Added to Saved");
    }

    // Save to LocalStorage
    localStorage.setItem('ghadget_saved', JSON.stringify(savedItems));

    // Toggle Icon Style (if clicked from a button with an icon)
    if (e.currentTarget) {
        const icon = e.currentTarget.querySelector('i');
        if (icon) {
            if (idx > -1) icon.className = "far fa-heart"; // Removed
            else icon.className = "fas fa-heart text-red-500"; // Added
        }
    }

    updateWalletUI(); // Update badges
}

function toggleCartModal() {
    const modal = document.getElementById('cart-modal');
    if (modal.classList.contains('hidden')) {
        renderCart();
        modal.classList.remove('hidden');
    } else {
        modal.classList.add('hidden');
    }
}

function renderCart() {
    const container = document.querySelector('#cart-modal .flex-grow');
    if (!container) return;

    if (cart.length === 0) {
        container.innerHTML = '<div class="flex flex-col items-center justify-center h-full"><p class="text-gray-400 text-sm">Your cart is empty.</p></div>';
        return;
    }

    let html = '<div class="w-full p-6 space-y-4 overflow-y-auto h-full">';
    let total = 0;

    cart.forEach((item, index) => {
        total += item.price;
        html += `
            <div class="flex gap-4 items-center bg-white p-3 rounded-xl shadow-sm">
                <img src="${item.image || item.images[0]}" class="w-16 h-16 rounded-lg object-cover mix-blend-multiply">
                <div class="flex-grow">
                    <h4 class="font-bold text-brand-dark text-xs line-clamp-1">${item.name}</h4>
                    <p class="text-gray-500 text-[10px]">${new Intl.NumberFormat('en-NG', { style: 'currency', currency: 'NGN' }).format(item.price)}</p>
                </div>
                <button onclick="removeFromCart(${index})" class="text-red-500 w-8 h-8 flex items-center justify-center"><i class="fas fa-trash"></i></button>
            </div>
        `;
    });

    html += '</div>';

    html += `
        <div class="p-6 bg-white border-t border-gray-100 w-full mt-auto">
            <div class="flex justify-between items-center mb-4">
                <span class="text-gray-400 text-xs font-bold uppercase">Total</span>
                <span class="text-xl font-bold text-brand-dark">${new Intl.NumberFormat('en-NG', { style: 'currency', currency: 'NGN' }).format(total)}</span>
            </div>
            <button onclick="openCheckoutModal()" class="w-full bg-brand-dark text-white py-4 rounded-xl font-bold shadow-lg">Proceed to Checkout</button>
        </div>
    `;

    container.innerHTML = html;
    container.classList.remove('items-center', 'justify-center');
    container.classList.add('flex-col');
}

// CHECKOUT LOGIC
function openCheckoutModal() {
    document.getElementById('cart-modal').classList.add('hidden');
    document.getElementById('checkout-modal').classList.remove('hidden');

    // Calculate totals for summary
    const total = cart.reduce((sum, item) => sum + item.price, 0);
    const shipping = 2500; // Flat rate mock
    const grandTotal = total + shipping;

    document.getElementById('chk-subtotal').innerText = new Intl.NumberFormat('en-NG', { style: 'currency', currency: 'NGN' }).format(total);
    document.getElementById('chk-total').innerText = new Intl.NumberFormat('en-NG', { style: 'currency', currency: 'NGN' }).format(grandTotal);
}

function confirmOrder(e) {
    e.preventDefault();

    // Basic Validation
    const address = document.getElementById('chk-address').value;
    if (!address) {
        showToast("Please enter delivery address", "error");
        return;
    }

    // Check Payment Method
    const paymentMethod = document.querySelector('input[name="payment_method"]:checked').value;
    const total = cart.reduce((sum, item) => sum + item.price, 0);
    const balance = currentUser ? currentUser.balance : (parseFloat(localStorage.getItem('guest_balance')) || 0);

    // 1. Wallet Check
    if (paymentMethod === 'wallet') {
        const effectiveReal = balance; // We are already using strict 'balance' (real)

        // Block if 0 or negative
        if (effectiveReal <= 0) {
            showToast("Wallet is Empty! Fund first.", "error");
            if (confirm("Your wallet is empty. Fund now?")) {
                fundWithPaystack();
            }
            return;
        }

        if (balance < total) {
            showToast("Insufficient Real Funds!", "error");
            if (confirm("Insufficient Funds. Fund Wallet now with Paystack?")) {
                fundWithPaystack();
            }
            return;
        }
        // If funds ok, fall through to finalize
    }

    // 2. WhatsApp Check
    if (paymentMethod === 'whatsapp') {
        const phone = "2349036135326";
        let msg = `*New Order Request*\n\n`;
        msg += `*Items:*\n`;
        cart.forEach(i => msg += `- ${i.name} (${new Intl.NumberFormat('en-NG', { style: 'currency', currency: 'NGN' }).format(i.price)})\n`);
        msg += `\n*Total:* ${new Intl.NumberFormat('en-NG', { style: 'currency', currency: 'NGN' }).format(total)}\n`;
        msg += `*Address:* ${address}\n`;
        msg += `*User:* ${currentUser ? currentUser.username : 'Guest'}\n\n`;
        msg += `Please confirm availability and payment details.`;

        const url = `https://wa.me/${phone}?text=${encodeURIComponent(msg)}`;
        window.open(url, '_blank');

        finalizeOrder(total, true); // Treat as external/pending
        return;
    }

    // 3. Paystack Check
    if (paymentMethod === 'paystack') {
        directPaystackCheckout(total);
        return;
    }

    // WALLET PROCESS (Continue if Sufficient funds)
    finalizeOrder(total);
}

function directPaystackCheckout(amount) {
    const email = currentUser ? (currentUser.email || 'user@ghadget.com') : 'guest@ghadget.com';
    let handler = PaystackPop.setup({
        key: 'pk_test_xxxxxxxxxxxxxxxxxxxxxxxx',
        email: email,
        amount: amount * 100,
        currency: 'NGN',
        ref: 'checkout-' + Math.floor((Math.random() * 1000000000) + 1),
        onClose: function () {
            showToast("Payment cancelled", "error");
        },
        callback: function (response) {
            finalizeOrder(amount, true); // True = Paid via External
        }
    });
    handler.openIframe();
}

function finalizeOrder(total, externalPaid = false) {
    // Create Order Object
    const order = {
        id: 'ORD-' + Math.floor(Math.random() * 100000),
        date: new Date().toLocaleDateString(),
        items: [...cart],
        total: total,
        status: 'Processing',
        payment: externalPaid ? 'Paystack Card' : 'Wallet'
    };

    // Save to User History
    if (currentUser) {
        if (!currentUser.orders) currentUser.orders = [];
        currentUser.orders.unshift(order);

        // Deduct Only if Wallet (Not External)
        if (!externalPaid) {
            currentUser.balance -= order.total;
            saveUser(currentUser);
        }
    } else {
        // Guest Deduction (Only if Wallet)
        if (!externalPaid) {
            let guestBal = parseFloat(localStorage.getItem('guest_balance')) || 0;
            guestBal -= total;
            localStorage.setItem('guest_balance', guestBal.toString());
        }
    }

    // Clear Cart ... (Rest of logic)

    // Clear Cart
    cart = [];

    // Reset UI
    document.getElementById('checkout-modal').classList.add('hidden');
    updateWalletUI(); // Reset visual debit

    // Remove badges
    const mobileBadge = document.getElementById('mobile-cart-badge');
    const bottomBadge = document.getElementById('bottom-cart-badge');
    [mobileBadge, bottomBadge].forEach(el => {
        if (el) {
            el.innerText = '0';
            el.classList.add('hidden');
        }
    });

    // Success & Reward
    showToast("Order Placed Successfully!");
    // RewardSystem.award('buy'); // Bonus disabled for vanity reasons per user? Or allowed? logic says "vanity funds cannot be used", maybe earning them is fine? Leaving for now.

    // Celebrate
    startConfetti();

    // Redirect to Orders (after delay)
    setTimeout(() => {
        if (currentUser) {
            openDashboard();
            switchDashTab('orders');
        }
    }, 2000);
}

// AUTO SLIDER (Hero)
window.addEventListener('load', () => {
    const slider = document.querySelector('.snap-x'); // Assuming hero uses snap-x class
    if (slider) {
        let scrollAmount = 0;
        const speed = 900; // 0.9s

        setInterval(() => {
            const cardWidth = slider.querySelector('div')?.offsetWidth || 300;
            const gap = 16;
            const maxScroll = slider.scrollWidth - slider.clientWidth;

            scrollAmount += (cardWidth + gap);
            if (scrollAmount > maxScroll) scrollAmount = 0;

            slider.scrollTo({
                left: scrollAmount,
                behavior: 'smooth'
            });
        }, speed);
    }
});

function startConfetti() {
    // Simple CSS/JS confetti shim
    for (let i = 0; i < 50; i++) {
        const c = document.createElement('div');
        c.className = 'fixed w-3 h-3 rounded-full z-[300] animate-confetti';
        c.style.left = Math.random() * 100 + 'vw';
        c.style.top = '-10px';
        c.style.backgroundColor = ['#EAB308', '#A855F7', '#EF4444', '#3B82F6'][Math.floor(Math.random() * 4)];
        c.style.animationDuration = (Math.random() * 2 + 2) + 's'; // 2-4s
        document.body.appendChild(c);
        setTimeout(() => c.remove(), 4000);
    }
}
// SEARCH FUNCTIONALITY
function handleSearch(input) {
    const query = input.value.trim().toLowerCase();
    if (!query) {
        filterProducts('all');
        return;
    }

    const filtered = products.filter(p => {
        return (p.name && p.name.toLowerCase().includes(query)) ||
            (p.category && p.category.toLowerCase().includes(query)) ||
            (p.subcategory && p.subcategory.toLowerCase().includes(query)) ||
            (p.brand && p.brand.toLowerCase().includes(query)) ||
            (p.description && p.description.toLowerCase().includes(query));
    });

    renderProducts(filtered);
}

// Helper for Header Avatar Click
function handleHeaderAvatarClick() {
    if (currentUser) {
        openDashboard('overview');
    } else {
        openAuthModal();
    }
}

function openAuthModal() {
    document.getElementById('auth-modal').classList.remove('hidden');
}

// Helper for Saved Button Click
function handleSavedClick() {
    // Both Guests and Users can view saved items
    openDashboard('saved');
}

function openDashboard(initialTab = 'overview') {
    updateProfileUI(); // Ensure fresh data
    updateWalletUI();

    // Auth Check
    const isGuest = !currentUser;
    // If we want to force login for Profile but allow Saved/Cart for guests:
    // This logic handles "opening the dashboard modal" in general.

    // For specific tabs (like 'saved'), we allow access.
    // For 'settings' or generic 'account' access via Avatar, we might prefer Auth Modal (handled by handleHeaderAvatarClick).

    const modal = document.getElementById('dashboard-modal');
    modal.classList.remove('hidden');

    // Render content
    if (initialTab === 'orders') {
        // If orders tab doesn't exist, show overview and render orders in it
        switchDashTab('overview');
        setTimeout(() => renderDashHistory(), 100);
    } else if (initialTab) {
        switchDashTab(initialTab);
    } else {
        switchDashTab('overview');
    }
}

function switchDashTab(tab) {
    ['overview', 'orders', 'services', 'settings', 'saved', 'cart'].forEach(t => {
        const content = document.getElementById(`dash-tab-${t}`);
        const btn = document.getElementById(`btn-dash-${t}`);
        if (content) content.classList.add('hidden');
        if (btn) {
            btn.classList.remove('text-brand-dark', 'bg-white', 'shadow-sm');
            btn.classList.add('text-gray-400');
        }
    });

    const targetContent = document.getElementById(`dash-tab-${tab}`);
    const targetBtn = document.getElementById(`btn-dash-${tab}`);

    if (targetContent) targetContent.classList.remove('hidden');
    if (targetBtn) {
        targetBtn.classList.remove('text-gray-400');
        targetBtn.classList.add('text-brand-dark', 'bg-white', 'shadow-sm');
    }

    if (tab === 'saved') renderDashSaved();
    if (tab === 'cart') renderDashCart();
    if (tab === 'orders') renderDashHistory();
}

function renderDashHistory() {
    // Try to find orders list element, create it if it doesn't exist in overview tab
    let list = document.getElementById('dash-orders-list');
    const overviewTab = document.getElementById('dash-tab-overview');

    if (!list && overviewTab) {
        // Create orders section in overview tab
        const ordersSection = document.createElement('div');
        ordersSection.id = 'dash-orders-section';
        ordersSection.className = 'mt-6 space-y-4';
        ordersSection.innerHTML = `
            <h3 class="font-bold text-brand-dark mb-4">Recent Orders</h3>
            <div id="dash-orders-list" class="space-y-3"></div>
        `;
        overviewTab.appendChild(ordersSection);
        list = document.getElementById('dash-orders-list');
    }

    if (!list) {
        console.warn('Orders list element not found');
        return;
    }

    if (!currentUser || !currentUser.orders || currentUser.orders.length === 0) {
        list.innerHTML = '<div class="text-center text-gray-400 py-10 text-xs">No recent orders.</div>';
        return;
    }

    list.innerHTML = '';
    currentUser.orders.forEach(order => {
        const el = document.createElement('div');
        el.className = 'bg-white p-4 rounded-2xl flex flex-col gap-3 shadow-sm border border-gray-50';

        // Item Previews (First 3)
        const images = order.items.slice(0, 3).map(i => {
            const imgSrc = i.image || (i.images && i.images[0]) || '';
            return `<img src="${imgSrc}" class="w-8 h-8 rounded-md object-cover bg-gray-50">`;
        }).join('');

        el.innerHTML = `
            <div class="flex justify-between items-center border-b border-gray-100 pb-2">
                <span class="text-[10px] font-bold text-brand-dark">${order.id}</span>
                <span class="text-[10px] text-gray-400">${order.date}</span>
            </div>
            <div class="flex gap-2">
                ${images}
                ${order.items.length > 3 ? `<div class="w-8 h-8 rounded-md bg-gray-100 flex items-center justify-center text-[10px] text-gray-500 font-bold">+${order.items.length - 3}</div>` : ''}
            </div>
            <div class="flex justify-between items-center pt-1">
                <span class="text-xs font-bold text-green-500">${order.status}</span>
                <span class="text-xs font-bold text-brand-dark">${new Intl.NumberFormat('en-NG', { style: 'currency', currency: 'NGN' }).format(order.total)}</span>
            </div>
        `;
        list.appendChild(el);
    });
}

function renderDashSaved() {
    const container = document.getElementById('dash-saved-grid');
    if (!container) return;

    if (savedItems.length === 0) {
        container.innerHTML = '<div class="col-span-2 text-center text-gray-400 py-10 text-xs">No saved items found.</div>';
        return;
    }

    container.innerHTML = '';
    savedItems.forEach(item => {
        // Handle both ID strings and product objects
        const p = (typeof item === 'string' || typeof item === 'object')
            ? (typeof item === 'string' ? products.find(prod => prod.id === item) : item)
            : null;
        if (!p) return;

        const card = document.createElement('div');
        card.className = 'bg-white p-3 rounded-xl shadow-sm border border-gray-100';
        card.innerHTML = `
            <div class="w-full h-24 bg-gray-50 rounded-lg mb-2 overflow-hidden relative">
                <img src="${p.image || (p.images && p.images[0]) || ''}" class="w-full h-full object-cover mix-blend-multiply">
            <button onclick="toggleSaved(event, '${p.id}'); renderDashSaved()" class="absolute top-1 right-1 w-6 h-6 bg-white/90 rounded-full flex items-center justify-center shadow-sm">
                    <i class="fas fa-trash text-[10px] text-red-500"></i>
                </button>
            </div>
            <h4 class="font-bold text-brand-dark text-xs truncate mb-1">${p.name}</h4>
            <div class="flex justify-between items-center">
                <span class="text-[10px] font-bold text-gray-500">${new Intl.NumberFormat('en-NG', { style: 'currency', currency: 'NGN' }).format(p.price)}</span>
                <button onclick="addToCart(event, '${p.id}')" class="w-6 h-6 bg-brand-dark text-white rounded-full flex items-center justify-center text-[10px]">
                    <i class="fas fa-plus"></i>
                </button>
            </div>
        `;
        container.appendChild(card);
    });
}

function renderDashCart() {
    const container = document.getElementById('dash-cart-list');
    if (!container) return;

    if (cart.length === 0) {
        container.innerHTML = '<div class="text-center text-gray-400 py-10 text-xs">Your cart is empty.</div>';
        return;
    }

    container.innerHTML = '';
    cart.forEach((item, index) => {
        const el = document.createElement('div');
        el.className = 'flex gap-3 items-center bg-white p-3 rounded-xl shadow-sm border border-gray-100';
        el.innerHTML = `
            <img src="${item.image || item.images[0]}" class="w-12 h-12 rounded-lg object-cover mix-blend-multiply bg-gray-50">
            <div class="flex-grow min-w-0">
                <h4 class="font-bold text-brand-dark text-xs truncate">${item.name}</h4>
                <p class="text-[10px] text-gray-500">${new Intl.NumberFormat('en-NG', { style: 'currency', currency: 'NGN' }).format(item.price)}</p>
            </div>
            <button onclick="removeFromCart(${index})" class="w-8 h-8 flex items-center justify-center text-gray-400 hover:text-red-500 transition">
                <i class="fas fa-times"></i>
            </button>
        `;
        container.appendChild(el);
    });

    // Add Checkout Button if not empty
    if (cart.length > 0) {
        const btn = document.createElement('button');
        btn.onclick = () => { openCheckoutModal(); };
        btn.className = "w-full bg-brand-dark text-white py-3 rounded-xl font-bold mt-4 shadow-lg text-xs";
        btn.innerText = "Proceed to Checkout";
        container.appendChild(btn);
    }
}

function updateProfile(e) {
    e.preventDefault();
    const newName = document.getElementById('edit-username').value;
    const newEmail = document.getElementById('edit-email').value;

    if (newName) currentUser.username = newName;
    if (newEmail) currentUser.email = newEmail;

    saveUser(currentUser);
    alert('Profile Updated!');
    // Ideally stay on settings or go back to overview
}

// GAMIFICATION & REWARD SYSTEM
const RewardSystem = {
    rewards: {
        login: { amount: 1, label: 'Daily Login Reward' },
        share: { amount: 3, label: 'Share Bonus' },
        buy: { amount: 10, label: 'Purchase Reward' },
        fund: { amount: 100, label: 'Funding Bonus' }
    },

    award: function (type) {
        let amount = this.rewards[type].amount;
        const lucky = Math.random() < 0.2;
        const bonusAmount = lucky ? Math.floor(Math.random() * 5) + 1 : 0;
        amount += bonusAmount;

        // CREDIT BONDS (NOT REAL BALANCE)
        if (currentUser) {
            currentUser.bonus = (currentUser.bonus || 0) + amount;
            saveUser(currentUser);
        } else {
            // Guest Bonus tracking (optional, simple shim)
            let b = parseFloat(localStorage.getItem('guest_bonus')) || 0;
            localStorage.setItem('guest_bonus', (b + amount).toString());
            updateWalletUI(); // To update badges if we showed bonus
        }

        showToast(`🎉 Earned ₦${amount} Bonus Credits!`);
    }
};

// WALLET MODALS
function openFundingModal() {
    document.getElementById('funding-modal').classList.remove('hidden');
}

function openVanityModal() {
    document.getElementById('funding-modal').classList.add('hidden');
    document.getElementById('vanity-modal').classList.remove('hidden');
}

function toggleVanityModal() {
    const el = document.getElementById('vanity-modal');
    if (el.classList.contains('hidden')) el.classList.remove('hidden');
    else el.classList.add('hidden');
}

function openTopUpModal() {
    document.getElementById('funding-modal').classList.add('hidden');
    document.getElementById('topup-modal').classList.remove('hidden');
}

function addVanityFunds(amount) {
    if (currentUser) {
        currentUser.bonus = (currentUser.bonus || 0) + amount;
        saveUser(currentUser);
    } else {
        let b = parseFloat(localStorage.getItem('guest_bonus')) || 0;
        localStorage.setItem('guest_bonus', (b + amount).toString());
        updateWalletUI();
    }

    showToast(`Added ₦${amount} to Demo Balance`);
    document.getElementById('vanity-modal').classList.add('hidden');
}

// SHARING
function shareApp() {
    if (navigator.share) {
        navigator.share({
            title: 'Ghadget',
            text: 'Check out Ghadget for curated luxury setups!',
            url: window.location.href,
        }).then(() => {
            RewardSystem.award('share');
        }).catch((error) => console.log('Error sharing', error));
    } else {
        // Fallback or just award for clicking (Shim)
        alert('Sharing link copied to clipboard!');
        RewardSystem.award('share');
    }
}



// HOME CATEGORIES & PRODUCTS
function renderHomeCategories() {
    const container = document.getElementById('home-cat-row');
    if (!container || typeof window.categoryHierarchy === 'undefined') return;

    container.innerHTML = '';

    // Add "All"
    // container.innerHTML += ...

    Object.keys(window.categoryHierarchy).forEach(cat => {
        const btn = document.createElement('button');
        btn.className = 'flex-shrink-0 flex flex-col items-center gap-2 group cursor-pointer';
        btn.onclick = () => openCategoriesModal(cat); // Open modal pre-selected

        // Icon Logic (Simple mapping or generic)
        let iconClass = 'fa-layer-group';
        if (cat.includes('Computer')) iconClass = 'fa-laptop';
        if (cat.includes('Phone') || cat.includes('Mobile')) iconClass = 'fa-mobile-alt';
        if (cat.includes('Audio')) iconClass = 'fa-headphones';
        if (cat.includes('Camera')) iconClass = 'fa-camera';
        if (cat.includes('Game') || cat.includes('Console')) iconClass = 'fa-gamepad';
        if (cat.includes('Home')) iconClass = 'fa-home';

        btn.innerHTML = `
            <div class="w-16 h-16 rounded-2xl bg-white border border-gray-100 flex items-center justify-center shadow-sm group-active:scale-95 transition group-hover:border-brand-dark">
                <i class="fas ${iconClass} text-xl text-gray-400 group-hover:text-brand-dark transition"></i>
            </div>
            <span class="text-[10px] font-bold text-gray-500 group-hover:text-brand-dark">${cat}</span>
        `;
        container.appendChild(btn);
    });
}

function filterProducts(category) {
    let filtered = products;

    if (category !== 'all') {
        if (category === 'under-50k') {
            filtered = products.filter(p => p.price <= 50000);
        } else if (category === 'under-100k') {
            filtered = products.filter(p => p.price <= 100000);
        } else if (category === 'cheap-offer') {
            // For now, let's treat cheap offer as cheapest 20% or simply under 30k
            filtered = products.filter(p => p.price <= 30000);
        } else if (category === 'locked' || category === 'nigeria-used') {
            // Look for specific tags or just match subcategory/category for now.
            // We will assume these are stored in 'category' or 'subcategory' or we check a 'tags' property if we add it.
            // For simplicity, we'll check category/subcategory keys.
            filtered = products.filter(p => p.category === category || p.subcategory === category || (p.tags && p.tags.includes(category)));
        } else {
            // Standard category/subcategory filter
            filtered = products.filter(p => p.category === category || p.subcategory === category);
        }
    }
    renderProducts(filtered);

    // Update active state visual if using text buttons
    // The visual feedback is often handled by the caller (like in renderDealsCategories)
}


function renderProducts(list, targetGridId = null) {
    let grid;
    if (targetGridId) {
        grid = document.getElementById(targetGridId);
    } else {
        // Default to home grid, or check if store is visible?
        // Let's check visibility
        const storePage = document.getElementById('page-store');
        const dealsPage = document.getElementById('page-deals');

        if (storePage && !storePage.classList.contains('hidden')) {
            grid = document.getElementById('product-grid-store');
        } else if (dealsPage && !dealsPage.classList.contains('hidden')) {
            grid = document.getElementById('product-grid-deals');
        } else {
            // Default to Home Grid
            grid = document.getElementById('product-grid');
        }
    }

    if (!grid) {
        console.warn('Product grid element not found');
        return;
    }
    grid.innerHTML = '';

    if (!list || list.length === 0) {
        grid.innerHTML = '<div class="col-span-full text-center text-gray-400 py-10 text-sm">No products found.</div>';
        return;
    }

    // Feature 5: Featured Products First (Simple Sort)
    const sortedList = [...list].sort((a, b) => (b.isFeatured ? 1 : 0) - (a.isFeatured ? 1 : 0));

    sortedList.forEach(p => {
        // Feature 2: Promo Calculation
        let discountBadge = '';
        let priceDisplay = `<span class="text-sm font-bold text-brand-dark block mb-4">${formatCurrency(p.price)}</span>`;

        if (p.originalPrice && p.originalPrice > p.price) {
            const pct = Math.round(((p.originalPrice - p.price) / p.originalPrice) * 100);
            discountBadge = `<div class="absolute top-3 left-3 bg-red-500 text-white text-[10px] font-bold px-2 py-1 rounded-full shadow-sm">-${pct}% OFF</div>`;
            priceDisplay = `
                <div class="flex items-center gap-2 mb-4">
                    <span class="text-sm font-bold text-brand-dark">${formatCurrency(p.price)}</span>
                    <span class="text-xs text-gray-400 line-through">${formatCurrency(p.originalPrice)}</span>
                </div>
            `;
        }

        // Feature 1: Fix "Unidentified" and Feature 4: Views
        const brandDisplay = p.brand || p.category || 'Ghadget';
        const imgSrc = p.image || (p.images && Array.isArray(p.images) && p.images[0]) || '';
        const isSoldOut = (typeof p.stock !== 'undefined' && p.stock <= 0);
        const lowStock = (p.stock > 0 && p.stock < 10) ? `<span class="text-[9px] font-bold text-red-500 bg-red-50 px-2 py-0.5 rounded-full ml-auto">Only ${p.stock} left</span>` : '';
        const colorsHtml = (p.colors && p.colors.length > 0) ?
            `<div class="flex gap-1 mt-1 mb-2">
                ${p.colors.slice(0, 3).map(c => `<div class="w-3 h-3 rounded-full border border-gray-200" style="background-color: ${c.toLowerCase()};" title="${c}"></div>`).join('')}
                ${p.colors.length > 3 ? `<span class="text-[9px] text-gray-400">+${p.colors.length - 3}</span>` : ''}
            </div>` : '';

        const el = document.createElement('div');
        el.className = `bg-white p-2 rounded-2xl shadow-sm hover:shadow-lg transition group cursor-pointer border border-gray-50 relative flex flex-col ${isSoldOut ? 'opacity-70' : ''}`;
        el.onclick = (e) => {
            if (e.target.closest('.action-btn')) return;
            // Feature 4: Track Views
            p.views = (p.views || 0) + 1;
            saveProductViews(p.id, p.views);
            openProduct(p);
        };

        let actionButtons = `
            <div class="grid grid-cols-2 gap-2 mt-auto">
                <button class="action-btn bg-gray-100 text-brand-dark py-3 rounded-xl text-xs font-bold hover:bg-gray-200 transition" onclick="addToCart(event, '${p.id}')">
                    Add
                </button>
                <button class="action-btn bg-brand-dark text-white py-3 rounded-xl text-xs font-bold hover:bg-black transition shadow-lg" onclick="buyNow(event, '${p.id}')">
                    Buy
                </button>
            </div>
        `;

        if (isSoldOut) {
            actionButtons = `
                <div class="mt-auto">
                    <button disabled class="w-full bg-gray-100 text-gray-400 py-3 rounded-xl text-xs font-bold cursor-not-allowed">
                        Sold Out
                    </button>
                </div>
            `;
        }

        el.innerHTML = `
            <div class="h-40 bg-gray-50 rounded-xl mb-3 relative overflow-hidden">
                <img src="${imgSrc}" loading="lazy" class="w-full h-full object-cover mix-blend-multiply group-hover:scale-105 transition duration-500 ${isSoldOut ? 'grayscale' : ''}" onerror="this.src='data:image/svg+xml,%3Csvg xmlns=\\'http://www.w3.org/2000/svg\\' width=\\'100\\' height=\\'100\\'%3E%3Crect fill=\\'%23f3f4f6\\' width=\\'100\\' height=\\'100\\'/%3E%3C/svg%3E'">
                ${discountBadge}
                ${isSoldOut ? '<div class="absolute inset-0 bg-white/50 flex items-center justify-center font-bold text-gray-500 text-sm tracking-wider uppercase backdrop-blur-[1px]">Sold Out</div>' : ''}
                <button class="action-btn absolute top-2 right-2 w-8 h-8 bg-white/80 backdrop-blur rounded-full flex items-center justify-center text-gray-400 hover:text-red-500 shadow-sm transition" onclick="toggleSaved(event, '${p.id}')">
                    <i class="${savedItems && savedItems.some(i => i.id === p.id) ? 'fas fa-heart text-red-500' : 'far fa-heart'} text-sm"></i>
                </button>
            </div>
            <div class="flex-grow">
                <div class="flex items-center justify-between mb-1">
                    <p class="text-[10px] font-bold text-brand-accent uppercase tracking-wider">${brandDisplay}</p>
                    ${!isSoldOut ? lowStock : ''}
                </div>
                <h3 class="font-bold text-brand-dark leading-tight mb-1 line-clamp-2 text-sm min-h-[2.5em]">${p.name}</h3>
                ${colorsHtml}
                ${priceDisplay}
            </div>
            ${actionButtons}
        `;
        grid.appendChild(el);
    });
}

// Helper for views
function saveProductViews(id, views) {
    const localProducts = JSON.parse(localStorage.getItem('ghadget_products')) || [];
    const idx = localProducts.findIndex(p => p.id === id);
    if (idx !== -1) {
        localProducts[idx].views = views;
        localStorage.setItem('ghadget_products', JSON.stringify(localProducts));
    }
}

function formatCurrency(amount) {
    return new Intl.NumberFormat('en-NG', { style: 'currency', currency: 'NGN' }).format(amount);
}

// HOME & NAV LOGIC
function navigateToPage(pageId) {
    // Hide all pages
    const pages = ['page-store', 'page-deals', 'page-orders', 'page-support'];
    pages.forEach(id => {
        const el = document.getElementById(id);
        if (el) el.classList.add('hidden');
    });

    // Hide Home Products Section explicitly if leaving home
    const homeProd = document.getElementById('home-products');
    const desktopHome = document.getElementById('desktop-home-container');

    if (pageId === 'home') {
        if (homeProd) homeProd.classList.remove('hidden');
        if (desktopHome) desktopHome.classList.remove('hidden');
    } else {
        if (homeProd) homeProd.classList.add('hidden');
        if (desktopHome) desktopHome.classList.add('hidden');
    }

    // Toggle target page
    if (pageId !== 'home') {
        const target = document.getElementById(`page-${pageId}`);
        if (target) {
            target.classList.remove('hidden');
            // Populate if store/deals
            if (pageId === 'store') filterProducts('all');
            if (pageId === 'deals') {
                filterProducts('all');
                // Scroll to deals categories on mobile
                const dealsGrid = document.getElementById('deals-cat-grid');
                if (dealsGrid) {
                    setTimeout(() => {
                        dealsGrid.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    }, 100);
                }
            }
            // Populate if orders
            if (pageId === 'orders') renderOrdersPage();
        }
    } else {
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }
}


function handleHomeClick() {
    navigateToPage('home');
}

// SAVED ITEMS LOGIC
// SAVED ITEMS LOGIC (Consolidated above)
// let savedItems = JSON.parse(localStorage.getItem('savedItems')) || []; // REMOVE DUPLICATE

// toggleLove replaced by toggleSaved
// openSavedItems replaced by Dashboard Saved Tab

function buyNow(e, pid) {
    if (e) e.stopPropagation();
    addToCart(null, pid);
    // Directly to checkout? Or cart? User prefers clear flow.
    // openCheckoutModal depends on cart being rendered... 
    // Let's just open Cart (Bundle) as before so they can review total
    toggleCartModal();
}

// renderDashHistory duplicated logic removed

// renderDashOrders duplicated logic removed (use renderDashHistory)


// CATEGORIES MODAL LOGIC (Refactored from misplaced style tag)
function openCategoriesModal(preSelectCat = null) {
    const modal = document.getElementById('categories-modal');
    const sidebar = document.getElementById('cat-sidebar');

    // Check if hierarchy exists and sidebar empty
    if (typeof window.categoryHierarchy !== 'undefined' && sidebar.innerHTML.trim() === '') {
        sidebar.innerHTML = '';
        Object.keys(window.categoryHierarchy).forEach((cat, index) => {
            const btn = document.createElement('button');
            btn.className = `w-full text-left px-6 py-4 text-xs font-bold uppercase tracking-wider hover:bg-white transition border-l-4 border-transparent hover:border-brand-dark text-gray-400`;
            btn.dataset.cat = cat; // Store cat name
            btn.innerText = cat;
            btn.onclick = (e) => {
                // Reset all
                Array.from(sidebar.children).forEach(b => {
                    b.className = b.className.replace('bg-white border-brand-dark text-brand-dark', 'text-gray-400').replace('border-l-4 border-brand-dark', 'border-l-4 border-transparent');
                });
                // Activate clicked
                e.target.className = e.target.className.replace('text-gray-400', 'bg-white border-brand-dark text-brand-dark').replace('border-transparent', 'border-brand-dark');
                renderSubcategories(cat);
            };
            sidebar.appendChild(btn);
        });
    }

    modal.classList.remove('hidden');

    // Handle Pre-select
    if (preSelectCat && typeof window.categoryHierarchy[preSelectCat] !== 'undefined') {
        // Find button and click it to trigger logic
        const btn = Array.from(sidebar.children).find(b => b.innerText === preSelectCat);
        if (btn) btn.click();
    } else if (sidebar.children.length > 0 && document.getElementById('subcat-content').innerHTML.trim() === '') {
        // Default first
        sidebar.children[0].click();
    }
}

function renderSubcategories(cat) {
    const content = document.getElementById('subcat-content');
    const subcats = window.categoryHierarchy[cat] || [];
    if (subcats.length === 0) {
        content.innerHTML = `<p class="text-gray-400 text-sm">No subcategories found.</p>`;
        return;
    }
    content.innerHTML = `
        <div class="mb-6">
            <h3 class="text-2xl font-bold text-brand-dark mb-1">${cat}</h3>
            <p class="text-xs text-gray-400">${subcats.length} subcategories found</p>
        </div>
        <div class="grid grid-cols-1 gap-3">
            ${subcats.map(sub => `
                <button onclick="filterBySubcat('${sub}')" class="p-4 bg-gray-50 rounded-2xl border border-gray-100 hover:border-brand-dark hover:bg-white transition text-left group flex justify-between items-center">
                    <h4 class="font-bold text-brand-dark text-sm group-hover:text-brand-accent transition">${sub}</h4>
                    <i class="fas fa-arrow-right text-gray-300 group-hover:text-brand-dark transition"></i>
                </button>
            `).join('')}
        </div>
    `;
}

function filterBySubcat(sub) {
    document.getElementById('categories-modal').classList.add('hidden');
    const filtered = products.filter(p => p.subcategory === sub || p.category === sub);
    if (filtered.length > 0) {
        renderProducts(filtered);
        document.getElementById('product-grid').scrollIntoView({ behavior: 'smooth' });
    } else {
        alert(`No products found for ${sub} yet.`);
    }
}


// AI SEARCH
function openAISearch() {
    document.getElementById('ai-search-modal').classList.remove('hidden');
    setTimeout(() => document.getElementById('ai-input').focus(), 100);
}

function handleAISearch(e) {
    e.preventDefault();
    const input = document.getElementById('ai-input');
    const query = input.value.trim();
    if (!query) return;

    // 1. User Bubble
    appendMessage(query, 'user');
    input.value = '';

    // 2. Thinking...
    const thinkingId = appendMessage('Thinking...', 'ai', true);

    // 3. Process Logic (Simulated Gemini)
    setTimeout(() => {
        document.getElementById(thinkingId).remove();
        const response = generateGeminiResponse(query);
        appendMessage(response.text, 'ai');

        if (response.products.length > 0) {
            appendProductCarousel(response.products);
        }
    }, 1500);
}

function appendMessage(text, sender, isThinking = false) {
    const box = document.getElementById('ai-chat-box');
    const id = 'msg-' + Date.now();
    const isAi = sender === 'ai';

    const div = document.createElement('div');
    div.id = id;
    div.className = `flex gap-3 items-start ${isAi ? '' : 'flex-row-reverse'}`;

    div.innerHTML = `
        <div class="w-8 h-8 rounded-full ${isAi ? 'bg-brand-dark' : 'bg-gray-200'} flex items-center justify-center ${isAi ? 'text-white' : 'text-gray-500'} text-xs shrink-0">
            <i class="fas ${isAi ? (isThinking ? 'fa-spinner fa-spin' : 'fa-robot') : 'fa-user'}"></i>
        </div>
        <div class="${isAi ? 'bg-white border border-gray-100' : 'bg-brand-dark text-white'} p-4 rounded-2xl ${isAi ? 'rounded-tl-none' : 'rounded-tr-none'} shadow-sm text-sm max-w-[80%]">
            ${text}
        </div>
    `;

    box.appendChild(div);
    box.scrollTop = box.scrollHeight;
    return id;
}

function appendProductCarousel(productsList) {
    const box = document.getElementById('ai-chat-box');
    const div = document.createElement('div');
    div.className = "flex gap-4 overflow-x-auto hide-scrollbar pb-2 pl-11"; // Indent for AI avatar alignment

    productsList.forEach((p, index) => {
        const productCard = document.createElement('div');
        productCard.className = "min-w-[140px] w-[140px] bg-white border border-gray-100 rounded-xl overflow-hidden shrink-0 cursor-pointer hover:shadow-md transition";
        productCard.onclick = () => openProduct(p);
        productCard.innerHTML = `
            <div class="h-24 bg-gray-50">
                <img src="${p.image || (p.images && p.images[0]) || ''}" class="w-full h-full object-cover mix-blend-multiply">
            </div>
            <div class="p-2">
                <h4 class="font-bold text-[10px] truncate">${p.name}</h4>
                <p class="text-[10px] text-brand-accent font-bold">₦${p.price.toLocaleString()}</p>
            </div>
        `;
        div.appendChild(productCard);
    });

    box.appendChild(div);
    box.scrollTop = box.scrollHeight;
}

function generateGeminiResponse(query) {
    const q = query.toLowerCase();

    // 1. High Priority Intents (Greetings, Identity)
    if (/(hi|hello|hey|greetings|morning|afternoon)/.test(q)) {
        return { text: "Hello! 👋 I'm your Ghadget AI. I can check our stock, prices, and recommend tech for you. Try asking about 'iPhones' or 'Laptops'.", products: [] };
    }

    if (/(who are you|what are you)/.test(q)) {
        return { text: "I am Ghadget's Gemini-Powered Assistant. I help you find the best deals in our store.", products: [] };
    }

    const allProducts = [...products, ...(JSON.parse(localStorage.getItem('ghadget_products')) || [])];

    // 2. RAG: Keyword Matching
    const matches = allProducts.filter(p => {
        return p.name.toLowerCase().includes(q) ||
            (p.category && p.category.toLowerCase().includes(q)) ||
            (p.description && p.description.toLowerCase().includes(q));
    }).slice(0, 5);

    if (matches.length > 0) {
        const phrases = [
            `I found ${matches.length} matches for "${query}". Check these out:`,
            `Here is what we have in stock for "${query}":`,
            `Top results from our inventory:`
        ];
        return {
            text: phrases[Math.floor(Math.random() * phrases.length)],
            products: matches
        };
    }

    return {
        text: "I couldn't find anything matching that description in our current inventory. Try broader terms like 'phones', 'audio', or 'setup'.",
        products: []
    };
}

// [Legacy AI Logic Removed to enable Gemini Integration]

function removeMessage(id) {
    const el = document.getElementById(id);
    if (el) el.remove();
}


// PRODUCT MODAL etc
function openProduct(p) {
    // Handle both object and ID string
    if (typeof p === 'string') {
        p = products.find(prod => prod.id === p);
    }
    if (!p) {
        console.error('Product not found');
        return;
    }

    const modalImg = document.getElementById('modal-img');
    const modalTitle = document.getElementById('modal-title');
    const modalPrice = document.getElementById('modal-price');
    const modalDesc = document.getElementById('modal-desc');
    const modalAddBtn = document.getElementById('modal-add-btn');
    const modalBuyBtn = document.getElementById('modal-buy-btn');

    if (modalImg) modalImg.src = p.image || (p.images && Array.isArray(p.images) && p.images[0]) || '';
    if (modalTitle) modalTitle.innerText = p.name || 'Unknown Product';
    if (modalPrice) modalPrice.innerText = new Intl.NumberFormat('en-NG', { style: 'currency', currency: 'NGN' }).format(p.price || 0);
    if (modalDesc) modalDesc.innerText = p.description || 'No description available.';

    // Add to cart button logic
    if (modalAddBtn) {
        modalAddBtn.onclick = () => { addToCart(null, p.id); };
    }
    if (modalBuyBtn) {
        modalBuyBtn.onclick = () => { buyNow(null, p.id); };
    }

    const modal = document.getElementById('product-modal');
    if (modal) modal.classList.remove('hidden');
}


// function openPaymentModal() { ... } // Removed duplicate
// function processCheckout() { ... } // Removed duplicate

function openServiceModal(svc) {
    // Populate service modal
    document.getElementById('svc-title').innerText = svc;
    document.getElementById('service-modal').classList.remove('hidden');
}

// DESKTOP CATEGORIES
function renderDesktopCategories() {
    const list = document.getElementById('desk-cat-list');
    if (!list) return;

    const cats = [
        { id: 'phones', name: 'Phones', icon: 'fa-mobile-alt' },
        { id: 'laptops', name: 'Laptops', icon: 'fa-laptop' },
        { id: 'audio', name: 'Audio', icon: 'fa-headphones' },
        { id: 'setup', name: 'Setup', icon: 'fa-desktop' },
        { id: 'accessories', name: 'Accessories', icon: 'fa-plug' }
    ];

    cats.forEach(c => {
        const btn = document.createElement('button');
        btn.className = "px-6 py-3 rounded-xl bg-white text-gray-500 font-bold shadow-sm hover:shadow-md hover:text-brand-dark hover:bg-gray-50 transition flex items-center gap-2 whitespace-nowrap border border-gray-100";
        btn.onclick = () => filterProducts(c.id);
        btn.innerHTML = `<i class="fas ${c.icon}"></i> ${c.name}`;
        list.appendChild(btn);
    });
}

// DEALS CATEGORIES (Special)
function renderDealsCategories() {
    const grid = document.getElementById('deals-cat-grid');
    if (!grid) return;

    const dealsCats = [
        { id: 'locked', name: 'Locked Devices', icon: 'fa-lock', style: 'bg-red-50 text-red-600 border-red-100' },
        { id: 'under-50k', name: '50k Below', icon: 'fa-tag', style: 'bg-blue-50 text-blue-600 border-blue-100' },
        { id: 'under-100k', name: '100k Below', icon: 'fa-tags', style: 'bg-indigo-50 text-indigo-600 border-indigo-100' },
        { id: 'nigeria-used', name: 'Nigeria Used', icon: 'fa-map-marker-alt', style: 'bg-green-50 text-green-600 border-green-100' },
        { id: 'cheap-offer', name: 'Cheap Offer', icon: 'fa-fire', style: 'bg-orange-50 text-orange-600 border-orange-100' }
    ];

    grid.innerHTML = '';
    dealsCats.forEach(c => {
        const div = document.createElement('div');
        div.className = `p-4 rounded-2xl border ${c.style} flex flex-col items-center justify-center gap-2 cursor-pointer hover:scale-105 transition shadow-sm h-28 lg:h-32`;
        div.onclick = () => {
            // Visual feedback
            Array.from(grid.children).forEach(child => child.classList.remove('ring-2', 'ring-offset-2', 'ring-brand-dark'));
            div.classList.add('ring-2', 'ring-offset-2', 'ring-brand-dark');
            filterProducts(c.id);
        };
        div.innerHTML = `
            <div class="w-10 h-10 rounded-full bg-white flex items-center justify-center shadow-sm">
                <i class="fas ${c.icon}"></i>
            </div>
            <span class="text-[10px] lg:text-xs font-bold uppercase tracking-wide text-center leading-tight">${c.name}</span>
        `;
        grid.appendChild(div);
    });
}

// Init Desktop


// Init Desktop
renderDesktopCategories();
renderDealsCategories(); // Init Deals Categories

// Ensure products load
document.addEventListener('DOMContentLoaded', () => {
    filterProducts('all');
    updateWalletUI(); // Init badges
    updateProfileUI(); // Init auth
    renderDealsCategories(); // Ensure render
    navigateToPage('home'); // Ensure correct initial state
});

// Make globally accessible
window.filterProducts = filterProducts;
window.addToCart = addToCart;
window.toggleSaved = toggleSaved;
window.renderDashboard = openDashboard;
window.openProduct = openProduct;
window.renderDesktopCategories = renderDesktopCategories;
window.renderDealsCategories = renderDealsCategories;
window.handleUserLogout = null; // Cleanup
window.userLogout = userLogout;
window.openAuthModal = openAuthModal;
window.switchAuth = switchAuth;
window.renderDashSaved = renderDashSaved;
window.renderDashCart = renderDashCart;
window.handleSignup = handleSignup;
window.handleSearch = handleSearch;
window.handleHeaderAvatarClick = handleHeaderAvatarClick;
window.switchDashTab = switchDashTab;
window.renderDashHistory = renderDashHistory;


