<?php

require_once __DIR__ . '/db.php';

try {
    $pixel = $pdo->query("SELECT meta_pixel_id, meta_pixel_enabled FROM stores WHERE id = 1")->fetch();
} catch (Exception $e) {
    $pixel = null;
}

if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $product_id = (int) $_GET['id'];
} else {
    die("معرف المنتج غير صالح أو مفقود");
}

if (session_status() === PHP_SESSION_NONE) session_start();
$session_key = 'meta_event_id_' . $product_id;
if (empty($_SESSION[$session_key])) {
    $_SESSION[$session_key] = 'evt_' . bin2hex(random_bytes(16));
}
$meta_event_id = $_SESSION[$session_key];

$product = [];
$product_attributes = [];
$product_images = [];
$product_variants = [];
$delivery_info = [];
$delivery_prices_home = [];
$delivery_prices_office = [];
$wilayas = [];

function formatWilayaForDisplay($id, $name) {
    $id_padded = str_pad($id, 2, '0', STR_PAD_LEFT);
    $arabic_names = [
        1=>'أدرار',2=>'الشلف',3=>'الأغواط',4=>'أم البواقي',5=>'باتنة',
        6=>'بجاية',7=>'بسكرة',8=>'بشار',9=>'البليدة',10=>'البويرة',
        11=>'تمنراست',12=>'تبسة',13=>'تلمسان',14=>'تيارت',15=>'تيزي وزو',
        16=>'الجزائر',17=>'الجلفة',18=>'جيجل',19=>'سطيف',20=>'سعيدة',
        21=>'سكيكدة',22=>'سيدي بلعباس',23=>'عنابة',24=>'قالمة',25=>'قسنطينة',
        26=>'المدية',27=>'مستغانم',28=>'المسيلة',29=>'معسكر',30=>'ورقلة',
        31=>'وهران',32=>'البيض',33=>'إليزي',34=>'برج بوعريريج',35=>'بومرداس',
        36=>'الطارف',37=>'تندوف',38=>'تيسمسيلت',39=>'الوادي',40=>'خنشلة',
        41=>'سوق أهراس',42=>'تيبازة',43=>'ميلة',44=>'عين الدفلة',45=>'النعامة',
        46=>'عين تموشنت',47=>'غرداية',48=>'غليزان',49=>'تيميمون',50=>'برج باجي مختار',
        51=>'أولاد جلال',52=>'بني عباس',53=>'عين صالح',54=>'عين قزام',55=>'تقرت',
        56=>'جانت',57=>'المغير',58=>'المنيعة'
    ];
    $arabic_name = isset($arabic_names[$id]) ? $arabic_names[$id] : $name;
    return $id_padded . ' - ' . $name . ' / ' . $arabic_name;
}

try {
    $stmt = $pdo->prepare("
        SELECT p.*, c.name AS category_name,
               (SELECT GROUP_CONCAT(dc.id) FROM product_delivery_companies pdc
                JOIN delivery_companies dc ON pdc.delivery_company_id = dc.id
                WHERE pdc.product_id = p.id) AS delivery_company_ids
        FROM products p
        LEFT JOIN categories c ON p.category_id = c.id
        WHERE p.id = ?
    ");
    $stmt->execute([$product_id]);
    $product = $stmt->fetch();
    if (!$product) { die("المنتج غير موجود"); }

    $stmt = $pdo->prepare("SELECT a.id, a.name, pa.value, a.input_type, a.values_list FROM product_attributes pa JOIN attributes a ON pa.attribute_id = a.id WHERE pa.product_id = ?");
    $stmt->execute([$product_id]);
    $product_attributes = $stmt->fetchAll();

    $stmt = $pdo->prepare("SELECT image_url, is_primary FROM product_images WHERE product_id = ? ORDER BY is_primary DESC, id ASC");
    $stmt->execute([$product_id]);
    $product_images = $stmt->fetchAll();

    $stmt = $pdo->prepare("SELECT pv.id, pv.sku, pv.price, pv.stock, pv.is_default FROM product_variants pv WHERE pv.product_id = ?");
    $stmt->execute([$product_id]);
    $product_variants = $stmt->fetchAll();

    foreach ($product_variants as &$variant) {
        $stmt = $pdo->prepare("SELECT a.name AS attribute_name, va.attribute_value FROM variant_attributes va JOIN attributes a ON va.attribute_id = a.id WHERE va.variant_id = ?");
        $stmt->execute([$variant['id']]);
        $variant['variant_attrs'] = $stmt->fetchAll();
        $stmt = $pdo->prepare("SELECT image_url, is_primary FROM variant_images WHERE variant_id = ? ORDER BY is_primary DESC, id ASC");
        $stmt->execute([$variant['id']]);
        $variant['variant_images'] = $stmt->fetchAll();
    }
    unset($variant);

    if (!empty($product['delivery_company_ids'])) {
        $delivery_company_ids = explode(',', $product['delivery_company_ids']);
        $first_company_id = $delivery_company_ids[0];
        $stmt = $pdo->prepare("SELECT dc.id, dc.name FROM delivery_companies dc WHERE dc.id = ?");
        $stmt->execute([$first_company_id]);
        $delivery_info = $stmt->fetch();
        $stmt = $pdo->prepare("SELECT dp.wilaya_id, dp.price, w.name AS wilaya_name FROM delivery_prices dp JOIN wilayas w ON dp.wilaya_id = w.id WHERE dp.delivery_company_id = ? AND dp.delivery_type = 'home'");
        $stmt->execute([$first_company_id]);
        $delivery_prices_home = $stmt->fetchAll();
        $stmt = $pdo->prepare("SELECT dp.wilaya_id, dp.price, w.name AS wilaya_name FROM delivery_prices dp JOIN wilayas w ON dp.wilaya_id = w.id WHERE dp.delivery_company_id = ? AND dp.delivery_type = 'office'");
        $stmt->execute([$first_company_id]);
        $delivery_prices_office = $stmt->fetchAll();
        $available_wilayas = array_unique(array_merge(array_column($delivery_prices_home, 'wilaya_id'), array_column($delivery_prices_office, 'wilaya_id')));
        if (!empty($available_wilayas)) {
            sort($available_wilayas);
            $stmt = $pdo->prepare("SELECT id, name FROM wilayas WHERE id IN (" . implode(',', array_fill(0, count($available_wilayas), '?')) . ") ORDER BY id ASC");
            $stmt->execute($available_wilayas);
            $wilayas = $stmt->fetchAll();
        }
    }
} catch (PDOException $e) {
    die("خطأ: " . $e->getMessage());
}

$communes_data = [];
$cities_json_file = __DIR__ . '/cities.json';
if (file_exists($cities_json_file)) {
    $json_content = file_get_contents($cities_json_file);
    $communes_data = json_decode($json_content, true);
    if (json_last_error() !== JSON_ERROR_NONE) { $communes_data = []; }
}

$default_variant = !empty($product_variants) ? $product_variants[0] : null;
$default_price_for_display = $product['price'];
if (!empty($product_variants)) {
    foreach ($product_variants as $variant) {
        if ($variant['stock'] > 0) { $default_price_for_display = $variant['price']; break; }
    }
}

$stmt2 = $pdo->query("SELECT * FROM stores WHERE id = 1");
$store = $stmt2->fetch();

// ══════════════════════════════════════════════════════
// ── تحميل إعدادات الثيم الديناميكي من قاعدة البيانات ──
// ══════════════════════════════════════════════════════
$theme_settings = [];
if (!empty($store['theme_settings'])) {
    $theme_settings = json_decode($store['theme_settings'], true) ?? [];
}
$theme_defaults = [
    'primary_color' => '#0F172A',
    'accent_color'  => '#6C63FF',
    'bg_color'      => '#F7F8FA',
    'btn_radius'    => 'rounded',
];
$theme_settings = array_merge($theme_defaults, $theme_settings);

// تعيين قيمة border-radius حسب الخيار المحفوظ
$radius_map = [
    'rounded' => '14px',
    'square'  => '4px',
    'pill'    => '100px',
];
$btn_radius_val = $radius_map[$theme_settings['btn_radius']] ?? '14px';

// تنظيف القيم لمنع XSS
$t_primary = preg_match('/^#[0-9A-Fa-f]{6}$/', $theme_settings['primary_color']) ? $theme_settings['primary_color'] : '#0F172A';
$t_accent  = preg_match('/^#[0-9A-Fa-f]{6}$/', $theme_settings['accent_color'])  ? $theme_settings['accent_color']  : '#6C63FF';
$t_bg      = preg_match('/^#[0-9A-Fa-f]{6}$/', $theme_settings['bg_color'])      ? $theme_settings['bg_color']      : '#F7F8FA';
$t_radius  = $btn_radius_val;
// ══════════════════════════════════════════════════════

$stmt = $pdo->prepare("SELECT id, name FROM categories ORDER BY name");
$stmt->execute();
$categories = $stmt->fetchAll();

$related_products = [];
try {
    $stmt = $pdo->prepare("SELECT p.*, pi.image_url AS image FROM products p LEFT JOIN product_images pi ON p.id = pi.product_id AND pi.is_primary = 1 WHERE p.category_id = ? AND p.id != ? AND p.is_active = 1 ORDER BY p.created_at DESC LIMIT 4");
    $stmt->execute([$product['category_id'], $product_id]);
    $related_products = $stmt->fetchAll();
} catch (PDOException $e) {}

$all_images = [];
foreach ($product_images as $image) {
    $all_images[] = ['type'=>'product','image_url'=>$image['image_url'],'is_primary'=>$image['is_primary']];
}

$variant_attributes = [];
if (!empty($product_variants)) {
    foreach ($product_variants as $variant) {
        if ($variant['stock'] > 0) {
            foreach ($variant['variant_attrs'] as $attr) {
                $attr_name = $attr['attribute_name'];
                $attr_value = $attr['attribute_value'];
                if (!isset($variant_attributes[$attr_name])) { $variant_attributes[$attr_name] = []; }
                if (!in_array($attr_value, $variant_attributes[$attr_name])) { $variant_attributes[$attr_name][] = $attr_value; }
            }
        }
        foreach ($variant['variant_images'] as $image) {
            $found = false;
            foreach ($all_images as $existing) { if ($existing['image_url'] === $image['image_url']) { $found = true; break; } }
            if (!$found) { $all_images[] = ['type'=>'variant','variant_id'=>$variant['id'],'image_url'=>$image['image_url'],'is_primary'=>$image['is_primary']]; }
        }
    }
}

usort($all_images, function($a, $b) { if ($a['is_primary'] == $b['is_primary']) return 0; return ($a['is_primary'] > $b['is_primary']) ? -1 : 1; });
$main_image_url = !empty($all_images) ? $all_images[0]['image_url'] : '';

$is_product_available = false;
$available_stock = 0;
if (!empty($product_variants)) {
    foreach ($product_variants as $variant) { if ($variant['stock'] > 0) { $is_product_available = true; $available_stock += $variant['stock']; } }
} else {
    $is_product_available = ($product['stock_quantity'] > 0);
    $available_stock = $product['stock_quantity'];
}

$has_variants = !empty($variant_attributes);
$has_discount = $product['discounted_price'] && $product['discounted_price'] < $product['price'];
$discount_pct = $has_discount ? round(($product['price'] - $product['discounted_price']) / $product['price'] * 100) : 0;

$display_stock = 0;
if (!empty($product_variants) && $has_variants) {
    foreach ($product_variants as $v) {
        if ($v['stock'] > 0) { $display_stock = $v['stock']; break; }
    }
} else {
    $display_stock = $product['stock_quantity'] ?? 0;
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($product['name']); ?> — <?php echo htmlspecialchars($store['name']); ?></title>
    <link rel="icon" href="<?php echo BASE_URL . 'admin/' . htmlspecialchars($store['logo']); ?>" type="image/jpg">

    <?php if ($pixel && $pixel['meta_pixel_enabled'] && !empty(trim($pixel['meta_pixel_id']))): ?>
    <?php $pixel_id = htmlspecialchars(trim($pixel['meta_pixel_id'])); ?>
    <script>
    !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js');
    fbq('init','<?php echo $pixel_id; ?>');fbq('track','PageView');
    fbq('track','ViewContent',{content_ids:['<?php echo $product['id']; ?>'],content_name:'<?php echo addslashes($product['name']); ?>',content_type:'product',value:<?php echo $product['discounted_price'] ?: $product['price']; ?>,currency:'DZD'});
    </script>
    <noscript><img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=<?php echo $pixel_id; ?>&ev=PageView&noscript=1"/></noscript>
    <?php endif; ?>

    <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=Cairo:wght@300;400;500;600;700;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<style>
/* ══════════════════════════════════════════════════
   ── متغيرات الثيم الديناميكية من قاعدة البيانات ──
   ══════════════════════════════════════════════════ */
:root {
    --theme-primary:  <?php echo $t_primary; ?>;
    --theme-accent:   <?php echo $t_accent; ?>;
    --theme-bg:       <?php echo $t_bg; ?>;
    --theme-radius:   <?php echo $t_radius; ?>;
}

/* ══════════════════════════════════════════════════
   ── المتغيرات الأساسية (تستخدم قيم الثيم) ──
   ══════════════════════════════════════════════════ */
:root {
    --black:        var(--theme-primary);
    --white:        #ffffff;
    --off-white:    var(--theme-bg);
    --cream:        #f2ede6;
    --accent:       var(--theme-accent);
    --accent-dark:  color-mix(in srgb, var(--theme-accent) 75%, #000);
    --accent-light: color-mix(in srgb, var(--theme-accent) 30%, #fff);
    --accent-bg:    color-mix(in srgb, var(--theme-accent) 10%, #fff);
    --blue:         var(--theme-accent);
    --blue-dark:    color-mix(in srgb, var(--theme-accent) 75%, #000);
    --blue-light:   color-mix(in srgb, var(--theme-accent) 15%, #fff);
    --blue-mid:     color-mix(in srgb, var(--theme-accent) 85%, #fff);
    --gray-50:      #fafafa;
    --gray-100:     #f5f5f5;
    --gray-200:     #e8e8e8;
    --gray-300:     #d0d0d0;
    --gray-400:     #a0a0a0;
    --gray-500:     #6b6b6b;
    --gray-600:     #4a4a4a;
    --gray-800:     #2a2a2a;
    --green:        #16a34a;
    --green-bg:     #f0fdf4;
    --green-border: #86efac;
    --red:          #dc2626;
    --red-bg:       #fef2f2;
    --red-border:   #fca5a5;
    --orange:       #ea580c;
    --orange-bg:    #fff7ed;
    --orange-border:#fed7aa;
    --r:            var(--theme-radius);
    --r-sm:         8px;
    --r-lg:         20px;
    --r-xl:         28px;
    --shadow-xs:    0 1px 3px rgba(0,0,0,0.06);
    --shadow-sm:    0 2px 8px rgba(0,0,0,0.08);
    --shadow-md:    0 4px 20px rgba(0,0,0,0.10);
    --shadow-lg:    0 12px 40px rgba(0,0,0,0.12);
    --shadow-xl:    0 24px 60px rgba(0,0,0,0.16);
    --t:            all 0.28s cubic-bezier(0.4,0,0.2,1);
    --t-fast:       all 0.15s ease;
    --t-bounce:     all 0.4s cubic-bezier(0.34,1.56,0.64,1);
}
*,*::before,*::after{margin:0;padding:0;box-sizing:border-box;}
html{scroll-behavior:smooth;}
body{font-family:'Cairo',sans-serif;background:var(--off-white);color:var(--black);line-height:1.65;-webkit-font-smoothing:antialiased;overflow-x:hidden;}
a{text-decoration:none;color:inherit;}
img{max-width:100%;display:block;}
button{font-family:'Cairo',sans-serif;cursor:pointer;border:none;background:none;}
select,input,textarea{font-family:'Cairo',sans-serif;}

.announce-bar{background:var(--blue);color:#fff;text-align:center;padding:9px 20px;font-size:13px;font-weight:600;position:relative;overflow:hidden;display:flex;align-items:center;justify-content:center;}
.announce-bar::before{content:'';position:absolute;top:0;left:-100%;width:60%;height:100%;background:linear-gradient(90deg,transparent,rgba(255,255,255,0.12),transparent);animation:shimmer 3s infinite;}
@keyframes shimmer{to{left:200%;}}
.announce-pills{display:flex;align-items:center;gap:6px;flex-wrap:wrap;justify-content:center;}
.announce-pill{display:inline-flex;align-items:center;gap:6px;background:rgba(255,255,255,0.18);border:1px solid rgba(255,255,255,0.28);padding:3px 12px;border-radius:50px;font-size:12px;font-weight:700;}
.announce-pill i{font-size:11px;}
.announce-sep{width:4px;height:4px;background:rgba(255,255,255,0.4);border-radius:50%;margin:0 4px;}

.header{position:sticky;top:0;z-index:900;background:rgba(255,255,255,0.97);backdrop-filter:blur(20px);-webkit-backdrop-filter:blur(20px);border-bottom:1px solid var(--gray-200);transition:var(--t);}
.header.scrolled{box-shadow:var(--shadow-md);}
.header-inner{max-width:1400px;margin:0 auto;padding:0 24px;display:flex;align-items:center;gap:16px;height:68px;}

.logo{display:flex;align-items:center;gap:11px;text-decoration:none;flex-shrink:0;}
.logo-circle{width:46px;height:46px;border-radius:50%;background:linear-gradient(135deg,var(--blue) 0%,var(--blue-mid) 50%,#ffffff 100%);display:flex;align-items:center;justify-content:center;box-shadow:0 3px 12px color-mix(in srgb, var(--theme-accent) 35%, transparent);overflow:hidden;flex-shrink:0;border:2.5px solid #fff;position:relative;}
.logo-circle::after{content:'';position:absolute;inset:0;border-radius:50%;border:2px solid color-mix(in srgb, var(--theme-accent) 30%, transparent);}
.logo-circle img{width:100%;height:100%;object-fit:cover;border-radius:50%;}
.logo-circle-placeholder{color:white;font-size:20px;font-weight:900;}
.logo-name{font-size:20px;font-weight:900;color:var(--black);letter-spacing:-0.5px;line-height:1.1;}
.logo-name span{display:block;font-size:10px;font-weight:600;color:var(--blue);letter-spacing:0.5px;text-transform:uppercase;}

.desktop-nav{display:flex;align-items:center;gap:2px;margin-right:8px;}
.nav-link{color:var(--gray-500);text-decoration:none;font-size:14px;font-weight:600;padding:8px 14px;border-radius:var(--r-sm);transition:var(--t-fast);white-space:nowrap;position:relative;}
.nav-link:hover{color:var(--black);background:var(--gray-100);}
.nav-dropdown{position:relative;}
.nav-dropdown-menu{position:absolute;top:calc(100% + 8px);right:0;background:white;border:1px solid var(--gray-200);border-radius:var(--r);min-width:200px;box-shadow:var(--shadow-lg);opacity:0;visibility:hidden;transform:translateY(-8px);transition:var(--t);z-index:1000;overflow:hidden;}
.nav-dropdown:hover .nav-dropdown-menu{opacity:1;visibility:visible;transform:translateY(0);}
.nav-dropdown-item{display:flex;align-items:center;gap:10px;padding:11px 16px;color:var(--gray-500);font-size:14px;font-weight:500;border-bottom:1px solid var(--gray-100);transition:var(--t-fast);}
.nav-dropdown-item:last-child{border-bottom:none;}
.nav-dropdown-item:hover{background:var(--off-white);color:var(--black);padding-right:22px;}
.nav-dropdown-item i{color:var(--blue);font-size:12px;}

.search-wrap{flex:1;max-width:440px;margin:0 auto;}
.search-form{display:flex;align-items:center;background:var(--gray-100);border:2px solid transparent;border-radius:50px;overflow:hidden;transition:var(--t);}
.search-form:focus-within{background:white;border-color:var(--blue);box-shadow:0 0 0 4px color-mix(in srgb, var(--theme-accent) 10%, transparent);}
.search-form input{flex:1;background:none;border:none;outline:none;padding:10px 18px;font-family:'Cairo',sans-serif;font-size:14px;color:var(--black);}
.search-form input::placeholder{color:var(--gray-400);}
.search-btn{background:var(--blue);border:none;color:white;width:42px;height:42px;display:flex;align-items:center;justify-content:center;margin:2px;border-radius:50px;cursor:pointer;transition:var(--t-fast);font-size:14px;}
.search-btn:hover{background:var(--blue-dark);}

.header-actions{display:flex;align-items:center;gap:4px;flex-shrink:0;}
.icon-btn{width:42px;height:42px;display:flex;align-items:center;justify-content:center;border-radius:50%;cursor:pointer;transition:var(--t-fast);color:var(--gray-500);font-size:18px;text-decoration:none;}
.icon-btn:hover{background:var(--gray-100);color:var(--black);}

.menu-toggle{display:none;flex-direction:column;gap:5px;cursor:pointer;padding:8px;border-radius:var(--r-sm);}
.menu-toggle span{display:block;width:22px;height:2px;background:var(--black);border-radius:2px;transition:var(--t);}
.menu-toggle.open span:nth-child(1){transform:rotate(45deg) translate(5px,5px);}
.menu-toggle.open span:nth-child(2){opacity:0;}
.menu-toggle.open span:nth-child(3){transform:rotate(-45deg) translate(5px,-5px);}

.mobile-search-bar{display:none;background:white;border-bottom:1px solid var(--gray-200);padding:10px 16px;}
.mobile-search-bar .search-form{border-radius:var(--r-sm);}

.mobile-menu{position:fixed;top:0;right:-100%;width:min(340px,100vw);height:100vh;background:white;z-index:1100;transition:right 0.4s cubic-bezier(0.4,0,0.2,1);display:flex;flex-direction:column;box-shadow:var(--shadow-xl);}
.mobile-menu.open{right:0;}
.overlay{position:fixed;inset:0;background:rgba(0,0,0,0.5);backdrop-filter:blur(4px);z-index:1099;opacity:0;visibility:hidden;transition:var(--t);}
.overlay.open{opacity:1;visibility:visible;}
.mobile-menu-header{padding:20px 24px;border-bottom:1px solid var(--gray-200);display:flex;align-items:center;justify-content:space-between;}
.mobile-menu-body{flex:1;overflow-y:auto;padding:16px 0;}
.mob-link{display:flex;align-items:center;gap:14px;padding:14px 24px;color:var(--gray-800);font-size:15px;font-weight:600;border-bottom:1px solid var(--gray-100);transition:var(--t-fast);}
.mob-link:hover{background:var(--off-white);color:var(--blue);}
.mob-link i{width:20px;color:var(--blue);font-size:14px;}
.mob-section-label{padding:12px 24px 6px;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:var(--gray-400);}
.close-btn{width:36px;height:36px;display:flex;align-items:center;justify-content:center;background:var(--gray-100);border-radius:50%;cursor:pointer;font-size:16px;color:var(--gray-500);}
.close-btn:hover{background:var(--gray-200);}

.page-wrap{max-width:1400px;margin:0 auto;padding:24px 24px 80px;}

.breadcrumb{display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:13px;color:var(--gray-400);font-weight:500;margin-bottom:24px;}
.breadcrumb a{color:var(--gray-500);transition:var(--t-fast);}
.breadcrumb a:hover{color:var(--blue);}
.breadcrumb i{font-size:10px;color:var(--gray-300);}
.breadcrumb span{color:var(--black);font-weight:600;}

.trust-strip{display:flex;align-items:center;flex-wrap:wrap;gap:10px;background:white;border:1px solid var(--gray-200);border-radius:var(--r);padding:14px 20px;margin-bottom:28px;box-shadow:var(--shadow-xs);}
.trust-pill{display:flex;align-items:center;gap:7px;font-size:12px;font-weight:700;padding:6px 14px;border-radius:50px;border:1.5px solid;white-space:nowrap;}
.trust-pill.green{color:var(--green);background:var(--green-bg);border-color:var(--green-border);}
.trust-pill.blue{color:var(--blue);background:var(--blue-light);border-color:color-mix(in srgb, var(--theme-accent) 30%, #fff);}
.trust-pill.orange{color:var(--orange);background:var(--orange-bg);border-color:var(--orange-border);}
.trust-pill.gold{color:#92400e;background:#fffbeb;border-color:#fde68a;}

.product-wrap{display:grid;grid-template-columns:1fr 1fr;gap:36px;background:white;border-radius:var(--r-xl);box-shadow:var(--shadow-md);padding:32px;margin-bottom:32px;border:1px solid var(--gray-200);animation:fadeUp 0.5s ease forwards;}
@keyframes fadeUp{from{opacity:0;transform:translateY(20px);}to{opacity:1;transform:translateY(0);}}

.gallery{position:relative;}
.gallery-main{position:relative;overflow:hidden;border-radius:var(--r-lg);background:var(--gray-50);border:1px solid var(--gray-200);aspect-ratio:1;display:flex;align-items:center;justify-content:center;cursor:zoom-in;}
.gallery-main img{max-width:100%;max-height:100%;width:auto;height:auto;object-fit:contain;transition:transform 0.4s ease,opacity 0.15s ease;}
.gallery-main:hover img{transform:scale(1.5);}
.gallery-overlay{position:absolute;inset:0;background:rgba(10,10,10,0.6);backdrop-filter:blur(4px);border-radius:var(--r-lg);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;opacity:0;pointer-events:none;transition:var(--t);z-index:10;}
.gallery-overlay.show{opacity:1;pointer-events:all;}
.gallery-overlay i{font-size:40px;color:var(--blue);}
.gallery-overlay p{color:white;font-size:15px;font-weight:700;text-align:center;padding:0 24px;}
.gallery-nav{position:absolute;top:50%;transform:translateY(-50%);z-index:5;width:40px;height:40px;background:rgba(255,255,255,0.92);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:14px;color:var(--black);box-shadow:var(--shadow-sm);border:1px solid var(--gray-200);transition:var(--t-fast);cursor:pointer;}
.gallery-nav:hover{background:var(--blue);color:white;border-color:var(--blue);}
.gallery-nav.prev{right:12px;}
.gallery-nav.next{left:12px;}
.gallery-badge{position:absolute;top:14px;right:14px;z-index:6;background:var(--red);color:white;font-size:12px;font-weight:800;padding:5px 12px;border-radius:50px;box-shadow:var(--shadow-sm);}
.thumbs-row{display:flex;gap:8px;margin-top:12px;overflow-x:auto;padding:2px 2px 6px;scrollbar-width:thin;scrollbar-color:var(--blue) var(--gray-200);}
.thumbs-row::-webkit-scrollbar{height:4px;}
.thumbs-row::-webkit-scrollbar-track{background:var(--gray-200);border-radius:4px;}
.thumbs-row::-webkit-scrollbar-thumb{background:var(--blue);border-radius:4px;}
.thumb{width:72px;height:72px;flex-shrink:0;border-radius:var(--r-sm);overflow:hidden;border:2.5px solid transparent;cursor:pointer;transition:var(--t-fast);background:var(--gray-100);}
.thumb img{width:100%;height:100%;object-fit:cover;}
.thumb:hover{border-color:var(--blue);transform:scale(1.05);}
.thumb.active{border-color:var(--blue);box-shadow:0 0 0 3px color-mix(in srgb, var(--theme-accent) 20%, transparent);}

.product-info{display:flex;flex-direction:column;gap:20px;}
.product-cat-badge{display:inline-flex;align-items:center;gap:6px;background:var(--blue-light);color:var(--blue-dark);border:1px solid color-mix(in srgb, var(--theme-accent) 30%, #fff);padding:5px 14px;border-radius:50px;font-size:12px;font-weight:700;letter-spacing:0.3px;width:fit-content;}
.product-name{font-size:26px;font-weight:900;color:var(--black);line-height:1.3;letter-spacing:-0.3px;}
.product-desc{background:var(--off-white);border-radius:var(--r-sm);padding:16px 18px;border-right:4px solid var(--blue);font-size:14px;color:var(--gray-600);line-height:1.8;}

.price-box{background:linear-gradient(135deg, color-mix(in srgb, var(--theme-accent) 8%, #fff), color-mix(in srgb, var(--theme-accent) 18%, #fff));border:1.5px solid color-mix(in srgb, var(--theme-accent) 30%, #fff);border-radius:var(--r);padding:20px 22px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;}
.price-current{font-size:34px;font-weight:900;color:var(--black);letter-spacing:-1px;}
.price-old{font-size:18px;color:var(--gray-400);text-decoration:line-through;font-weight:500;}
.price-save-badge{background:var(--red);color:white;font-size:12px;font-weight:800;padding:4px 12px;border-radius:50px;display:inline-block;margin-top:4px;}
.price-note{font-size:12px;color:var(--gray-400);display:flex;align-items:center;gap:4px;margin-top:6px;}

.stock-badge{display:inline-flex;align-items:center;gap:8px;padding:10px 18px;border-radius:var(--r);font-size:13px;font-weight:800;border:2px solid;width:fit-content;}
.stock-badge.low{background:var(--red-bg);border-color:var(--red-border);color:var(--red);animation:stockPulse 1.8s ease infinite;}
.stock-badge.medium{background:var(--orange-bg);border-color:var(--orange-border);color:var(--orange);}
.stock-badge i{font-size:15px;}
@keyframes stockPulse{0%,100%{box-shadow:0 0 0 0 rgba(220,38,38,0.3);}50%{box-shadow:0 0 0 6px rgba(220,38,38,0);}}

.oos-box{background:var(--red-bg);border:2px solid var(--red-border);border-radius:var(--r);padding:24px;text-align:center;}
.oos-box i{font-size:44px;color:var(--red);display:block;margin-bottom:12px;}
.oos-box h3{color:var(--red);font-size:18px;font-weight:800;margin-bottom:6px;}
.oos-box p{color:var(--gray-500);font-size:14px;}

.variants-wrap{display:flex;flex-direction:column;gap:14px;}
.vblock{background:var(--gray-50);border:2px solid var(--gray-200);border-radius:var(--r);padding:18px;transition:var(--t);}
.vblock.done{border-color:var(--green);background:var(--green-bg);}
.vblock.needs{border-color:#f59e0b;background:#fffbeb;animation:needsPulse 1.5s ease 3;}
@keyframes needsPulse{0%,100%{box-shadow:0 0 0 0 rgba(245,158,11,0.4);}50%{box-shadow:0 0 0 8px rgba(245,158,11,0);}}
.vblock-label{font-size:12px;font-weight:800;text-transform:uppercase;letter-spacing:0.6px;color:var(--gray-400);margin-bottom:12px;display:flex;align-items:center;gap:8px;}
.vblock-label i{color:var(--blue);}
.vblock-status{margin-right:auto;width:22px;height:22px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:900;transition:var(--t-bounce);}
.vblock.done .vblock-status{background:var(--green);color:white;}
.vblock:not(.done) .vblock-status{background:#fde68a;color:#92400e;}
.variant-chips{display:flex;gap:8px;flex-wrap:wrap;}
.v-chip{padding:8px 18px;border:2px solid var(--gray-200);border-radius:var(--r);cursor:pointer;font-size:13px;font-weight:700;color:var(--gray-500);background:white;transition:var(--t-fast);user-select:none;display:inline-flex;align-items:center;gap:8px;}
.v-chip:hover{border-color:var(--blue);color:var(--blue);}
.v-chip.selected{border-color:var(--blue);background:var(--blue);color:white;box-shadow:0 4px 14px color-mix(in srgb, var(--theme-accent) 30%, transparent);}
.v-chip.has-img{padding:6px 16px 6px 8px;}
.v-chip .chip-thumb{width:28px;height:28px;border-radius:6px;object-fit:cover;border:1px solid rgba(0,0,0,0.1);}
.v-chip.oos{opacity:0.4;cursor:not-allowed;text-decoration:line-through;}
.vblock-hint{display:none;margin-top:10px;padding:8px 12px;background:#fffbeb;border:1px solid #fbbf24;border-radius:var(--r-sm);font-size:12px;font-weight:700;color:#92400e;align-items:center;gap:6px;}
.vblock.needs .vblock-hint{display:flex;}

.variant-alert{display:none;background:var(--orange-bg);border:2px solid var(--orange-border);border-radius:var(--r);padding:18px 20px;gap:14px;align-items:flex-start;animation:slideDown 0.3s ease;}
@keyframes slideDown{from{opacity:0;transform:translateY(-10px);}to{opacity:1;transform:translateY(0);}}
.variant-alert.show{display:flex;}
.variant-alert-icon{width:44px;height:44px;flex-shrink:0;background:var(--orange);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:20px;color:white;}
.variant-alert-title{font-size:15px;font-weight:900;color:#9a3412;margin-bottom:6px;}
.variant-alert-list{list-style:none;padding:0;margin:0;display:flex;flex-direction:column;gap:4px;}
.variant-alert-list li{font-size:13px;color:#7c2d12;font-weight:600;display:flex;align-items:center;gap:6px;}
.variant-alert-list li i{color:var(--orange);}
.variant-alert-action{display:inline-flex;align-items:center;gap:6px;margin-top:10px;padding:8px 16px;background:var(--orange);color:white;border-radius:50px;font-size:13px;font-weight:800;cursor:pointer;font-family:'Cairo',sans-serif;border:none;transition:var(--t-fast);}
.variant-alert-action:hover{background:#c2410c;}

.variant-done-badge{display:none;background:var(--green-bg);border:2px solid var(--green-border);border-radius:var(--r);padding:14px 18px;align-items:center;gap:12px;animation:popIn 0.35s cubic-bezier(0.34,1.56,0.64,1);}
@keyframes popIn{from{opacity:0;transform:scale(0.92);}to{opacity:1;transform:scale(1);}}
.variant-done-badge.show{display:flex;}
.done-badge-icon{width:42px;height:42px;flex-shrink:0;background:var(--green);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:18px;color:white;}
.done-badge-title{font-size:14px;font-weight:800;color:#166534;margin-bottom:6px;}
.done-badge-tags{display:flex;flex-wrap:wrap;gap:6px;}
.done-tag{background:var(--green);color:white;padding:3px 12px;border-radius:50px;font-size:12px;font-weight:700;}

.order-fab{position:fixed;bottom:80px;left:16px;right:16px;z-index:800;text-align:center;opacity:0;transform:translateY(16px);pointer-events:none;transition:var(--t);}
.order-fab.show{opacity:1;transform:translateY(0);pointer-events:all;}
.fab-btn{display:inline-flex;align-items:center;justify-content:center;gap:10px;color:white;border:none;padding:17px 32px;border-radius:var(--r);font-size:16px;font-weight:900;width:100%;max-width:440px;font-family:'Cairo',sans-serif;cursor:pointer;transition:var(--t);}
.fab-btn.state-select{background:linear-gradient(135deg,#f59e0b,#d97706);box-shadow:0 8px 28px rgba(245,158,11,0.5);animation:fabWarn 2.5s ease infinite;}
.fab-btn.state-ready{background:linear-gradient(135deg,var(--blue),var(--blue-mid));box-shadow:0 8px 28px color-mix(in srgb, var(--theme-accent) 45%, transparent);animation:fabPulse 2.5s ease infinite;}
.fab-btn.state-disabled{background:var(--gray-300);box-shadow:none;cursor:not-allowed;}
@keyframes fabPulse{0%,100%{box-shadow:0 8px 28px color-mix(in srgb, var(--theme-accent) 45%, transparent);}50%{box-shadow:0 12px 40px color-mix(in srgb, var(--theme-accent) 60%, transparent),0 0 0 8px color-mix(in srgb, var(--theme-accent) 10%, transparent);}}
@keyframes fabWarn{0%,100%{box-shadow:0 8px 28px rgba(245,158,11,0.5);}50%{box-shadow:0 12px 40px rgba(245,158,11,0.7),0 0 0 8px rgba(245,158,11,0.12);}}
.fab-btn:hover:not(.state-disabled){animation:none;transform:translateY(-2px);}

.order-section{background:white;border-radius:var(--r-xl);box-shadow:var(--shadow-md);overflow:hidden;margin-bottom:40px;border:1px solid var(--gray-200);animation:fadeUp 0.5s ease 0.15s both;}
.order-header{background:var(--theme-primary);padding:24px 32px;display:flex;align-items:center;gap:16px;}
.order-header-icon{width:48px;height:48px;background:rgba(255,255,255,0.15);border:1px solid rgba(255,255,255,0.25);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:20px;color:rgba(255,255,255,0.9);flex-shrink:0;}
.order-header-title{font-size:20px;font-weight:900;color:white;}
.order-header-sub{font-size:13px;color:rgba(255,255,255,0.55);margin-top:2px;}
.order-body{padding:28px 32px;}

.attrs-preview{background:var(--gray-50);border:2px dashed var(--gray-200);border-radius:var(--r-sm);padding:14px 16px;display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:14px;color:var(--gray-400);margin-bottom:24px;transition:var(--t);}
.attrs-preview.has-value{background:var(--green-bg);border-color:var(--green-border);color:var(--black);}
.attr-tag{background:var(--blue);color:white;padding:4px 12px;border-radius:50px;font-size:12px;font-weight:700;}

.fields-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:16px;}
.form-group{display:flex;flex-direction:column;gap:5px;}
.form-label{font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:0.7px;color:var(--gray-400);display:flex;align-items:center;gap:6px;}
.form-label i{color:var(--blue);}
.form-input{padding:12px 14px;border:2px solid var(--gray-200);border-radius:var(--r-sm);font-size:14px;font-family:'Cairo',sans-serif;background:white;transition:var(--t-fast);outline:none;width:100%;color:var(--black);}
.form-input:focus{border-color:var(--blue);box-shadow:0 0 0 3px color-mix(in srgb, var(--theme-accent) 8%, transparent);}
.form-input.err{border-color:var(--red);}
.field-with-icon{position:relative;}
.field-with-icon .form-input{padding-right:42px;}
.field-icon{position:absolute;top:50%;right:14px;transform:translateY(-50%);color:var(--gray-400);font-size:15px;pointer-events:none;}
.divider{display:flex;align-items:center;gap:12px;margin:22px 0;color:var(--gray-400);font-size:12px;font-weight:700;}
.divider::before,.divider::after{content:'';flex:1;height:1px;background:var(--gray-200);}
.divider i{color:var(--blue);}

.del-type-row{display:flex;gap:10px;margin-top:6px;}
.del-pill{flex:1;display:flex;align-items:center;justify-content:center;gap:8px;padding:12px;border-radius:var(--r-sm);border:2px solid var(--gray-200);cursor:pointer;transition:var(--t-fast);background:white;font-size:13px;font-weight:700;color:var(--gray-500);}
.del-pill input[type="radio"]{display:none;}
.del-pill:has(input:checked){border-color:var(--blue);background:var(--blue-light);color:var(--blue);}
.del-pill i{font-size:17px;}

.commune-required-note{display:none;margin-top:6px;padding:7px 12px;background:#fef2f2;border:1px solid #fca5a5;border-radius:var(--r-sm);font-size:12px;font-weight:700;color:var(--red);align-items:center;gap:6px;}
.commune-required-note.show{display:flex;}
.commune-optional-note{display:none;margin-top:6px;padding:7px 12px;background:var(--green-bg);border:1px solid var(--green-border);border-radius:var(--r-sm);font-size:12px;font-weight:700;color:var(--green);align-items:center;gap:6px;}
.commune-optional-note.show{display:flex;}

.order-summary{background:var(--gray-50);border:1.5px solid var(--gray-200);border-radius:var(--r);padding:18px 22px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:14px;margin:22px 0;}
.summary-item{display:flex;flex-direction:column;align-items:center;gap:3px;}
.summary-label{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:var(--gray-400);}
.summary-val{font-size:20px;font-weight:900;color:var(--black);}
.summary-val.big{font-size:26px;color:var(--blue);}
.qty-wrap{display:flex;align-items:center;gap:8px;}
.qty-btn-ctrl{width:34px;height:34px;border-radius:var(--r-sm);border:2px solid var(--gray-200);background:white;color:var(--black);font-size:18px;font-weight:700;display:flex;align-items:center;justify-content:center;cursor:pointer;transition:var(--t-fast);}
.qty-btn-ctrl:hover{background:var(--blue);color:white;border-color:var(--blue);}
.qty-val{width:52px;height:34px;text-align:center;border:2px solid var(--gray-200);border-radius:var(--r-sm);font-size:16px;font-weight:800;outline:none;transition:var(--t-fast);}
.qty-val:focus{border-color:var(--blue);}

.submit-btn{width:100%;padding:17px;border-radius:var(--r);border:none;cursor:pointer;background:linear-gradient(135deg,var(--blue),var(--blue-mid));color:white;font-family:'Cairo',sans-serif;font-size:17px;font-weight:900;display:flex;align-items:center;justify-content:center;gap:10px;box-shadow:0 6px 24px color-mix(in srgb, var(--theme-accent) 35%, transparent);transition:var(--t);letter-spacing:0.3px;}
.submit-btn:hover:not(:disabled){background:linear-gradient(135deg,var(--blue-dark),var(--blue));transform:translateY(-2px);box-shadow:0 10px 32px color-mix(in srgb, var(--theme-accent) 45%, transparent);}
.submit-btn:disabled{background:var(--gray-200);color:var(--gray-400);box-shadow:none;cursor:not-allowed;}
.submit-note{display:flex;align-items:center;justify-content:center;gap:8px;margin-top:14px;padding:11px;background:var(--off-white);border:1px solid var(--gray-200);border-radius:var(--r-sm);font-size:13px;color:var(--gray-500);font-weight:600;}
.submit-note i{color:var(--blue);}

.section-title{display:flex;align-items:center;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px;}
.section-title h2{font-size:24px;font-weight:900;color:var(--black);display:flex;align-items:center;gap:10px;}
.section-title h2 span{background:var(--blue-light);color:var(--blue);border:1px solid color-mix(in srgb, var(--theme-accent) 30%, #fff);font-size:13px;font-weight:700;padding:3px 12px;border-radius:50px;}
.related-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:18px;margin-bottom:60px;}
.rel-card{background:white;border-radius:var(--r-lg);border:1px solid var(--gray-200);overflow:hidden;box-shadow:var(--shadow-xs);transition:var(--t);text-decoration:none;color:inherit;display:flex;flex-direction:column;}
.rel-card:hover{transform:translateY(-6px);box-shadow:var(--shadow-lg);border-color:var(--blue);}
.rel-img{height:180px;overflow:hidden;background:var(--gray-100);flex-shrink:0;}
.rel-img img{width:100%;height:100%;object-fit:cover;transition:transform 0.4s ease;}
.rel-card:hover .rel-img img{transform:scale(1.07);}
.rel-img-placeholder{width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-size:36px;color:var(--gray-300);}
.rel-body{padding:14px;flex:1;display:flex;flex-direction:column;}
.rel-name{font-size:14px;font-weight:700;color:var(--black);line-height:1.4;height:40px;overflow:hidden;margin-bottom:8px;}
.rel-price{font-size:17px;font-weight:900;color:var(--black);margin-top:auto;}
.rel-price-old{font-size:12px;color:var(--gray-400);text-decoration:line-through;margin-left:6px;}
.rel-cta{display:flex;align-items:center;justify-content:center;gap:6px;margin-top:10px;padding:9px;background:var(--gray-100);border-radius:var(--r-sm);font-size:13px;font-weight:700;color:var(--gray-600);transition:var(--t-fast);}
.rel-card:hover .rel-cta{background:var(--blue);color:white;}

.bottom-nav{display:none;position:fixed;bottom:0;left:0;right:0;z-index:800;padding-bottom:env(safe-area-inset-bottom,0px);}
.bottom-nav-bg{background:rgba(255,255,255,0.98);backdrop-filter:blur(24px);-webkit-backdrop-filter:blur(24px);border-top:1px solid rgba(0,0,0,0.08);box-shadow:0 -4px 24px rgba(0,0,0,0.08);}
.bottom-nav-inner{display:flex;align-items:center;height:62px;position:relative;}
.bnav-item{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:3px;padding:8px 4px;color:#9ca3af;font-size:10px;font-weight:700;cursor:pointer;text-decoration:none;transition:color 0.2s ease;border:none;background:none;font-family:'Cairo',sans-serif;position:relative;letter-spacing:0.2px;}
.bnav-icon{width:26px;height:26px;display:flex;align-items:center;justify-content:center;border-radius:8px;font-size:17px;transition:all 0.2s cubic-bezier(0.34,1.56,0.64,1);}
.bnav-item:hover .bnav-icon,.bnav-item.active .bnav-icon{background:var(--blue-light);color:var(--blue);transform:translateY(-1px) scale(1.08);}
.bnav-item.active{color:var(--blue);}
.bnav-cta{flex:1;display:flex;align-items:center;justify-content:center;padding:8px 4px;cursor:pointer;border:none;background:none;font-family:'Cairo',sans-serif;text-decoration:none;}
.bnav-cta-inner{width:50px;height:50px;background:linear-gradient(135deg,var(--blue),var(--blue-mid));border-radius:16px;display:flex;align-items:center;justify-content:center;color:white;font-size:22px;box-shadow:0 4px 14px color-mix(in srgb, var(--theme-accent) 45%, transparent);transition:all 0.2s cubic-bezier(0.34,1.56,0.64,1);margin-top:-12px;}
.bnav-cta:hover .bnav-cta-inner,.bnav-cta:active .bnav-cta-inner{transform:scale(1.1) translateY(-2px);box-shadow:0 8px 20px color-mix(in srgb, var(--theme-accent) 50%, transparent);}

.scroll-top{position:fixed;bottom:80px;left:24px;width:46px;height:46px;background:var(--theme-primary);color:white;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:16px;cursor:pointer;box-shadow:var(--shadow-lg);transition:var(--t);opacity:0;visibility:hidden;z-index:700;border:none;}
.scroll-top.show{opacity:1;visibility:visible;}
.scroll-top:hover{background:var(--blue);transform:translateY(-3px);}

.toast-wrap{position:fixed;bottom:90px;left:50%;transform:translateX(-50%);z-index:2000;display:flex;flex-direction:column;gap:8px;pointer-events:none;}
.toast{background:var(--theme-primary);color:white;padding:11px 20px;border-radius:50px;font-size:14px;font-weight:600;display:flex;align-items:center;gap:8px;box-shadow:var(--shadow-lg);white-space:nowrap;animation:toastIn 0.4s cubic-bezier(0.34,1.56,0.64,1) forwards;}
.toast i{color:color-mix(in srgb, var(--theme-accent) 80%, #fff);}
.toast.out{animation:toastOut 0.3s ease forwards;}
@keyframes toastIn{from{opacity:0;transform:translateY(16px) scale(0.9);}to{opacity:1;transform:translateY(0) scale(1);}}
@keyframes toastOut{from{opacity:1;}to{opacity:0;transform:translateY(-8px);}}

.footer{background:var(--theme-primary);color:white;margin-top:60px;}
.footer-inner{max-width:1400px;margin:0 auto;padding:50px 24px 20px;display:grid;grid-template-columns:2fr 1fr 1fr;gap:48px;}
.footer-brand p{color:rgba(255,255,255,0.45);font-size:14px;line-height:1.8;margin-top:14px;max-width:300px;}
.footer-col-title{font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:1px;color:color-mix(in srgb, var(--theme-accent) 80%, #fff);margin-bottom:18px;}
.footer-links-list{list-style:none;display:flex;flex-direction:column;gap:10px;}
.footer-links-list a{color:rgba(255,255,255,0.55);font-size:14px;transition:var(--t-fast);display:flex;align-items:center;gap:8px;}
.footer-links-list a:hover{color:white;}
.social-row{display:flex;gap:10px;margin-top:20px;}
.social-btn{width:40px;height:40px;border-radius:50%;background:rgba(255,255,255,0.08);color:white;display:flex;align-items:center;justify-content:center;text-decoration:none;font-size:16px;transition:var(--t);}
.social-btn:hover{background:var(--blue);transform:translateY(-3px);}
.footer-bottom{border-top:1px solid rgba(255,255,255,0.08);text-align:center;padding:20px 24px;color:rgba(255,255,255,0.3);font-size:13px;}

@media(max-width:1024px){.product-wrap{grid-template-columns:1fr;gap:24px;}.related-grid{grid-template-columns:repeat(2,1fr);}.footer-inner{grid-template-columns:1fr 1fr;}.footer-brand{grid-column:1/-1;}}
@media(max-width:900px){.desktop-nav{display:none;}.menu-toggle{display:flex;}.search-wrap{display:none;}.order-body{padding:20px;}.bottom-nav{display:flex;flex-direction:column;}.order-fab{bottom:74px;}.scroll-top{bottom:90px;left:16px;}.footer-inner{grid-template-columns:1fr;padding:36px 16px 16px;gap:32px;margin-bottom:70px;}.mobile-search-bar{display:block;}}
@media(max-width:600px){.page-wrap{padding:16px 16px 80px;}.product-wrap{padding:16px;}.order-header{padding:18px 20px;}.fields-grid{grid-template-columns:1fr;}.product-name{font-size:21px;}.price-current{font-size:28px;}.related-grid{grid-template-columns:repeat(2,1fr);gap:12px;}.trust-strip{padding:10px 14px;}.logo-circle{width:40px;height:40px;}.logo-name{font-size:17px;}.header-inner{height:58px;padding:0 14px;}}
</style>
</head>
<body>

<div class="announce-bar">
    <div class="announce-pills">
        <div class="announce-pill"><i class="fas fa-truck"></i> توصيل سريع لجميع ولايات الجزائر</div>
        <div class="announce-sep"></div>
        <div class="announce-pill"><i class="fas fa-hand-holding-usd"></i> دفع عند الاستلام</div>
    </div>
</div>

<header class="header" id="mainHeader">
    <div class="header-inner">
        <button class="menu-toggle" id="menuToggle"><span></span><span></span><span></span></button>
        <a href="index.php" class="logo">
            <div class="logo-circle">
                <?php if(!empty($store['logo'])): ?>
                    <img src="<?php echo BASE_URL.'admin/'.htmlspecialchars($store['logo']); ?>"
                         alt="<?php echo htmlspecialchars($store['name']); ?>"
                         onerror="this.style.display='none'; this.nextElementSibling.style.display='flex'">
                    <div class="logo-circle-placeholder" style="display:none;"><?php echo mb_substr($store['name'], 0, 1); ?></div>
                <?php else: ?>
                    <div class="logo-circle-placeholder"><?php echo mb_substr($store['name'], 0, 1); ?></div>
                <?php endif; ?>
            </div>
            <div class="logo-name">
                <?php echo htmlspecialchars($store['name']); ?>
                <span>متجر إلكتروني</span>
            </div>
        </a>
        <nav class="desktop-nav">
            <a href="index.php" class="nav-link">الرئيسية</a>
            <div class="nav-dropdown">
                <a href="#" class="nav-link">الأقسام <i class="fas fa-chevron-down" style="font-size:10px;margin-right:4px;"></i></a>
                <div class="nav-dropdown-menu">
                    <a href="index.php" class="nav-dropdown-item"><i class="fas fa-th-large"></i> كل المنتجات</a>
                    <?php foreach($categories as $cat): ?>
                    <a href="index.php?category=<?php echo $cat['id']; ?>" class="nav-dropdown-item">
                        <i class="fas fa-arrow-left"></i> <?php echo htmlspecialchars($cat['name']); ?>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>
            <a href="track_order.php" class="nav-link">طلباتي</a>
        </nav>
        <div class="search-wrap">
            <form action="index.php" method="GET" class="search-form">
                <input type="text" name="search" placeholder="ابحث عن منتج...">
                <button type="submit" class="search-btn"><i class="fas fa-search"></i></button>
            </form>
        </div>
        <div class="header-actions">
            <a href="index.php" class="icon-btn" title="الرئيسية"><i class="fas fa-home"></i></a>
            <a href="tel:<?php echo htmlspecialchars($store['phone']); ?>" class="icon-btn" title="اتصل بنا"><i class="fas fa-phone-alt"></i></a>
        </div>
    </div>
</header>

<div class="mobile-search-bar">
    <form action="index.php" method="GET" class="search-form">
        <input type="text" name="search" placeholder="ابحث عن منتج...">
        <button type="submit" class="search-btn"><i class="fas fa-search"></i></button>
    </form>
</div>

<div class="overlay" id="mobileOverlay"></div>
<div class="mobile-menu" id="mobileMenu">
    <div class="mobile-menu-header">
        <div class="logo">
            <div class="logo-circle" style="width:38px;height:38px;">
                <?php if(!empty($store['logo'])): ?>
                    <img src="<?php echo BASE_URL.'admin/'.htmlspecialchars($store['logo']); ?>" alt="">
                <?php else: ?>
                    <div class="logo-circle-placeholder" style="font-size:16px;"><?php echo mb_substr($store['name'], 0, 1); ?></div>
                <?php endif; ?>
            </div>
            <span class="logo-name" style="font-size:17px;"><?php echo htmlspecialchars($store['name']); ?></span>
        </div>
        <button class="close-btn" id="closeMenu"><i class="fas fa-times"></i></button>
    </div>
    <div class="mobile-menu-body">
        <a href="index.php" class="mob-link"><i class="fas fa-home"></i> الرئيسية</a>
        <a href="track_order.php" class="mob-link"><i class="fas fa-box"></i> طلباتي</a>
        <div class="mob-section-label">الأقسام</div>
        <a href="index.php" class="mob-link"><i class="fas fa-th-large"></i> كل المنتجات</a>
        <?php foreach($categories as $cat): ?>
        <a href="index.php?category=<?php echo $cat['id']; ?>" class="mob-link">
            <i class="fas fa-tag"></i> <?php echo htmlspecialchars($cat['name']); ?>
        </a>
        <?php endforeach; ?>
        <div class="mob-section-label">تواصل معنا</div>
        <a href="tel:<?php echo htmlspecialchars($store['phone']); ?>" class="mob-link"><i class="fas fa-phone-alt"></i> <?php echo htmlspecialchars($store['phone']); ?></a>
    </div>
</div>

<div class="page-wrap">

    <div class="breadcrumb">
        <a href="index.php"><i class="fas fa-home"></i> الرئيسية</a>
        <i class="fas fa-chevron-left"></i>
        <?php if(!empty($product['category_name'])): ?>
            <a href="index.php?category=<?php echo $product['category_id']; ?>"><?php echo htmlspecialchars($product['category_name']); ?></a>
            <i class="fas fa-chevron-left"></i>
        <?php endif; ?>
        <span><?php echo htmlspecialchars($product['name']); ?></span>
    </div>

    <div class="trust-strip">
        <div class="trust-pill green"><i class="fas fa-shield-alt"></i> دفع عند الاستلام</div>
        <div class="trust-pill blue"><i class="fas fa-truck"></i> توصيل لجميع الولايات</div>
        <div class="trust-pill orange"><i class="fas fa-undo"></i> إمكانية الإرجاع</div>
        <div class="trust-pill gold"><i class="fas fa-star"></i> منتجات أصلية مضمونة</div>
    </div>

    <div class="product-wrap">
        <div class="gallery" id="productGallery">
            <div class="gallery-main" id="galleryMain">
                <div class="gallery-overlay" id="galleryOverlay">
                    <i class="fas fa-hand-pointer"></i>
                    <p>اختر الخصائص أدناه<br>لرؤية صورة المنتج</p>
                </div>
                <?php if($has_discount): ?>
                    <div class="gallery-badge">-<?php echo $discount_pct; ?>%</div>
                <?php endif; ?>
                <button class="gallery-nav prev" onclick="prevImg()"><i class="fas fa-chevron-right"></i></button>
                <img id="mainImg"
                     src="<?php echo $main_image_url ? BASE_URL.'admin/'.htmlspecialchars($main_image_url) : ''; ?>"
                     alt="<?php echo htmlspecialchars($product['name']); ?>">
                <button class="gallery-nav next" onclick="nextImg()"><i class="fas fa-chevron-left"></i></button>
            </div>
            <div class="thumbs-row" id="thumbsRow">
                <?php foreach($all_images as $i => $img): if(empty($img['image_url'])) continue; ?>
                <div class="thumb <?php echo $i===0?'active':''; ?> <?php echo $img['type']==='variant'?'variant-thumb':''; ?>"
                     data-index="<?php echo $i; ?>"
                     data-variant="<?php echo $img['type']==='variant'?$img['variant_id']:''; ?>"
                     onclick="setMainImg('<?php echo BASE_URL.'admin/'.htmlspecialchars($img['image_url']); ?>',<?php echo $i; ?>)">
                    <img src="<?php echo BASE_URL.'admin/'.htmlspecialchars($img['image_url']); ?>" alt="">
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="product-info">
            <?php if(!empty($product['category_name'])): ?>
            <div class="product-cat-badge"><i class="fas fa-tag"></i> <?php echo htmlspecialchars($product['category_name']); ?></div>
            <?php endif; ?>
            <h1 class="product-name"><?php echo htmlspecialchars($product['name']); ?></h1>
            <?php if(!empty($product['description'])): ?>
            <div class="product-desc"><?php echo nl2br(htmlspecialchars($product['description'])); ?></div>
            <?php endif; ?>

            <?php if(!$is_product_available): ?>
            <div class="oos-box">
                <i class="fas fa-ban"></i>
                <h3>المنتج غير متوفر حالياً</h3>
                <p>نعمل على تجديد المخزون قريباً. تفقد منتجاتنا الأخرى.</p>
            </div>
            <?php endif; ?>

            <?php if($is_product_available && $has_variants): ?>
            <div class="variant-alert" id="variantAlert">
                <div class="variant-alert-icon"><i class="fas fa-exclamation"></i></div>
                <div>
                    <div class="variant-alert-title">يرجى اختيار الخصائص التالية أولاً</div>
                    <ul class="variant-alert-list" id="missingList"></ul>
                    <button type="button" class="variant-alert-action" id="goToMissing"><i class="fas fa-arrow-up"></i> اختر الآن</button>
                </div>
            </div>
            <div class="variants-wrap" id="variantsWrap">
                <?php foreach($variant_attributes as $attr_name => $attr_values):
                    $block_id = 'vb-'.preg_replace('/\s+/','_',$attr_name);
                    $sicon_id = 'si-'.preg_replace('/\s+/','_',$attr_name);
                ?>
                <div class="vblock" id="<?php echo $block_id; ?>" data-attr="<?php echo htmlspecialchars($attr_name); ?>">
                    <div class="vblock-label">
                        <i class="fas fa-sliders-h"></i>
                        <?php echo htmlspecialchars($attr_name); ?>
                        <span class="vblock-status" id="<?php echo $sicon_id; ?>"><i class="fas fa-question"></i></span>
                    </div>
                    <div class="variant-chips">
                        <?php foreach($attr_values as $val):
                            $chip_img = '';
                            foreach($product_variants as $vv) {
                                $has_val = false;
                                foreach($vv['variant_attrs'] as $va) {
                                    if($va['attribute_name']===$attr_name && $va['attribute_value']===$val) { $has_val=true; break; }
                                }
                                if($has_val && !empty($vv['variant_images'])) {
                                    $chip_img = BASE_URL.'admin/'.htmlspecialchars($vv['variant_images'][0]['image_url']);
                                    break;
                                }
                            }
                        ?>
                        <div class="v-chip <?php echo $chip_img?'has-img':''; ?>"
                             data-attribute="<?php echo htmlspecialchars($attr_name); ?>"
                             data-value="<?php echo htmlspecialchars($val); ?>">
                            <?php if($chip_img): ?><img src="<?php echo $chip_img; ?>" class="chip-thumb" alt=""><?php endif; ?>
                            <?php echo htmlspecialchars($val); ?>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <div class="vblock-hint"><i class="fas fa-hand-point-up"></i> يرجى اختيار <?php echo htmlspecialchars($attr_name); ?> للمتابعة</div>
                </div>
                <?php endforeach; ?>
            </div>
            <div class="variant-done-badge" id="variantDone">
                <div class="done-badge-icon"><i class="fas fa-check"></i></div>
                <div>
                    <div class="done-badge-title">✓ ممتاز! تم تحديد جميع الخصائص</div>
                    <div class="done-badge-tags" id="doneTags"></div>
                </div>
            </div>
            <?php endif; ?>

            <?php if($is_product_available): ?>
            <div class="price-box">
                <div>
                    <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:var(--gray-400);margin-bottom:4px;">السعر</div>
                    <div class="price-current" id="priceDisplay"><?php echo number_format($default_price_for_display,0); ?> دج</div>
                    <div class="price-note"><i class="fas fa-info-circle"></i> السعر لا يشمل التوصيل</div>
                </div>
                <div style="display:flex;flex-direction:column;align-items:flex-end;gap:6px;">
                    <?php if($has_discount): ?>
                    <div class="price-old"><?php echo number_format($product['price'],0); ?> دج</div>
                    <div class="price-save-badge">وفر <?php echo $discount_pct; ?>%</div>
                    <?php endif; ?>
                </div>
            </div>
            <?php if($display_stock > 0 && $display_stock < 5): ?>
            <div class="stock-badge <?php echo $display_stock < 3 ? 'low' : 'medium'; ?>" id="stockBadge">
                <i class="fas fa-<?php echo $display_stock < 3 ? 'fire' : 'exclamation-triangle'; ?>"></i>
                تبقى <strong style="font-size:16px;margin:0 3px;"><?php echo $display_stock; ?></strong>
                <?php echo $display_stock == 1 ? 'حبة فقط! 🔥' : 'حبات فقط!'; ?>
            </div>
            <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>

    <div class="order-fab" id="orderFab">
        <button class="fab-btn <?php echo !$is_product_available?'state-disabled':($has_variants?'state-select':'state-ready'); ?>"
                id="fabBtn" <?php echo !$is_product_available?'disabled':''; ?>>
            <?php if(!$is_product_available): ?>
                <i class="fas fa-ban"></i> المنتج غير متوفر
            <?php elseif($has_variants): ?>
                <i class="fas fa-hand-pointer"></i><span id="fabText">اختر الخصائص أولاً</span>
            <?php else: ?>
                <i class="fas fa-bolt"></i> اطلب الآن
            <?php endif; ?>
        </button>
    </div>

    <div class="order-section" id="orderSection">
        <div class="order-header">
            <div class="order-header-icon"><i class="fas fa-clipboard-list"></i></div>
            <div>
                <div class="order-header-title">أكمل طلبك</div>
                <div class="order-header-sub">أدخل بياناتك وسنتصل بك لتأكيد الطلب</div>
            </div>
        </div>
        <div class="order-body">
            <form id="orderForm" action="submit_order.php" method="POST">
                <?php if($has_variants): ?>
                <div style="margin-bottom:20px;">
                    <div class="form-label" style="margin-bottom:6px;"><i class="fas fa-check-circle"></i> الخصائص المختارة</div>
                    <div class="attrs-preview" id="attrsPreview"><i class="fas fa-mouse-pointer"></i> اختر الخصائص من الأعلى</div>
                    <input type="hidden" id="selectedAttrsInput" name="selected_attributes" value="">
                </div>
                <?php else: ?>
                <input type="hidden" id="selectedAttrsInput" name="selected_attributes" value="[]">
                <?php endif; ?>

                <div class="fields-grid">
                    <div class="form-group">
                        <label class="form-label"><i class="fas fa-user"></i> الاسم الكامل *</label>
                        <div class="field-with-icon">
                            <span class="field-icon"><i class="fas fa-id-card"></i></span>
                            <input type="text" name="customer_name" id="customer_name" class="form-input" placeholder="أدخل اسمك الكامل" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label"><i class="fas fa-phone"></i> الهاتف الأساسي *</label>
                        <div class="field-with-icon">
                            <span class="field-icon"><i class="fas fa-mobile-alt"></i></span>
                            <input type="tel" name="phone" id="phone" class="form-input" placeholder="0XXXXXXXXX" required>
                        </div>
                    </div>
                </div>
                <div class="fields-grid" style="margin-top:0;">
                    <div class="form-group">
                        <label class="form-label"><i class="fas fa-phone-volume"></i> هاتف إضافي <span style="font-weight:400;text-transform:none;">(اختياري)</span></label>
                        <div class="field-with-icon">
                            <span class="field-icon"><i class="fas fa-phone-square"></i></span>
                            <input type="tel" name="phone2" id="phone2" class="form-input" placeholder="0XXXXXXXXX">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label"><i class="fas fa-map-marker-alt"></i> العنوان <span style="font-weight:400;text-transform:none;">(اختياري)</span></label>
                        <div class="field-with-icon">
                            <span class="field-icon"><i class="fas fa-home"></i></span>
                            <input type="text" name="address" id="address" class="form-input" placeholder="الشارع، الحي...">
                        </div>
                    </div>
                </div>

                <div class="divider"><i class="fas fa-map-marked-alt"></i> معلومات التوصيل</div>

                <div style="margin-bottom:18px;">
                    <label class="form-label" style="margin-bottom:8px;"><i class="fas fa-truck"></i> نوع التوصيل *</label>
                    <div class="del-type-row">
                        <label class="del-pill" id="pillHome">
                            <input type="radio" name="delivery_type" value="home" checked>
                            <i class="fas fa-home"></i> إلى المنزل
                        </label>
                        <label class="del-pill" id="pillOffice">
                            <input type="radio" name="delivery_type" value="office">
                            <i class="fas fa-building"></i> إلى المكتب
                        </label>
                    </div>
                </div>

                <div class="form-group" style="margin-bottom:14px;">
                    <label class="form-label"><i class="fas fa-city"></i> الولاية *</label>
                    <div class="field-with-icon">
                        <span class="field-icon"><i class="fas fa-map"></i></span>
                        <select name="wilaya_id" id="wilayaSelect" class="form-input" required>
                            <option value="">— اختر ولايتك —</option>
                            <?php foreach($wilayas as $w): ?>
                            <option value="<?php echo $w['id']; ?>"><?php echo formatWilayaForDisplay($w['id'],$w['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div style="font-size:11px;color:var(--gray-400);margin-top:4px;"><i class="fas fa-info-circle"></i> اختر ولايتك لحساب رسوم التوصيل</div>
                </div>

                <div class="form-group" id="communeRow" style="margin-bottom:18px;display:none;">
                    <label class="form-label" id="communeLabel">
                        <i class="fas fa-location-arrow"></i>
                        البلدية <span id="communeRequiredMark" style="color:var(--red);">*</span>
                    </label>
                    <div class="field-with-icon">
                        <span class="field-icon"><i class="fas fa-map-pin"></i></span>
                        <select name="commune_id" id="communeSelect" class="form-input">
                            <option value="">— اختر بلديتك —</option>
                        </select>
                    </div>
                    <div class="commune-required-note" id="communeRequiredNote">
                        <i class="fas fa-exclamation-circle"></i>
                        يجب اختيار البلدية للتوصيل إلى المنزل
                    </div>
                </div>

                <div class="order-summary">
                    <div class="summary-item">
                        <div class="summary-label">الكمية</div>
                        <div class="qty-wrap">
                            <button type="button" class="qty-btn-ctrl minus">−</button>
                            <input type="number" class="qty-val" id="qtyInput" name="quantity" value="1" min="1" max="<?php echo $available_stock; ?>">
                            <button type="button" class="qty-btn-ctrl plus">+</button>
                        </div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-label">التوصيل</div>
                        <div class="summary-val" id="deliveryDisplay">—</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-label">المجموع الكلي</div>
                        <div class="summary-val big" id="totalDisplay"><?php echo number_format($default_price_for_display,0); ?> دج</div>
                    </div>
                </div>

                <input type="hidden" name="product_id" value="<?php echo $product_id; ?>">
                <input type="hidden" name="event_id" id="metaEventId" value="<?php echo $meta_event_id; ?>">

                <!-- ══════════════════════════════════════════════════
                     حقول Meta Pixel — fbp و fbc للمطابقة المتقدمة
                     ══════════════════════════════════════════════════ -->
                <input type="hidden" name="fbp" id="metaFbp" value="">
                <input type="hidden" name="fbc" id="metaFbc" value="">

                <input type="hidden" id="variantIdInput" name="variant_id" value="<?php echo $default_variant['id'] ?? ''; ?>">
                <input type="hidden" name="delivery_company_id" value="<?php echo $delivery_info['id'] ?? ''; ?>">
                <input type="hidden" id="deliveryPriceInput" name="delivery_price" value="0">

                <button type="submit" class="submit-btn" id="submitBtn" <?php echo !$is_product_available?'disabled':''; ?>>
                    <i class="fas fa-check-circle"></i> تأكيد الطلب الآن
                </button>
                <div class="submit-note"><i class="fas fa-phone-alt"></i> سيتصل بكم فريقنا للتأكيد وتحديد موعد التوصيل</div>
            </form>
        </div>
    </div>

    <?php if(!empty($related_products)): ?>
    <div class="section-title">
        <h2><i class="fas fa-th-large" style="font-size:18px;color:var(--blue);"></i> منتجات مشابهة <span><?php echo count($related_products); ?></span></h2>
        <a href="index.php?category=<?php echo $product['category_id']; ?>" style="font-size:13px;color:var(--gray-400);display:flex;align-items:center;gap:6px;font-weight:700;"><i class="fas fa-arrow-left"></i> عرض الكل</a>
    </div>
    <div class="related-grid">
        <?php foreach($related_products as $rel):
            $ri = !empty($rel['image']) ? BASE_URL.'admin/'.htmlspecialchars($rel['image']) : '';
            $rp = $rel['discounted_price'] ?? $rel['price'];
            $ro = $rel['discounted_price'] ? $rel['price'] : null;
        ?>
        <a href="det.php?id=<?php echo $rel['id']; ?>" class="rel-card">
            <div class="rel-img">
                <?php if($ri): ?><img src="<?php echo $ri; ?>" alt="<?php echo htmlspecialchars($rel['name']); ?>"><?php else: ?><div class="rel-img-placeholder"><i class="fas fa-pills"></i></div><?php endif; ?>
            </div>
            <div class="rel-body">
                <div class="rel-name"><?php echo htmlspecialchars($rel['name']); ?></div>
                <div><?php if($ro): ?><span class="rel-price-old"><?php echo number_format($ro,0); ?> دج</span><?php endif; ?><span class="rel-price"><?php echo number_format($rp,0); ?> دج</span></div>
                <div class="rel-cta"><i class="fas fa-eye"></i> عرض المنتج</div>
            </div>
        </a>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

</div>

<nav class="bottom-nav">
    <div class="bottom-nav-bg">
        <div class="bottom-nav-inner">
            <a href="index.php" class="bnav-item">
                <div class="bnav-icon"><i class="fas fa-home"></i></div>
                <span>الرئيسية</span>
            </a>
            <button class="bnav-item" id="menuToggleMob">
                <div class="bnav-icon"><i class="fas fa-bars"></i></div>
                <span>القائمة</span>
            </button>
            <button class="bnav-cta" id="fabTriggerMob">
                <div class="bnav-cta-inner"><i class="fas fa-bolt"></i></div>
            </button>
            <a href="track_order.php" class="bnav-item">
                <div class="bnav-icon"><i class="fas fa-box"></i></div>
                <span>طلباتي</span>
            </a>
            <a href="tel:<?php echo htmlspecialchars($store['phone']); ?>" class="bnav-item">
                <div class="bnav-icon"><i class="fas fa-phone-alt"></i></div>
                <span>اتصل بنا</span>
            </a>
        </div>
    </div>
</nav>

<button class="scroll-top" id="scrollTopBtn"><i class="fas fa-chevron-up"></i></button>
<div class="toast-wrap" id="toastWrap"></div>

<footer class="footer">
    <div class="footer-inner">
        <div class="footer-brand">
            <div class="logo">
                <div class="logo-circle" style="width:44px;height:44px;">
                    <?php if(!empty($store['logo'])): ?>
                        <img src="<?php echo BASE_URL.'admin/'.htmlspecialchars($store['logo']); ?>" alt="">
                    <?php else: ?>
                        <div class="logo-circle-placeholder"><?php echo mb_substr($store['name'], 0, 1); ?></div>
                    <?php endif; ?>
                </div>
                <span class="logo-name" style="color:white;font-size:20px;"><?php echo htmlspecialchars($store['name']); ?></span>
            </div>
            <p><?php echo htmlspecialchars($store['description'] ?? ''); ?></p>
            <div class="social-row">
                <?php if(!empty($store['facebook'])): ?><a href="<?php echo htmlspecialchars($store['facebook']); ?>" class="social-btn" target="_blank"><i class="fab fa-facebook-f"></i></a><?php endif; ?>
                <?php if(!empty($store['telegram'])): ?><a href="<?php echo htmlspecialchars($store['telegram']); ?>" class="social-btn" target="_blank"><i class="fab fa-telegram-plane"></i></a><?php endif; ?>
                <?php if(!empty($store['instgrame'])): ?><a href="<?php echo htmlspecialchars($store['instgrame']); ?>" class="social-btn" target="_blank"><i class="fab fa-instagram"></i></a><?php endif; ?>
            </div>
        </div>
        <div>
            <div class="footer-col-title">روابط سريعة</div>
            <ul class="footer-links-list">
                <li><a href="index.php"><i class="fas fa-chevron-left"></i> الرئيسية</a></li>
                <li><a href="index.php"><i class="fas fa-chevron-left"></i> جميع المنتجات</a></li>
                <li><a href="track_order.php"><i class="fas fa-chevron-left"></i> تتبع طلبي</a></li>
            </ul>
        </div>
        <div>
            <div class="footer-col-title">تواصل معنا</div>
            <ul class="footer-links-list">
                <li><a href="tel:<?php echo htmlspecialchars($store['phone']); ?>"><i class="fas fa-phone-alt"></i> <?php echo htmlspecialchars($store['phone']); ?></a></li>
                <li><a href="mailto:<?php echo htmlspecialchars($store['emailp']); ?>"><i class="fas fa-envelope"></i> <?php echo htmlspecialchars($store['emailp']); ?></a></li>
            </ul>
        </div>
    </div>
    <div class="footer-bottom">© <?php echo date('Y'); ?> <strong style="color:var(--theme-accent);"><?php echo htmlspecialchars($store['name']); ?></strong> — جميع الحقوق محفوظة</div>
</footer>

<script>
const allImagesData   = <?php echo json_encode($all_images); ?>;
const productVariants = <?php echo json_encode($product_variants); ?>;
const deliveryHome    = <?php echo json_encode($delivery_prices_home); ?>;
const deliveryOffice  = <?php echo json_encode($delivery_prices_office); ?>;
const communesData    = <?php echo json_encode($communes_data); ?>;
const variantAttrMap  = <?php echo json_encode($variant_attributes); ?>;
const hasVariants     = <?php echo $has_variants ? 'true' : 'false'; ?>;
const isAvailable     = <?php echo $is_product_available ? 'true' : 'false'; ?>;
let   defaultPrice    = <?php echo (float)$default_price_for_display; ?>;
const originalImages  = <?php echo json_encode($all_images); ?>;

let selectedAttrs  = {};
let currentVariant = <?php echo json_encode($default_variant); ?>;
let currentImgIdx  = 0;

/* =========================================
   GALLERY
   ========================================= */
function setMainImg(url, idx) {
    const img = document.getElementById('mainImg');
    img.style.opacity = '0';
    setTimeout(() => { img.src = url; img.style.opacity = '1'; }, 120);
    currentImgIdx = idx;
    document.querySelectorAll('.thumb').forEach((t,i) => t.classList.toggle('active', i === idx));
    const at = document.querySelectorAll('.thumb')[idx];
    if (at) at.scrollIntoView({ behavior:'smooth', block:'nearest', inline:'center' });
}
function nextImg() {
    if (!allImagesData.length) return;
    const idx = (currentImgIdx + 1) % allImagesData.length;
    setMainImg('<?php echo BASE_URL; ?>admin/' + allImagesData[idx].image_url, idx);
}
function prevImg() {
    if (!allImagesData.length) return;
    const idx = (currentImgIdx - 1 + allImagesData.length) % allImagesData.length;
    setMainImg('<?php echo BASE_URL; ?>admin/' + allImagesData[idx].image_url, idx);
}
function rebuildThumbs(images, activeIdx) {
    const row = document.getElementById('thumbsRow');
    row.innerHTML = '';
    images.forEach((img, i) => {
        const url = '<?php echo BASE_URL; ?>admin/' + img.image_url;
        const vid = img.type === 'variant' ? `data-variant="${img.variant_id}"` : '';
        const vc  = img.type === 'variant' ? 'variant-thumb' : '';
        row.innerHTML += `<div class="thumb ${i===activeIdx?'active':''} ${vc}" data-index="${i}" ${vid} onclick="setMainImg('${url}',${i})"><img src="${url}" alt=""></div>`;
    });
}
function updateVariantImages(vid) {
    const v = productVariants.find(x => x.id == vid);
    let merged = originalImages.slice();
    if (v && v.variant_images && v.variant_images.length) {
        v.variant_images.forEach(vi => {
            if (!merged.some(m => m.image_url === vi.image_url))
                merged.push({ type:'variant', variant_id:vid, image_url:vi.image_url, is_primary:vi.is_primary });
        });
        const ti = merged.findIndex(m => m.image_url === v.variant_images[0].image_url);
        const si = ti >= 0 ? ti : 0;
        rebuildThumbs(merged, si);
        setMainImg('<?php echo BASE_URL; ?>admin/' + v.variant_images[0].image_url, si);
    } else {
        rebuildThumbs(merged, 0);
        if (merged.length) setMainImg('<?php echo BASE_URL; ?>admin/' + merged[0].image_url, 0);
    }
}

/* =========================================
   STOCK BADGE
   ========================================= */
function updateStockBadge(stock) {
    const badge = document.getElementById('stockBadge');
    if (!badge) return;
    if (stock > 0 && stock < 5) {
        badge.style.display = 'inline-flex';
        badge.className = 'stock-badge ' + (stock < 3 ? 'low' : 'medium');
        const icon = stock < 3 ? 'fire' : 'exclamation-triangle';
        const text = stock == 1 ? 'حبة فقط! 🔥' : 'حبات فقط!';
        badge.innerHTML = `<i class="fas fa-${icon}"></i> تبقى <strong style="font-size:16px;margin:0 3px;">${stock}</strong> ${text}`;
    } else {
        badge.style.display = 'none';
    }
}

/* =========================================
   VARIANT SELECTION
   ========================================= */
document.getElementById('thumbsRow').addEventListener('click', function(e) {
    const thumb = e.target.closest('.thumb');
    if (!thumb) return;
    const vid = thumb.dataset.variant;
    if (!vid) return;
    const v = productVariants.find(x => x.id == vid);
    if (!v) return;
    v.variant_attrs.forEach(va => {
        selectedAttrs[va.attribute_name] = va.attribute_value;
        document.querySelectorAll(`.v-chip[data-attribute="${va.attribute_name}"]`).forEach(c => c.classList.remove('selected'));
        const chip = document.querySelector(`.v-chip[data-attribute="${va.attribute_name}"][data-value="${va.attribute_value}"]`);
        if (chip) chip.classList.add('selected');
    });
    currentVariant = v;
    applyVariant(v, false);
    refreshBlockStates(); updateAttrsDisplay(); updateFabBtn(); hideAlert();
});

document.querySelectorAll('.v-chip:not(.oos)').forEach(chip => {
    chip.addEventListener('click', function() {
        const attr = this.dataset.attribute, val = this.dataset.value;
        document.querySelectorAll(`.v-chip[data-attribute="${attr}"]`).forEach(c => c.classList.remove('selected'));
        this.classList.add('selected');
        selectedAttrs[attr] = val;
        findVariant(true); refreshBlockStates(); updateAttrsDisplay(); updateFabBtn(); hideAlert();
    });
});

function findVariant(updateImgs) {
    const match = productVariants.find(v =>
        Object.keys(variantAttrMap).every(attr =>
            v.variant_attrs.some(va => va.attribute_name === attr && va.attribute_value === selectedAttrs[attr])
        ) && v.stock > 0
    );
    if (match) { currentVariant = match; applyVariant(match, updateImgs !== false); }
    else currentVariant = null;
}
function applyVariant(v, updateImgs) {
    document.getElementById('priceDisplay').textContent = Number(v.price).toFixed(0) + ' دج';
    document.getElementById('variantIdInput').value = v.id;
    document.getElementById('qtyInput').max = v.stock;
    updateTotal();
    updateStockBadge(v.stock);
    if (updateImgs) updateVariantImages(v.id);
}

if (hasVariants && isAvailable) {
    Object.keys(variantAttrMap).forEach(attr => {
        const vals = variantAttrMap[attr];
        if (vals && vals.length) {
            selectedAttrs[attr] = vals[0];
            const chip = document.querySelector(`.v-chip[data-attribute="${attr}"][data-value="${vals[0]}"]`);
            if (chip) chip.classList.add('selected');
        }
    });
    findVariant(false); refreshBlockStates(); updateAttrsDisplay(); updateFabBtn();
}

function refreshBlockStates() {
    Object.keys(variantAttrMap).forEach(attr => {
        const bid = 'vb-' + attr.replace(/\s+/g,'_');
        const sid = 'si-' + attr.replace(/\s+/g,'_');
        const block = document.getElementById(bid), icon = document.getElementById(sid);
        if (!block) return;
        if (selectedAttrs[attr]) {
            block.classList.add('done'); block.classList.remove('needs');
            if (icon) icon.innerHTML = '<i class="fas fa-check"></i>';
        } else {
            block.classList.remove('done'); block.classList.add('needs');
            if (icon) icon.innerHTML = '<i class="fas fa-question"></i>';
        }
    });
}

function updateAttrsDisplay() {
    const preview = document.getElementById('attrsPreview');
    if (!preview) return;
    const entries = Object.entries(selectedAttrs).filter(([,v]) => v);
    if (!entries.length) {
        preview.innerHTML = '<i class="fas fa-mouse-pointer"></i> اختر الخصائص من الأعلى';
        preview.classList.remove('has-value');
    } else {
        preview.innerHTML = entries.map(([k,v]) => `<span class="attr-tag">${k}: ${v}</span>`).join(' ');
        preview.classList.add('has-value');
    }
    document.getElementById('selectedAttrsInput').value = JSON.stringify(selectedAttrs);
    const db = document.getElementById('variantDone'), dt = document.getElementById('doneTags');
    if (isAllSelected()) {
        if (dt) dt.innerHTML = entries.map(([k,v]) => `<span class="done-tag">${k}: ${v}</span>`).join('');
        if (db) db.classList.add('show');
    } else { if (db) db.classList.remove('show'); }
}

function isAllSelected() { return Object.keys(variantAttrMap).every(k => selectedAttrs[k]); }
function getMissing() { return Object.keys(variantAttrMap).filter(k => !selectedAttrs[k]); }

function updateFabBtn() {
    if (!hasVariants || !isAvailable) return;
    const btn = document.getElementById('fabBtn');
    if (!btn) return;
    if (isAllSelected()) {
        btn.className = 'fab-btn state-ready';
        btn.innerHTML = '<i class="fas fa-bolt"></i> اطلب الآن';
    } else {
        btn.className = 'fab-btn state-select';
        const m = getMissing();
        btn.innerHTML = `<i class="fas fa-hand-pointer"></i> اختر ${m[0] || ''} أولاً`;
    }
}

function showAlert() {
    const missing = getMissing();
    if (!missing.length) return;
    const list = document.getElementById('missingList');
    if (list) list.innerHTML = missing.map(a => `<li><i class="fas fa-arrow-left"></i> ${a}</li>`).join('');
    document.getElementById('variantAlert')?.classList.add('show');
    missing.forEach(attr => {
        const b = document.getElementById('vb-' + attr.replace(/\s+/g,'_'));
        if (b) { b.classList.remove('done'); b.classList.add('needs'); }
    });
    const fb = document.getElementById('vb-' + missing[0].replace(/\s+/g,'_'));
    if (fb) fb.scrollIntoView({ behavior:'smooth', block:'center' });
}
function hideAlert() { if (isAllSelected()) document.getElementById('variantAlert')?.classList.remove('show'); }

document.getElementById('goToMissing')?.addEventListener('click', () => {
    const m = getMissing();
    if (m.length) { const b = document.getElementById('vb-' + m[0].replace(/\s+/g,'_')); if (b) b.scrollIntoView({ behavior:'smooth', block:'center' }); }
});

function handleOrderClick() {
    if (!isAvailable) return;
    if (hasVariants && !isAllSelected()) { showAlert(); return; }
    document.getElementById('orderSection')?.scrollIntoView({ behavior:'smooth', block:'start' });
}
document.getElementById('fabBtn')?.addEventListener('click', handleOrderClick);
document.getElementById('fabTriggerMob')?.addEventListener('click', handleOrderClick);

function handleFab() {
    const fab = document.getElementById('orderFab'), sec = document.getElementById('orderSection');
    if (!fab || !sec) return;
    const st = sec.getBoundingClientRect().top;
    if (st < window.innerHeight) fab.classList.remove('show'); else fab.classList.add('show');
}
window.addEventListener('scroll', handleFab, { passive:true });
setTimeout(handleFab, 300);

/* =========================================
   COMMUNES
   ========================================= */
function getCurrentDeliveryType() {
    return document.querySelector('input[name="delivery_type"]:checked')?.value || 'home';
}

function updateCommuneUI() {
    const dtype = getCurrentDeliveryType();
    const reqNote  = document.getElementById('communeRequiredNote');
    const reqMark  = document.getElementById('communeRequiredMark');
    const sel      = document.getElementById('communeSelect');
    if (dtype === 'home') {
        if (reqNote) reqNote.classList.add('show');
        if (reqMark) reqMark.style.display = 'inline';
        if (sel)    sel.required = true;
    } else {
        if (reqNote) reqNote.classList.remove('show');
        if (reqMark) reqMark.style.display = 'none';
        if (sel)    sel.required = false;
    }
}

function loadCommunes(wid) {
    const row = document.getElementById('communeRow'), sel = document.getElementById('communeSelect');
    if (!wid) { row.style.display='none'; return; }
    const filtered = communesData.filter(c => parseInt(c.wilaya_code) === parseInt(wid));
    filtered.sort((a,b) => (a.commune_name_ascii||'').localeCompare(b.commune_name_ascii||''));
    if (filtered.length) {
        sel.innerHTML = '<option value="">— اختر بلديتك —</option>' +
            filtered.map(c => {
                const fr=c.commune_name_ascii||'', ar=c.commune_name||'';
                const label=(fr&&ar&&fr!==ar)?`${fr} / ${ar}`:(ar||fr);
                return `<option value="${c.id}">${label}</option>`;
            }).join('');
        row.style.display = 'flex';
        updateCommuneUI();
    } else {
        row.style.display = 'none';
    }
}

function updateDelivery() {
    const wid   = document.getElementById('wilayaSelect').value;
    const dtype = getCurrentDeliveryType();
    if (!wid) {
        document.getElementById('deliveryDisplay').textContent='—';
        document.getElementById('deliveryPriceInput').value=0;
        updateTotal(); return;
    }
    const arr   = dtype==='home' ? deliveryHome : deliveryOffice;
    const found = arr.find(x => x.wilaya_id == wid);
    if (found) {
        document.getElementById('deliveryDisplay').textContent=parseFloat(found.price).toFixed(0)+' دج';
        document.getElementById('deliveryPriceInput').value=found.price;
    } else {
        document.getElementById('deliveryDisplay').textContent='غير متوفر';
        document.getElementById('deliveryPriceInput').value=0;
    }
    updateTotal();
}

function updateTotal() {
    const qty=parseInt(document.getElementById('qtyInput').value)||1;
    const del=parseFloat(document.getElementById('deliveryPriceInput').value)||0;
    let price=defaultPrice;
    if (currentVariant) price=parseFloat(currentVariant.price);
    document.getElementById('totalDisplay').textContent=((price*qty)+del).toFixed(0)+' دج';
}

document.getElementById('wilayaSelect').addEventListener('change', function() {
    loadCommunes(this.value);
    updateDelivery();
});

document.querySelectorAll('input[name="delivery_type"]').forEach(r => r.addEventListener('change', function() {
    updateDelivery();
    updateCommuneUI();
}));

document.querySelector('.qty-btn-ctrl.minus')?.addEventListener('click', () => {
    const i=document.getElementById('qtyInput');
    if(parseInt(i.value)>1){i.value=parseInt(i.value)-1;updateTotal();}
});
document.querySelector('.qty-btn-ctrl.plus')?.addEventListener('click', () => {
    const i=document.getElementById('qtyInput'), m=parseInt(i.max)||100;
    if(parseInt(i.value)<m){i.value=parseInt(i.value)+1;updateTotal();}
});
document.getElementById('qtyInput')?.addEventListener('change', function() {
    let v=parseInt(this.value), m=parseInt(this.max)||100;
    if(isNaN(v)||v<1)v=1; if(v>m)v=m; this.value=v; updateTotal();
});

/* =========================================
   FORM SUBMIT VALIDATION
   ========================================= */
document.getElementById('orderForm')?.addEventListener('submit', function(e) {
    if (hasVariants && !isAllSelected()) { e.preventDefault(); showAlert(); return; }
    const name  = document.getElementById('customer_name').value.trim();
    const phone = document.getElementById('phone').value.trim();
    const wid   = document.getElementById('wilayaSelect').value;
    const dtype = getCurrentDeliveryType();
    const commune = document.getElementById('communeSelect')?.value;
    if (!name) {
        e.preventDefault();
        document.getElementById('customer_name').classList.add('err');
        showToast('يرجى إدخال الاسم الكامل', 'exclamation-circle');
        document.getElementById('customer_name').scrollIntoView({ behavior:'smooth', block:'center' });
        return;
    }
    if (!phone) {
        e.preventDefault();
        document.getElementById('phone').classList.add('err');
        showToast('يرجى إدخال رقم الهاتف', 'exclamation-circle');
        document.getElementById('phone').scrollIntoView({ behavior:'smooth', block:'center' });
        return;
    }
    if (!/^(\+?213[567]\d{8}|0[567]\d{8})$/.test(phone)) {
        e.preventDefault();
        document.getElementById('phone').classList.add('err');
        showToast('❌ رقم غير صحيح — يبدأ بـ 05 أو 06 أو 07 ويكون 10 أرقام', 'exclamation-circle');
        document.getElementById('phone').scrollIntoView({ behavior:'smooth', block:'center' });
        return;
    }
    const phone2 = document.getElementById('phone2').value.trim();
    if (phone2 && !/^(\+?213[567]\d{8}|0[567]\d{8})$/.test(phone2)) {
        e.preventDefault();
        document.getElementById('phone2').classList.add('err');
        showToast('❌ رقم الهاتف الإضافي غير صحيح');
        return;
    }
    if (!wid) {
        e.preventDefault();
        document.getElementById('wilayaSelect').classList.add('err');
        showToast('يرجى اختيار الولاية', 'exclamation-circle');
        document.getElementById('wilayaSelect').scrollIntoView({ behavior:'smooth', block:'center' });
        return;
    }
    const communeRow = document.getElementById('communeRow');
    const communeVisible = communeRow && communeRow.style.display !== 'none';
    if (dtype === 'home' && communeVisible && !commune) {
        e.preventDefault();
        document.getElementById('communeSelect').classList.add('err');
        showToast('❌ يجب اختيار البلدية للتوصيل إلى المنزل', 'exclamation-circle');
        document.getElementById('communeRow').scrollIntoView({ behavior:'smooth', block:'center' });
        return;
    }
});

document.querySelectorAll('.form-input').forEach(el => el.addEventListener('input', () => el.classList.remove('err')));

/* =========================================
   TOAST
   ========================================= */
function showToast(msg, icon) {
    const wrap=document.getElementById('toastWrap'), t=document.createElement('div');
    t.className='toast'; t.innerHTML=`<i class="fas fa-${icon||'info-circle'}"></i> ${msg}`;
    wrap.appendChild(t);
    setTimeout(() => { t.classList.add('out'); setTimeout(()=>t.remove(),300); }, 2800);
}

/* =========================================
   HEADER / SCROLL / MENU
   ========================================= */
const header=document.getElementById('mainHeader'), scrollBtn=document.getElementById('scrollTopBtn');
window.addEventListener('scroll', () => {
    const y=window.scrollY;
    header.classList.toggle('scrolled',y>60);
    scrollBtn.classList.toggle('show',y>400);
}, { passive:true });
scrollBtn.addEventListener('click', () => window.scrollTo({ top:0, behavior:'smooth' }));

function openMenu() {
    document.getElementById('mobileMenu').classList.add('open');
    document.getElementById('mobileOverlay').classList.add('open');
    document.getElementById('menuToggle').classList.add('open');
    document.body.style.overflow='hidden';
}
function closeMenu() {
    document.getElementById('mobileMenu').classList.remove('open');
    document.getElementById('mobileOverlay').classList.remove('open');
    document.getElementById('menuToggle').classList.remove('open');
    document.body.style.overflow='';
}
document.getElementById('menuToggle').addEventListener('click', openMenu);
document.getElementById('closeMenu').addEventListener('click', closeMenu);
document.getElementById('mobileOverlay').addEventListener('click', closeMenu);
document.getElementById('menuToggleMob')?.addEventListener('click', openMenu);

document.querySelectorAll('.gallery-main img, .thumb img, .rel-img img').forEach(img => img.addEventListener('error', function() { this.style.display='none'; }));

updateDelivery();
updateTotal();

/* =========================================
   META COOKIES — fbp و fbc للمطابقة المتقدمة
   ========================================= */
(function() {
    function getCookie(name) {
        const match = document.cookie.match(new RegExp("(^| )" + name + "=([^;]+)"));
        return match ? match[2] : "";
    }
    const fbp = getCookie("_fbp");
    const fbc = getCookie("_fbc");
    if (fbp) document.getElementById("metaFbp").value = fbp;
    if (fbc) document.getElementById("metaFbc").value = fbc;
})();

<?php if ($pixel && $pixel['meta_pixel_enabled'] && !empty(trim($pixel['meta_pixel_id']))): ?>
(function() {
    const orderSection = document.getElementById('orderSection');
    if (orderSection && typeof fbq !== 'undefined') {
        const observer = new IntersectionObserver((entries) => {
            if (entries[0].isIntersecting) {
                fbq('track', 'InitiateCheckout', {
                    content_ids:  ['<?php echo $product_id; ?>'],
                    content_type: 'product',
                    value:        <?php echo (float)$default_price_for_display; ?>,
                    currency:     'DZD',
                    num_items:    1
                });
                observer.disconnect();
            }
        }, { threshold: 0.3 });
        observer.observe(orderSection);
    }
})();
<?php endif; ?>

/* ══════════════════════════════════════════════════
   ── استقبال تحديثات الثيم من معاينة الأدمن ──
   ══════════════════════════════════════════════════ */
window.addEventListener('message', function(e) {
    if (!e.data || e.data.type !== 'THEME_UPDATE') return;
    const t    = e.data.theme;
    const root = document.documentElement.style;
    if (t.primary_color) {
        root.setProperty('--theme-primary', t.primary_color);
    }
    if (t.accent_color) {
        root.setProperty('--theme-accent',  t.accent_color);
    }
    if (t.bg_color) {
        root.setProperty('--theme-bg',      t.bg_color);
        document.body.style.background = t.bg_color;
    }
    if (t.btn_radius) {
        root.setProperty('--theme-radius',  t.btn_radius);
    }
});
</script>
</body>
</html>