<?php
/**
 * GlowSpace - Front Controller
 * Production-safe error handling:
 * - Errors are logged to /logs/php-error.log, never shown to customers.
 * - Set GS_DEBUG=1 in config.php (local/dev only) to see errors on screen.
 */
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('display_startup_errors', '0');
ini_set('log_errors', '1');
$gsLogDir = __DIR__ . '/logs';
if (!is_dir($gsLogDir)) { @mkdir($gsLogDir, 0755, true); }
ini_set('error_log', $gsLogDir . '/php-error.log');

session_start();
ob_start();

// Load configuration and database
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/auth.php';

// If config.php defines GS_DEBUG (local/dev only), allow on-screen errors
if (defined('GS_DEBUG') && GS_DEBUG) {
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
}

// Catch fatal errors gracefully instead of a blank/500 page for customers
register_shutdown_function(function () {
    $err = error_get_last();
    if ($err && in_array($err['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) {
        error_log('[GlowSpace FATAL] ' . $err['message'] . ' in ' . $err['file'] . ':' . $err['line']);
        if (!headers_sent()) {
            http_response_code(500);
        }
        if (ob_get_length()) { @ob_end_clean(); }
        if (!(defined('GS_DEBUG') && GS_DEBUG)) {
            echo '<!DOCTYPE html><html><head><meta charset="utf-8"><title>GlowSpace - Temporarily Unavailable</title></head>'
               . '<body style="font-family:sans-serif;text-align:center;padding:80px 20px;">'
               . '<h1>Something went wrong</h1><p>We are working on it. Please try again shortly.</p>'
               . '<a href="/">Back to GlowSpace</a></body></html>';
        }
    }
});

// Initialize auth
auth()->getInstance();

// Load data from database
$settings = getSettings();
$categories = getCategories();
$products = getProducts(['status' => 1]);
$banners = getBanners();
$coupons = getCoupons();
$reviews = getReviews();

// Legacy function compatibility
function gsSanitize($str) {
    return sanitize($str);
}
function gsGenId($prefix='GS') {
    return generateId($prefix);
}
function gsValidIcon($icon, $default='fas fa-box') {
    return validIcon($icon, $default);
}
function gsRedirect($url) {
    redirect($url);
}
function gsImgUrl($path) {
    return imgUrl($path);
}

$gsIsAjax = (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])==='xmlhttprequest')
    || isset($_POST['action']) || isset($_GET['action']);
if($gsIsAjax) {
    header('Content-Type: application/json');
    $action = $_POST['action'] ?? $_GET['action'] ?? '';
    
    switch($action) {
        case 'search':
            $q = gsSanitize($_GET['q'] ?? '');
            $results = getProducts(['search' => $q, 'limit' => 10]);
            echo json_encode($results);
            exit;
        
        case 'add_to_cart':
            if(!auth()->validateCsrfToken($_POST['csrf_token'] ?? '')) {
                echo json_encode(['success'=>false,'msg'=>'Security error']); exit;
            }
            $pid = gsSanitize($_POST['product_id'] ?? '');
            $size = gsSanitize($_POST['size'] ?? '');
            $qty = max(1, intval($_POST['qty'] ?? 1));
            $product = getProductById($pid);
            if(!$product) { echo json_encode(['success'=>false,'msg'=>'Product not found']); exit; }
            
            // Add to session cart
            if(!isset($_SESSION['cart'])) $_SESSION['cart'] = [];
            $cartKey = $pid.'_'.$size;
            if(isset($_SESSION['cart'][$cartKey])) {
                $_SESSION['cart'][$cartKey]['qty'] += $qty;
            } else {
                $_SESSION['cart'][$cartKey] = [
                    'id'=>$pid, 'title'=>$product['title'], 'image'=>imgUrl($product['images'][0]??''),
                    'price'=>floatval($product['offer_price']??$product['price']),
                    'original_price'=>floatval($product['price']),
                    'size'=>$size, 'qty'=>$qty
                ];
            }
            
            // Sync to database if user is logged in
            if(auth()->isLoggedIn()) {
                $userId = $_SESSION['user_id'];
                $dbCart = db()->fetchOne("SELECT * FROM cart WHERE user_id = ? AND product_id = ? AND size = ?", [$userId, $pid, $size]);
                if($dbCart) {
                    db()->query("UPDATE cart SET quantity = quantity + ? WHERE id = ?", [$qty, $dbCart['id']]);
                } else {
                    Database::getInstance()->insert('cart', [
                        'user_id' => $userId,
                        'product_id' => $pid,
                        'product_title' => $product['title'],
                        'product_image' => imgUrl($product['images'][0]??''),
                        'price' => floatval($product['offer_price']??$product['price']),
                        'original_price' => floatval($product['price']),
                        'size' => $size,
                        'quantity' => $qty
                    ]);
                }
            }
            
            echo json_encode(['success'=>true,'cart_count'=>array_sum(array_column($_SESSION['cart'],'qty'))]);
            exit;
        
        case 'update_cart':
            $cartKey = gsSanitize($_POST['cart_key'] ?? '');
            $qty = max(0, intval($_POST['qty'] ?? 0));
            if($qty===0) { 
                unset($_SESSION['cart'][$cartKey]);
                // Remove from database if logged in
                if(auth()->isLoggedIn() && isset($_SESSION['cart'][$cartKey])) {
                    $item = $_SESSION['cart'][$cartKey];
                    db()->query("DELETE FROM cart WHERE user_id = ? AND product_id = ? AND size = ?", 
                        [$_SESSION['user_id'], $item['id'], $item['size']]);
                }
            }
            elseif(isset($_SESSION['cart'][$cartKey])) { 
                $_SESSION['cart'][$cartKey]['qty']=$qty;
                // Update database if logged in
                if(auth()->isLoggedIn()) {
                    $item = $_SESSION['cart'][$cartKey];
                    db()->query("UPDATE cart SET quantity = ? WHERE user_id = ? AND product_id = ? AND size = ?", 
                        [$qty, $_SESSION['user_id'], $item['id'], $item['size']]);
                }
            }
            echo json_encode(['success'=>true,'cart_count'=>array_sum(array_column($_SESSION['cart']??[],'qty'))]);
            exit;
        
        case 'remove_cart':
            $cartKey = gsSanitize($_POST['cart_key'] ?? '');
            if(isset($_SESSION['cart'][$cartKey])) {
                $item = $_SESSION['cart'][$cartKey];
                unset($_SESSION['cart'][$cartKey]);
                // Remove from database if logged in
                if(auth()->isLoggedIn()) {
                    db()->query("DELETE FROM cart WHERE user_id = ? AND product_id = ? AND size = ?", 
                        [$_SESSION['user_id'], $item['id'], $item['size']]);
                }
            }
            echo json_encode(['success'=>true,'cart_count'=>array_sum(array_column($_SESSION['cart']??[],'qty'))]);
            exit;
        
        case 'get_cart':
            $cartItems = [];
            $cartSub = 0;
            foreach($_SESSION['cart'] ?? [] as $ck => $ci) {
                $cartSub += $ci['price'] * $ci['qty'];
                $cartItems[] = [
                    'key' => $ck,
                    'title' => $ci['title'],
                    'image' => $ci['image'],
                    'price' => $ci['price'],
                    'qty' => $ci['qty'],
                    'size' => $ci['size'] ?? ''
                ];
            }
            echo json_encode([
                'success' => true,
                'items' => $cartItems,
                'subtotal' => round($cartSub, 2),
                'count' => array_sum(array_column($_SESSION['cart'] ?? [], 'qty')),
                'currency' => $settings['currency'] ?? '৳'
            ]);
            exit;
        
        case 'apply_coupon':
            $code = strtoupper(gsSanitize($_POST['code'] ?? ''));
            $coupon = null;
            foreach($coupons as $c) { if(strtoupper($c['code'])===$code && ($c['status']??1)==1) { $coupon=$c; break; } }
            if(!$coupon) { echo json_encode(['success'=>false,'msg'=>'Invalid coupon code']); exit; }
            if($coupon['expiry'] && strtotime($coupon['expiry'])<time()) { echo json_encode(['success'=>false,'msg'=>'Coupon expired']); exit; }
            $_SESSION['coupon'] = $coupon;
            echo json_encode(['success'=>true,'discount'=>$coupon['discount'],'type'=>$coupon['type']??'percent','msg'=>'Coupon applied!']);
            exit;
        
        case 'remove_coupon':
            unset($_SESSION['coupon']);
            echo json_encode(['success'=>true]);
            exit;
        
        case 'wishlist_toggle':
            if(!auth()->validateCsrfToken($_POST['csrf_token'] ?? '')) {
                echo json_encode(['success'=>false,'msg'=>'Security error']); exit;
            }
            $pid = gsSanitize($_POST['product_id'] ?? '');
            
            // Handle session wishlist for guests
            if(!isset($_SESSION['wishlist'])) $_SESSION['wishlist'] = [];
            $idx = array_search($pid, $_SESSION['wishlist']);
            
            if($idx!==false) { 
                unset($_SESSION['wishlist'][$idx]); 
                $_SESSION['wishlist']=array_values($_SESSION['wishlist']);
                
                // Remove from database if logged in
                if(auth()->isLoggedIn()) {
                    db()->query("DELETE FROM wishlist WHERE user_id = ? AND product_id = ?", [$_SESSION['user_id'], $pid]);
                }
                
                echo json_encode(['status'=>'removed']); 
            } else { 
                $_SESSION['wishlist'][]=$pid;
                
                // Add to database if logged in
                if(auth()->isLoggedIn()) {
                    Database::getInstance()->insert('wishlist', [
                        'user_id' => $_SESSION['user_id'],
                        'product_id' => $pid
                    ]);
                }
                
                echo json_encode(['status'=>'added']); 
            }
            exit;
        
        case 'submit_review':
            if(!auth()->validateCsrfToken($_POST['csrf_token'] ?? '')) {
                echo json_encode(['success'=>false,'msg'=>'Security error']); exit;
            }
            $rev = [
                'review_id'=>gsGenId('RV'), 
                'product_id'=>gsSanitize($_POST['product_id']??''),
                'user_id'=>auth()->isLoggedIn() ? $_SESSION['user_id'] : null,
                'name'=>gsSanitize($_POST['name']??''), 
                'rating'=>min(5,max(1,intval($_POST['rating']??5))),
                'text'=>gsSanitize($_POST['text']??''), 
                'status'=>0
            ];
            Database::getInstance()->insert('reviews', $rev);
            logActivity('review_submitted', "Review submitted for product: {$rev['product_id']}", $rev['user_id']);
            echo json_encode(['success'=>true,'msg'=>'Review submitted for approval']);
            exit;
        
        case 'contact':
            if(!auth()->validateCsrfToken($_POST['csrf_token'] ?? '')) {
                echo json_encode(['success'=>false,'msg'=>'Security error']); exit;
            }
            logActivity('contact_form', gsSanitize($_POST['name']??'').' - '.gsSanitize($_POST['email']??''));
            echo json_encode(['success'=>true,'msg'=>'Message sent successfully!']);
            exit;
        
        case 'newsletter':
            $email = gsSanitize($_POST['email']??'');
            if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo json_encode(['success'=>false,'msg'=>'Invalid email']); exit; }
            logActivity('newsletter_subscribe', $email);
            echo json_encode(['success'=>true,'msg'=>'Subscribed successfully!']);
            exit;
        
        case 'check_order':
            $oid = gsSanitize($_POST['order_id']??'');
            $order = getOrderById($oid);
            if(!$order) { echo json_encode(['success'=>false,'msg'=>'Order not found']); exit; }
            echo json_encode(['success'=>true,'order'=>['id'=>$order['order_id'],'status'=>$order['status'],'tracking'=>$order['tracking_number']??'','date'=>$order['created_at'],'total'=>$order['total']]]);
            exit;
        
        case 'place_order':
            if(!auth()->validateCsrfToken($_POST['csrf_token'] ?? '')) {
                echo json_encode(['success'=>false,'msg'=>'Security error']); exit;
            }
            if(empty($_SESSION['cart'])) { echo json_encode(['success'=>false,'msg'=>'Cart is empty']); exit; }
            
            $oid = gsGenId('ORD');
            $subtotal = 0;
            foreach($_SESSION['cart'] as $item) { $subtotal += $item['price'] * $item['qty']; }
            
            $discount = 0;
            if(isset($_SESSION['coupon'])) {
                $c = $_SESSION['coupon'];
                $discount = ($c['type']??'percent')==='percent' ? $subtotal*$c['discount']/100 : min($c['discount'], $subtotal);
            }
            $shipping = 120;
            $total = $subtotal - $discount + $shipping;
            
            $orderData = [
                'order_id' => $oid,
                'user_id' => auth()->isLoggedIn() ? $_SESSION['user_id'] : null,
                'customer_name' => gsSanitize($_POST['fullname']??''),
                'customer_phone' => gsSanitize($_POST['phone']??''),
                'customer_alt_phone' => gsSanitize($_POST['alt_phone']??''),
                'customer_email' => gsSanitize($_POST['email']??''),
                'customer_district' => gsSanitize($_POST['district']??''),
                'customer_upazila' => gsSanitize($_POST['upazila']??''),
                'customer_address' => gsSanitize($_POST['address']??''),
                'customer_postal' => gsSanitize($_POST['postal']??''),
                'subtotal' => round($subtotal,2),
                'discount' => round($discount,2),
                'shipping' => $shipping,
                'total' => round($total,2),
                'coupon_code' => $_SESSION['coupon']['code']??'',
                'status' => 'pending',
                'payment_status' => 'pending',
                'payment_method' => 'cod',
                'tracking_number' => ''
            ];
            
            // Prepare order items
            $orderItems = [];
            foreach($_SESSION['cart'] as $item) {
                $orderItems[] = [
                    'product_id' => $item['id'],
                    'product_title' => $item['title'],
                    'product_image' => $item['image'],
                    'price' => $item['price'],
                    'original_price' => $item['original_price'],
                    'size' => $item['size'],
                    'quantity' => $item['qty'],
                    'subtotal' => $item['price'] * $item['qty']
                ];
            }
            
            // Create order in database
            if(createOrder($orderData, $orderItems)) {
                logActivity('new_order', "Order placed: $oid", $orderData['user_id']);
                
                // Steadfast courier integration
                $tracking = '';
                $sfKey = STEADFAST_API_KEY;
                $sfSecret = STEADFAST_SECRET_KEY;
                $sfData = json_encode([
                    'invoice' => $oid,
                    'recipient_name' => $orderData['customer_name'],
                    'recipient_phone' => $orderData['customer_phone'],
                    'recipient_address' => $orderData['customer_address'].', '.$orderData['customer_upazila'].', '.$orderData['customer_district'],
                    'cod_amount' => round($total, 0),
                    'delivery_type' => 'regular',
                    'item_description' => implode(', ', array_map(function($i){return $i['product_title'].' x'.$i['quantity'];}, $orderItems))
                ]);
                
                $ch = curl_init(STEADFAST_API_URL);
                curl_setopt_array($ch, [
                    CURLOPT_POST => true,
                    CURLOPT_POSTFIELDS => $sfData,
                    CURLOPT_HTTPHEADER => [
                        'Content-Type: application/json',
                        'Api-Key: '.$sfKey,
                        'Secret-Key: '.$sfSecret
                    ],
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_SSL_VERIFYPEER => true,
                    CURLOPT_TIMEOUT => 15
                ]);
                $sfResp = curl_exec($ch);
                $sfErr = curl_error($ch);
                curl_close($ch);
                
                if($sfResp) {
                    $sfJson = json_decode($sfResp, true);
                    if(isset($sfJson['tracking_code'])) {
                        $tracking = $sfJson['tracking_code'];
                        updateOrderStatus($oid, 'confirmed', $tracking);
                        logActivity('steadfast_created', "Order $oid → $tracking", $orderData['user_id']);
                    } else {
                        logActivity('steadfast_error', "Order $oid: $sfResp", $orderData['user_id']);
                    }
                } else {
                    logActivity('steadfast_curl_error', "Order $oid: $sfErr", $orderData['user_id']);
                }
                
                // Clear cart and coupon
                unset($_SESSION['cart'], $_SESSION['coupon']);
                
                // Clear database cart if logged in
                if(auth()->isLoggedIn()) {
                    db()->query("DELETE FROM cart WHERE user_id = ?", [$_SESSION['user_id']]);
                }
                
                $_SESSION['last_order'] = ['id'=>$oid,'tracking'=>$tracking,'total'=>$total,'customer'=>$orderData,'items'=>$orderItems];
                echo json_encode(['success'=>true,'order_id'=>$oid]);
            } else {
                echo json_encode(['success'=>false,'msg'=>'Failed to create order']);
            }
            exit;
        
        default:
            echo json_encode(['error'=>'Invalid action']);
            exit;
    }
}

$rateKey = 'rl_'.md5($_SERVER['REMOTE_ADDR']??'localhost');
if(!isset($_SESSION[$rateKey])) $_SESSION[$rateKey] = ['count'=>0,'time'=>time()];
if(time()-$_SESSION[$rateKey]['time']>60) $_SESSION[$rateKey] = ['count'=>0,'time'=>time()];
$_SESSION[$rateKey]['count']++;
if($_SESSION[$rateKey]['count']>200) { http_response_code(429); exit('Too many requests'); }

$page = gsSanitize($_GET['page'] ?? 'home');
$slug = gsSanitize($_GET['slug'] ?? '');
$view = gsSanitize($_GET['view'] ?? '');

if($page==='product' && $slug) {
    $currentProduct = null;
    foreach($products as $p) { if(isset($p['slug']) && $p['slug']===$slug) { $currentProduct=$p; break; } }
    if(!$currentProduct) gsRedirect('index.php');
    if(!isset($_SESSION['recently_viewed'])) $_SESSION['recently_viewed'] = [];
    $_SESSION['recently_viewed'] = array_diff($_SESSION['recently_viewed'], [$currentProduct['id']]);
    array_unshift($_SESSION['recently_viewed'], $currentProduct['id']);
    if(count($_SESSION['recently_viewed'])>20) $_SESSION['recently_viewed'] = array_slice($_SESSION['recently_viewed'], 0, 20);
}

$cartCount = array_sum(array_column($_SESSION['cart']??[], 'qty'));
$wishlistCount = count($_SESSION['wishlist']??[]);
$csrfToken = $_SESSION['csrf_token'];

/**
 * Bangladesh District / Upazila data
 * Loaded from local /data JSON files (no external network dependency).
 * Safe loading: checks existence, handles decode errors, never warns on
 * the frontend, always falls back to an empty array.
 */
function gsLoadJsonData($relativePath) {
    $fullPath = __DIR__ . $relativePath;
    try {
        if (!is_file($fullPath) || !is_readable($fullPath)) {
            error_log("GlowSpace: data file missing or unreadable: $fullPath");
            return [];
        }
        $raw = @file_get_contents($fullPath);
        if ($raw === false || $raw === '') {
            error_log("GlowSpace: failed to read data file: $fullPath");
            return [];
        }
        $decoded = json_decode($raw, true);
        if (json_last_error() !== JSON_ERROR_NONE || !is_array($decoded)) {
            error_log("GlowSpace: invalid JSON in $fullPath - " . json_last_error_msg());
            return [];
        }
        return $decoded;
    } catch (Throwable $e) {
        error_log('GlowSpace: exception loading ' . $fullPath . ' - ' . $e->getMessage());
        return [];
    }
}

$bdDistricts = gsLoadJsonData('/data/districts.json');
$bdUpazilasRaw = gsLoadJsonData('/data/upazilas.json');

// Normalize upazilas to the flat {name, district} shape the checkout UI
// expects, regardless of whether the source JSON uses district_id (foreign
// key) or an already-flat district name.
$gsDistrictNameById = [];
foreach ($bdDistricts as $d) {
    if (isset($d['id'])) $gsDistrictNameById[(string)$d['id']] = $d['name'] ?? '';
}
$bdUpazilas = [];
foreach ($bdUpazilasRaw as $u) {
    $districtName = $u['district'] ?? ($gsDistrictNameById[(string)($u['district_id'] ?? '')] ?? '');
    if (!empty($u['name']) && $districtName !== '') {
        $bdUpazilas[] = ['name' => $u['name'], 'district' => $districtName];
    }
}

function gsSortProducts($prods, $sort='newest') {
    switch($sort) {
        case 'price_low': usort($prods, fn($a,$b)=>floatval($a['offer_price']??$a['price'])<=>floatval($b['offer_price']??$b['price'])); break;
        case 'price_high': usort($prods, fn($a,$b)=>floatval($b['offer_price']??$b['price'])<=>floatval($a['offer_price']??$a['price'])); break;
        case 'popular': usort($prods, fn($a,$b)=>($b['views']??0)<=>($a['views']??0)); break;
        case 'rating': usort($prods, fn($a,$b)=>($b['rating']??0)<=>($a['rating']??0)); break;
        default: usort($prods, fn($a,$b)=>strtotime($b['created']??'2024-01-01')<=>strtotime($a['created']??'2024-01-01'));
    }
    return $prods;
}

$activeProducts = array_filter($products, fn($p)=>($p['status']??1)==1);
$flashProducts = array_filter($activeProducts, fn($p)=>($p['flash_sale']??0)==1);
$newProducts = gsSortProducts(array_filter($activeProducts, fn($p)=>($p['is_new']??0)==1), 'newest');
$popularProducts = gsSortProducts(array_values($activeProducts), 'popular');
$allActiveProducts = gsSortProducts(array_values($activeProducts), 'newest');
$approvedReviews = array_filter($reviews, fn($r)=>($r['status']??0)==1);

$pageTitle = gsSanitize($settings['seo_title']??'GlowSpace');
if($page==='product' && $currentProduct) $pageTitle = gsSanitize($currentProduct['title']).' - GlowSpace';
elseif($page==='shop') $pageTitle = 'Shop All Products - GlowSpace';
elseif($page==='cart') $pageTitle = 'Shopping Cart - GlowSpace';
elseif($page==='checkout') $pageTitle = 'Checkout - GlowSpace';
elseif($page==='wishlist') $pageTitle = 'Wishlist - GlowSpace';
elseif($page==='contact') $pageTitle = 'Contact Us - GlowSpace';
elseif($page==='track') $pageTitle = 'Track Order - GlowSpace';

$productHasSizes = false;
if($page==='product' && $currentProduct) {
    $sizes = $currentProduct['sizes'] ?? [];
    if(is_string($sizes)) $sizes = json_decode($sizes, true) ?: [];
    $productHasSizes = !empty($sizes);
}
?>
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="description" content="<?=gsSanitize($settings['seo_description']??'')?>">
<meta name="keywords" content="<?=gsSanitize($settings['seo_keywords']??'')?>">
<meta property="og:title" content="<?=gsSanitize($pageTitle)?>">
<meta property="og:description" content="<?=gsSanitize($settings['seo_description']??'')?>">
<meta property="og:type" content="website">
<meta name="twitter:card" content="summary_large_image">
<title><?=gsSanitize($pageTitle)?></title>
<link rel="manifest" href="data:application/json,{}">
<meta name="theme-color" content="#0A0A1A">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
:root {
    --primary: #D4AF37;
    --primary-light: #E5C767;
    --primary-dark: #B8912A;
    --secondary: #F5A623;
    --accent: #FF4D6D;
    --accent-light: #FF6B85;
    --success: #10B981;
    --warning: #F59E0B;
    --bg: #0A0A1A;
    --bg2: #12121F;
    --bg3: #1A1A2E;
    --text: #FFFFFF;
    --text2: #B0B0C0;
    --text3: #7A7A90;
    --border: #2A2A3E;
    --border-light: #22223A;
    --shadow-sm: 0 1px 2px rgba(0,0,0,0.25);
    --shadow: 0 4px 16px rgba(0,0,0,0.35);
    --shadow-md: 0 6px 24px rgba(0,0,0,0.4);
    --shadow-lg: 0 12px 36px rgba(0,0,0,0.45);
    --shadow-xl: 0 20px 56px rgba(0,0,0,0.5), 0 8px 16px rgba(0,0,0,0.3);
    --radius-sm: 8px;
    --radius: 12px;
    --radius-lg: 20px;
    --radius-xl: 28px;
    --glass: rgba(26,26,46,0.55);
    --glass-border: rgba(212,175,55,0.18);
    --gradient: linear-gradient(135deg, #D4AF37 0%, #F5A623 100%);
    --gradient-warm: linear-gradient(135deg, #F5A623 0%, #FF8A5C 100%);
    --gradient-dark: linear-gradient(135deg, #0A0A1A 0%, #12121F 50%, #1A1A2E 100%);
    --transition-fast: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
    --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    --transition-slow: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
    --font: 'Inter', system-ui, -apple-system, sans-serif;
}
[data-theme="dark"] {
    --bg: #0A0A1A;
    --bg2: #12121F;
    --bg3: #1A1A2E;
    --text: #FFFFFF;
    --text2: #B0B0C0;
    --text3: #7A7A90;
    --border: #2A2A3E;
    --border-light: #22223A;
    --shadow-sm: 0 1px 2px rgba(0,0,0,0.3);
    --shadow: 0 4px 16px rgba(0,0,0,0.4);
    --shadow-md: 0 6px 24px rgba(0,0,0,0.45);
    --shadow-lg: 0 12px 36px rgba(0,0,0,0.5);
    --shadow-xl: 0 20px 56px rgba(0,0,0,0.6);
    --glass: rgba(18,18,31,0.7);
    --glass-border: rgba(212,175,55,0.22);
}
*,*::before,*::after { margin:0; padding:0; box-sizing:border-box; }
html { scroll-behavior:smooth; -webkit-text-size-adjust:100%; -webkit-tap-highlight-color:transparent; width:100%; overflow-x:hidden; }
body { font-family:var(--font); background:var(--bg); color:var(--text); line-height:1.6; overflow-x:hidden; width:100%; transition:background 0.3s, color 0.3s; -webkit-font-smoothing:antialiased; -moz-osx-font-smoothing:grayscale; animation:pageFadeIn 0.7s ease; }
@keyframes pageFadeIn { from{opacity:0} to{opacity:1} }
@keyframes fadeInUp { from{opacity:0; transform:translateY(24px);} to{opacity:1; transform:translateY(0);} }
.header, .hero { animation:fadeInUp 0.8s cubic-bezier(0.4,0,0.2,1) both; }
.hero { animation-delay:0.1s; }
a { text-decoration:none; color:inherit; transition:var(--transition-fast); }
img { max-width:100%; height:auto; display:block; }
button { cursor:pointer; border:none; background:none; font-family:inherit; transition:var(--transition-fast); }
input,select,textarea { font-family:inherit; transition:var(--transition-fast); font-size:16px; }
ul,ol { list-style:none; }
.container { max-width:1280px; margin:0 auto; padding:0 24px; width:100%; }
@media(max-width:768px) { .container { padding:0 16px; } }
@media(max-width:480px) { input,select,textarea,button { font-size:0.92rem; } }

/* === LOADER === */
#loader { position:fixed; inset:0; z-index:99999; background:var(--bg); display:flex; flex-direction:column; align-items:center; justify-content:center; transition:opacity 0.6s ease, visibility 0.6s ease; }
#loader.hide { opacity:0; visibility:hidden; pointer-events:none; }
.loader-brand { display:flex; align-items:center; gap:12px; margin-bottom:32px; }
.loader-brand img { width:42px; height:42px; object-fit:contain; }
.loader-brand span { font-size:1.8rem; font-weight:900; background:var(--gradient); -webkit-background-clip:text; -webkit-text-fill-color:transparent; background-clip:text; }
.loader-bar { width:180px; height:3px; background:var(--bg3); border-radius:10px; overflow:hidden; }
.loader-bar-inner { height:100%; width:0; background:var(--gradient); border-radius:10px; animation:loaderFill 1.8s ease forwards; }
@keyframes loaderFill { 0%{width:0} 100%{width:100%} }

/* === HEADER === */
.header { position:sticky; top:0; z-index:1000; background:var(--glass); backdrop-filter:blur(24px) saturate(180%); -webkit-backdrop-filter:blur(24px) saturate(180%); border-bottom:1px solid var(--glass-border); transition:var(--transition); }
.header.scrolled { box-shadow:var(--shadow-md); }
.header-top-bar { background:var(--gradient-dark); color:rgba(255,255,255,0.9); font-size:0.78rem; padding:7px 0; text-align:center; font-weight:500; letter-spacing:0.3px; }
.header-top-bar span { color:var(--secondary); font-weight:700; }
.header-main { display:flex; align-items:center; justify-content:space-between; padding:14px 0; gap:20px; }
.logo { display:flex; align-items:center; gap:10px; flex-shrink:0; text-decoration:none; }
.logo img { width:38px; height:38px; object-fit:contain; filter:drop-shadow(0 2px 8px rgba(212,175,55,0.3)); }
.logo-text { font-size:1.5rem; font-weight:900; background:var(--gradient); -webkit-background-clip:text; -webkit-text-fill-color:transparent; background-clip:text; letter-spacing:-0.5px; }
.search-box { flex:1; max-width:540px; position:relative; }
.search-box input { width:100%; padding:11px 50px 11px 20px; border:2px solid var(--border); border-radius:50px; background:var(--bg2); color:var(--text); font-size:0.9rem; font-weight:500; outline:none; transition:var(--transition); }
.search-box input::placeholder { color:var(--text3); font-weight:400; }
.search-box input:focus { border-color:var(--primary); box-shadow:0 0 0 4px rgba(212,175,55,0.08); }
.search-box .search-btn { position:absolute; right:5px; top:50%; transform:translateY(-50%); width:40px; height:40px; background:var(--gradient); border-radius:50%; color:#0A0A1A; font-size:0.9rem; display:flex; align-items:center; justify-content:center; box-shadow:0 2px 10px rgba(212,175,55,0.3); }
.search-box .search-btn:hover { transform:translateY(-50%) scale(1.05); }
.search-results { position:absolute; top:calc(100% + 8px); left:0; right:0; background:var(--bg2); border:1px solid var(--border); border-radius:var(--radius-lg); box-shadow:var(--shadow-xl); max-height:420px; overflow-y:auto; display:none; z-index:200; }
.search-results.active { display:block; animation:dropIn 0.25s ease; }
@keyframes dropIn { from{opacity:0;transform:translateY(-8px)} to{opacity:1;transform:translateY(0)} }
.search-result-item { display:flex; align-items:center; gap:14px; padding:12px 18px; cursor:pointer; transition:var(--transition-fast); border-bottom:1px solid var(--border-light); }
.search-result-item:last-child { border-bottom:none; }
.search-result-item:hover { background:var(--bg3); }
.search-result-item img { width:48px; height:48px; object-fit:cover; border-radius:var(--radius-sm); background:var(--bg3); }
.sr-info h4 { font-size:0.88rem; font-weight:700; line-height:1.3; margin-bottom:2px; }
.sr-info span { font-size:0.82rem; color:var(--primary); font-weight:800; }
.sr-info .sr-cat { font-size:0.75rem; color:var(--text3); font-weight:500; }
.search-empty { padding:32px 18px; text-align:center; color:var(--text3); font-size:0.9rem; }
.search-empty i { font-size:2rem; margin-bottom:8px; display:block; opacity:0.5; }
.header-actions { display:flex; align-items:center; gap:4px; }
.hdr-btn { width:42px; height:42px; border-radius:50%; display:flex; align-items:center; justify-content:center; color:var(--text2); font-size:1.1rem; position:relative; transition:var(--transition-fast); }
.hdr-btn:hover { background:var(--bg3); color:var(--primary); }
.hdr-btn .badge { position:absolute; top:3px; right:3px; min-width:18px; height:18px; background:var(--accent); color:#fff; font-size:0.65rem; font-weight:800; border-radius:50%; display:flex; align-items:center; justify-content:center; padding:0 4px; border:2px solid var(--bg2); }
.hdr-divider { width:1px; height:24px; background:var(--border); margin:0 6px; }

/* Hamburger */
.hamburger { display:none; flex-direction:column; justify-content:center; align-items:center; width:42px; height:42px; border-radius:50%; cursor:pointer; gap:5px; transition:var(--transition-fast); }
.hamburger:hover { background:var(--bg3); }
.hamburger span { display:block; width:20px; height:2px; background:var(--text); border-radius:2px; transition:var(--transition); transform-origin:center; }
.hamburger.active span:nth-child(1) { transform:translateY(7px) rotate(45deg); }
.hamburger.active span:nth-child(2) { opacity:0; transform:scaleX(0); }
.hamburger.active span:nth-child(3) { transform:translateY(-7px) rotate(-45deg); }
@media(max-width:960px) {
    .search-box { display:none; }
    .hamburger { display:flex; }
    .header-actions .hdr-btn.theme-btn { display:none; }
}

/* Mobile Menu — Premium Slide Drawer */
.mobile-menu { position:fixed; top:0; left:0; bottom:0; width:48%; min-width:260px; max-width:340px; z-index:2000; background:var(--bg); transform:translateX(-100%); transition:transform 0.4s cubic-bezier(0.32, 0.72, 0, 1); overflow-y:auto; -webkit-overflow-scrolling:touch; box-shadow:0 0 40px rgba(0,0,0,0.2); border-radius:0 20px 20px 0; }
@media(max-width:360px) { .mobile-menu { width:78%; min-width:0; } }
.mobile-menu.open { transform:translateX(0); }
.mobile-menu-overlay { position:fixed; inset:0; z-index:1999; background:rgba(15,17,26,0.55); backdrop-filter:blur(3px); opacity:0; visibility:hidden; transition:var(--transition); }
.mobile-menu-overlay.open { opacity:1; visibility:visible; }
.mm-header { display:flex; align-items:center; justify-content:space-between; padding:18px 16px; border-bottom:1px solid var(--border); }
.mm-logo { display:flex; align-items:center; gap:8px; }
.mm-logo img { width:28px; height:28px; object-fit:contain; }
.mm-logo span { font-size:1.1rem; font-weight:900; background:var(--gradient); -webkit-background-clip:text; -webkit-text-fill-color:transparent; background-clip:text; }
.mm-close { width:34px; height:34px; flex-shrink:0; border-radius:50%; background:var(--bg3); display:flex; align-items:center; justify-content:center; font-size:0.95rem; color:var(--text2); transition:var(--transition-fast); }
.mm-close:hover { background:var(--accent); color:#fff; }
.mm-body { padding:14px 14px 32px; }
.mm-search { margin-bottom:18px; position:relative; }
.mm-search input { width:100%; padding:11px 36px 11px 14px; border:2px solid var(--border); border-radius:var(--radius); background:var(--bg2); color:var(--text); font-size:16px; font-weight:500; outline:none; }
.mm-search input:focus { border-color:var(--primary); }
.mm-search i { position:absolute; right:12px; top:50%; transform:translateY(-50%); color:var(--text3); font-size:0.85rem; }
.mm-nav { display:flex; flex-direction:column; gap:2px; }
.mm-nav a { display:flex; align-items:center; gap:12px; padding:11px 12px; border-radius:var(--radius); font-size:0.86rem; font-weight:600; color:var(--text2); transition:var(--transition-fast); }
.mm-nav a:hover, .mm-nav a.active { background:var(--bg3); color:var(--primary); }
.mm-nav a i { width:18px; text-align:center; font-size:0.9rem; flex-shrink:0; }
.mm-nav a.active i { color:var(--primary); }
.mm-divider { height:1px; background:var(--border); margin:14px 0; }
.mm-bottom { display:flex; gap:6px; flex-wrap:wrap; }
.mm-bottom a { flex:1; min-width:calc(50% - 3px); display:flex; align-items:center; justify-content:center; gap:6px; padding:10px 6px; border-radius:var(--radius); background:var(--bg3); font-size:0.76rem; font-weight:600; color:var(--text2); text-align:center; }
.mm-bottom a:hover { color:var(--primary); background:rgba(212,175,55,0.08); }
.mm-bottom a i { font-size:0.8rem; }

/* Cart Drawer — Premium Slide Panel */
.cart-drawer { position:fixed; top:0; right:0; bottom:0; width:48%; min-width:280px; max-width:400px; z-index:2100; background:var(--bg); transform:translateX(100%); transition:transform 0.4s cubic-bezier(0.32, 0.72, 0, 1); box-shadow:0 0 40px rgba(0,0,0,0.2); border-radius:20px 0 0 20px; display:flex; flex-direction:column; }
@media(max-width:360px) { .cart-drawer { width:88%; min-width:0; } }
.cart-drawer.open { transform:translateX(0); }
.cart-drawer-overlay { position:fixed; inset:0; z-index:2099; background:rgba(15,17,26,0.55); backdrop-filter:blur(3px); opacity:0; visibility:hidden; transition:var(--transition); }
.cart-drawer-overlay.open { opacity:1; visibility:visible; }
.cd-header { display:flex; align-items:center; justify-content:space-between; padding:18px 16px; border-bottom:1px solid var(--border); flex-shrink:0; }
.cd-header h3 { font-size:1rem; font-weight:800; display:flex; align-items:center; gap:8px; }
.cd-close { width:34px; height:34px; flex-shrink:0; border-radius:50%; background:var(--bg3); display:flex; align-items:center; justify-content:center; font-size:0.95rem; color:var(--text2); transition:var(--transition-fast); }
.cd-close:hover { background:var(--accent); color:#fff; }
.cd-body { flex:1; overflow-y:auto; -webkit-overflow-scrolling:touch; padding:12px; }
.cd-item { display:flex; gap:10px; padding:10px 6px; border-bottom:1px solid var(--border-light); }
.cd-item img { width:56px; height:56px; object-fit:cover; border-radius:var(--radius-sm); background:var(--bg3); flex-shrink:0; }
.cd-item-info { flex:1; min-width:0; }
.cd-item-info h4 { font-size:0.8rem; font-weight:700; line-height:1.3; margin-bottom:4px; overflow:hidden; text-overflow:ellipsis; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; }
.cd-item-info .cd-price { font-size:0.82rem; font-weight:800; color:var(--primary); }
.cd-item-qty { display:inline-flex; align-items:center; border:1.5px solid var(--border); border-radius:8px; margin-top:6px; }
.cd-item-qty button { width:24px; height:24px; font-size:0.7rem; display:flex; align-items:center; justify-content:center; color:var(--text); background:var(--bg3); }
.cd-item-qty span { width:26px; text-align:center; font-size:0.78rem; font-weight:700; }
.cd-remove { width:26px; height:26px; flex-shrink:0; border-radius:50%; background:rgba(255,77,109,0.08); color:var(--accent); display:flex; align-items:center; justify-content:center; font-size:0.72rem; align-self:flex-start; }
.cd-remove:hover { background:var(--accent); color:#fff; }
.cd-empty { text-align:center; padding:60px 16px; color:var(--text3); }
.cd-empty i { font-size:2.4rem; opacity:0.35; margin-bottom:12px; display:block; }
.cd-footer { padding:14px 16px 18px; border-top:1px solid var(--border); flex-shrink:0; background:var(--bg2); }
.cd-subtotal { display:flex; justify-content:space-between; font-size:0.95rem; font-weight:800; margin-bottom:12px; }
.cd-subtotal span:last-child { color:var(--primary); font-size:1.1rem; }
.cd-footer .btn-checkout { display:flex; align-items:center; justify-content:center; gap:8px; }
.cd-viewcart { display:block; text-align:center; margin-top:8px; font-size:0.8rem; font-weight:700; color:var(--text2); padding:8px; }
.cd-viewcart:hover { color:var(--primary); }

/* === HERO SLIDER === */
.hero { position:relative; overflow:hidden; }
.hero-slider { display:flex; transition:transform 0.7s cubic-bezier(0.4, 0, 0.2, 1); will-change:transform; }
.hero-slide { min-width:100%; position:relative; }
.hero-slide img { width:100%; display:block; }
.hero-dots { position:absolute; bottom:20px; left:50%; transform:translateX(-50%); display:flex; gap:8px; z-index:10; }
.hero-dot { width:10px; height:10px; border-radius:50%; background:rgba(255,255,255,0.4); cursor:pointer; transition:var(--transition); border:none; }
.hero-dot.active { background:#fff; width:28px; border-radius:5px; }
.hero-arrows { position:absolute; top:50%; width:100%; display:flex; justify-content:space-between; padding:0 16px; transform:translateY(-50%); z-index:10; pointer-events:none; }
.hero-arrow { pointer-events:all; width:44px; height:44px; border-radius:50%; background:rgba(255,255,255,0.15); backdrop-filter:blur(10px); color:#fff; font-size:1rem; display:flex; align-items:center; justify-content:center; transition:var(--transition); border:1px solid rgba(255,255,255,0.2); }
.hero-arrow:hover { background:rgba(255,255,255,0.3); transform:scale(1.08); }
@media(max-width:640px) { .hero-arrows { display:none; } }

/* === SECTION === */
.section { padding:56px 0; }
@media(max-width:768px) { .section { padding:36px 0; } }
.section-head { display:flex; align-items:flex-end; justify-content:space-between; margin-bottom:28px; gap:16px; flex-wrap:wrap; }
.section-head h2 { font-size:clamp(1.4rem, 2.5vw, 1.9rem); font-weight:900; letter-spacing:-0.3px; line-height:1.2; }
.section-head h2 .highlight { background:var(--gradient); -webkit-background-clip:text; -webkit-text-fill-color:transparent; background-clip:text; }
.section-head a { color:var(--primary); font-weight:700; font-size:0.88rem; display:flex; align-items:center; gap:6px; transition:var(--transition-fast); }
.section-head a:hover { gap:10px; color:var(--primary-dark); }

/* === CATEGORIES === */
.cat-grid { display:flex; gap:8px; overflow-x:auto; padding:4px 2px 8px; scroll-snap-type:x proximity; -webkit-overflow-scrolling:touch; }
.cat-grid::-webkit-scrollbar { height:3px; }
.cat-grid::-webkit-scrollbar-thumb { background:var(--border); border-radius:3px; }
@media(min-width:900px) { .cat-grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(64px, 1fr)); overflow:visible; padding:2px; gap:10px; } }
.cat-card { flex:0 0 auto; min-width:58px; scroll-snap-align:start; background:var(--bg2); border-radius:10px; padding:8px 4px 7px; text-align:center; box-shadow:var(--shadow-sm); border:1px solid var(--border-light); transition:var(--transition); cursor:pointer; position:relative; overflow:hidden; }
.cat-card:hover { border-color:var(--primary); transform:translateY(-2px); box-shadow:var(--shadow-md); }
.cat-icon-circle { width:26px; height:26px; border-radius:50%; background:rgba(212,175,55,0.08); display:flex; align-items:center; justify-content:center; margin:0 auto 5px; transition:var(--transition); }
.cat-card:hover .cat-icon-circle { background:var(--gradient); }
.cat-card i { font-size:0.68rem; color:var(--primary); display:block; transition:var(--transition); }
.cat-card:hover i { color:#fff; transform:scale(1.1); }
.cat-card h3 { font-size:0.62rem; font-weight:700; line-height:1.2; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }

/* === FLASH SALE === */
.flash-sale { background:var(--gradient-dark); color:#fff; border-radius:var(--radius-xl); padding:32px; margin:40px 0; position:relative; overflow:hidden; }
.flash-sale::before { content:''; position:absolute; top:-60%; right:-15%; width:400px; height:400px; background:radial-gradient(circle, rgba(212,175,55,0.25), transparent 70%); border-radius:50%; pointer-events:none; }
.flash-sale::after { content:''; position:absolute; bottom:-40%; left:-10%; width:300px; height:300px; background:radial-gradient(circle, rgba(245,166,35,0.15), transparent 70%); border-radius:50%; pointer-events:none; }
.flash-header { display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:16px; margin-bottom:24px; position:relative; z-index:1; }
.flash-header h2 { font-size:1.6rem; font-weight:900; display:flex; align-items:center; gap:10px; }
.flash-header h2 i { color:var(--primary); font-size:1.3rem; animation:flashPulse 1s ease infinite; }
@keyframes flashPulse { 0%,100%{transform:scale(1)} 50%{transform:scale(1.2)} }
.countdown { display:flex; gap:8px; }
.countdown-item { background:rgba(212,175,55,0.1); backdrop-filter:blur(10px); padding:8px 12px; border-radius:var(--radius-sm); text-align:center; min-width:52px; border:1px solid rgba(212,175,55,0.25); }
.countdown-item .num { font-size:1.3rem; font-weight:900; display:block; line-height:1; color:var(--primary); }
.countdown-item .label { font-size:0.62rem; text-transform:uppercase; opacity:0.6; letter-spacing:1px; margin-top:3px; display:block; }
.flash-scroll { display:flex; gap:16px; overflow-x:auto; padding-bottom:12px; scroll-snap-type:x mandatory; -webkit-overflow-scrolling:touch; position:relative; z-index:1; }
.flash-scroll::-webkit-scrollbar { height:4px; }
.flash-scroll::-webkit-scrollbar-track { background:rgba(255,255,255,0.05); border-radius:4px; }
.flash-scroll::-webkit-scrollbar-thumb { background:var(--primary); border-radius:4px; }

/* === PRODUCT CARD === */
.product-card { background:var(--glass); backdrop-filter:blur(18px) saturate(140%); -webkit-backdrop-filter:blur(18px) saturate(140%); border-radius:var(--radius-lg); overflow:hidden; box-shadow:var(--shadow-sm); transition:var(--transition); scroll-snap-align:start; position:relative; display:flex; flex-direction:column; border:1px solid var(--glass-border); }
.product-card:hover { transform:translateY(-6px); box-shadow:var(--shadow-xl), 0 0 0 1px rgba(212,175,55,0.25); border-color:var(--primary); }
.product-card .badge-area { position:absolute; top:12px; left:12px; display:flex; flex-direction:column; gap:5px; z-index:5; }
.p-badge { padding:4px 10px; border-radius:20px; font-size:0.66rem; font-weight:800; text-transform:uppercase; letter-spacing:0.5px; box-shadow:0 2px 6px rgba(0,0,0,0.15); }
.p-badge.hot { background:var(--gradient-warm); color:#fff; }
.p-badge.new { background:var(--secondary); color:#0F172A; }
.p-badge.sale { background:var(--success); color:#fff; }
.p-badge.limited { background:var(--warning); color:#0F172A; }
.product-card .card-actions { position:absolute; top:12px; right:12px; display:flex; flex-direction:column; gap:6px; z-index:5; opacity:0; transform:translateX(10px); transition:var(--transition); }
.product-card:hover .card-actions { opacity:1; transform:translateX(0); }
.p-action-btn { width:34px; height:34px; border-radius:50%; background:rgba(26,26,46,0.85); backdrop-filter:blur(8px); display:flex; align-items:center; justify-content:center; font-size:0.82rem; color:var(--text2); box-shadow:var(--shadow); border:1px solid var(--glass-border); }
.p-action-btn:hover { background:var(--primary); color:#0A0A1A; transform:scale(1.1); border-color:var(--primary); }
.p-action-btn.wishlisted { color:var(--accent); }
.product-card .card-image { position:relative; aspect-ratio:1; background:var(--bg3); overflow:hidden; }
.product-card .card-image img { width:100%; height:100%; object-fit:cover; transition:transform 0.6s cubic-bezier(0.4, 0, 0.2, 1); }
.product-card:hover .card-image img { transform:scale(1.1); }
.product-card .card-info { padding:14px 16px 16px; flex:1; display:flex; flex-direction:column; }
.product-card .card-info .brand { font-size:0.7rem; color:var(--secondary); text-transform:uppercase; letter-spacing:1.2px; font-weight:700; margin-bottom:4px; }
.product-card .card-info h3 { font-size:1rem; font-weight:700; line-height:1.4; margin-bottom:8px; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden; flex:1; color:var(--text); }
.product-card .price-row { display:flex; align-items:baseline; gap:8px; margin-bottom:4px; flex-wrap:wrap; }
.product-card .price { font-size:1.25rem; font-weight:800; color:var(--primary); letter-spacing:-0.2px; }
.product-card .original { font-size:0.8rem; color:var(--text2); text-decoration:line-through; font-weight:500; }
.product-card .discount-tag { font-size:0.66rem; background:rgba(255,77,109,0.1); color:var(--accent); padding:2px 8px; border-radius:20px; font-weight:800; }
.product-card .stock-info { font-size:0.72rem; margin:6px 0 10px; color:var(--text3); display:flex; align-items:center; gap:4px; }
.stock-low { color:var(--accent)!important; font-weight:700; }
.product-card .card-btns { display:flex; gap:8px; }
.product-card .btn-add-cart { flex:1; padding:9px 12px; background:var(--gradient); color:#0A0A1A; font-weight:700; font-size:0.78rem; border-radius:var(--radius-sm); display:flex; align-items:center; justify-content:center; gap:6px; transition:var(--transition-fast); box-shadow:0 3px 10px rgba(212,175,55,0.25); }
.product-card .btn-add-cart:hover { transform:translateY(-2px); box-shadow:0 6px 16px rgba(212,175,55,0.35); }
.product-card .btn-order-now { flex:1; padding:9px 12px; background:var(--bg3); color:var(--text); font-weight:700; font-size:0.78rem; border-radius:var(--radius-sm); display:flex; align-items:center; justify-content:center; gap:6px; transition:var(--transition-fast); border:1px solid var(--border); }
.product-card .btn-order-now:hover { background:var(--primary); color:#0A0A1A; border-color:var(--primary); transform:translateY(-2px); }

/* Product Grid */
.product-grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(230px, 1fr)); gap:20px; }
@media(max-width:768px) { .product-grid { grid-template-columns:repeat(2, 1fr); gap:12px; } }
@media(max-width:400px) { .product-grid { grid-template-columns:repeat(2, 1fr); gap:10px; } .product-card .card-btns { flex-direction:column; } }

/* Flash card overrides */
.flash-scroll .product-card { min-width:210px; max-width:240px; flex-shrink:0; }
@media(max-width:640px) { .flash-scroll .product-card { min-width:175px; max-width:195px; } .flash-scroll .product-card .card-btns { flex-direction:column; } }

/* === OFFER BANNER === */
.offer-banner { background:var(--gradient); border-radius:var(--radius-xl); padding:48px 56px; color:#0A0A1A; position:relative; overflow:hidden; display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:24px; }
.offer-banner::before { content:''; position:absolute; right:-60px; top:-60px; width:280px; height:280px; background:rgba(255,255,255,0.08); border-radius:50%; }
.offer-banner::after { content:''; position:absolute; left:30%; bottom:-80px; width:200px; height:200px; background:rgba(255,255,255,0.05); border-radius:50%; }
.offer-banner h2 { font-size:clamp(1.4rem, 3vw, 2rem); font-weight:900; position:relative; z-index:1; }
.offer-banner p { opacity:0.9; position:relative; z-index:1; margin-top:4px; }
.offer-banner .offer-btn { background:#fff; color:var(--primary); padding:14px 32px; border-radius:50px; font-weight:800; position:relative; z-index:1; font-size:0.95rem; transition:var(--transition-fast); box-shadow:0 4px 20px rgba(0,0,0,0.15); }
.offer-banner .offer-btn:hover { transform:translateY(-2px); box-shadow:0 8px 30px rgba(0,0,0,0.2); }
@media(max-width:640px) { .offer-banner { padding:32px 24px; text-align:center; justify-content:center; } }

/* === REVIEWS === */
.reviews-grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(280px, 1fr)); gap:20px; }
.review-card { background:var(--bg2); border-radius:var(--radius-lg); padding:24px; box-shadow:var(--shadow-sm); border:1px solid var(--border-light); transition:var(--transition); }
.review-card:hover { box-shadow:var(--shadow-md); }
.review-card .stars { color:var(--warning); margin-bottom:10px; font-size:0.85rem; letter-spacing:2px; }
.review-card .text { color:var(--text2); font-size:0.9rem; line-height:1.7; margin-bottom:14px; font-style:italic; }
.review-card .author { display:flex; align-items:center; gap:10px; }
.review-card .avatar { width:38px; height:38px; border-radius:50%; background:var(--gradient); display:flex; align-items:center; justify-content:center; color:#0A0A1A; font-weight:800; font-size:0.85rem; flex-shrink:0; }
.review-card .author-info .name { font-weight:700; font-size:0.88rem; }
.review-card .author-info .date { font-size:0.75rem; color:var(--text3); }

/* === NEWSLETTER === */
.newsletter { background:var(--bg2); border-radius:var(--radius-xl); padding:48px 32px; text-align:center; box-shadow:var(--shadow-sm); border:1px solid var(--border-light); position:relative; overflow:hidden; }
.newsletter::before { content:''; position:absolute; top:0; left:0; right:0; height:3px; background:var(--gradient); }
.newsletter h2 { font-size:1.5rem; font-weight:900; margin-bottom:6px; }
.newsletter p { color:var(--text2); margin-bottom:24px; font-size:0.92rem; }
.newsletter-form { display:flex; max-width:460px; margin:0 auto; gap:8px; }
.newsletter-form input { flex:1; padding:14px 20px; border:2px solid var(--border); border-radius:50px; background:var(--bg); color:var(--text); font-size:0.92rem; outline:none; font-weight:500; }
.newsletter-form input:focus { border-color:var(--primary); }
.newsletter-form button { padding:14px 28px; background:var(--gradient); color:#0A0A1A; font-weight:700; border-radius:50px; white-space:nowrap; font-size:0.92rem; box-shadow:0 4px 15px rgba(212,175,55,0.3); }
.newsletter-form button:hover { transform:translateY(-1px); box-shadow:0 6px 20px rgba(212,175,55,0.4); }
@media(max-width:640px) { .newsletter-form { flex-direction:column; } .newsletter-form button { width:100%; } }

/* === FOOTER === */
.footer { background:var(--bg2); border-top:1px solid var(--border); padding:56px 0 0; position:relative; }
.footer::before { content:''; position:absolute; top:-1px; left:0; right:0; height:3px; background:var(--gradient); }
.footer-grid { display:grid; grid-template-columns:2fr 1fr 1fr 1fr; gap:40px; margin-bottom:40px; }
@media(max-width:900px) { .footer-grid { grid-template-columns:1fr 1fr; } }
@media(max-width:640px) { .footer-grid { grid-template-columns:1fr; gap:28px; } }
.footer-col h4 { font-size:0.95rem; font-weight:800; margin-bottom:18px; position:relative; padding-bottom:12px; letter-spacing:-0.2px; }
.footer-col h4::after { content:''; position:absolute; bottom:0; left:0; width:28px; height:3px; background:var(--gradient); border-radius:3px; }
.footer-col p { color:var(--text2); font-size:0.86rem; line-height:1.7; margin-bottom:16px; }
.footer-col ul li { margin-bottom:10px; }
.footer-col ul li a { color:var(--text2); font-size:0.86rem; display:flex; align-items:center; gap:8px; font-weight:500; }
.footer-col ul li a:hover { color:var(--primary); padding-left:4px; }
.footer-col ul li a i { font-size:0.7rem; opacity:0.5; }
.social-links { display:flex; gap:8px; flex-wrap:wrap; }
.social-link { width:38px; height:38px; border-radius:var(--radius-sm); background:var(--bg3); display:flex; align-items:center; justify-content:center; color:var(--text2); font-size:0.95rem; transition:var(--transition-fast); }
.social-link:hover { background:var(--primary); color:#0A0A1A; transform:translateY(-3px); box-shadow:0 4px 12px rgba(212,175,55,0.3); }
.footer-bottom { border-top:1px solid var(--border); padding:18px 0; display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:12px; font-size:0.8rem; color:var(--text3); }
.footer-bottom a { color:var(--text3); }
.footer-bottom a:hover { color:var(--primary); }

/* === PRODUCT DETAIL === */
.pd-wrap { display:grid; grid-template-columns:1fr 1fr; gap:48px; padding:32px 0; max-width:100%; }
@media(max-width:960px) { .pd-wrap { grid-template-columns:1fr; gap:24px; padding:20px 0; } }
.pd-gallery { position:sticky; top:90px; min-width:0; }
@media(max-width:960px) { .pd-gallery { position:static; } }
.pd-main-img { width:100%; max-width:100%; aspect-ratio:1; background:var(--bg2); border-radius:var(--radius-lg); overflow:hidden; margin-bottom:12px; touch-action:pan-y; border:1px solid var(--border-light); }
.pd-main-img img { width:100%; height:100%; object-fit:contain; background:var(--bg2); }
.pd-thumbs { display:flex; gap:8px; overflow-x:auto; padding-bottom:4px; -webkit-overflow-scrolling:touch; scroll-snap-type:x proximity; }
.pd-thumbs::-webkit-scrollbar { height:3px; }
.pd-thumbs::-webkit-scrollbar-thumb { background:var(--border); border-radius:3px; }
.pd-thumb { width:64px; height:64px; flex-shrink:0; border-radius:var(--radius-sm); overflow:hidden; border:2px solid transparent; cursor:pointer; opacity:0.5; transition:var(--transition-fast); scroll-snap-align:start; background:var(--bg2); }
.pd-thumb.active, .pd-thumb:hover { border-color:var(--primary); opacity:1; }
.pd-thumb img { width:100%; height:100%; object-fit:cover; }
.pd-info { min-width:0; max-width:100%; }
.pd-info h1 { font-size:clamp(1.15rem, 4vw, 1.7rem); font-weight:900; line-height:1.3; margin-bottom:8px; letter-spacing:-0.3px; word-wrap:break-word; overflow-wrap:break-word; }
.pd-info .pd-brand { color:var(--primary); font-weight:700; font-size:0.88rem; margin-bottom:12px; }
.pd-info .pd-rating { display:flex; align-items:center; gap:8px; margin-bottom:16px; font-size:0.88rem; flex-wrap:wrap; }
.pd-info .pd-rating .stars { color:var(--warning); }
.pd-info .pd-rating span { color:var(--text3); }
.pd-price-box { background:var(--bg3); border-radius:var(--radius); padding:16px 20px; margin-bottom:20px; display:flex; align-items:baseline; gap:10px; flex-wrap:wrap; max-width:100%; }
.pd-price { font-size:clamp(1.4rem, 5.5vw, 1.9rem); font-weight:900; color:var(--primary); line-height:1; }
.pd-original { font-size:1.05rem; color:var(--text3); text-decoration:line-through; font-weight:500; }
.pd-save { background:rgba(255,77,109,0.1); color:var(--accent); padding:4px 12px; border-radius:6px; font-size:0.82rem; font-weight:800; white-space:nowrap; }
.pd-desc-section { margin-bottom:24px; max-width:100%; }
.pd-desc-section h3 { font-size:1rem; font-weight:800; margin-bottom:12px; }
.pd-desc-content { color:var(--text2); line-height:1.85; font-size:0.93rem; padding:0; max-width:100%; word-wrap:break-word; overflow-wrap:break-word; word-break:break-word; }
.pd-desc-content p { margin-bottom:12px; }
.pd-features { list-style:none; padding:0; max-width:100%; }
.pd-features li { padding:6px 0 6px 24px; position:relative; color:var(--text2); font-size:0.9rem; line-height:1.6; word-wrap:break-word; overflow-wrap:break-word; }
.pd-features li::before { content:'\f00c'; font-family:'Font Awesome 6 Free'; font-weight:900; position:absolute; left:0; top:6px; color:var(--success); font-size:0.78rem; }
.pd-option { margin-bottom:16px; }
.pd-option label { display:block; font-weight:700; font-size:0.88rem; margin-bottom:8px; color:var(--text); }
.pd-option select { width:100%; max-width:300px; padding:12px 16px; border:2px solid var(--border); border-radius:var(--radius); background:var(--bg2); color:var(--text); font-size:16px; font-weight:500; outline:none; cursor:pointer; }
.pd-option select:focus { border-color:var(--primary); box-shadow:0 0 0 4px rgba(212,175,55,0.08); }
.pd-qty { display:inline-flex; align-items:center; border:2px solid var(--border); border-radius:var(--radius); overflow:hidden; }
.pd-qty button { width:44px; height:44px; flex-shrink:0; font-size:1.1rem; display:flex; align-items:center; justify-content:center; color:var(--text); background:var(--bg3); }
.pd-qty button:hover { background:var(--primary); color:#0A0A1A; }
.pd-qty input { width:56px; height:44px; text-align:center; border:none; background:transparent; font-weight:700; font-size:16px; color:var(--text); outline:none; }
.pd-actions { display:flex; gap:10px; margin-top:24px; flex-wrap:wrap; max-width:100%; }
.pd-actions .btn-cart { flex:1 1 45%; min-width:0; padding:14px 20px; background:var(--gradient); color:#0A0A1A; font-weight:700; font-size:0.95rem; border-radius:var(--radius); display:flex; align-items:center; justify-content:center; gap:8px; box-shadow:0 4px 15px rgba(212,175,55,0.3); white-space:nowrap; }
.pd-actions .btn-cart:hover { transform:translateY(-2px); box-shadow:0 8px 25px rgba(212,175,55,0.4); }
.pd-actions .btn-buy { flex:1 1 45%; min-width:0; padding:14px 20px; background:var(--accent); color:#fff; font-weight:700; font-size:0.95rem; border-radius:var(--radius); display:flex; align-items:center; justify-content:center; gap:8px; box-shadow:0 4px 15px rgba(255,77,109,0.3); white-space:nowrap; }
.pd-actions .btn-buy:hover { transform:translateY(-2px); box-shadow:0 8px 25px rgba(255,77,109,0.4); }
.pd-actions .btn-wish { width:50px; height:50px; flex-shrink:0; border:2px solid var(--border); border-radius:var(--radius); display:flex; align-items:center; justify-content:center; font-size:1.15rem; color:var(--text2); }
.pd-actions .btn-wish:hover, .pd-actions .btn-wish.active { border-color:var(--accent); color:var(--accent); background:rgba(255,77,109,0.05); }
@media(max-width:420px) {
    .pd-actions { flex-direction:column; }
    .pd-actions .btn-cart, .pd-actions .btn-buy { flex:1 1 100%; width:100%; }
    .pd-actions .btn-wish { width:100%; height:46px; order:3; }
}
.pd-meta { margin-top:28px; display:grid; grid-template-columns:1fr 1fr; gap:10px; }
@media(max-width:480px) { .pd-meta { grid-template-columns:1fr; } }
.pd-meta-item { display:flex; align-items:center; gap:8px; font-size:0.84rem; color:var(--text2); min-width:0; }
.pd-meta-item i { color:var(--primary); width:16px; font-size:0.8rem; flex-shrink:0; }
.pd-tabs { margin-top:40px; max-width:100%; }
.tab-nav { display:flex; gap:4px; border-bottom:2px solid var(--border); margin-bottom:24px; overflow-x:auto; -webkit-overflow-scrolling:touch; }
.tab-btn { padding:12px 20px; font-weight:600; font-size:0.9rem; color:var(--text3); border-bottom:2px solid transparent; margin-bottom:-2px; white-space:nowrap; transition:var(--transition-fast); flex-shrink:0; }
.tab-btn:hover { color:var(--text); }
.tab-btn.active { color:var(--primary); border-bottom-color:var(--primary); }
.pd-tab-content { display:none; animation:fadeIn 0.3s ease; max-width:100%; }
.pd-tab-content.active { display:block; }
@keyframes fadeIn { from{opacity:0} to{opacity:1} }
.spec-table { width:100%; border-collapse:collapse; display:block; overflow-x:auto; -webkit-overflow-scrolling:touch; }
.spec-table tr:nth-child(even) { background:var(--bg3); }
.spec-table td { padding:12px 18px; font-size:0.88rem; border-bottom:1px solid var(--border-light); word-wrap:break-word; overflow-wrap:break-word; }
.spec-table td:first-child { font-weight:600; width:40%; color:var(--text2); white-space:nowrap; }
@media(max-width:600px) { .spec-table td:first-child { white-space:normal; width:45%; } }

/* === CART PAGE === */
.cart-wrap { padding:32px 0; }
.cart-layout { display:grid; grid-template-columns:1.3fr 0.7fr; gap:32px; align-items:start; }
@media(max-width:900px) { .cart-layout { grid-template-columns:1fr; } }
.cart-table { width:100%; border-collapse:collapse; background:var(--bg2); border-radius:var(--radius-lg); overflow:hidden; box-shadow:var(--shadow-sm); border:1px solid var(--border-light); }
.cart-table th { text-align:left; padding:14px 18px; font-size:0.78rem; text-transform:uppercase; letter-spacing:1px; color:var(--text3); font-weight:700; background:var(--bg3); border-bottom:1px solid var(--border); }
.cart-table td { padding:16px 18px; border-bottom:1px solid var(--border-light); vertical-align:middle; }
.cart-item-info { display:flex; align-items:center; gap:14px; }
.cart-item-info img { width:72px; height:72px; object-fit:cover; border-radius:var(--radius-sm); background:var(--bg3); flex-shrink:0; }
.cart-item-info h4 { font-size:0.9rem; font-weight:700; line-height:1.3; margin-bottom:2px; }
.cart-item-info span { font-size:0.78rem; color:var(--text3); font-weight:500; }
.cart-remove-btn { width:34px; height:34px; border-radius:50%; background:rgba(255,77,109,0.08); color:var(--accent); display:flex; align-items:center; justify-content:center; font-size:0.85rem; transition:var(--transition-fast); }
.cart-remove-btn:hover { background:var(--accent); color:#fff; }
@media(max-width:768px) {
    .cart-table thead { display:none; }
    .cart-table, .cart-table tbody, .cart-table tr, .cart-table td { display:block; width:100%; }
    .cart-table tr { background:var(--bg2); padding:16px; margin-bottom:12px; border-radius:var(--radius-lg); box-shadow:var(--shadow-sm); border:1px solid var(--border-light); }
    .cart-table td { padding:6px 0; border:none; display:flex; justify-content:space-between; align-items:center; }
    .cart-table td::before { content:attr(data-label); font-weight:700; font-size:0.8rem; color:var(--text3); text-transform:uppercase; letter-spacing:0.5px; }
    .cart-remove-btn { margin-top:8px; }
}
.cart-summary { background:var(--bg2); border-radius:var(--radius-lg); padding:28px; box-shadow:var(--shadow-sm); border:1px solid var(--border-light); position:sticky; top:90px; }
@media(max-width:900px) { .cart-summary { position:static; } }
.cart-summary h3 { font-size:1.15rem; font-weight:800; margin-bottom:20px; padding-bottom:14px; border-bottom:2px solid var(--border); }
.cart-summary .row { display:flex; justify-content:space-between; padding:9px 0; font-size:0.92rem; color:var(--text2); }
.cart-summary .row.total { font-size:1.2rem; font-weight:900; color:var(--primary); border-top:2px solid var(--border); padding-top:16px; margin-top:8px; }
.coupon-input { display:flex; gap:8px; margin:16px 0; }
.coupon-input input { flex:1; padding:10px 14px; border:2px solid var(--border); border-radius:var(--radius-sm); background:var(--bg); color:var(--text); font-size:0.88rem; outline:none; font-weight:500; }
.coupon-input input:focus { border-color:var(--primary); }
.coupon-input button { padding:10px 18px; background:var(--bg3); color:var(--text); font-weight:700; border-radius:var(--radius-sm); font-size:0.82rem; border:1px solid var(--border); }
.coupon-input button:hover { background:var(--primary); color:#0A0A1A; border-color:var(--primary); }
.btn-checkout { width:100%; padding:15px; background:var(--gradient); color:#0A0A1A; font-weight:800; font-size:1rem; border-radius:var(--radius); margin-top:16px; display:flex; align-items:center; justify-content:center; gap:8px; box-shadow:0 4px 15px rgba(212,175,55,0.3); }
.btn-checkout:hover { transform:translateY(-2px); box-shadow:0 8px 25px rgba(212,175,55,0.4); }

/* === CHECKOUT === */
.checkout-wrap { padding:32px 0; }
.checkout-grid { display:grid; grid-template-columns:1.2fr 0.8fr; gap:32px; align-items:start; }
@media(max-width:900px) { .checkout-grid { grid-template-columns:1fr; } }
.checkout-form { background:var(--bg2); border-radius:var(--radius-lg); padding:28px; box-shadow:var(--shadow-sm); border:1px solid var(--border-light); }
.checkout-form h2 { font-size:1.25rem; font-weight:900; margin-bottom:24px; }
.form-group { margin-bottom:16px; }
.form-group label { display:block; font-weight:600; font-size:0.85rem; margin-bottom:6px; color:var(--text2); }
.form-group input, .form-group select, .form-group textarea { width:100%; padding:12px 16px; border:2px solid var(--border); border-radius:var(--radius); background:var(--bg); color:var(--text); font-size:0.92rem; outline:none; font-weight:500; }
.form-group input:focus, .form-group select:focus, .form-group textarea:focus { border-color:var(--primary); box-shadow:0 0 0 4px rgba(212,175,55,0.08); }
.form-row { display:grid; grid-template-columns:1fr 1fr; gap:16px; }
@media(max-width:640px) { .form-row { grid-template-columns:1fr; } }
.checkout-order { background:var(--bg2); border-radius:var(--radius-lg); padding:28px; box-shadow:var(--shadow-sm); border:1px solid var(--border-light); position:sticky; top:90px; }
@media(max-width:900px) { .checkout-order { position:static; } }
.checkout-order h2 { font-size:1.15rem; font-weight:900; margin-bottom:20px; }
.co-item { display:flex; gap:12px; padding:12px 0; border-bottom:1px solid var(--border-light); }
.co-item img { width:56px; height:56px; object-fit:cover; border-radius:var(--radius-sm); background:var(--bg3); flex-shrink:0; }
.co-info h4 { font-size:0.85rem; font-weight:700; line-height:1.3; margin-bottom:2px; }
.co-info span { font-size:0.78rem; color:var(--text3); }

/* === ORDER SUCCESS === */
.order-success { text-align:center; padding:60px 0; }
.order-success .icon { width:96px; height:96px; background:linear-gradient(135deg, #10B981, #059669); border-radius:50%; display:flex; align-items:center; justify-content:center; margin:0 auto 24px; font-size:2.4rem; color:#fff; animation:successPop 0.6s cubic-bezier(0.175, 0.885, 0.32, 1.275); box-shadow:0 8px 30px rgba(16,185,129,0.3); }
@keyframes successPop { 0%{transform:scale(0);opacity:0} 60%{transform:scale(1.15)} 100%{transform:scale(1);opacity:1} }
.order-success h1 { font-size:1.8rem; font-weight:900; margin-bottom:8px; }
.order-success .order-id { font-size:1.05rem; color:var(--primary); font-weight:700; margin-bottom:6px; }
.order-success p { color:var(--text2); margin-bottom:24px; font-size:0.95rem; }
.order-actions { display:flex; gap:12px; justify-content:center; flex-wrap:wrap; }
.order-actions a { padding:13px 28px; border-radius:50px; font-weight:700; font-size:0.92rem; }
.order-actions .btn-primary { background:var(--gradient); color:#0A0A1A; box-shadow:0 4px 15px rgba(212,175,55,0.3); }
.order-actions .btn-primary:hover { transform:translateY(-2px); }
.order-actions .btn-outline { border:2px solid var(--border); color:var(--text); }
.order-actions .btn-outline:hover { border-color:var(--primary); color:var(--primary); }

/* === PAGE HEADERS === */
.page-header { background:var(--gradient-dark); color:#fff; padding:44px 0; text-align:center; position:relative; overflow:hidden; }
.page-header::before { content:''; position:absolute; inset:0; background:radial-gradient(ellipse at 30% 50%, rgba(212,175,55,0.3), transparent 70%); }
.page-header h1 { font-size:clamp(1.4rem, 3vw, 2rem); font-weight:900; position:relative; z-index:1; }
.page-header p { opacity:0.8; margin-top:6px; font-size:0.92rem; position:relative; z-index:1; }
.shop-filters { background:var(--bg2); padding:14px 0; border-bottom:1px solid var(--border); position:sticky; top:56px; z-index:50; }
.filter-row { display:flex; gap:10px; align-items:center; flex-wrap:wrap; }
.filter-row select, .filter-row input { padding:9px 14px; border:2px solid var(--border); border-radius:var(--radius-sm); background:var(--bg); color:var(--text); font-size:0.84rem; outline:none; font-weight:500; cursor:pointer; }
.filter-row select:focus, .filter-row input:focus { border-color:var(--primary); }

/* === FLOATING === */
.floating-whatsapp { position:fixed; bottom:24px; right:24px; z-index:900; width:54px; height:54px; background:#25D366; border-radius:50%; display:flex; align-items:center; justify-content:center; color:#fff; font-size:1.5rem; box-shadow:0 4px 20px rgba(37,211,102,0.4); transition:var(--transition); }
.floating-whatsapp:hover { transform:scale(1.1); box-shadow:0 6px 30px rgba(37,211,102,0.5); }
.back-to-top { position:fixed; bottom:24px; left:24px; z-index:900; width:42px; height:42px; background:var(--bg2); border:2px solid var(--border); border-radius:50%; display:flex; align-items:center; justify-content:center; color:var(--text2); font-size:0.9rem; opacity:0; visibility:hidden; transition:var(--transition); box-shadow:var(--shadow); }
.back-to-top.visible { opacity:1; visibility:visible; }
.back-to-top:hover { background:var(--primary); color:#0A0A1A; border-color:var(--primary); transform:translateY(-2px); }

/* === COOKIE === */
.cookie-notice { position:fixed; bottom:0; left:0; right:0; z-index:950; background:var(--bg2); border-top:1px solid var(--border); padding:14px 24px; display:flex; align-items:center; justify-content:space-between; gap:16px; box-shadow:0 -4px 20px rgba(0,0,0,0.08); transform:translateY(100%); transition:transform 0.4s cubic-bezier(0.4, 0, 0.2, 1); }
.cookie-notice.show { transform:translateY(0); }
.cookie-notice p { font-size:0.85rem; color:var(--text2); }
.cookie-notice button { padding:10px 24px; background:var(--gradient); color:#0A0A1A; font-weight:700; border-radius:var(--radius-sm); white-space:nowrap; font-size:0.85rem; }
@media(max-width:640px) { .cookie-notice { flex-direction:column; text-align:center; padding:20px 16px; } }

/* === PROMO POPUP === */
.promo-popup { position:fixed; inset:0; z-index:9600; display:flex; align-items:center; justify-content:center; background:rgba(0,0,0,0.55); backdrop-filter:blur(6px); opacity:0; visibility:hidden; transition:var(--transition); padding:20px; }
.promo-popup.show { opacity:1; visibility:visible; }
.promo-popup-box { background:var(--bg2); border-radius:var(--radius-xl); max-width:420px; width:100%; padding:40px 32px; text-align:center; position:relative; transform:scale(0.9) translateY(20px); transition:var(--transition-slow); box-shadow:var(--shadow-xl); }
.promo-popup.show .promo-popup-box { transform:scale(1) translateY(0); }
.promo-popup-close { position:absolute; top:14px; right:14px; width:36px; height:36px; border-radius:50%; background:var(--bg3); display:flex; align-items:center; justify-content:center; font-size:0.95rem; color:var(--text2); transition:var(--transition-fast); }
.promo-popup-close:hover { background:var(--accent); color:#fff; }
.promo-popup-box h2 { font-size:1.5rem; font-weight:900; margin-bottom:8px; }
.promo-popup-box p { color:var(--text2); font-size:0.9rem; margin-bottom:16px; }
.promo-code { display:inline-block; padding:10px 24px; background:var(--bg3); border:2px dashed var(--primary); border-radius:var(--radius); font-size:1.25rem; font-weight:900; color:var(--primary); letter-spacing:3px; margin:12px 0; }

/* === TOAST === */
.toast-container { position:fixed; top:76px; right:20px; z-index:9700; display:flex; flex-direction:column; gap:8px; pointer-events:none; }
.toast { padding:14px 20px; border-radius:var(--radius); background:var(--bg2); box-shadow:var(--shadow-xl); display:flex; align-items:center; gap:10px; font-size:0.88rem; font-weight:500; min-width:280px; max-width:380px; animation:toastSlide 0.4s cubic-bezier(0.4, 0, 0.2, 1); border-left:4px solid var(--primary); pointer-events:auto; }
.toast.error { border-left-color:var(--accent); }
.toast.success { border-left-color:var(--success); }
.toast i { font-size:1rem; flex-shrink:0; }
.toast.error i { color:var(--accent); }
.toast.success i { color:var(--success); }
@keyframes toastSlide { from{opacity:0;transform:translateX(40px)} to{opacity:1;transform:translateX(0)} }

/* === TRACK ORDER === */
.track-card { background:var(--bg2); border-radius:var(--radius-lg); padding:32px; box-shadow:var(--shadow-sm); border:1px solid var(--border-light); max-width:560px; margin:40px auto; }
.track-card h2 { font-size:1.2rem; font-weight:900; margin-bottom:20px; }

/* === WISHLIST === */
.wishlist-empty { text-align:center; padding:60px 20px; color:var(--text3); }
.wishlist-empty i { font-size:3rem; margin-bottom:16px; opacity:0.4; }
.wishlist-empty h3 { font-size:1.2rem; font-weight:800; color:var(--text); margin-bottom:8px; }

/* === CONTACT === */
.contact-grid { display:grid; grid-template-columns:1fr 1fr; gap:32px; }
@media(max-width:768px) { .contact-grid { grid-template-columns:1fr; } }
.contact-info-cards { display:grid; gap:16px; }
.contact-info-card { display:flex; gap:16px; align-items:flex-start; padding:20px; background:var(--bg2); border-radius:var(--radius-lg); box-shadow:var(--shadow-sm); border:1px solid var(--border-light); }
.contact-info-card .icon { width:48px; height:48px; border-radius:var(--radius); background:var(--gradient); display:flex; align-items:center; justify-content:center; color:#0A0A1A; font-size:1.1rem; flex-shrink:0; }
.contact-info-card h4 { font-size:0.92rem; font-weight:700; margin-bottom:4px; }
.contact-info-card p { font-size:0.85rem; color:var(--text2); line-height:1.5; }

/* === ANIMATIONS === */
.animate-on-scroll { opacity:0; transform:translateY(24px); transition:opacity 0.6s ease, transform 0.6s ease; }
.animate-on-scroll.visible { opacity:1; transform:translateY(0); }
@media(max-width:768px) { .animate-on-scroll { opacity:1; transform:none; } }

/* === EMPTY STATE === */
.empty-state { text-align:center; padding:60px 20px; }
.empty-state i { font-size:3rem; color:var(--text3); opacity:0.3; margin-bottom:16px; }
.empty-state h3 { font-size:1.2rem; font-weight:800; margin-bottom:8px; }
.empty-state p { color:var(--text3); margin-bottom:20px; }
.empty-state a { display:inline-flex; align-items:center; gap:8px; padding:12px 28px; background:var(--gradient); color:#0A0A1A; border-radius:50px; font-weight:700; font-size:0.92rem; }
</style>
</head>
<body>

<!-- Loader -->
<div id="loader">
    <div class="loader-brand">
        <img src="https://i.postimg.cc/RZCmbTyt/file-00000000ac58820b832611934d0192fe.png" alt="GlowSpace">
        <span>GlowSpace</span>
    </div>
    <div class="loader-bar"><div class="loader-bar-inner"></div></div>
</div>
<script>
/* Loader failsafe: runs immediately, independent of the main script below.
   Hides the loader as soon as the DOM is ready, and force-hides it after
   3s no matter what, so a slow/blocked image or a later JS error can never
   leave the loader stuck on top of the header (which looked like a
   duplicated "GlowSpace" logo/name). */
(function () {
    function hideLoader() {
        var el = document.getElementById("loader");
        if (el) el.classList.add("hide");
    }
    if (document.readyState === "complete" || document.readyState === "interactive") {
        hideLoader();
    } else {
        document.addEventListener("DOMContentLoaded", hideLoader);
    }
    window.setTimeout(hideLoader, 3000);
})();
</script>

<!-- Toast Container -->
<div class="toast-container" id="toastContainer"></div>

<!-- Promo Popup -->
<?php if(($settings['promo_popup']??false) && empty($_SESSION['promo_dismissed'])): ?>
<div class="promo-popup" id="promoPopup">
    <div class="promo-popup-box">
        <button class="promo-popup-close" onclick="closePromo()"><i class="fas fa-times"></i></button>
        <h2><?=gsSanitize($settings['site_name']??'GlowSpace')?></h2>
        <p><?=gsSanitize($settings['promo_text']??'Welcome!')?></p>
        <div class="promo-code">GLOW10</div>
        <br>
        <button onclick="closePromo()" style="padding:12px 32px;background:var(--gradient);color:#0A0A1A;font-weight:700;border-radius:50px;font-size:0.92rem;">Shop Now</button>
    </div>
</div>
<?php endif; ?>

<!-- Cookie Notice -->
<?php if(($settings['cookie_notice']??false) && empty($_COOKIE['cookie_accepted'])): ?>
<div class="cookie-notice" id="cookieNotice">
    <p><i class="fas fa-cookie-bite" style="color:var(--warning);margin-right:6px;"></i> We use cookies to enhance your shopping experience.</p>
    <button onclick="acceptCookies()">Accept</button>
</div>
<?php endif; ?>

<!-- Mobile Menu Overlay -->
<div class="mobile-menu-overlay" id="mmOverlay"></div>

<!-- Mobile Menu -->
<nav class="mobile-menu" id="mobileMenu">
    <div class="mm-header">
        <div class="mm-logo">
            <img src="https://i.postimg.cc/RZCmbTyt/file-00000000ac58820b832611934d0192fe.png" alt="GlowSpace">
            <span>GlowSpace</span>
        </div>
        <button class="mm-close" id="mmClose"><i class="fas fa-times"></i></button>
    </div>
    <div class="mm-body">
        <div class="mm-search">
            <input type="text" placeholder="Search products..." id="mmSearchInput" autocomplete="off">
            <i class="fas fa-search"></i>
            <div class="search-results" id="mmSearchResults"></div>
        </div>
        <div class="mm-nav">
            <a href="index.php" class="<?=$page==='home'?'active':''?>"><i class="fas fa-home"></i> Home</a>
            <a href="index.php?page=shop" class="<?=$page==='shop'?'active':''?>"><i class="fas fa-store"></i> Shop</a>
            <a href="index.php?page=wishlist" class="<?=$page==='wishlist'?'active':''?>"><i class="fas fa-heart"></i> Wishlist <?=$wishlistCount>0?'<span style="margin-left:auto;background:var(--accent);color:#fff;font-size:0.7rem;padding:1px 7px;border-radius:50px;font-weight:800;">'.$wishlistCount.'</span>':''?></a>
            <a href="index.php?page=cart" class="<?=$page==='cart'?'active':''?>"><i class="fas fa-shopping-bag"></i> Cart <?=$cartCount>0?'<span style="margin-left:auto;background:var(--accent);color:#fff;font-size:0.7rem;padding:1px 7px;border-radius:50px;font-weight:800;">'.$cartCount.'</span>':''?></a>
            <a href="index.php?page=contact" class="<?=$page==='contact'?'active':''?>"><i class="fas fa-envelope"></i> Contact</a>
            <a href="index.php?page=track" class="<?=$page==='track'?'active':''?>"><i class="fas fa-truck"></i> Track Order</a>
        </div>
        <div class="mm-divider"></div>
        <div class="mm-bottom">
            <a href="index.php?page=shop&sort=popular"><i class="fas fa-fire"></i> Popular</a>
            <a href="index.php?page=shop&sort=newest"><i class="fas fa-sparkles"></i> New Arrivals</a>
        </div>
    </div>
</nav>

<!-- Cart Drawer Overlay -->
<div class="cart-drawer-overlay" id="cartDrawerOverlay"></div>

<!-- Cart Drawer -->
<aside class="cart-drawer" id="cartDrawer">
    <div class="cd-header">
        <h3><i class="fas fa-shopping-bag" style="color:var(--primary);"></i> Your Cart</h3>
        <button class="cd-close" id="cdClose"><i class="fas fa-times"></i></button>
    </div>
    <div class="cd-body" id="cdBody">
        <div class="cd-empty"><i class="fas fa-spinner fa-spin"></i></div>
    </div>
    <div class="cd-footer" id="cdFooter" style="display:none;">
        <div class="cd-subtotal"><span>Subtotal</span><span id="cdSubtotalVal">৳0</span></div>
        <a href="index.php?page=checkout" class="btn-checkout"><i class="fas fa-lock"></i> Checkout</a>
        <a href="index.php?page=cart" class="cd-viewcart">View Full Cart</a>
    </div>
</aside>

<!-- Header -->
<header class="header" id="mainHeader">
    <div class="header-top-bar">
        Free shipping on orders over ৳999 &mdash; <span>Shop Now</span>
    </div>
    <div class="container">
        <div class="header-main">
            <a href="index.php" class="logo">
                <img src="https://i.postimg.cc/RZCmbTyt/file-00000000ac58820b832611934d0192fe.png" alt="GlowSpace Logo">
                <span class="logo-text">GlowSpace</span>
            </a>
            <div class="search-box">
                <input type="text" placeholder="Search products, categories, brands..." id="searchInput" autocomplete="off">
                <button class="search-btn" onclick="doSearch()"><i class="fas fa-search"></i></button>
                <div class="search-results" id="searchResults"></div>
            </div>
            <div class="header-actions">
                <button class="hdr-btn theme-btn" onclick="toggleTheme()" title="Toggle theme"><i class="fas fa-moon" id="themeIcon"></i></button>
                <div class="hdr-divider"></div>
                <a href="index.php?page=wishlist" class="hdr-btn" title="Wishlist">
                    <i class="far fa-heart"></i>
                    <?php if($wishlistCount>0): ?><span class="badge"><?=$wishlistCount?></span><?php endif; ?>
                </a>
                <a href="index.php?page=cart" class="hdr-btn cart-btn" id="cartDrawerBtn" title="Cart">
                    <i class="fas fa-shopping-bag"></i>
                    <?php if($cartCount>0): ?><span class="badge"><?=$cartCount?></span><?php endif; ?>
                </a>
                <div class="hamburger" id="hamburgerBtn">
                    <span></span><span></span><span></span>
                </div>
            </div>
        </div>
    </div>
</header>

<main>
<?php if($page==='home'): ?>

<!-- Hero Slider -->
<?php if(!empty($banners)): ?>
<section class="hero">
    <div class="hero-slider" id="heroSlider">
        <?php foreach($banners as $bn): ?>
        <div class="hero-slide">
            <img src="<?=gsImgUrl($bn['image']??'')?>" alt="<?=gsSanitize($bn['title']??'Banner')?>" loading="eager">
        </div>
        <?php endforeach; ?>
    </div>
    <?php if(count($banners)>1): ?>
    <div class="hero-dots" id="heroDots">
        <?php foreach($banners as $i=>$bn): ?>
        <button class="hero-dot <?=$i===0?'active':''?>" data-slide="<?=$i?>"></button>
        <?php endforeach; ?>
    </div>
    <div class="hero-arrows">
        <button class="hero-arrow" id="heroPrev"><i class="fas fa-chevron-left"></i></button>
        <button class="hero-arrow" id="heroNext"><i class="fas fa-chevron-right"></i></button>
    </div>
    <?php endif; ?>
</section>
<?php endif; ?>

<!-- Categories -->
<?php if(!empty($categories)): ?>
<section class="section">
    <div class="container">
        <div class="section-head animate-on-scroll">
            <h2>Shop by <span class="highlight">Category</span></h2>
            <a href="index.php?page=shop">View All <i class="fas fa-arrow-right"></i></a>
        </div>
        <div class="cat-grid animate-on-scroll">
            <?php foreach(array_slice($categories, 0, 8) as $cat): ?>
            <a href="index.php?page=shop&category=<?=urlencode($cat['name']??'')?>" class="cat-card">
                <div class="cat-icon-circle">
                    <i class="<?=gsSanitize(gsValidIcon($cat['icon']??''))?>" style="color:<?=gsSanitize(!empty($cat['color']) ? $cat['color'] : 'var(--primary)')?>"></i>
                </div>
                <h3><?=gsSanitize($cat['name']??'')?></h3>
            </a>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- Flash Sale -->
<?php if(!empty($flashProducts)): ?>
<section class="flash-sale animate-on-scroll">
    <div class="container">
        <div class="flash-header">
            <h2><i class="fas fa-bolt"></i> Flash Sale</h2>
            <div class="countdown" id="flashCountdown">
                <div class="countdown-item"><span class="num" id="cdHours">00</span><span class="label">Hours</span></div>
                <div class="countdown-item"><span class="num" id="cdMins">00</span><span class="label">Mins</span></div>
                <div class="countdown-item"><span class="num" id="cdSecs">00</span><span class="label">Secs</span></div>
            </div>
        </div>
        <div class="flash-scroll">
            <?php foreach($flashProducts as $fp): ?>
            <?php 
                $fImg = gsImgUrl($fp['images'][0]??'');
                $fPrice = floatval($fp['offer_price']??$fp['price']);
                $fOrig = floatval($fp['price']);
                $fDisc = $fOrig>0 ? round(($fOrig-$fPrice)/$fOrig*100) : 0;
                $fSizes = $fp['sizes'] ?? [];
                if(is_string($fSizes)) $fSizes = json_decode($fSizes, true) ?: [];
                $fHasSizes = !empty($fSizes);
                $fDefaultSize = $fHasSizes ? $fSizes[0] : 'Default';
            ?>
            <div class="product-card">
                <div class="badge-area">
                    <?php if($fDisc>0): ?><span class="p-badge sale">-<?=$fDisc?>%</span><?php endif; ?>
                </div>
                <div class="card-actions">
                    <button class="p-action-btn <?=in_array($fp['id'], $_SESSION['wishlist']??[])?'wishlisted':''?>" onclick="toggleWishlist('<?=$fp['id']?>',this)" title="Wishlist"><i class="fas fa-heart"></i></button>
                </div>
                <div class="card-image">
                    <a href="index.php?page=product&slug=<?=gsSanitize($fp['slug']??'')?>">
                        <img src="<?=$fImg?>" alt="<?=gsSanitize($fp['title']??'')?>" loading="lazy">
                    </a>
                </div>
                <div class="card-info">
                    <?php if(!empty($fp['brand'])): ?><div class="brand"><?=gsSanitize($fp['brand'])?></div><?php endif; ?>
                    <h3><a href="index.php?page=product&slug=<?=gsSanitize($fp['slug']??'')?>" style="color:var(--text)"><?=gsSanitize($fp['title'])?></a></h3>
                    <div class="price-row">
                        <span class="price"><?=$settings['currency']??'৳'?><?=number_format($fPrice)?></span>
                        <?php if($fDisc>0): ?><span class="original"><?=$settings['currency']??'৳'?><?=number_format($fOrig)?></span><?php endif; ?>
                    </div>
                    <div class="card-btns">
                        <button class="btn-add-cart" onclick="addToCart('<?=$fp['id']?>','<?=$fDefaultSize?>',1,this)"><i class="fas fa-shopping-bag"></i> Add</button>
                        <button class="btn-order-now" onclick="orderNow('<?=$fp['id']?>','<?=$fDefaultSize?>')"><i class="fas fa-bolt"></i> Order</button>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- New Arrivals -->
<?php if(!empty($newProducts)): ?>
<section class="section">
    <div class="container">
        <div class="section-head animate-on-scroll">
            <h2>New <span class="highlight">Arrivals</span></h2>
            <a href="index.php?page=shop&sort=newest">View All <i class="fas fa-arrow-right"></i></a>
        </div>
        <div class="product-grid animate-on-scroll">
            <?php foreach(array_slice($newProducts, 0, 8) as $np): ?>
            <?php 
                $nImg = gsImgUrl($np['images'][0]??'');
                $nPrice = floatval($np['offer_price']??$np['price']);
                $nOrig = floatval($np['price']);
                $nDisc = $nOrig>0 ? round(($nOrig-$nPrice)/$nOrig*100) : 0;
                $nSizes = $np['sizes'] ?? [];
                if(is_string($nSizes)) $nSizes = json_decode($nSizes, true) ?: [];
                $nHasSizes = !empty($nSizes);
                $nDefaultSize = $nHasSizes ? $nSizes[0] : 'Default';
            ?>
            <div class="product-card">
                <div class="badge-area">
                    <?php if(($np['is_new']??0)==1): ?><span class="p-badge new">New</span><?php endif; ?>
                    <?php if($nDisc>0): ?><span class="p-badge sale">-<?=$nDisc?>%</span><?php endif; ?>
                </div>
                <div class="card-actions">
                    <button class="p-action-btn <?=in_array($np['id'], $_SESSION['wishlist']??[])?'wishlisted':''?>" onclick="toggleWishlist('<?=$np['id']?>',this)" title="Wishlist"><i class="fas fa-heart"></i></button>
                </div>
                <div class="card-image">
                    <a href="index.php?page=product&slug=<?=gsSanitize($np['slug']??'')?>">
                        <img src="<?=$nImg?>" alt="<?=gsSanitize($np['title']??'')?>" loading="lazy">
                    </a>
                </div>
                <div class="card-info">
                    <?php if(!empty($np['brand'])): ?><div class="brand"><?=gsSanitize($np['brand'])?></div><?php endif; ?>
                    <h3><a href="index.php?page=product&slug=<?=gsSanitize($np['slug']??'')?>" style="color:var(--text)"><?=gsSanitize($np['title'])?></a></h3>
                    <div class="price-row">
                        <span class="price"><?=$settings['currency']??'৳'?><?=number_format($nPrice)?></span>
                        <?php if($nDisc>0): ?><span class="original"><?=$settings['currency']??'৳'?><?=number_format($nOrig)?></span><span class="discount-tag">-<?=$nDisc?>%</span><?php endif; ?>
                    </div>
                    <div class="card-btns">
                        <button class="btn-add-cart" onclick="addToCart('<?=$np['id']?>','<?=$nDefaultSize?>',1,this)"><i class="fas fa-shopping-bag"></i> Add to Cart</button>
                        <button class="btn-order-now" onclick="orderNow('<?=$np['id']?>','<?=$nDefaultSize?>')"><i class="fas fa-bolt"></i> Order Now</button>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- Offer Banner -->
<section class="section" style="padding-top:0;">
    <div class="container animate-on-scroll">
        <div class="offer-banner">
            <div>
                <h2>Mega Sale is Live!</h2>
                <p>Up to 50% off on selected items. Don't miss out.</p>
            </div>
            <a href="index.php?page=shop" class="offer-btn">Shop Now <i class="fas fa-arrow-right" style="margin-left:6px;"></i></a>
        </div>
    </div>
</section>

<!-- Popular Products -->
<?php if(!empty($popularProducts)): ?>
<section class="section">
    <div class="container">
        <div class="section-head animate-on-scroll">
            <h2>Popular <span class="highlight">Products</span></h2>
            <a href="index.php?page=shop&sort=popular">View All <i class="fas fa-arrow-right"></i></a>
        </div>
        <div class="product-grid animate-on-scroll">
            <?php foreach(array_slice($popularProducts, 0, 8) as $pp): ?>
            <?php 
                $pImg = gsImgUrl($pp['images'][0]??'');
                $pPrice = floatval($pp['offer_price']??$pp['price']);
                $pOrig = floatval($pp['price']);
                $pDisc = $pOrig>0 ? round(($pOrig-$pPrice)/$pOrig*100) : 0;
                $pSizes = $pp['sizes'] ?? [];
                if(is_string($pSizes)) $pSizes = json_decode($pSizes, true) ?: [];
                $pHasSizes = !empty($pSizes);
                $pDefaultSize = $pHasSizes ? $pSizes[0] : 'Default';
            ?>
            <div class="product-card">
                <div class="badge-area">
                    <?php if(($pp['is_hot']??0)==1): ?><span class="p-badge hot">Hot</span><?php endif; ?>
                    <?php if($pDisc>0): ?><span class="p-badge sale">-<?=$pDisc?>%</span><?php endif; ?>
                </div>
                <div class="card-actions">
                    <button class="p-action-btn <?=in_array($pp['id'], $_SESSION['wishlist']??[])?'wishlisted':''?>" onclick="toggleWishlist('<?=$pp['id']?>',this)" title="Wishlist"><i class="fas fa-heart"></i></button>
                </div>
                <div class="card-image">
                    <a href="index.php?page=product&slug=<?=gsSanitize($pp['slug']??'')?>">
                        <img src="<?=$pImg?>" alt="<?=gsSanitize($pp['title']??'')?>" loading="lazy">
                    </a>
                </div>
                <div class="card-info">
                    <?php if(!empty($pp['brand'])): ?><div class="brand"><?=gsSanitize($pp['brand'])?></div><?php endif; ?>
                    <h3><a href="index.php?page=product&slug=<?=gsSanitize($pp['slug']??'')?>" style="color:var(--text)"><?=gsSanitize($pp['title'])?></a></h3>
                    <div class="price-row">
                        <span class="price"><?=$settings['currency']??'৳'?><?=number_format($pPrice)?></span>
                        <?php if($pDisc>0): ?><span class="original"><?=$settings['currency']??'৳'?><?=number_format($pOrig)?></span><span class="discount-tag">-<?=$pDisc?>%</span><?php endif; ?>
                    </div>
                    <div class="card-btns">
                        <button class="btn-add-cart" onclick="addToCart('<?=$pp['id']?>','<?=$pDefaultSize?>',1,this)"><i class="fas fa-shopping-bag"></i> Add to Cart</button>
                        <button class="btn-order-now" onclick="orderNow('<?=$pp['id']?>','<?=$pDefaultSize?>')"><i class="fas fa-bolt"></i> Order Now</button>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- Reviews -->
<?php if(!empty($approvedReviews)): ?>
<section class="section" style="background:var(--bg3);">
    <div class="container">
        <div class="section-head animate-on-scroll">
            <h2>Customer <span class="highlight">Reviews</span></h2>
        </div>
        <div class="reviews-grid animate-on-scroll">
            <?php foreach(array_slice($approvedReviews, 0, 3) as $rv): ?>
            <div class="review-card">
                <div class="stars"><?php for($s=0;$s<$rv['rating'];$s++) echo '<i class="fas fa-star"></i> '; for($s=$rv['rating'];$s<5;$s++) echo '<i class="far fa-star"></i> '; ?></div>
                <p class="text">"<?=gsSanitize($rv['text'])?>"</p>
                <div class="author">
                    <div class="avatar"><?=strtoupper(substr($rv['name']??'U',0,1))?></div>
                    <div class="author-info">
                        <div class="name"><?=gsSanitize($rv['name'])?></div>
                        <div class="date"><?=date('M d, Y', strtotime($rv['date']))?></div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- Newsletter -->
<section class="section">
    <div class="container animate-on-scroll">
        <div class="newsletter">
            <h2>Stay in the Loop</h2>
            <p>Subscribe for exclusive deals, new arrivals, and insider-only discounts.</p>
            <form class="newsletter-form" onsubmit="subscribeNewsletter(event)">
                <input type="email" placeholder="Enter your email address" required id="newsletterEmail">
                <button type="submit">Subscribe</button>
            </form>
        </div>
    </div>
</section>

<?php elseif($page==='product' && $currentProduct): ?>
<?php
    $pdImg = gsImgUrl($currentProduct['images'][0]??'');
    $pdImgs = array_map('gsImgUrl', $currentProduct['images']??[]);
    $pdPrice = floatval($currentProduct['offer_price']??$currentProduct['price']);
    $pdOrig = floatval($currentProduct['price']);
    $pdDisc = $pdOrig>0 ? round(($pdOrig-$pdPrice)/$pdOrig*100) : 0;
    $pdSizes = $currentProduct['sizes'] ?? [];
    if(is_string($pdSizes)) $pdSizes = json_decode($pdSizes, true) ?: [];
    $pdFeatures = $currentProduct['features'] ?? [];
    if(is_string($pdFeatures)) {
        $decodedFeat = json_decode($pdFeatures, true);
        if(is_array($decodedFeat)) { $pdFeatures = $decodedFeat; }
        else { $pdFeatures = array_values(array_filter(array_map('trim', preg_split('/\r\n|\r|\n|,/', $pdFeatures)))); }
    }
    if(!is_array($pdFeatures)) $pdFeatures = [];
    $pdSpecs = $currentProduct['specifications'] ?? [];
    if(is_string($pdSpecs)) {
        $decodedSpec = json_decode($pdSpecs, true);
        if(is_array($decodedSpec)) { $pdSpecs = $decodedSpec; }
        else {
            $pdSpecs = [];
            foreach(preg_split('/\r\n|\r|\n/', $currentProduct['specifications']) as $specLine) {
                if(strpos($specLine, ':') !== false) {
                    list($sk, $sv) = explode(':', $specLine, 2);
                    $sk = trim($sk); $sv = trim($sv);
                    if($sk !== '') $pdSpecs[$sk] = $sv;
                }
            }
        }
    }
    if(!is_array($pdSpecs)) $pdSpecs = [];
    $pdRating = floatval($currentProduct['rating']??0);
    $pdReviews = array_filter($reviews, fn($r)=>($r['product_id']===$currentProduct['id'])&&($r['status']??0)==1);
    $pdReviewCount = count($pdReviews);
    $relatedProducts = array_filter($activeProducts, fn($p)=>$p['id']!==$currentProduct['id'] && ($p['category']??'')===($currentProduct['category']??''));
    $relatedProducts = array_slice(array_values($relatedProducts), 0, 4);
    if(empty($relatedProducts)) {
        $relatedProducts = array_filter($activeProducts, fn($p)=>$p['id']!==$currentProduct['id']);
        $relatedProducts = array_slice(array_values($relatedProducts), 0, 4);
    }
?>
<div class="page-header">
    <div class="container">
        <h1><?=gsSanitize($currentProduct['title'])?></h1>
        <p><?=gsSanitize($currentProduct['category']??'')?><?php if(!empty($currentProduct['brand'])): ?> / <?=gsSanitize($currentProduct['brand'])?><?php endif; ?></p>
    </div>
</div>
<div class="container">
    <div class="pd-wrap">
        <div class="pd-gallery">
            <div class="pd-main-img">
                <img src="<?=$pdImg?>" alt="<?=gsSanitize($currentProduct['title'])?>" id="pdMainImage">
            </div>
            <?php if(count($pdImgs)>1): ?>
            <div class="pd-thumbs">
                <?php foreach($pdImgs as $ti=>$tImg): ?>
                <div class="pd-thumb <?=$ti===0?'active':''?>" onclick="changePdImage('<?=$tImg?>',this)">
                    <img src="<?=$tImg?>" alt="Thumb">
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
        <div class="pd-info">
            <h1><?=gsSanitize($currentProduct['title'])?></h1>
            <?php if(!empty($currentProduct['brand'])): ?><div class="pd-brand"><i class="fas fa-tag" style="margin-right:4px;"></i> <?=gsSanitize($currentProduct['brand'])?></div><?php endif; ?>
            <div class="pd-rating">
                <span class="stars"><?php for($s=1;$s<=5;$s++) echo $s<=round($pdRating)?'<i class="fas fa-star"></i> ':'<i class="far fa-star"></i> '; ?></span>
                <span>(<?=$pdReviewCount?> reviews)</span>
            </div>
            <div class="pd-price-box">
                <span class="pd-price"><?=$settings['currency']??'৳'?><?=number_format($pdPrice)?></span>
                <?php if($pdDisc>0): ?>
                <span class="pd-original"><?=$settings['currency']??'৳'?><?=number_format($pdOrig)?></span>
                <span class="pd-save">Save <?=$pdDisc?>%</span>
                <?php endif; ?>
            </div>

            <?php if(!empty($currentProduct['description'])): ?>
            <div class="pd-desc-section">
                <h3>Description</h3>
                <div class="pd-desc-content">
                    <p><?=nl2br(gsSanitize($currentProduct['description']))?></p>
                </div>
            </div>
            <?php endif; ?>

            <?php if(!empty($pdFeatures)): ?>
            <div class="pd-desc-section">
                <h3>Key Features</h3>
                <ul class="pd-features">
                    <?php foreach($pdFeatures as $feat): ?>
                    <li><?=gsSanitize($feat)?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <?php endif; ?>

            <?php if($productHasSizes): ?>
            <div class="pd-option">
                <label>Select Size <span style="color:var(--accent);">*</span></label>
                <select id="pdSizeSelect">
                    <?php foreach($pdSizes as $sz): ?>
                    <option value="<?=gsSanitize($sz)?>"><?=gsSanitize($sz)?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>

            <div style="margin-bottom:16px;">
                <label style="display:block;font-weight:700;font-size:0.88rem;margin-bottom:8px;">Quantity</label>
                <div class="pd-qty">
                    <button onclick="pdQtyChange(-1)"><i class="fas fa-minus"></i></button>
                    <input type="number" value="1" min="1" max="99" id="pdQtyInput">
                    <button onclick="pdQtyChange(1)"><i class="fas fa-plus"></i></button>
                </div>
            </div>

            <div class="pd-actions">
                <button class="btn-cart" onclick="pdAddToCart()"><i class="fas fa-shopping-bag"></i> Add to Cart</button>
                <button class="btn-buy" onclick="pdBuyNow()"><i class="fas fa-bolt"></i> Order Now</button>
                <button class="btn-wish <?=in_array($currentProduct['id'], $_SESSION['wishlist']??[])?'active':''?>" id="pdWishBtn" onclick="toggleWishlist('<?=$currentProduct['id']?>',this)"><i class="fas fa-heart"></i></button>
            </div>

            <div class="pd-meta">
                <div class="pd-meta-item"><i class="fas fa-truck"></i> Free shipping over ৳999</div>
                <div class="pd-meta-item"><i class="fas fa-shield-halved"></i> Genuine product</div>
                <div class="pd-meta-item"><i class="fas fa-rotate-left"></i> Easy returns</div>
                <div class="pd-meta-item"><i class="fas fa-lock"></i> Secure checkout</div>
            </div>
        </div>
    </div>

    <!-- Tabs -->
    <div class="pd-tabs">
        <div class="tab-nav">
            <button class="tab-btn active" data-tab="desc">Description</button>
            <?php if(!empty($pdSpecs)): ?><button class="tab-btn" data-tab="specs">Specifications</button><?php endif; ?>
            <button class="tab-btn" data-tab="reviews">Reviews (<?=$pdReviewCount?>)</button>
        </div>
        <div class="pd-tab-content active" id="tab-desc">
            <div class="pd-desc-content" style="max-width:800px;">
                <?php if(!empty($currentProduct['description'])): ?>
                <p><?=nl2br(gsSanitize($currentProduct['description']))?></p>
                <?php else: ?>
                <p style="color:var(--text3);">No description available.</p>
                <?php endif; ?>
                <?php if(!empty($pdFeatures)): ?>
                <h3 style="font-size:1rem;font-weight:800;margin:20px 0 12px;">Features</h3>
                <ul class="pd-features">
                    <?php foreach($pdFeatures as $feat): ?>
                    <li><?=gsSanitize($feat)?></li>
                    <?php endforeach; ?>
                </ul>
                <?php endif; ?>
            </div>
        </div>
        <?php if(!empty($pdSpecs)): ?>
        <div class="pd-tab-content" id="tab-specs">
            <table class="spec-table">
                <?php foreach($pdSpecs as $sk=>$sv): ?>
                <tr><td><?=gsSanitize($sk)?></td><td><?=gsSanitize($sv)?></td></tr>
                <?php endforeach; ?>
            </table>
        </div>
        <?php endif; ?>
        <div class="pd-tab-content" id="tab-reviews">
            <?php if(!empty($pdReviews)): ?>
            <div class="reviews-grid">
                <?php foreach($pdReviews as $rv): ?>
                <div class="review-card">
                    <div class="stars"><?php for($s=0;$s<$rv['rating'];$s++) echo '<i class="fas fa-star"></i> '; for($s=$rv['rating'];$s<5;$s++) echo '<i class="far fa-star"></i> '; ?></div>
                    <p class="text">"<?=gsSanitize($rv['text'])?>"</p>
                    <div class="author">
                        <div class="avatar"><?=strtoupper(substr($rv['name']??'U',0,1))?></div>
                        <div class="author-info">
                            <div class="name"><?=gsSanitize($rv['name'])?></div>
                            <div class="date"><?=date('M d, Y', strtotime($rv['date']))?></div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php else: ?>
            <p style="color:var(--text3);text-align:center;padding:40px 0;">No reviews yet. Be the first to review!</p>
            <?php endif; ?>
            <div style="max-width:560px;margin-top:32px;padding:24px;background:var(--bg3);border-radius:var(--radius-lg);">
                <h3 style="font-size:1rem;font-weight:800;margin-bottom:16px;">Write a Review</h3>
                <form onsubmit="submitReview(event,'<?=$currentProduct['id']?>')">
                    <div class="form-row" style="margin-bottom:12px;">
                        <div class="form-group" style="margin:0;"><input type="text" placeholder="Your name" required id="revName"></div>
                        <div class="form-group" style="margin:0;">
                            <select id="revRating" style="padding:12px 16px;border:2px solid var(--border);border-radius:var(--radius);background:var(--bg2);color:var(--text);width:100%;">
                                <option value="5">5 Stars</option><option value="4">4 Stars</option><option value="3">3 Stars</option><option value="2">2 Stars</option><option value="1">1 Star</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group"><textarea placeholder="Your review..." rows="3" required id="revText" style="width:100%;padding:12px 16px;border:2px solid var(--border);border-radius:var(--radius);background:var(--bg2);color:var(--text);font-size:0.92rem;resize:vertical;outline:none;"></textarea></div>
                    <button type="submit" style="padding:12px 28px;background:var(--gradient);color:#0A0A1A;font-weight:700;border-radius:var(--radius);font-size:0.9rem;">Submit Review</button>
                </form>
            </div>
        </div>
    </div>

    <!-- Related Products -->
    <?php if(!empty($relatedProducts)): ?>
    <section class="section" style="padding-bottom:0;">
        <div class="section-head">
            <h2>Related <span class="highlight">Products</span></h2>
        </div>
        <div class="product-grid">
            <?php foreach($relatedProducts as $rp): ?>
            <?php 
                $rImg = gsImgUrl($rp['images'][0]??'');
                $rPrice = floatval($rp['offer_price']??$rp['price']);
                $rOrig = floatval($rp['price']);
                $rDisc = $rOrig>0 ? round(($rOrig-$rPrice)/$rOrig*100) : 0;
                $rSizes = $rp['sizes'] ?? [];
                if(is_string($rSizes)) $rSizes = json_decode($rSizes, true) ?: [];
                $rHasSizes = !empty($rSizes);
                $rDefaultSize = $rHasSizes ? $rSizes[0] : 'Default';
            ?>
            <div class="product-card">
                <div class="badge-area">
                    <?php if($rDisc>0): ?><span class="p-badge sale">-<?=$rDisc?>%</span><?php endif; ?>
                </div>
                <div class="card-actions">
                    <button class="p-action-btn <?=in_array($rp['id'], $_SESSION['wishlist']??[])?'wishlisted':''?>" onclick="toggleWishlist('<?=$rp['id']?>',this)"><i class="fas fa-heart"></i></button>
                </div>
                <div class="card-image">
                    <a href="index.php?page=product&slug=<?=gsSanitize($rp['slug']??'')?>">
                        <img src="<?=$rImg?>" alt="<?=gsSanitize($rp['title']??'')?>" loading="lazy">
                    </a>
                </div>
                <div class="card-info">
                    <?php if(!empty($rp['brand'])): ?><div class="brand"><?=gsSanitize($rp['brand'])?></div><?php endif; ?>
                    <h3><a href="index.php?page=product&slug=<?=gsSanitize($rp['slug']??'')?>" style="color:var(--text)"><?=gsSanitize($rp['title'])?></a></h3>
                    <div class="price-row">
                        <span class="price"><?=$settings['currency']??'৳'?><?=number_format($rPrice)?></span>
                        <?php if($rDisc>0): ?><span class="original"><?=$settings['currency']??'৳'?><?=number_format($rOrig)?></span><?php endif; ?>
                    </div>
                    <div class="card-btns">
                        <button class="btn-add-cart" onclick="addToCart('<?=$rp['id']?>','<?=$rDefaultSize?>',1,this)"><i class="fas fa-shopping-bag"></i> Add to Cart</button>
                        <button class="btn-order-now" onclick="orderNow('<?=$rp['id']?>','<?=$rDefaultSize?>')"><i class="fas fa-bolt"></i> Order Now</button>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </section>
    <?php endif; ?>
</div>

<?php elseif($page==='shop'): ?>
<?php
    $shopCategory = gsSanitize($_GET['category'] ?? '');
    $shopSort = gsSanitize($_GET['sort'] ?? 'newest');
    $shopMin = floatval($_GET['min'] ?? 0);
    $shopMax = floatval($_GET['max'] ?? 999999);
    $shopQ = strtolower(gsSanitize($_GET['q'] ?? ''));
    
    $shopProducts = $allActiveProducts;
    if($shopCategory) $shopProducts = array_filter($shopProducts, fn($p)=>($p['category']??'')=== $shopCategory);
    if($shopQ) $shopProducts = array_filter($shopProducts, fn($p)=>strpos(strtolower($p['title']),$shopQ)!==false||strpos(strtolower($p['brand']??''),$shopQ)!==false||strpos(strtolower($p['tags']??''),$shopQ)!==false);
    $shopProducts = array_filter($shopProducts, fn($p)=>floatval($p['offer_price']??$p['price'])>=$shopMin && floatval($p['offer_price']??$p['price'])<=$shopMax);
    $shopProducts = gsSortProducts(array_values($shopProducts), $shopSort);
?>
<div class="page-header">
    <div class="container">
        <h1><?=$shopCategory ? gsSanitize($shopCategory) : 'All Products'?></h1>
        <p><?=count($shopProducts)?> products found</p>
    </div>
</div>
<div class="shop-filters">
    <div class="container">
        <div class="filter-row">
            <select onchange="window.location.href=this.value" style="min-width:140px;">
                <option value="index.php?page=shop" <?=$shopCategory===''?'selected':''?>>All Categories</option>
                <?php foreach($categories as $cat): ?>
                <option value="index.php?page=shop&category=<?=urlencode($cat['name'])?>" <?=$shopCategory===$cat['name']?'selected':''?>><?=gsSanitize($cat['name'])?></option>
                <?php endforeach; ?>
            </select>
            <select onchange="window.location.href='index.php?page=shop&category=<?=$shopCategory?>&sort='+this.value" style="min-width:140px;">
                <option value="newest" <?=$shopSort==='newest'?'selected':''?>>Newest First</option>
                <option value="popular" <?=$shopSort==='popular'?'selected':''?>>Most Popular</option>
                <option value="price_low" <?=$shopSort==='price_low'?'selected':''?>>Price: Low to High</option>
                <option value="price_high" <?=$shopSort==='price_high'?'selected':''?>>Price: High to Low</option>
                <option value="rating" <?=$shopSort==='rating'?'selected':''?>>Top Rated</option>
            </select>
        </div>
    </div>
</div>
<section class="section">
    <div class="container">
        <?php if(!empty($shopProducts)): ?>
        <div class="product-grid">
            <?php foreach($shopProducts as $sp): ?>
            <?php 
                $sImg = gsImgUrl($sp['images'][0]??'');
                $sPrice = floatval($sp['offer_price']??$sp['price']);
                $sOrig = floatval($sp['price']);
                $sDisc = $sOrig>0 ? round(($sOrig-$sPrice)/$sOrig*100) : 0;
                $sSizes = $sp['sizes'] ?? [];
                if(is_string($sSizes)) $sSizes = json_decode($sSizes, true) ?: [];
                $sHasSizes = !empty($sSizes);
                $sDefaultSize = $sHasSizes ? $sSizes[0] : 'Default';
            ?>
            <div class="product-card">
                <div class="badge-area">
                    <?php if(($sp['is_new']??0)==1): ?><span class="p-badge new">New</span><?php endif; ?>
                    <?php if(($sp['is_hot']??0)==1): ?><span class="p-badge hot">Hot</span><?php endif; ?>
                    <?php if($sDisc>0): ?><span class="p-badge sale">-<?=$sDisc?>%</span><?php endif; ?>
                </div>
                <div class="card-actions">
                    <button class="p-action-btn <?=in_array($sp['id'], $_SESSION['wishlist']??[])?'wishlisted':''?>" onclick="toggleWishlist('<?=$sp['id']?>',this)"><i class="fas fa-heart"></i></button>
                </div>
                <div class="card-image">
                    <a href="index.php?page=product&slug=<?=gsSanitize($sp['slug']??'')?>">
                        <img src="<?=$sImg?>" alt="<?=gsSanitize($sp['title']??'')?>" loading="lazy">
                    </a>
                </div>
                <div class="card-info">
                    <?php if(!empty($sp['brand'])): ?><div class="brand"><?=gsSanitize($sp['brand'])?></div><?php endif; ?>
                    <h3><a href="index.php?page=product&slug=<?=gsSanitize($sp['slug']??'')?>" style="color:var(--text)"><?=gsSanitize($sp['title'])?></a></h3>
                    <div class="price-row">
                        <span class="price"><?=$settings['currency']??'৳'?><?=number_format($sPrice)?></span>
                        <?php if($sDisc>0): ?><span class="original"><?=$settings['currency']??'৳'?><?=number_format($sOrig)?></span><span class="discount-tag">-<?=$sDisc?>%</span><?php endif; ?>
                    </div>
                    <div class="card-btns">
                        <button class="btn-add-cart" onclick="addToCart('<?=$sp['id']?>','<?=$sDefaultSize?>',1,this)"><i class="fas fa-shopping-bag"></i> Add to Cart</button>
                        <button class="btn-order-now" onclick="orderNow('<?=$sp['id']?>','<?=$sDefaultSize?>')"><i class="fas fa-bolt"></i> Order Now</button>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php else: ?>
        <div class="empty-state">
            <i class="fas fa-box-open"></i>
            <h3>No Products Found</h3>
            <p>Try adjusting your filters or search terms.</p>
            <a href="index.php?page=shop">Browse All Products</a>
        </div>
        <?php endif; ?>
    </div>
</section>

<?php elseif($page==='cart'): ?>
<div class="page-header">
    <div class="container">
        <h1>Shopping Cart</h1>
        <p><?=$cartCount?> item(s) in your cart</p>
    </div>
</div>
<div class="cart-wrap">
    <div class="container">
        <?php if(!empty($_SESSION['cart'])): ?>
        <?php
            $cartSubtotal = 0;
            foreach($_SESSION['cart'] as $ci) { $cartSubtotal += $ci['price'] * $ci['qty']; }
            
            $cartDiscount = 0;
            if(isset($_SESSION['coupon'])) {
                $c = $_SESSION['coupon'];
                $cartDiscount = ($c['type']??'percent')==='percent' ? $cartSubtotal*$c['discount']/100 : min($c['discount'], $cartSubtotal);
            }
            $cartShipping = 120;
            $cartTotal = $cartSubtotal - $cartDiscount + $cartShipping;
        ?>
        <div class="cart-layout">
            <div>
                <table class="cart-table">
                    <thead><tr><th>Product</th><th>Price</th><th>Quantity</th><th>Total</th><th></th></tr></thead>
                    <tbody>
                        <?php foreach($_SESSION['cart'] as $ck=>$ci): ?>
                        <tr>
                            <td data-label="Product">
                                <div class="cart-item-info">
                                    <img src="<?=$ci['image']?>" alt="<?=gsSanitize($ci['title'])?>">
                                    <div><h4><?=gsSanitize($ci['title'])?></h4><?php if($ci['size']): ?><span>Size: <?=gsSanitize($ci['size'])?></span><?php endif; ?></div>
                                </div>
                            </td>
                            <td data-label="Price"><?=$settings['currency']??'৳'?><?=number_format($ci['price'])?></td>
                            <td data-label="Quantity">
                                <div class="pd-qty">
                                    <button onclick="updateCartQty('<?=$ck?>',<?=$ci['qty']-1?>)"><i class="fas fa-minus"></i></button>
                                    <input type="number" value="<?=$ci['qty']?>" min="1" onchange="updateCartQty('<?=$ck?>',this.value)" style="width:44px;">
                                    <button onclick="updateCartQty('<?=$ck?>',<?=$ci['qty']+1?>)"><i class="fas fa-plus"></i></button>
                                </div>
                            </td>
                            <td data-label="Total" style="font-weight:700;"><?=$settings['currency']??'৳'?><?=number_format($ci['price']*$ci['qty'])?></td>
                            <td data-label=""><button class="cart-remove-btn" onclick="removeCartItem('<?=$ck?>')"><i class="fas fa-trash-alt"></i></button></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <div class="cart-summary">
                <h3>Order Summary</h3>
                <div class="row"><span>Subtotal</span><span><?=$settings['currency']??'৳'?><?=number_format($cartSubtotal)?></span></div>
                <?php if(isset($_SESSION['coupon'])): ?>
                <div class="row" style="color:var(--success);"><span>Discount (<?=$_SESSION['coupon']['code']?>)</span><span>-<?=$settings['currency']??'৳'?><?=number_format($cartDiscount)?></span></div>
                <?php endif; ?>
                <div class="row"><span>Shipping</span><span><?=$settings['currency']??'৳'?><?=number_format($cartShipping)?></span></div>
                <div class="row total"><span>Total</span><span><?=$settings['currency']??'৳'?><?=number_format($cartTotal)?></span></div>
                <?php if(!isset($_SESSION['coupon'])): ?>
                <div class="coupon-input">
                    <input type="text" placeholder="Coupon code" id="couponInput">
                    <button onclick="applyCoupon()">Apply</button>
                </div>
                <?php else: ?>
                <div style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;">
                    <span style="font-size:0.85rem;color:var(--success);font-weight:600;"><i class="fas fa-check-circle"></i> <?=$_SESSION['coupon']['code']?> applied</span>
                    <button onclick="removeCoupon()" style="font-size:0.8rem;color:var(--accent);font-weight:600;">Remove</button>
                </div>
                <?php endif; ?>
                <a href="index.php?page=checkout" class="btn-checkout" style="display:block;text-align:center;text-decoration:none;"><i class="fas fa-lock"></i> Proceed to Checkout</a>
            </div>
        </div>
        <?php else: ?>
        <div class="empty-state">
            <i class="fas fa-shopping-bag"></i>
            <h3>Your Cart is Empty</h3>
            <p>Looks like you haven't added anything yet.</p>
            <a href="index.php?page=shop">Start Shopping</a>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php elseif($page==='checkout'): ?>
<?php if(empty($_SESSION['cart'])): gsRedirect('index.php?page=cart'); ?>
<?php else: ?>
<?php
    $coSubtotal = 0;
    foreach($_SESSION['cart'] as $ci) { $coSubtotal += $ci['price'] * $ci['qty']; }
    $coDiscount = 0;
    if(isset($_SESSION['coupon'])) {
        $cc = $_SESSION['coupon'];
        $coDiscount = ($cc['type']??'percent')==='percent' ? $coSubtotal*$cc['discount']/100 : min($cc['discount'], $coSubtotal);
    }
    $coShipping = 120;
    $coTotal = $coSubtotal - $coDiscount + $coShipping;
?>
<div class="page-header">
    <div class="container"><h1>Checkout</h1><p>Complete your order</p></div>
</div>
<div class="checkout-wrap">
    <div class="container">
        <div class="checkout-grid">
            <div class="checkout-form">
                <h2><i class="fas fa-map-marker-alt" style="color:var(--primary);margin-right:8px;"></i> Delivery Information</h2>
                <form id="checkoutForm" onsubmit="placeOrder(event)">
                    <div class="form-row">
                        <div class="form-group"><label>Full Name *</label><input type="text" name="fullname" required></div>
                        <div class="form-group"><label>Phone Number *</label><input type="tel" name="phone" required pattern="[0-9]{11}" title="Enter valid 11-digit phone number"></div>
                    </div>
                    <div class="form-row">
                        <div class="form-group"><label>Alternative Phone</label><input type="tel" name="alt_phone"></div>
                        <div class="form-group"><label>Email</label><input type="email" name="email"></div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>District *</label>
                            <select name="district" required id="coDistrict">
                                <option value="">Select District</option>
                                <?php foreach($bdDistricts as $dist): ?>
                                <option value="<?=gsSanitize($dist['name']??'')?>" <?=(!empty($_POST['district'])&&$_POST['district']===$dist['name'])?'selected':''?>><?=gsSanitize($dist['name']??'')?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Upazila *</label>
                            <select name="upazila" required id="coUpazila">
                                <option value="">Select District First</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group"><label>Full Address *</label><textarea name="address" rows="3" required placeholder="House, Road, Area..."></textarea></div>
                    <div class="form-group"><label>Postal Code</label><input type="text" name="postal"></div>
                    <input type="hidden" name="csrf_token" value="<?=$csrfToken?>">
                    <button type="submit" class="btn-checkout" id="placeOrderBtn"><i class="fas fa-check-circle"></i> Place Order — <?=$settings['currency']??'৳'?><?=number_format($coTotal)?></button>
                </form>
            </div>
            <div class="checkout-order">
                <h2>Order Summary</h2>
                <?php foreach($_SESSION['cart'] as $ci): ?>
                <div class="co-item">
                    <img src="<?=$ci['image']?>" alt="<?=gsSanitize($ci['title'])?>">
                    <div class="co-info">
                        <h4><?=gsSanitize($ci['title'])?></h4>
                        <span><?=$settings['currency']??'৳'?><?=number_format($ci['price'])?> x <?=$ci['qty']?><?php if($ci['size']): ?> — <?=$ci['size']?><?php endif; ?></span>
                    </div>
                </div>
                <?php endforeach; ?>
                <div style="margin-top:16px;padding-top:16px;border-top:2px solid var(--border);">
                    <div class="row" style="display:flex;justify-content:space-between;padding:6px 0;font-size:0.9rem;color:var(--text2);"><span>Subtotal</span><span><?=$settings['currency']??'৳'?><?=number_format($coSubtotal)?></span></div>
                    <?php if($coDiscount>0): ?><div class="row" style="display:flex;justify-content:space-between;padding:6px 0;font-size:0.9rem;color:var(--success);"><span>Discount</span><span>-<?=$settings['currency']??'৳'?><?=number_format($coDiscount)?></span></div><?php endif; ?>
                    <div class="row" style="display:flex;justify-content:space-between;padding:6px 0;font-size:0.9rem;color:var(--text2);"><span>Shipping</span><span><?=$settings['currency']??'৳'?><?=number_format($coShipping)?></span></div>
                    <div class="row" style="display:flex;justify-content:space-between;padding:12px 0 0;font-size:1.15rem;font-weight:900;color:var(--primary);border-top:2px solid var(--border);margin-top:8px;"><span>Total</span><span><?=$settings['currency']??'৳'?><?=number_format($coTotal)?></span></div>
                </div>
                <div style="margin-top:16px;padding:14px;background:var(--bg3);border-radius:var(--radius);display:flex;align-items:center;gap:10px;font-size:0.84rem;color:var(--text2);">
                    <i class="fas fa-shield-halved" style="color:var(--success);font-size:1.1rem;"></i>
                    Cash on Delivery — Pay when you receive
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<?php elseif($page==='order-success'): ?>
<?php $lastOrder = $_SESSION['last_order'] ?? null; ?>
<?php if($lastOrder): ?>
<div class="order-success">
    <div class="container">
        <div class="icon"><i class="fas fa-check"></i></div>
        <h1>Order Placed Successfully!</h1>
        <div class="order-id">Order ID: <?=$lastOrder['id']?></div>
        <?php if(!empty($lastOrder['tracking'])): ?>
        <p>Tracking Code: <strong style="color:var(--primary);"><?=$lastOrder['tracking']?></strong></p>
        <?php endif; ?>
        <p>Total: <strong><?=$settings['currency']??'৳'?><?=number_format($lastOrder['total'])?></strong></p>
        <div class="order-actions">
            <a href="index.php" class="btn-primary">Continue Shopping</a>
            <a href="index.php?page=track" class="btn-outline">Track Order</a>
        </div>
    </div>
</div>
<?php unset($_SESSION['last_order']); ?>
<?php else: gsRedirect('index.php'); endif; ?>

<?php elseif($page==='wishlist'): ?>
<div class="page-header">
    <div class="container"><h1>My Wishlist</h1><p><?=$wishlistCount?> saved items</p></div>
</div>
<section class="section">
    <div class="container">
        <?php
            $wishlistProducts = [];
            foreach($_SESSION['wishlist']??[] as $wId) {
                foreach($products as $wp) {
                    if($wp['id']===$wId && ($wp['status']??1)==1) { $wishlistProducts[] = $wp; break; }
                }
            }
        ?>
        <?php if(!empty($wishlistProducts)): ?>
        <div class="product-grid">
            <?php foreach($wishlistProducts as $wp): ?>
            <?php 
                $wImg = gsImgUrl($wp['images'][0]??'');
                $wPrice = floatval($wp['offer_price']??$wp['price']);
                $wOrig = floatval($wp['price']);
                $wDisc = $wOrig>0 ? round(($wOrig-$wPrice)/$wOrig*100) : 0;
                $wSizes = $wp['sizes'] ?? [];
                if(is_string($wSizes)) $wSizes = json_decode($wSizes, true) ?: [];
                $wHasSizes = !empty($wSizes);
                $wDefaultSize = $wHasSizes ? $wSizes[0] : 'Default';
            ?>
            <div class="product-card">
                <div class="badge-area">
                    <?php if($wDisc>0): ?><span class="p-badge sale">-<?=$wDisc?>%</span><?php endif; ?>
                </div>
                <div class="card-actions" style="opacity:1;transform:none;">
                    <button class="p-action-btn wishlisted" onclick="toggleWishlist('<?=$wp['id']?>',this)"><i class="fas fa-heart"></i></button>
                </div>
                <div class="card-image">
                    <a href="index.php?page=product&slug=<?=gsSanitize($wp['slug']??'')?>">
                        <img src="<?=$wImg?>" alt="<?=gsSanitize($wp['title']??'')?>" loading="lazy">
                    </a>
                </div>
                <div class="card-info">
                    <?php if(!empty($wp['brand'])): ?><div class="brand"><?=gsSanitize($wp['brand'])?></div><?php endif; ?>
                    <h3><a href="index.php?page=product&slug=<?=gsSanitize($wp['slug']??'')?>" style="color:var(--text)"><?=gsSanitize($wp['title'])?></a></h3>
                    <div class="price-row">
                        <span class="price"><?=$settings['currency']??'৳'?><?=number_format($wPrice)?></span>
                        <?php if($wDisc > 0): ?><span class="original"><?=$settings['currency']??'৳'?><?=number_format($wOrig)?></span><?php endif; ?>
                    </div>
                    <div class="card-btns">
                        <button class="btn-add-cart" onclick="addToCart('<?=$wp['id']?>','<?=$wDefaultSize?>',1,this)"><i class="fas fa-shopping-bag"></i> Add to Cart</button>
                        <button class="btn-order-now" onclick="orderNow('<?=$wp['id']?>','<?=$wDefaultSize?>')"><i class="fas fa-bolt"></i> Order Now</button>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php else: ?>
        <div class="wishlist-empty">
            <i class="far fa-heart"></i>
            <h3>Your Wishlist is Empty</h3>
            <p style="color:var(--text3);margin-bottom:20px;">Save your favorite items here.</p>
            <a href="index.php?page=shop" style="display:inline-flex;align-items:center;gap:8px;padding:12px 28px;background:var(--gradient);color:#0A0A1A;border-radius:50px;font-weight:700;font-size:0.92rem;">Browse Products</a>
        </div>
        <?php endif; ?>
    </div>
</section>

<?php elseif($page==='contact'): ?>
<div class="page-header">
    <div class="container"><h1>Contact Us</h1><p>We'd love to hear from you</p></div>
</div>
<section class="section">
    <div class="container">
        <div class="contact-grid">
            <div>
                <div class="contact-info-cards">
                    <div class="contact-info-card">
                        <div class="icon"><i class="fas fa-map-marker-alt"></i></div>
                        <div><h4>Our Location</h4><p>Dhaka, Bangladesh</p></div>
                    </div>
                    <div class="contact-info-card">
                        <div class="icon"><i class="fas fa-phone"></i></div>
                        <div><h4>Phone</h4><p>+880 1XXX-XXXXXX</p></div>
                    </div>
                    <div class="contact-info-card">
                        <div class="icon"><i class="fas fa-envelope"></i></div>
                        <div><h4>Email</h4><p>support@glowspace.com</p></div>
                    </div>
                    <div class="contact-info-card">
                        <div class="icon"><i class="fas fa-clock"></i></div>
                        <div><h4>Business Hours</h4><p>Sat - Thu: 10AM - 10PM</p></div>
                    </div>
                </div>
                <?php if(!empty($settings['facebook']) || !empty($settings['instagram']) || !empty($settings['tiktok'])): ?>
                <div style="margin-top:24px;">
                    <h4 style="font-weight:800;margin-bottom:12px;">Follow Us</h4>
                    <div class="social-links">
                        <?php if(!empty($settings['facebook'])): ?><a href="<?=gsSanitize($settings['facebook'])?>" target="_blank" class="social-link"><i class="fab fa-facebook-f"></i></a><?php endif; ?>
                        <?php if(!empty($settings['instagram'])): ?><a href="<?=gsSanitize($settings['instagram'])?>" target="_blank" class="social-link"><i class="fab fa-instagram"></i></a><?php endif; ?>
                        <?php if(!empty($settings['tiktok'])): ?><a href="<?=gsSanitize($settings['tiktok'])?>" target="_blank" class="social-link"><i class="fab fa-tiktok"></i></a><?php endif; ?>
                        <?php if(!empty($settings['youtube'])): ?><a href="<?=gsSanitize($settings['youtube'])?>" target="_blank" class="social-link"><i class="fab fa-youtube"></i></a><?php endif; ?>
                        <?php if(!empty($settings['telegram'])): ?><a href="<?=gsSanitize($settings['telegram'])?>" target="_blank" class="social-link"><i class="fab fa-telegram-plane"></i></a><?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            <div class="checkout-form">
                <h2><i class="fas fa-paper-plane" style="color:var(--primary);margin-right:8px;"></i> Send Message</h2>
                <form onsubmit="submitContact(event)">
                    <div class="form-group"><label>Your Name *</label><input type="text" required id="contactName"></div>
                    <div class="form-group"><label>Your Email *</label><input type="email" required id="contactEmail"></div>
                    <div class="form-group"><label>Subject</label><input type="text" id="contactSubject"></div>
                    <div class="form-group"><label>Message *</label><textarea rows="5" required id="contactMessage" style="width:100%;padding:12px 16px;border:2px solid var(--border);border-radius:var(--radius);background:var(--bg);color:var(--text);font-size:0.92rem;resize:vertical;outline:none;"></textarea></div>
                    <input type="hidden" id="contactCsrf" value="<?=$csrfToken?>">
                    <button type="submit" class="btn-checkout" style="border-radius:var(--radius);"><i class="fas fa-paper-plane"></i> Send Message</button>
                </form>
            </div>
        </div>
    </div>
</section>

<?php elseif($page==='track'): ?>
<div class="page-header">
    <div class="container"><h1>Track Your Order</h1><p>Enter your order ID to check status</p></div>
</div>
<section class="section">
    <div class="container">
        <div class="track-card">
            <h2><i class="fas fa-search" style="color:var(--primary);margin-right:8px;"></i> Track Order</h2>
            <form onsubmit="trackOrder(event)">
                <div class="form-group">
                    <label>Order ID</label>
                    <input type="text" placeholder="e.g. ORD-XXXXXXXX" required id="trackOrderId" style="width:100%;padding:12px 16px;border:2px solid var(--border);border-radius:var(--radius);background:var(--bg);color:var(--text);font-size:0.95rem;outline:none;font-weight:600;text-transform:uppercase;">
                </div>
                <button type="submit" class="btn-checkout" style="border-radius:var(--radius);margin-top:8px;"><i class="fas fa-truck"></i> Track Order</button>
            </form>
            <div id="trackResult" style="margin-top:20px;"></div>
        </div>
    </div>
</section>

<?php else: ?>
<section class="section" style="padding:80px 0;">
    <div class="container">
        <div class="empty-state">
            <i class="fas fa-compass"></i>
            <h3>Page Not Found</h3>
            <p>The page you're looking for doesn't exist.</p>
            <a href="index.php">Go Home</a>
        </div>
    </div>
</section>
<?php endif; ?>
</main>

<!-- Footer -->
<footer class="footer">
    <div class="container">
        <div class="footer-grid">
            <div class="footer-col">
                <a href="index.php" class="logo" style="margin-bottom:14px;display:inline-flex;">
                    <img src="https://i.postimg.cc/RZCmbTyt/file-00000000ac58820b832611934d0192fe.png" alt="GlowSpace" style="width:34px;height:34px;">
                    <span class="logo-text" style="font-size:1.3rem;">GlowSpace</span>
                </a>
                <p><?=gsSanitize($settings['tagline']??'Premium Tech Store')?> — Your trusted destination for the latest tech gadgets and accessories at the best prices in Bangladesh.</p>
                <?php if(!empty($settings['facebook']) || !empty($settings['instagram']) || !empty($settings['tiktok']) || !empty($settings['youtube']) || !empty($settings['telegram'])): ?>
                <div class="social-links" style="margin-top:16px;">
                    <?php if(!empty($settings['facebook'])): ?><a href="<?=gsSanitize($settings['facebook'])?>" target="_blank" class="social-link" aria-label="Facebook"><i class="fab fa-facebook-f"></i></a><?php endif; ?>
                    <?php if(!empty($settings['instagram'])): ?><a href="<?=gsSanitize($settings['instagram'])?>" target="_blank" class="social-link" aria-label="Instagram"><i class="fab fa-instagram"></i></a><?php endif; ?>
                    <?php if(!empty($settings['tiktok'])): ?><a href="<?=gsSanitize($settings['tiktok'])?>" target="_blank" class="social-link" aria-label="TikTok"><i class="fab fa-tiktok"></i></a><?php endif; ?>
                    <?php if(!empty($settings['youtube'])): ?><a href="<?=gsSanitize($settings['youtube'])?>" target="_blank" class="social-link" aria-label="YouTube"><i class="fab fa-youtube"></i></a><?php endif; ?>
                    <?php if(!empty($settings['telegram'])): ?><a href="<?=gsSanitize($settings['telegram'])?>" target="_blank" class="social-link" aria-label="Telegram"><i class="fab fa-telegram-plane"></i></a><?php endif; ?>
                    <?php if(!empty($settings['whatsapp'])): ?><a href="<?=gsSanitize($settings['whatsapp'])?>" target="_blank" class="social-link" aria-label="WhatsApp"><i class="fab fa-whatsapp"></i></a><?php endif; ?>
                </div>
                <?php endif; ?>
            </div>
            <div class="footer-col">
                <h4>Quick Links</h4>
                <ul>
                    <li><a href="index.php"><i class="fas fa-chevron-right"></i> Home</a></li>
                    <li><a href="index.php?page=shop"><i class="fas fa-chevron-right"></i> Shop</a></li>
                    <li><a href="index.php?page=cart"><i class="fas fa-chevron-right"></i> Cart</a></li>
                    <li><a href="index.php?page=wishlist"><i class="fas fa-chevron-right"></i> Wishlist</a></li>
                    <li><a href="index.php?page=contact"><i class="fas fa-chevron-right"></i> Contact</a></li>
                </ul>
            </div>
            <div class="footer-col">
                <h4>Categories</h4>
                <ul>
                    <?php foreach(array_slice($categories, 0, 6) as $fcat): ?>
                    <li><a href="index.php?page=shop&category=<?=urlencode($fcat['name']??'')?>"><i class="fas fa-chevron-right"></i> <?=gsSanitize($fcat['name']??'')?></a></li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <div class="footer-col">
                <h4>Support</h4>
                <ul>
                    <li><a href="index.php?page=track"><i class="fas fa-chevron-right"></i> Track Order</a></li>
                    <li><a href="index.php?page=contact"><i class="fas fa-chevron-right"></i> Help Center</a></li>
                    <li><a href="index.php?page=contact"><i class="fas fa-chevron-right"></i> Returns</a></li>
                    <li><a href="index.php?page=contact"><i class="fas fa-chevron-right"></i> Privacy Policy</a></li>
                    <li><a href="index.php?page=contact"><i class="fas fa-chevron-right"></i> Terms</a></li>
                </ul>
            </div>
        </div>
    </div>
    <div class="footer-bottom">
        <div class="container" style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;">
            <span>&copy; <?=date('Y')?> GlowSpace. All rights reserved.</span>
            <span>Powered by <strong style="color:var(--primary);">GlowSpace</strong></span>
        </div>
    </div>
</footer>

<!-- Floating WhatsApp -->
<?php if(!empty($settings['whatsapp'])): ?>
<a href="<?=gsSanitize($settings['whatsapp'])?>" target="_blank" class="floating-whatsapp" aria-label="WhatsApp"><i class="fab fa-whatsapp"></i></a>
<?php endif; ?>

<!-- Back to Top -->
<button class="back-to-top" id="backToTop" aria-label="Back to top"><i class="fas fa-chevron-up"></i></button>

<script>
(function(){
    'use strict';

    // === LOADER ===
    window.addEventListener('load', function() {
        setTimeout(function() {
            document.getElementById('loader').classList.add('hide');
        }, 1800);
    });

    // === THEME ===
    var savedTheme = localStorage.getItem('gs_theme') || 'light';
    document.documentElement.setAttribute('data-theme', savedTheme);
    updateThemeIcon(savedTheme);

    function updateThemeIcon(t) {
        var icon = document.getElementById('themeIcon');
        if (icon) {
            icon.className = t === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
        }
    }

    window.toggleTheme = function() {
        var current = document.documentElement.getAttribute('data-theme');
        var next = current === 'dark' ? 'light' : 'dark';
        document.documentElement.setAttribute('data-theme', next);
        localStorage.setItem('gs_theme', next);
        updateThemeIcon(next);
    };

    // === HEADER SCROLL ===
    var header = document.getElementById('mainHeader');
    var lastScroll = 0;
    window.addEventListener('scroll', function() {
        var st = window.pageYOffset;
        if (header) {
            if (st > 50) {
                header.classList.add('scrolled');
            } else {
                header.classList.remove('scrolled');
            }
        }
        lastScroll = st;
    }, { passive: true });

    // === BACK TO TOP ===
    var btt = document.getElementById('backToTop');
    window.addEventListener('scroll', function() {
        if (btt) {
            if (window.pageYOffset > 400) {
                btt.classList.add('visible');
            } else {
                btt.classList.remove('visible');
            }
        }
    }, { passive: true });
    if (btt) {
        btt.addEventListener('click', function() {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        });
    }

    // === MOBILE MENU ===
    var hamburger = document.getElementById('hamburgerBtn');
    var mobileMenu = document.getElementById('mobileMenu');
    var mmOverlay = document.getElementById('mmOverlay');
    var mmClose = document.getElementById('mmClose');

    function openMenu() {
        if (mobileMenu) mobileMenu.classList.add('open');
        if (mmOverlay) mmOverlay.classList.add('open');
        if (hamburger) hamburger.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
    function closeMenu() {
        if (mobileMenu) mobileMenu.classList.remove('open');
        if (mmOverlay) mmOverlay.classList.remove('open');
        if (hamburger) hamburger.classList.remove('active');
        document.body.style.overflow = '';
    }
    if (hamburger) hamburger.addEventListener('click', function() {
        if (mobileMenu && mobileMenu.classList.contains('open')) { closeMenu(); } else { openMenu(); }
    });
    if (mmOverlay) mmOverlay.addEventListener('click', closeMenu);
    if (mmClose) mmClose.addEventListener('click', closeMenu);

    // === CART DRAWER ===
    var cartDrawer = document.getElementById('cartDrawer');
    var cartDrawerOverlay = document.getElementById('cartDrawerOverlay');
    var cartDrawerBtn = document.getElementById('cartDrawerBtn');
    var cdClose = document.getElementById('cdClose');
    var cdBody = document.getElementById('cdBody');
    var cdFooter = document.getElementById('cdFooter');
    var cdSubtotalVal = document.getElementById('cdSubtotalVal');
    var cartCurrency = '<?=$settings["currency"]??"৳"?>';

    function openCartDrawer() {
        if (!cartDrawer) return;
        closeMenu();
        cartDrawer.classList.add('open');
        if (cartDrawerOverlay) cartDrawerOverlay.classList.add('open');
        document.body.style.overflow = 'hidden';
        loadCartDrawer();
    }
    function closeCartDrawer() {
        if (!cartDrawer) return;
        cartDrawer.classList.remove('open');
        if (cartDrawerOverlay) cartDrawerOverlay.classList.remove('open');
        document.body.style.overflow = '';
    }
    window.closeCartDrawer = closeCartDrawer;

    function renderCartDrawer(data) {
        if (!cdBody) return;
        if (!data.items || data.items.length === 0) {
            cdBody.innerHTML = '<div class="cd-empty"><i class="fas fa-shopping-bag"></i><div style="font-weight:700;color:var(--text);margin-bottom:4px;">Your cart is empty</div><div style="font-size:0.85rem;">Add items to see them here</div></div>';
            if (cdFooter) cdFooter.style.display = 'none';
            return;
        }
        var html = '';
        data.items.forEach(function(item) {
            html += '<div class="cd-item" data-key="' + item.key + '">' +
                '<img src="' + item.image + '" alt="">' +
                '<div class="cd-item-info">' +
                '<h4>' + item.title + '</h4>' +
                (item.size ? '<div style="font-size:0.7rem;color:var(--text3);margin-bottom:2px;">Size: ' + item.size + '</div>' : '') +
                '<div class="cd-price">' + cartCurrency + Number(item.price).toLocaleString() + '</div>' +
                '<div class="cd-item-qty">' +
                '<button onclick="cdChangeQty(\'' + item.key + '\',' + (item.qty - 1) + ')"><i class="fas fa-minus"></i></button>' +
                '<span>' + item.qty + '</span>' +
                '<button onclick="cdChangeQty(\'' + item.key + '\',' + (item.qty + 1) + ')"><i class="fas fa-plus"></i></button>' +
                '</div></div>' +
                '<button class="cd-remove" onclick="cdRemoveItem(\'' + item.key + '\')"><i class="fas fa-trash-alt"></i></button>' +
                '</div>';
        });
        cdBody.innerHTML = html;
        if (cdFooter) cdFooter.style.display = 'block';
        if (cdSubtotalVal) cdSubtotalVal.textContent = cartCurrency + Number(data.subtotal).toLocaleString();
    }

    function loadCartDrawer() {
        if (!cdBody) return;
        cdBody.innerHTML = '<div class="cd-empty"><i class="fas fa-spinner fa-spin"></i></div>';
        var formData = new FormData();
        formData.append('action', 'get_cart');
        fetch('index.php', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.success) { renderCartDrawer(data); }
            })
            .catch(function() {
                cdBody.innerHTML = '<div class="cd-empty"><i class="fas fa-exclamation-triangle"></i>Could not load cart</div>';
            });
    }

    window.cdChangeQty = function(key, qty) {
        qty = parseInt(qty);
        var formData = new FormData();
        formData.append('action', 'update_cart');
        formData.append('cart_key', key);
        formData.append('qty', Math.max(0, qty));
        fetch('index.php', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.success) { updateCartBadges(data.cart_count); loadCartDrawer(); }
            });
    };

    window.cdRemoveItem = function(key) {
        var formData = new FormData();
        formData.append('action', 'remove_cart');
        formData.append('cart_key', key);
        fetch('index.php', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.success) { updateCartBadges(data.cart_count); loadCartDrawer(); showToast('Item removed', 'success'); }
            });
    };

    if (cartDrawerBtn) cartDrawerBtn.addEventListener('click', function(e) {
        if (e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1) return;
        e.preventDefault();
        openCartDrawer();
    });
    if (cartDrawerOverlay) cartDrawerOverlay.addEventListener('click', closeCartDrawer);
    if (cdClose) cdClose.addEventListener('click', closeCartDrawer);

    // === SEARCH ===
    var searchInput = document.getElementById('searchInput');
    var searchResults = document.getElementById('searchResults');
    var searchTimer = null;

    function performSearch(query, resultsEl) {
        if (!query || query.length < 2) {
            if (resultsEl) resultsEl.classList.remove('active');
            return;
        }
        fetch('index.php?action=search&q=' + encodeURIComponent(query), { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (!resultsEl) return;
                if (data.length === 0) {
                    resultsEl.innerHTML = '<div class="search-empty"><i class="fas fa-search"></i>No products found for "' + query + '"</div>';
                } else {
                    var html = '';
                    data.forEach(function(item) {
                        html += '<a href="index.php?page=product&slug=' + encodeURIComponent(item.slug || '') + '" class="search-result-item">' +
                            '<img src="' + (item.images[0] || '') + '" alt="">' +
                            '<div class="sr-info"><h4>' + item.title + '</h4>' +
                            '<span>' + (item.currency || '\u09f3') + Number(item.offer_price || item.price).toLocaleString() + '</span>' +
                            '<div class="sr-cat">' + (item.category || '') + (item.brand ? ' / ' + item.brand : '') + '</div></div></a>';
                    });
                    resultsEl.innerHTML = html;
                }
                resultsEl.classList.add('active');
            })
            .catch(function() {
                if (resultsEl) resultsEl.classList.remove('active');
            });
    }

    if (searchInput) {
        searchInput.addEventListener('input', function() {
            clearTimeout(searchTimer);
            var q = this.value.trim();
            searchTimer = setTimeout(function() { performSearch(q, searchResults); }, 250);
        });
        searchInput.addEventListener('focus', function() {
            if (this.value.trim().length >= 2) {
                performSearch(this.value.trim(), searchResults);
            }
        });
    }

    document.addEventListener('click', function(e) {
        if (searchResults && !searchResults.contains(e.target) && e.target !== searchInput) {
            searchResults.classList.remove('active');
        }
        if (mmSearchResults && !mmSearchResults.contains(e.target) && e.target !== mmSearchInput) {
            mmSearchResults.classList.remove('active');
        }
    });

    // Mobile search
    var mmSearchInput = document.getElementById('mmSearchInput');
    var mmSearchResults = document.getElementById('mmSearchResults');
    var mmSearchTimer = null;

    if (mmSearchInput) {
        mmSearchInput.addEventListener('input', function() {
            clearTimeout(mmSearchTimer);
            var q = this.value.trim();
            mmSearchTimer = setTimeout(function() { performSearch(q, mmSearchResults); }, 250);
        });
    }

    window.doSearch = function() {
        var q = searchInput ? searchInput.value.trim() : '';
        if (q.length >= 2) {
            window.location.href = 'index.php?page=shop&q=' + encodeURIComponent(q);
        }
    };

    if (searchInput) {
        searchInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') { e.preventDefault(); doSearch(); }
        });
    }

    // === HERO SLIDER ===
    var heroSlider = document.getElementById('heroSlider');
    var heroDots = document.getElementById('heroDots');
    var heroPrev = document.getElementById('heroPrev');
    var heroNext = document.getElementById('heroNext');
    var currentSlide = 0;
    var totalSlides = heroSlider ? heroSlider.children.length : 0;
    var slideInterval = null;

    function goToSlide(n) {
        if (!heroSlider || totalSlides <= 1) return;
        currentSlide = ((n % totalSlides) + totalSlides) % totalSlides;
        heroSlider.style.transform = 'translateX(-' + (currentSlide * 100) + '%)';
        if (heroDots) {
            var dots = heroDots.querySelectorAll('.hero-dot');
            dots.forEach(function(d, i) { d.classList.toggle('active', i === currentSlide); });
        }
    }

    function startSlider() {
        if (totalSlides <= 1) return;
        slideInterval = setInterval(function() { goToSlide(currentSlide + 1); }, 5000);
    }

    function stopSlider() { clearInterval(slideInterval); }

    if (heroPrev) heroPrev.addEventListener('click', function() { stopSlider(); goToSlide(currentSlide - 1); startSlider(); });
    if (heroNext) heroNext.addEventListener('click', function() { stopSlider(); goToSlide(currentSlide + 1); startSlider(); });
    if (heroDots) {
        heroDots.querySelectorAll('.hero-dot').forEach(function(dot) {
            dot.addEventListener('click', function() {
                stopSlider();
                goToSlide(parseInt(this.dataset.slide));
                startSlider();
            });
        });
    }

    // Touch swipe for hero
    if (heroSlider && totalSlides > 1) {
        var touchStartX = 0;
        var touchEndX = 0;
        heroSlider.addEventListener('touchstart', function(e) { touchStartX = e.changedTouches[0].screenX; stopSlider(); }, { passive: true });
        heroSlider.addEventListener('touchend', function(e) {
            touchEndX = e.changedTouches[0].screenX;
            var diff = touchStartX - touchEndX;
            if (Math.abs(diff) > 50) {
                if (diff > 0) goToSlide(currentSlide + 1);
                else goToSlide(currentSlide - 1);
            }
            startSlider();
        }, { passive: true });
    }

    startSlider();

    // === FLASH SALE COUNTDOWN ===
    function updateCountdown() {
        var now = new Date();
        var end = new Date();
        end.setHours(23, 59, 59, 999);
        var diff = end - now;
        if (diff <= 0) diff = 0;
        var h = Math.floor(diff / 3600000);
        var m = Math.floor((diff % 3600000) / 60000);
        var s = Math.floor((diff % 60000) / 1000);
        var hEl = document.getElementById('cdHours');
        var mEl = document.getElementById('cdMins');
        var sEl = document.getElementById('cdSecs');
        if (hEl) hEl.textContent = String(h).padStart(2, '0');
        if (mEl) mEl.textContent = String(m).padStart(2, '0');
        if (sEl) sEl.textContent = String(s).padStart(2, '0');
    }
    updateCountdown();
    setInterval(updateCountdown, 1000);

    // === TOAST ===
    window.showToast = function(msg, type) {
        type = type || 'success';
        var container = document.getElementById('toastContainer');
        if (!container) return;
        var toast = document.createElement('div');
        toast.className = 'toast ' + type;
        var iconClass = type === 'success' ? 'fas fa-check-circle' : type === 'error' ? 'fas fa-exclamation-circle' : 'fas fa-info-circle';
        toast.innerHTML = '<i class="' + iconClass + '"></i><span>' + msg + '</span>';
        container.appendChild(toast);
        setTimeout(function() {
            toast.style.opacity = '0';
            toast.style.transform = 'translateX(40px)';
            toast.style.transition = 'all 0.3s ease';
            setTimeout(function() { toast.remove(); }, 300);
        }, 3500);
    };

    // === ADD TO CART ===
    window.addToCart = function(pid, size, qty, btn) {
        if (btn) {
            btn.disabled = true;
            var origHTML = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Adding...';
        }
        var formData = new FormData();
        formData.append('action', 'add_to_cart');
        formData.append('product_id', pid);
        formData.append('size', size || '');
        formData.append('qty', qty || 1);
        formData.append('csrf_token', '<?=$csrfToken?>');

        fetch('index.php', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.success) {
                    showToast('Added to cart!', 'success');
                    updateCartBadges(data.cart_count);
                } else {
                    showToast(data.msg || 'Error adding to cart', 'error');
                }
            })
            .catch(function() { showToast('Network error', 'error'); })
            .finally(function() {
                if (btn) {
                    btn.disabled = false;
                    btn.innerHTML = origHTML;
                }
            });
    };

    // === ORDER NOW (instant checkout) ===
    window.orderNow = function(pid, size) {
        var formData = new FormData();
        formData.append('action', 'add_to_cart');
        formData.append('product_id', pid);
        formData.append('size', size || '');
        formData.append('qty', 1);
        formData.append('csrf_token', '<?=$csrfToken?>');

        fetch('index.php', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.success) {
                    updateCartBadges(data.cart_count);
                    window.location.href = 'index.php?page=checkout';
                } else {
                    showToast(data.msg || 'Error', 'error');
                }
            })
            .catch(function() { showToast('Network error', 'error'); });
    };

    // === UPDATE CART BADGES ===
    function updateCartBadges(count) {
        var badges = document.querySelectorAll('.hdr-btn .badge');
        badges.forEach(function(b) {
            if (b.closest('.cart-btn') || b.parentElement.href.indexOf('cart') > -1) {
                if (count > 0) { b.textContent = count; b.style.display = 'flex'; }
                else { b.style.display = 'none'; }
            }
        });
    }

    // === CART ACTIONS ===
    window.updateCartQty = function(key, qty) {
        qty = parseInt(qty);
        if (isNaN(qty) || qty < 1) qty = 1;
        var formData = new FormData();
        formData.append('action', 'update_cart');
        formData.append('cart_key', key);
        formData.append('qty', qty);
        fetch('index.php', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.success) { updateCartBadges(data.cart_count); window.location.reload(); }
            });
    };

    window.removeCartItem = function(key) {
        var formData = new FormData();
        formData.append('action', 'remove_cart');
        formData.append('cart_key', key);
        fetch('index.php', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.success) { updateCartBadges(data.cart_count); window.location.reload(); }
            });
    };

    // === COUPON ===
    window.applyCoupon = function() {
        var code = document.getElementById('couponInput');
        if (!code || !code.value.trim()) { showToast('Enter a coupon code', 'error'); return; }
        var formData = new FormData();
        formData.append('action', 'apply_coupon');
        formData.append('code', code.value.trim());
        fetch('index.php', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.success) { showToast(data.msg, 'success'); window.location.reload(); }
                else { showToast(data.msg, 'error'); }
            });
    };

    window.removeCoupon = function() {
        var formData = new FormData();
        formData.append('action', 'remove_coupon');
        fetch('index.php', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function(r) { return r.json(); })
            .then(function(data) { if (data.success) window.location.reload(); });
    };

    // === WISHLIST ===
    window.toggleWishlist = function(pid, btn) {
        var formData = new FormData();
        formData.append('action', 'wishlist_toggle');
        formData.append('product_id', pid);
        fetch('index.php', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.status === 'added') {
                    if (btn) btn.classList.add('wishlisted');
                    showToast('Added to wishlist!', 'success');
                } else {
                    if (btn) btn.classList.remove('wishlisted');
                    showToast('Removed from wishlist', 'success');
                    if ('<?=$page?>' === 'wishlist') window.location.reload();
                }
            });
    };

    // === PRODUCT DETAIL ===
    window.changePdImage = function(src, thumb) {
        var main = document.getElementById('pdMainImage');
        if (main) main.src = src;
        document.querySelectorAll('.pd-thumb').forEach(function(t) { t.classList.remove('active'); });
        if (thumb) thumb.classList.add('active');
    };

    window.pdQtyChange = function(delta) {
        var input = document.getElementById('pdQtyInput');
        if (!input) return;
        var val = parseInt(input.value) || 1;
        val = Math.max(1, Math.min(99, val + delta));
        input.value = val;
    };

    // Swipe gallery support on touch devices
    (function() {
        var pdMain = document.getElementById('pdMainImage');
        if (!pdMain) return;
        var pdThumbs = Array.prototype.slice.call(document.querySelectorAll('.pd-thumb'));
        if (pdThumbs.length < 2) return;
        var pdIdx = 0;
        var touchStartX = 0;
        var wrap = pdMain.closest('.pd-main-img') || pdMain.parentElement;
        wrap.addEventListener('touchstart', function(e) {
            touchStartX = e.changedTouches[0].screenX;
        }, { passive: true });
        wrap.addEventListener('touchend', function(e) {
            var diff = touchStartX - e.changedTouches[0].screenX;
            if (Math.abs(diff) > 40) {
                pdIdx = diff > 0 ? Math.min(pdIdx + 1, pdThumbs.length - 1) : Math.max(pdIdx - 1, 0);
                pdThumbs[pdIdx].click();
                pdThumbs[pdIdx].scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' });
            }
        }, { passive: true });
    })();

    <?php if($page==='product' && $currentProduct): ?>
    window.pdAddToCart = function() {
        var size = '';
        <?php if($productHasSizes): ?>
        var sel = document.getElementById('pdSizeSelect');
        size = sel ? sel.value : '';
        <?php endif; ?>
        var qty = parseInt(document.getElementById('pdQtyInput').value) || 1;
        addToCart('<?=$currentProduct['id']?>', size, qty, document.querySelector('.pd-actions .btn-cart'));
    };

    window.pdBuyNow = function() {
        var size = '';
        <?php if($productHasSizes): ?>
        var sel = document.getElementById('pdSizeSelect');
        size = sel ? sel.value : '';
        <?php endif; ?>
        var qty = parseInt(document.getElementById('pdQtyInput').value) || 1;
        var formData = new FormData();
        formData.append('action', 'add_to_cart');
        formData.append('product_id', '<?=$currentProduct['id']?>');
        formData.append('size', size);
        formData.append('qty', qty);
        formData.append('csrf_token', '<?=$csrfToken?>');
        var btn = document.querySelector('.pd-actions .btn-buy');
        if (btn) { btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...'; }
        fetch('index.php', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.success) {
                    updateCartBadges(data.cart_count);
                    window.location.href = 'index.php?page=checkout';
                } else {
                    showToast(data.msg || 'Error', 'error');
                    if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fas fa-bolt"></i> Order Now'; }
                }
            })
            .catch(function() {
                showToast('Network error', 'error');
                if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fas fa-bolt"></i> Order Now'; }
            });
    };
    <?php endif; ?>

    // === TABS ===
    document.querySelectorAll('.tab-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var tabId = this.dataset.tab;
            this.closest('.pd-tabs').querySelectorAll('.tab-btn').forEach(function(b) { b.classList.remove('active'); });
            this.classList.add('active');
            this.closest('.pd-tabs').querySelectorAll('.pd-tab-content').forEach(function(c) { c.classList.remove('active'); });
            var target = document.getElementById('tab-' + tabId);
            if (target) target.classList.add('active');
        });
    });

    // === PLACE ORDER ===
    window.placeOrder = function(e) {
        e.preventDefault();
        var form = document.getElementById('checkoutForm');
        var btn = document.getElementById('placeOrderBtn');
        if (!form || !btn) return;
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing Order...';

        var formData = new FormData(form);
        formData.append('action', 'place_order');

        fetch('index.php', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.success) {
                    window.location.href = 'index.php?page=order-success';
                } else {
                    showToast(data.msg || 'Order failed', 'error');
                    btn.disabled = false;
                    btn.innerHTML = '<i class="fas fa-check-circle"></i> Place Order';
                }
            })
            .catch(function() {
                showToast('Network error. Please try again.', 'error');
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-check-circle"></i> Place Order';
            });
    };

    // === CHECKOUT DISTRICT/UPAZILA ===
    var coDistrict = document.getElementById('coDistrict');
    var coUpazila = document.getElementById('coUpazila');
    var bdUpazilas = <?=json_encode($bdUpazilas)?>;

    if (coDistrict && coUpazila) {
        coDistrict.addEventListener('change', function() {
            var distName = this.value;
            coUpazila.innerHTML = '<option value="">Select Upazila</option>';
            if (!distName) return;
            var filtered = bdUpazilas.filter(function(u) { return u.district === distName; });
            filtered.forEach(function(u) {
                var opt = document.createElement('option');
                opt.value = u.name;
                opt.textContent = u.name;
                coUpazila.appendChild(opt);
            });
        });
        if (coDistrict.value) {
            coDistrict.dispatchEvent(new Event('change'));
        }
    }

    // === SUBMIT REVIEW ===
    window.submitReview = function(e, pid) {
        e.preventDefault();
        var formData = new FormData();
        formData.append('action', 'submit_review');
        formData.append('product_id', pid);
        formData.append('name', document.getElementById('revName').value);
        formData.append('rating', document.getElementById('revRating').value);
        formData.append('text', document.getElementById('revText').value);
        formData.append('csrf_token', '<?=$csrfToken?>');

        fetch('index.php', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.success) { showToast(data.msg, 'success'); document.getElementById('revName').value=''; document.getElementById('revText').value=''; }
                else { showToast(data.msg, 'error'); }
            });
    };

    // === CONTACT FORM ===
    window.submitContact = function(e) {
        e.preventDefault();
        var formData = new FormData();
        formData.append('action', 'contact');
        formData.append('name', document.getElementById('contactName').value);
        formData.append('email', document.getElementById('contactEmail').value);
        formData.append('csrf_token', document.getElementById('contactCsrf').value);

        fetch('index.php', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.success) { showToast(data.msg, 'success'); document.getElementById('contactName').value=''; document.getElementById('contactEmail').value=''; document.getElementById('contactSubject').value=''; document.getElementById('contactMessage').value=''; }
                else { showToast(data.msg, 'error'); }
            });
    };

    // === NEWSLETTER ===
    window.subscribeNewsletter = function(e) {
        e.preventDefault();
        var email = document.getElementById('newsletterEmail');
        if (!email || !email.value.trim()) return;
        var formData = new FormData();
        formData.append('action', 'newsletter');
        formData.append('email', email.value.trim());

        fetch('index.php', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.success) { showToast(data.msg, 'success'); email.value = ''; }
                else { showToast(data.msg, 'error'); }
            });
    };

    // === TRACK ORDER ===
    window.trackOrder = function(e) {
        e.preventDefault();
        var oid = document.getElementById('trackOrderId').value.trim().toUpperCase();
        var resultDiv = document.getElementById('trackResult');
        if (!oid || !resultDiv) return;

        resultDiv.innerHTML = '<div style="text-align:center;padding:20px;color:var(--text3);"><i class="fas fa-spinner fa-spin" style="font-size:1.5rem;"></i></div>';

        var formData = new FormData();
        formData.append('action', 'check_order');
        formData.append('order_id', oid);

        fetch('index.php', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.success) {
                    var o = data.order;
                    var statusColors = { pending: 'var(--warning)', confirmed: 'var(--secondary)', shipped: 'var(--primary)', delivered: 'var(--success)', cancelled: 'var(--accent)' };
                    var statusColor = statusColors[o.status] || 'var(--text3)';
                    resultDiv.innerHTML = '<div style="padding:20px;background:var(--bg3);border-radius:var(--radius-lg);border-left:4px solid ' + statusColor + ';">' +
                        '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;flex-wrap:wrap;gap:8px;">' +
                        '<div><strong style="font-size:0.82rem;color:var(--text3);text-transform:uppercase;letter-spacing:0.5px;">Order ID</strong><div style="font-weight:800;font-size:1.05rem;">' + o.id + '</div></div>' +
                        '<div style="padding:6px 16px;border-radius:50px;background:' + statusColor + ';color:#fff;font-weight:700;font-size:0.82rem;text-transform:uppercase;">' + o.status + '</div></div>' +
                        (o.tracking ? '<div style="margin-bottom:8px;"><strong>Tracking:</strong> <span style="color:var(--primary);font-weight:700;">' + o.tracking + '</span></div>' : '') +
                        '<div style="font-size:0.85rem;color:var(--text2);"><strong>Date:</strong> ' + o.date + '</div>' +
                        '<div style="font-size:0.85rem;color:var(--text2);margin-top:4px;"><strong>Total:</strong> <?=$settings['currency']??'৳'?>' + Number(o.total).toLocaleString() + '</div></div>';
                } else {
                    resultDiv.innerHTML = '<div style="padding:20px;background:rgba(255,77,109,0.06);border-radius:var(--radius-lg);color:var(--accent);text-align:center;"><i class="fas fa-exclamation-triangle" style="font-size:1.5rem;margin-bottom:8px;display:block;"></i>' + (data.msg || 'Order not found') + '</div>';
                }
            })
            .catch(function() {
                resultDiv.innerHTML = '<div style="padding:20px;color:var(--accent);text-align:center;">Network error. Please try again.</div>';
            });
    };

    // === PROMO POPUP ===
    window.closePromo = function() {
        var popup = document.getElementById('promoPopup');
        if (popup) popup.classList.remove('show');
        fetch('index.php?action=newsletter&email=promo_dismissed', { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
    };
    <?php if(($settings['promo_popup']??false) && empty($_SESSION['promo_dismissed'])): ?>
    setTimeout(function() {
        var popup = document.getElementById('promoPopup');
        if (popup) popup.classList.add('show');
    }, 2500);
    <?php endif; ?>

    // === COOKIE NOTICE ===
    window.acceptCookies = function() {
        var notice = document.getElementById('cookieNotice');
        if (notice) notice.classList.remove('show');
        document.cookie = 'cookie_accepted=1;path=/;max-age=' + (60*60*24*365);
    };
    <?php if(($settings['cookie_notice']??false) && empty($_COOKIE['cookie_accepted'])): ?>
    setTimeout(function() {
        var notice = document.getElementById('cookieNotice');
        if (notice) notice.classList.add('show');
    }, 3000);
    <?php endif; ?>

    // === SCROLL ANIMATIONS ===
    var observerOptions = { threshold: 0.1, rootMargin: '0px 0px -40px 0px' };
    var observer = new IntersectionObserver(function(entries) {
        entries.forEach(function(entry) {
            if (entry.isIntersecting) {
                entry.target.classList.add('visible');
                observer.unobserve(entry.target);
            }
        });
    }, observerOptions);

    document.querySelectorAll('.animate-on-scroll').forEach(function(el) {
        observer.observe(el);
    });

    // === KEYBOARD: ESC closes menus ===
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeMenu();
            var popup = document.getElementById('promoPopup');
            if (popup) popup.classList.remove('show');
        }
    });

})();
</script>
</body>
</html>