<?php
// ============================================================
//  visual_editor.php — محرر تصميم بصري للتاجر
//  v2: Click-to-Edit + Fixed Live Preview + Real Mobile View
// ============================================================

require_once __DIR__ . '/../db.php';

// ============================================================
//  AJAX Handlers
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax'])) {
    header('Content-Type: application/json');
    $action = $_POST['action'] ?? '';
    try {
        if ($action === 'save_all') {
            $data = json_decode($_POST['data'], true);
            $stmt = $pdo->prepare("UPDATE design_settings SET setting_value=? WHERE setting_key=?");
            foreach ($data['settings'] ?? [] as $k => $v) $stmt->execute([$v, $k]);
            $stmtB = $pdo->prepare("UPDATE button_settings SET background_color=?,text_color=?,hover_background=?,border_radius=?,font_size=?,font_weight=?,button_text=?,icon_class=?,box_shadow=?,animation_type=? WHERE button_type=?");
            foreach ($data['buttons'] ?? [] as $type => $b) {
                $stmtB->execute([$b['bg'],$b['color'],$b['hover_bg'],$b['radius'],$b['font_size'],$b['font_weight'],$b['btn_text'],$b['icon'],$b['shadow'],$b['anim'],$type]);
            }
            echo json_encode(['ok' => true]);
        }
    } catch (Exception $e) {
        echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

// ============================================================
//  Fetch Data
// ============================================================
$ds_raw = $pdo->query("SELECT * FROM design_settings ORDER BY category, id")->fetchAll();
$ds = [];
foreach ($ds_raw as $r) $ds[$r['setting_key']] = $r;

$btn_raw = $pdo->query("SELECT * FROM button_settings ORDER BY id")->fetchAll();
$btn = [];
foreach ($btn_raw as $b) $btn[$b['button_type']] = $b;

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

$sample_products = $pdo->query("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.is_active=1 ORDER BY RAND() LIMIT 3")->fetchAll();

function sv($ds, $key, $d='') {
    return isset($ds[$key]) ? htmlspecialchars($ds[$key]['setting_value'] ?? $d) : $d;
}
function svRaw($ds, $key, $d='') {
    return isset($ds[$key]) ? ($ds[$key]['setting_value'] ?? $d) : $d;
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🎨 محرر التصميم المرئي</title>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800;900&display=swap" rel="stylesheet">
<style>
:root {
    --dark:   #0A0E1A;
    --dark2:  #111827;
    --dark3:  #1F2937;
    --dark4:  #374151;
    --border: #2D3748;
    --p:      #6366F1;
    --p-l:    #818CF8;
    --p-d:    #4F46E5;
    --green:  #10B981;
    --yellow: #F59E0B;
    --red:    #EF4444;
    --text:   #F9FAFB;
    --text2:  #9CA3AF;
    --text3:  #6B7280;
    --r:      12px;
    --r-sm:   8px;
    --panel:  340px;
    --font:   'Tajawal', sans-serif;
}
*, *::before, *::after { margin:0; padding:0; box-sizing:border-box; font-family: var(--font); }
body { background: var(--dark); color: var(--text); height: 100vh; overflow: hidden; display: flex; flex-direction: column; }

/* TOP BAR */
.topbar {
    height: 56px; background: var(--dark2); border-bottom: 1px solid var(--border);
    display: flex; align-items: center; justify-content: space-between;
    padding: 0 20px; flex-shrink: 0; z-index: 100; gap: 16px;
}
.topbar-logo { display: flex; align-items: center; gap: 10px; font-size: 15px; font-weight: 900; }
.topbar-logo .icon { width: 32px; height: 32px; background: linear-gradient(135deg, var(--p), var(--p-l)); border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 16px; }
.topbar-actions { display: flex; gap: 8px; align-items: center; }
.btn { display: inline-flex; align-items: center; gap: 6px; padding: 8px 16px; border-radius: var(--r-sm); font-size: 13px; font-weight: 700; cursor: pointer; transition: all .2s; border: none; font-family: var(--font); white-space: nowrap; }
.btn-save { background: var(--green); color: white; }
.btn-save:hover { background: #059669; transform: translateY(-1px); }
.btn-save.saving { opacity: .7; pointer-events: none; }
.btn-preview { background: var(--dark3); color: var(--text2); border: 1px solid var(--border); }
.btn-preview:hover { color: var(--text); border-color: var(--p); }
.btn-reset { background: transparent; color: var(--red); border: 1px solid rgba(239,68,68,.3); }
.btn-reset:hover { background: rgba(239,68,68,.1); }
.save-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--yellow); display: none; animation: pulse 1.5s infinite; }
.save-dot.show { display: block; }
@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:.4} }

/* MODE TABS */
.preview-modes { display: flex; gap: 4px; background: var(--dark3); padding: 4px; border-radius: var(--r-sm); }
.preview-mode-btn { padding: 6px 14px; border-radius: 6px; font-size: 13px; font-weight: 700; cursor: pointer; transition: all .2s; color: var(--text2); border: none; background: none; font-family: var(--font); display: flex; align-items: center; gap: 6px; }
.preview-mode-btn.active { background: var(--p); color: white; }
.preview-mode-btn:hover:not(.active) { color: var(--text); background: var(--dark4); }

/* LAYOUT */
.editor-layout { display: flex; flex: 1; overflow: hidden; }

/* PANEL */
.panel { width: var(--panel); background: var(--dark2); border-left: 1px solid var(--border); display: flex; flex-direction: column; overflow: hidden; flex-shrink: 0; transition: width .3s; }
.panel-header { padding: 14px 16px 10px; border-bottom: 1px solid var(--border); flex-shrink: 0; }
.panel-header-title { font-size: 13px; font-weight: 800; color: var(--text2); text-transform: uppercase; letter-spacing: 1px; margin-bottom: 8px; display: flex; align-items: center; gap: 8px; }
.panel-header-title .ph-icon { width: 24px; height: 24px; border-radius: 6px; background: linear-gradient(135deg, var(--p), var(--p-l)); display: flex; align-items: center; justify-content: center; font-size: 12px; }
.panel-breadcrumb { font-size: 11px; color: var(--text3); display: flex; align-items: center; gap: 4px; }
.panel-breadcrumb span { color: var(--p-l); font-weight: 700; }

/* CLICK HINT */
.click-hint { display: flex; align-items: center; gap: 10px; padding: 14px 16px; background: rgba(99,102,241,.08); border-bottom: 1px solid rgba(99,102,241,.15); font-size: 12px; color: var(--text2); }
.click-hint .ch-icon { width: 32px; height: 32px; background: rgba(99,102,241,.2); border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 14px; flex-shrink: 0; }
.click-hint p { line-height: 1.5; }
.click-hint p strong { color: var(--p-l); }

.panel-content { flex: 1; overflow-y: auto; scrollbar-width: thin; scrollbar-color: var(--dark4) transparent; }
.panel-content::-webkit-scrollbar { width: 4px; }
.panel-content::-webkit-scrollbar-thumb { background: var(--dark4); border-radius: 4px; }

/* DEFAULT STATE */
.panel-default { padding: 20px 16px; }
.panel-default h3 { font-size: 14px; font-weight: 800; color: var(--text); margin-bottom: 8px; }
.panel-default p { font-size: 12px; color: var(--text3); line-height: 1.6; margin-bottom: 16px; }
.quick-sections { display: flex; flex-direction: column; gap: 8px; }
.qs-item { display: flex; align-items: center; gap: 10px; padding: 10px 12px; background: var(--dark3); border: 1px solid var(--border); border-radius: var(--r-sm); cursor: pointer; transition: all .2s; }
.qs-item:hover { border-color: var(--p); background: rgba(99,102,241,.08); }
.qs-item .qi-icon { font-size: 18px; }
.qs-item .qi-text { font-size: 13px; font-weight: 700; color: var(--text2); }
.qs-item:hover .qi-text { color: var(--text); }

/* EDIT PANELS */
.edit-panel { display: none; padding: 16px; }
.edit-panel.active { display: block; }

/* CTRL GROUP */
.ctrl-group { background: var(--dark3); border: 1px solid var(--border); border-radius: var(--r); margin-bottom: 12px; overflow: hidden; }
.ctrl-group-header { padding: 10px 14px; font-size: 11px; font-weight: 800; color: var(--text2); text-transform: uppercase; letter-spacing: 1px; cursor: pointer; display: flex; align-items: center; justify-content: space-between; user-select: none; transition: all .2s; }
.ctrl-group-header:hover { color: var(--text); }
.ctrl-group-header .caret { font-size: 9px; transition: transform .2s; }
.ctrl-group-header.collapsed .caret { transform: rotate(-90deg); }
.ctrl-group-body { padding: 12px 14px 14px; }
.ctrl-group-body.collapsed { display: none; }

/* CTRL ROW */
.ctrl-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; }
.ctrl-row:last-child { margin-bottom: 0; }
.ctrl-label { font-size: 12px; font-weight: 600; color: var(--text2); flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

/* COLOR CTRL */
.color-ctrl { display: flex; align-items: center; gap: 6px; flex-shrink: 0; }
.color-swatch { width: 28px; height: 28px; border-radius: 6px; border: 2px solid var(--border); cursor: pointer; position: relative; overflow: hidden; flex-shrink: 0; transition: all .2s; }
.color-swatch:hover { transform: scale(1.1); border-color: var(--p); }
.color-swatch input[type=color] { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; border: none; }
.color-hex { width: 76px; background: var(--dark); border: 1px solid var(--border); border-radius: 6px; color: var(--text); font-size: 11px; font-family: monospace; padding: 5px 8px; text-align: center; transition: all .2s; }
.color-hex:focus { border-color: var(--p); outline: none; box-shadow: 0 0 0 2px rgba(99,102,241,.2); }

/* TEXT CTRL */
.text-ctrl { flex-shrink: 0; width: 130px; }
.text-ctrl input, .text-ctrl select { width: 100%; background: var(--dark); border: 1px solid var(--border); border-radius: 6px; color: var(--text); font-size: 12px; padding: 6px 8px; font-family: var(--font); transition: all .2s; }
.text-ctrl input:focus, .text-ctrl select:focus { border-color: var(--p); outline: none; }
.text-ctrl select option { background: var(--dark3); }

/* FULL CTRL */
.full-ctrl { width: 100%; margin-bottom: 10px; }
.full-ctrl:last-child { margin-bottom: 0; }
.full-ctrl label { display: block; font-size: 11px; font-weight: 700; color: var(--text3); margin-bottom: 5px; text-transform: uppercase; letter-spacing: .5px; }
.full-ctrl input, .full-ctrl textarea { width: 100%; background: var(--dark); border: 1px solid var(--border); border-radius: 6px; color: var(--text); font-size: 12px; padding: 8px 10px; font-family: var(--font); transition: all .2s; resize: none; }
.full-ctrl input:focus, .full-ctrl textarea:focus { border-color: var(--p); outline: none; box-shadow: 0 0 0 2px rgba(99,102,241,.2); }

/* RANGE CTRL */
.range-ctrl { display: flex; align-items: center; gap: 8px; flex-shrink: 0; width: 130px; }
.range-ctrl input[type=range] { flex: 1; height: 4px; accent-color: var(--p); cursor: pointer; }
.range-val { font-size: 11px; color: var(--p-l); font-family: monospace; width: 36px; text-align: center; }

/* PALETTE GRID */
.palette-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin-top: 10px; }
.palette-dot { aspect-ratio: 1; border-radius: 8px; cursor: pointer; border: 2px solid transparent; transition: all .2s; position: relative; overflow: hidden; }
.palette-dot:hover { transform: scale(1.08); border-color: white; }
.palette-dot.active { border-color: white; box-shadow: 0 0 0 3px rgba(255,255,255,.25); }

/* PREVIEW AREA */
.preview-area { flex: 1; display: flex; flex-direction: column; overflow: hidden; background: var(--dark); position: relative; }
.preview-toolbar { height: 44px; background: var(--dark2); border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; padding: 0 16px; gap: 12px; flex-shrink: 0; }
.preview-label { font-size: 11px; color: var(--text3); font-weight: 600; }
.live-badge { font-size: 11px; color: var(--green); display: flex; align-items: center; gap: 5px; font-weight: 700; }
.live-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--green); animation: pulse 2s infinite; }

/* PREVIEW FRAME WRAP */
.preview-frame-wrap {
    flex: 1; overflow: hidden; display: flex; align-items: center; justify-content: center; padding: 20px;
    background: repeating-linear-gradient(45deg, rgba(255,255,255,.015) 0px, rgba(255,255,255,.015) 1px, transparent 1px, transparent 20px),
                repeating-linear-gradient(-45deg, rgba(255,255,255,.015) 0px, rgba(255,255,255,.015) 1px, transparent 1px, transparent 20px),
                var(--dark);
    position: relative;
}

/* DEVICE FRAMES */
.device-wrapper { display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; transition: all .35s cubic-bezier(.4,0,.2,1); }

/* DESKTOP: live preview DOM */
.preview-desktop-container {
    background: white; border-radius: 12px; overflow-y: auto; overflow-x: hidden;
    box-shadow: 0 24px 80px rgba(0,0,0,.6), 0 0 0 1px rgba(255,255,255,.06);
    width: 100%; max-width: 1100px; height: 100%;
    transition: all .35s;
}

/* PHONE FRAME: iframe */
.phone-frame {
    display: none;
    width: 375px;
    height: 812px;
    max-height: 100%;
    background: #1a1a2e;
    border-radius: 44px;
    padding: 16px 10px;
    box-shadow: 0 0 0 2px #333, 0 0 0 4px #555, 0 30px 80px rgba(0,0,0,.7);
    position: relative;
    flex-shrink: 0;
}
.phone-frame::before {
    content: '';
    position: absolute;
    top: 18px; left: 50%; transform: translateX(-50%);
    width: 100px; height: 28px;
    background: #1a1a2e;
    border-radius: 0 0 20px 20px;
    z-index: 10;
    box-shadow: inset 0 0 0 2px #333;
}
.phone-frame::after {
    content: '';
    position: absolute;
    top: 24px; left: 50%; transform: translateX(-50%);
    width: 12px; height: 12px;
    background: #222;
    border-radius: 50%;
    z-index: 11;
    box-shadow: 0 0 0 1px #444;
}
.phone-frame iframe {
    width: 100%;
    height: 100%;
    border: none;
    border-radius: 34px;
    overflow: hidden;
}

/* TABLET FRAME */
.tablet-frame {
    display: none;
    width: 768px;
    max-width: 90%;
    height: 90%;
    background: #1a1a2e;
    border-radius: 24px;
    padding: 20px 14px;
    box-shadow: 0 0 0 2px #333, 0 0 0 4px #555, 0 30px 80px rgba(0,0,0,.7);
    flex-shrink: 0;
}
.tablet-frame iframe { width: 100%; height: 100%; border: none; border-radius: 12px; }

/* MODE STATES */
.device-wrapper.mobile .phone-frame { display: block; }
.device-wrapper.mobile .preview-desktop-container { display: none; }
.device-wrapper.tablet .tablet-frame { display: block; }
.device-wrapper.tablet .preview-desktop-container { display: none; }

/* CLICK OVERLAY on preview elements */
[data-editable] { position: relative; cursor: pointer !important; }
[data-editable]:hover::after {
    content: attr(data-label);
    position: absolute; top: 4px; right: 4px; z-index: 999;
    background: var(--p); color: white;
    font-size: 10px; font-weight: 800;
    padding: 3px 8px; border-radius: 4px;
    pointer-events: none; white-space: nowrap;
    font-family: var(--font);
}
[data-editable]:hover { outline: 2px solid var(--p) !important; outline-offset: 2px; }
[data-editable].selected { outline: 2px solid var(--yellow) !important; outline-offset: 2px; }

/* TOAST */
.toast { position: fixed; top: 70px; left: 50%; transform: translateX(-50%) translateY(-20px); background: var(--dark3); border: 1px solid var(--border); color: var(--text); padding: 10px 20px; border-radius: var(--r-sm); font-size: 13px; font-weight: 700; display: flex; align-items: center; gap: 8px; box-shadow: 0 8px 32px rgba(0,0,0,.5); z-index: 9999; opacity: 0; transition: all .3s cubic-bezier(.34,1.56,.64,1); pointer-events: none; }
.toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
.toast.success { border-color: var(--green); color: var(--green); }
.toast.error { border-color: var(--red); color: var(--red); }

/* SECTION INDICATOR TAG */
.section-tag { display: inline-flex; align-items: center; gap: 6px; padding: 5px 10px; background: rgba(99,102,241,.15); border: 1px solid rgba(99,102,241,.3); border-radius: 6px; font-size: 11px; font-weight: 800; color: var(--p-l); margin-bottom: 12px; }

/* BACK BTN */
.back-btn { display: flex; align-items: center; gap: 6px; font-size: 12px; color: var(--text3); cursor: pointer; padding: 6px 0; margin-bottom: 8px; transition: color .2s; border: none; background: none; font-family: var(--font); }
.back-btn:hover { color: var(--text); }
</style>
</head>
<body>

<div class="toast" id="toast"><span>✅</span><span id="toastMsg">تم الحفظ</span></div>

<!-- TOP BAR -->
<div class="topbar">
    <div class="topbar-logo">
        <div class="icon">🎨</div>
        <span>محرر <strong>التصميم المرئي</strong></span>
        <div class="save-dot" id="saveDot"></div>
    </div>

    <div class="preview-modes">
        <button class="preview-mode-btn active" onclick="setMode('desktop',this)">🖥️ سطح المكتب</button>
        <button class="preview-mode-btn" onclick="setMode('tablet',this)">📱 تابلت</button>
        <button class="preview-mode-btn" onclick="setMode('mobile',this)">📱 هاتف</button>
    </div>

    <div class="topbar-actions">
        <a href="index33.php" target="_blank" class="btn btn-preview">🔗 معاينة حقيقية</a>
        <button class="btn btn-reset" onclick="confirmReset()">↺</button>
        <button class="btn btn-save" id="saveBtn" onclick="saveAll()">💾 حفظ الكل</button>
    </div>
</div>

<!-- EDITOR LAYOUT -->
<div class="editor-layout">

    <!-- PANEL -->
    <div class="panel" id="panel">

        <!-- Click Hint -->
        <div class="click-hint">
            <div class="ch-icon">👆</div>
            <p><strong>اضغط على أي عنصر</strong> في المعاينة لتعديل إعداداته مباشرة</p>
        </div>

        <div class="panel-content">

            <!-- DEFAULT: Quick navigation -->
            <div class="edit-panel active" id="panel-default">
                <div class="panel-default">
                    <h3>🎨 اختر عنصراً للتعديل</h3>
                    <p>اضغط على أي عنصر في المعاينة، أو اختر قسماً سريعاً:</p>
                    <div class="quick-sections">
                        <div class="qs-item" onclick="openPanel('colors')"><span class="qi-icon">🎨</span><span class="qi-text">الألوان والقوالب</span></div>
                        <div class="qs-item" onclick="openPanel('header-top')"><span class="qi-icon">📢</span><span class="qi-text">الشريط العلوي</span></div>
                        <div class="qs-item" onclick="openPanel('navbar')"><span class="qi-icon">🗂️</span><span class="qi-text">شريط التنقل</span></div>
                        <div class="qs-item" onclick="openPanel('hero')"><span class="qi-icon">⭐</span><span class="qi-text">البانر الرئيسي (Hero)</span></div>
                        <div class="qs-item" onclick="openPanel('products')"><span class="qi-icon">🛍️</span><span class="qi-text">قسم المنتجات</span></div>
                        <div class="qs-item" onclick="openPanel('order-btn')"><span class="qi-icon">🛒</span><span class="qi-text">زر الطلب</span></div>
                        <div class="qs-item" onclick="openPanel('footer')"><span class="qi-icon">🔽</span><span class="qi-text">الفوتر</span></div>
                    </div>
                </div>
            </div>

            <!-- PANEL: Colors & Palettes -->
            <div class="edit-panel" id="panel-colors">
                <button class="back-btn" onclick="backToDefault()">← رجوع</button>
                <div class="section-tag">🎨 الألوان والقوالب</div>

                <div class="ctrl-group">
                    <div class="ctrl-group-header" onclick="toggleGroup(this)">
                        <span>🎨 قوالب جاهزة</span><span class="caret">▾</span>
                    </div>
                    <div class="ctrl-group-body">
                        <div class="palette-grid">
                            <div class="palette-dot active" title="أزرق" style="background:linear-gradient(135deg,#1E3A8A,#3B82F6)" onclick="applyPalette('blue',this)"></div>
                            <div class="palette-dot" title="أخضر" style="background:linear-gradient(135deg,#047857,#10B981)" onclick="applyPalette('green',this)"></div>
                            <div class="palette-dot" title="بنفسجي" style="background:linear-gradient(135deg,#6D28D9,#8B5CF6)" onclick="applyPalette('purple',this)"></div>
                            <div class="palette-dot" title="أحمر" style="background:linear-gradient(135deg,#B91C1C,#EF4444)" onclick="applyPalette('red',this)"></div>
                            <div class="palette-dot" title="برتقالي" style="background:linear-gradient(135deg,#C2410C,#F97316)" onclick="applyPalette('orange',this)"></div>
                            <div class="palette-dot" title="وردي" style="background:linear-gradient(135deg,#9D174D,#EC4899)" onclick="applyPalette('pink',this)"></div>
                            <div class="palette-dot" title="ذهبي" style="background:linear-gradient(135deg,#92400E,#F59E0B)" onclick="applyPalette('gold',this)"></div>
                            <div class="palette-dot" title="رمادي" style="background:linear-gradient(135deg,#374151,#6B7280)" onclick="applyPalette('gray',this)"></div>
                        </div>
                    </div>
                </div>

                <div class="ctrl-group">
                    <div class="ctrl-group-header" onclick="toggleGroup(this)">
                        <span>🔵 الألوان الرئيسية</span><span class="caret">▾</span>
                    </div>
                    <div class="ctrl-group-body">
                        <?php foreach([
                            ['color_primary','اللون الرئيسي'],
                            ['color_primary_light','فاتح'],
                            ['color_primary_dark','داكن'],
                            ['color_accent','المميز ✨'],
                            ['color_danger','الخصم 🔴'],
                        ] as [$key,$lbl]):
                            $v = svRaw($ds,$key,'#1E40AF');
                            $v = preg_match('/^#[0-9a-fA-F]{6}$/',$v)?$v:'#1E40AF';
                        ?>
                        <div class="ctrl-row">
                            <span class="ctrl-label"><?=$lbl?></span>
                            <div class="color-ctrl">
                                <div class="color-swatch" style="background:<?=htmlspecialchars($v)?>" id="sw_<?=$key?>">
                                    <input type="color" value="<?=htmlspecialchars($v)?>" oninput="onColor('<?=$key?>',this.value)">
                                </div>
                                <input type="text" class="color-hex" id="ch_<?=$key?>" value="<?=htmlspecialchars($v)?>" maxlength="7" oninput="onHex('<?=$key?>',this.value)">
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="ctrl-group">
                    <div class="ctrl-group-header" onclick="toggleGroup(this)">
                        <span>🖼️ الصفحة والخلفية</span><span class="caret">▾</span>
                    </div>
                    <div class="ctrl-group-body">
                        <?php foreach([
                            ['color_bg','خلفية الصفحة'],
                            ['color_surface','البطاقات'],
                            ['color_text','لون النص'],
                        ] as [$key,$lbl]):
                            $v = svRaw($ds,$key,'#F8FAFF');
                            $v = preg_match('/^#[0-9a-fA-F]{6}$/',$v)?$v:'#F8FAFF';
                        ?>
                        <div class="ctrl-row">
                            <span class="ctrl-label"><?=$lbl?></span>
                            <div class="color-ctrl">
                                <div class="color-swatch" style="background:<?=htmlspecialchars($v)?>" id="sw_<?=$key?>">
                                    <input type="color" value="<?=htmlspecialchars($v)?>" oninput="onColor('<?=$key?>',this.value)">
                                </div>
                                <input type="text" class="color-hex" id="ch_<?=$key?>" value="<?=htmlspecialchars($v)?>" maxlength="7" oninput="onHex('<?=$key?>',this.value)">
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="ctrl-group">
                    <div class="ctrl-group-header" onclick="toggleGroup(this)">
                        <span>✏️ الخط والشكل</span><span class="caret">▾</span>
                    </div>
                    <div class="ctrl-group-body">
                        <div class="ctrl-row">
                            <span class="ctrl-label">نوع الخط</span>
                            <div class="text-ctrl">
                                <select onchange="onSetting('font_family',this.value)">
                                    <?php foreach(['Tajawal','Cairo','Almarai','Noto Sans Arabic','Amiri'] as $f): ?>
                                    <option value="<?=$f?>" <?=sv($ds,'font_family','Tajawal')===$f?'selected':''?>><?=$f?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="ctrl-row">
                            <span class="ctrl-label">حجم الخط</span>
                            <div class="range-ctrl">
                                <input type="range" min="12" max="20" step="1" value="<?=(int)sv($ds,'font_size_base','15')?>" oninput="onFontSize(this.value);this.nextElementSibling.textContent=this.value+'px'">
                                <span class="range-val"><?=sv($ds,'font_size_base','15')?>px</span>
                            </div>
                        </div>
                        <div class="ctrl-row">
                            <span class="ctrl-label">زوايا البطاقة</span>
                            <div class="range-ctrl">
                                <input type="range" min="0" max="30" step="2" value="<?=(int)sv($ds,'card_radius','14')?>" oninput="onRadius(this.value);this.nextElementSibling.textContent=this.value+'px'">
                                <span class="range-val"><?=sv($ds,'card_radius','14')?>px</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- PANEL: Header Top -->
            <div class="edit-panel" id="panel-header-top">
                <button class="back-btn" onclick="backToDefault()">← رجوع</button>
                <div class="section-tag">📢 الشريط العلوي</div>
                <div class="ctrl-group">
                    <div class="ctrl-group-header" onclick="toggleGroup(this)">
                        <span>🎨 لون الخلفية</span><span class="caret">▾</span>
                    </div>
                    <div class="ctrl-group-body">
                        <div class="full-ctrl">
                            <label>خلفية الشريط العلوي (CSS)</label>
                            <textarea rows="2" style="font-family:monospace;font-size:11px" oninput="onSetting('header_top_bg',this.value);applyDirect('#prevHeaderTop','background',this.value)"><?=sv($ds,'header_top_bg','linear-gradient(135deg,#1E3A8A,#1E40AF)')?></textarea>
                        </div>
                        <div class="palette-grid" style="grid-template-columns:repeat(3,1fr)">
                            <?php foreach([
                                ['linear-gradient(135deg,#1E3A8A,#1E40AF)','أزرق'],
                                ['linear-gradient(135deg,#047857,#059669)','أخضر'],
                                ['linear-gradient(135deg,#6D28D9,#7C3AED)','بنفسجي'],
                                ['linear-gradient(135deg,#B91C1C,#DC2626)','أحمر'],
                                ['linear-gradient(135deg,#1C1917,#44403C)','داكن'],
                                ['linear-gradient(135deg,#0C4A6E,#0EA5E9)','سماوي'],
                            ] as [$bg,$name]): ?>
                            <div class="palette-dot" title="<?=$name?>" style="background:<?=$bg?>"
                                 onclick="applyHeaderTopBg('<?=addslashes($bg)?>')"></div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- PANEL: Navbar -->
            <div class="edit-panel" id="panel-navbar">
                <button class="back-btn" onclick="backToDefault()">← رجوع</button>
                <div class="section-tag">🗂️ شريط التنقل</div>
                <div class="ctrl-group">
                    <div class="ctrl-group-header" onclick="toggleGroup(this)">
                        <span>🎨 لون الخلفية</span><span class="caret">▾</span>
                    </div>
                    <div class="ctrl-group-body">
                        <?php $v=svRaw($ds,'navbar_bg','#1E40AF'); $v=preg_match('/^#[0-9a-fA-F]{6}$/',$v)?$v:'#1E40AF'; ?>
                        <div class="ctrl-row">
                            <span class="ctrl-label">لون الـNavbar</span>
                            <div class="color-ctrl">
                                <div class="color-swatch" style="background:<?=htmlspecialchars($v)?>" id="sw_navbar_bg">
                                    <input type="color" value="<?=htmlspecialchars($v)?>" oninput="onColor('navbar_bg',this.value);applyDirect('#prevNavbar','background',this.value)">
                                </div>
                                <input type="text" class="color-hex" id="ch_navbar_bg" value="<?=htmlspecialchars($v)?>" maxlength="7" oninput="onHex('navbar_bg',this.value)">
                            </div>
                        </div>
                        <?php $v2=svRaw($ds,'header_bg','#FFFFFF'); $v2=preg_match('/^#[0-9a-fA-F]{6}$/',$v2)?$v2:'#FFFFFF'; ?>
                        <div class="ctrl-row">
                            <span class="ctrl-label">خلفية الهيدر</span>
                            <div class="color-ctrl">
                                <div class="color-swatch" style="background:<?=htmlspecialchars($v2)?>" id="sw_header_bg">
                                    <input type="color" value="<?=htmlspecialchars($v2)?>" oninput="onColor('header_bg',this.value);applyDirect('#prevHeaderMain','background',this.value)">
                                </div>
                                <input type="text" class="color-hex" id="ch_header_bg" value="<?=htmlspecialchars($v2)?>" maxlength="7" oninput="onHex('header_bg',this.value)">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- PANEL: Hero -->
            <div class="edit-panel" id="panel-hero">
                <button class="back-btn" onclick="backToDefault()">← رجوع</button>
                <div class="section-tag">⭐ البانر الرئيسي</div>

                <div class="ctrl-group">
                    <div class="ctrl-group-header" onclick="toggleGroup(this)">
                        <span>📝 النصوص</span><span class="caret">▾</span>
                    </div>
                    <div class="ctrl-group-body">
                        <div class="full-ctrl">
                            <label>الشارة الصغيرة</label>
                            <input type="text" value="<?=sv($ds,'hero_badge_text','متجرك المفضل')?>" oninput="onHero('badge',this.value)">
                        </div>
                        <div class="full-ctrl">
                            <label>العنوان الرئيسي</label>
                            <textarea rows="3" oninput="onHero('title',this.value)"><?=htmlspecialchars(svRaw($ds,'hero_title','اكتشف أفضل المنتجات'))?></textarea>
                        </div>
                        <div class="full-ctrl">
                            <label>النص الوصفي</label>
                            <textarea rows="2" oninput="onHero('subtitle',this.value)"><?=htmlspecialchars(sv($ds,'hero_subtitle','تسوّق بثقة وراحة'))?></textarea>
                        </div>
                        <div class="full-ctrl">
                            <label>زر رئيسي</label>
                            <input type="text" value="<?=sv($ds,'hero_btn_primary_text','تسوّق الآن')?>" oninput="onHero('btn1',this.value)">
                        </div>
                        <div class="full-ctrl">
                            <label>زر ثانوي</label>
                            <input type="text" value="<?=sv($ds,'hero_btn_sec_text','تتبع طلبك')?>" oninput="onHero('btn2',this.value)">
                        </div>
                        <div class="full-ctrl">
                            <label>Emoji الأيقونة</label>
                            <input type="text" value="<?=sv($ds,'hero_emoji','🛒')?>" oninput="onHero('emoji',this.value)">
                        </div>
                    </div>
                </div>

                <div class="ctrl-group">
                    <div class="ctrl-group-header" onclick="toggleGroup(this)">
                        <span>🎨 خلفية البانر</span><span class="caret">▾</span>
                    </div>
                    <div class="ctrl-group-body">
                        <div class="palette-grid" style="grid-template-columns:repeat(3,1fr); margin-bottom:10px">
                            <?php foreach([
                                ['linear-gradient(135deg,#1E3A8A,#1E40AF,#1D4ED8)','أزرق'],
                                ['linear-gradient(135deg,#064E3B,#059669,#34D399)','أخضر'],
                                ['linear-gradient(135deg,#4C1D95,#7C3AED,#A78BFA)','بنفسجي'],
                                ['linear-gradient(135deg,#7F1D1D,#DC2626,#FCA5A5)','أحمر'],
                                ['linear-gradient(135deg,#1C1917,#44403C,#78716C)','داكن'],
                                ['linear-gradient(135deg,#0C4A6E,#0EA5E9,#7DD3FC)','سماوي'],
                            ] as [$bg,$name]): ?>
                            <div class="palette-dot" title="<?=$name?>" style="background:<?=$bg?>"
                                 onclick="onHeroBg('<?=addslashes($bg)?>')"></div>
                            <?php endforeach; ?>
                        </div>
                        <div class="full-ctrl">
                            <label>خلفية مخصصة (CSS)</label>
                            <textarea rows="2" id="hero_bg_input" style="font-family:monospace;font-size:11px"
                                      oninput="onHeroBg(this.value)"><?=htmlspecialchars(sv($ds,'hero_bg',''))?></textarea>
                        </div>
                    </div>
                </div>
            </div>

            <!-- PANEL: Products -->
            <div class="edit-panel" id="panel-products">
                <button class="back-btn" onclick="backToDefault()">← رجوع</button>
                <div class="section-tag">🛍️ قسم المنتجات</div>
                <div class="ctrl-group">
                    <div class="ctrl-group-header" onclick="toggleGroup(this)">
                        <span>🎨 الألوان</span><span class="caret">▾</span>
                    </div>
                    <div class="ctrl-group-body">
                        <?php $bgv=svRaw($ds,'color_bg','#F8FAFF'); $bgv=preg_match('/^#[0-9a-fA-F]{6}$/',$bgv)?$bgv:'#F8FAFF'; ?>
                        <div class="ctrl-row">
                            <span class="ctrl-label">خلفية القسم</span>
                            <div class="color-ctrl">
                                <div class="color-swatch" style="background:<?=htmlspecialchars($bgv)?>" id="sw_color_bg">
                                    <input type="color" value="<?=htmlspecialchars($bgv)?>" oninput="onColor('color_bg',this.value);applyDirect('#prevProducts','background',this.value)">
                                </div>
                                <input type="text" class="color-hex" id="ch_color_bg" value="<?=htmlspecialchars($bgv)?>" maxlength="7" oninput="onHex('color_bg',this.value)">
                            </div>
                        </div>
                        <?php $pv=svRaw($ds,'color_primary','#1E40AF'); $pv=preg_match('/^#[0-9a-fA-F]{6}$/',$pv)?$pv:'#1E40AF'; ?>
                        <div class="ctrl-row">
                            <span class="ctrl-label">لون السعر والعنوان</span>
                            <div class="color-ctrl">
                                <div class="color-swatch" style="background:<?=htmlspecialchars($pv)?>" id="sw_color_primary_p">
                                    <input type="color" value="<?=htmlspecialchars($pv)?>" oninput="onColor('color_primary',this.value)">
                                </div>
                                <input type="text" class="color-hex" id="ch_color_primary_p" value="<?=htmlspecialchars($pv)?>" maxlength="7" oninput="onHex('color_primary',this.value)">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="ctrl-group">
                    <div class="ctrl-group-header" onclick="toggleGroup(this)">
                        <span>📐 شكل البطاقة</span><span class="caret">▾</span>
                    </div>
                    <div class="ctrl-group-body">
                        <div class="ctrl-row">
                            <span class="ctrl-label">زوايا البطاقة</span>
                            <div class="range-ctrl">
                                <input type="range" min="0" max="30" step="2" value="<?=(int)sv($ds,'card_radius','14')?>"
                                       oninput="onRadius(this.value);this.nextElementSibling.textContent=this.value+'px'">
                                <span class="range-val"><?=sv($ds,'card_radius','14')?>px</span>
                            </div>
                        </div>
                        <div class="ctrl-row">
                            <span class="ctrl-label">ارتفاع الصورة</span>
                            <div class="range-ctrl">
                                <input type="range" min="120" max="320" step="10" value="<?=(int)sv($ds,'card_img_height','210')?>"
                                       oninput="onCardImgH(this.value);this.nextElementSibling.textContent=this.value+'px'">
                                <span class="range-val"><?=sv($ds,'card_img_height','210')?>px</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- PANEL: Order Button -->
            <div class="edit-panel" id="panel-order-btn">
                <button class="back-btn" onclick="backToDefault()">← رجوع</button>
                <div class="section-tag">🛒 زر الطلب</div>
                <?php $ob=$btn['order_btn']??[]; ?>
                <div class="ctrl-group">
                    <div class="ctrl-group-header" onclick="toggleGroup(this)">
                        <span>🎨 الألوان</span><span class="caret">▾</span>
                    </div>
                    <div class="ctrl-group-body">
                        <?php foreach([
                            ['bg','background_color','خلفية الزر'],
                            ['color','text_color','لون النص'],
                            ['hover_bg','hover_background','Hover'],
                        ] as [$fk,$dbk,$lbl]):
                            $v=htmlspecialchars($ob[$dbk]??'#1E40AF');
                            $v=preg_match('/^#[0-9a-fA-F]{6}$/',$v)?$v:'#1E40AF';
                        ?>
                        <div class="ctrl-row">
                            <span class="ctrl-label"><?=$lbl?></span>
                            <div class="color-ctrl">
                                <div class="color-swatch" style="background:<?=$v?>" id="sw_ob_<?=$fk?>">
                                    <input type="color" value="<?=$v?>" oninput="onBtnColor('order_btn','<?=$fk?>',this.value)">
                                </div>
                                <input type="text" class="color-hex" id="ch_ob_<?=$fk?>" value="<?=$v?>" maxlength="7" oninput="onBtnHex('order_btn','<?=$fk?>',this.value)">
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="ctrl-group">
                    <div class="ctrl-group-header" onclick="toggleGroup(this)">
                        <span>📐 الشكل</span><span class="caret">▾</span>
                    </div>
                    <div class="ctrl-group-body">
                        <div class="ctrl-row">
                            <span class="ctrl-label">زوايا مستديرة</span>
                            <div class="range-ctrl">
                                <input type="range" min="0" max="50" step="2" value="<?=(int)($ob['border_radius']??8)?>"
                                       oninput="onBtnProp('order_btn','radius',this.value+'px');this.nextElementSibling.textContent=this.value+'px'">
                                <span class="range-val"><?=$ob['border_radius']??'8'?>px</span>
                            </div>
                        </div>
                        <div class="ctrl-row">
                            <span class="ctrl-label">حجم الخط</span>
                            <div class="range-ctrl">
                                <input type="range" min="10" max="22" step="1" value="<?=(int)($ob['font_size']??14)?>"
                                       oninput="onBtnProp('order_btn','font_size',this.value+'px');this.nextElementSibling.textContent=this.value+'px'">
                                <span class="range-val"><?=$ob['font_size']??'14'?>px</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="ctrl-group">
                    <div class="ctrl-group-header" onclick="toggleGroup(this)">
                        <span>💬 النص والأيقونة</span><span class="caret">▾</span>
                    </div>
                    <div class="ctrl-group-body">
                        <div class="full-ctrl">
                            <label>نص الزر</label>
                            <input type="text" value="<?=htmlspecialchars($ob['button_text']??'اطلب الآن')?>"
                                   oninput="onBtnProp('order_btn','btn_text',this.value)">
                        </div>
                        <div class="full-ctrl">
                            <label>أيقونة (Font Awesome class)</label>
                            <input type="text" value="<?=htmlspecialchars($ob['icon_class']??'fas fa-shopping-cart')?>"
                                   placeholder="fas fa-shopping-cart"
                                   oninput="onBtnProp('order_btn','icon',this.value)">
                        </div>
                    </div>
                </div>
            </div>

            <!-- PANEL: Footer -->
            <div class="edit-panel" id="panel-footer">
                <button class="back-btn" onclick="backToDefault()">← رجوع</button>
                <div class="section-tag">🔽 الفوتر</div>
                <div class="ctrl-group">
                    <div class="ctrl-group-header" onclick="toggleGroup(this)">
                        <span>🎨 خلفية الفوتر</span><span class="caret">▾</span>
                    </div>
                    <div class="ctrl-group-body">
                        <div class="full-ctrl">
                            <label>خلفية الفوتر (CSS)</label>
                            <textarea rows="2" style="font-family:monospace;font-size:11px"
                                      oninput="onSetting('footer_bg',this.value);applyDirect('#prevFooter','background',this.value)"><?=sv($ds,'footer_bg','linear-gradient(135deg,#0F172A,#1E293B)')?></textarea>
                        </div>
                        <div class="palette-grid" style="grid-template-columns:repeat(3,1fr)">
                            <?php foreach([
                                ['linear-gradient(135deg,#0F172A,#1E293B)','داكن'],
                                ['linear-gradient(135deg,#1E3A8A,#1E40AF)','أزرق'],
                                ['linear-gradient(135deg,#064E3B,#065F46)','أخضر'],
                                ['linear-gradient(135deg,#4C1D95,#5B21B6)','بنفسجي'],
                                ['linear-gradient(135deg,#1C1917,#292524)','فحمي'],
                                ['linear-gradient(135deg,#7F1D1D,#991B1B)','أحمر داكن'],
                            ] as [$bg,$name]): ?>
                            <div class="palette-dot" title="<?=$name?>" style="background:<?=$bg?>"
                                 onclick="onSetting('footer_bg','<?=addslashes($bg)?>');applyDirect('#prevFooter','background','<?=addslashes($bg)?>')"></div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>

        </div><!-- .panel-content -->
    </div><!-- .panel -->

    <!-- PREVIEW AREA -->
    <div class="preview-area">
        <div class="preview-toolbar">
            <span class="preview-label">👆 اضغط على أي عنصر للتعديل</span>
            <span class="preview-label" id="selectedLabel" style="color:var(--yellow)"></span>
            <div class="live-badge"><div class="live-dot"></div>Live</div>
        </div>

        <div class="preview-frame-wrap">
            <div class="device-wrapper" id="deviceWrapper">

                <!-- DESKTOP: Live DOM Preview -->
                <div class="preview-desktop-container" id="previewDesktop">
                    <div id="prevRoot" style="font-family:'Tajawal',sans-serif;direction:rtl;color:#0F172A;">

                        <!-- Header Top -->
                        <div id="prevHeaderTop" data-editable data-panel="header-top" data-label="الشريط العلوي"
                             style="background:<?=sv($ds,'header_top_bg','linear-gradient(135deg,#1E3A8A,#1E40AF)')?>;padding:9px 20px;display:flex;justify-content:flex-end;gap:20px;font-size:12px;color:rgba(255,255,255,.88);">
                            <span>📞 <?=htmlspecialchars($store['phone']??'0555000000')?></span>
                            <span>✉️ <?=htmlspecialchars($store['emailp']??'info@store.dz')?></span>
                        </div>

                        <!-- Header Main -->
                        <div id="prevHeaderMain" data-editable data-panel="navbar" data-label="الهيدر"
                             style="background:<?=sv($ds,'header_bg','#FFFFFF')?>;padding:12px 20px;display:flex;align-items:center;justify-content:space-between;gap:16px;border-bottom:1px solid #E2E8F0;">
                            <?php if(!empty($store['logo'])): ?>
                            <img src="<?=BASE_URL.'admin/'.htmlspecialchars($store['logo'])?>" style="height:40px;width:auto;object-fit:contain">
                            <?php else: ?>
                            <div style="font-size:18px;font-weight:900;color:<?=sv($ds,'color_primary','#1E40AF')?>"><?=htmlspecialchars($store['name']??'المتجر')?></div>
                            <?php endif; ?>
                            <div style="flex:1;max-width:400px;display:flex;border-radius:8px;border:2px solid #E2E8F0;overflow:hidden;">
                                <span style="flex:1;padding:8px 12px;font-size:12px;color:#94A3B8;background:white;">ابحث عن منتج...</span>
                                <div id="prevSearchBtn" style="padding:0 14px;display:flex;align-items:center;color:white;font-size:12px;background:<?=sv($ds,'color_primary','#1E40AF')?>">🔍</div>
                            </div>
                        </div>

                        <!-- Navbar -->
                        <div id="prevNavbar" data-editable data-panel="navbar" data-label="شريط التنقل"
                             style="background:<?=sv($ds,'navbar_bg','#1E40AF')?>;display:flex;justify-content:center;gap:0;">
                            <?php foreach(['🏠 الرئيسية','🛍️ طلباتي','📂 الأقسام'] as $ni): ?>
                            <div style="padding:10px 18px;font-size:13px;font-weight:600;color:rgba(255,255,255,.9);"><?=$ni?></div>
                            <?php endforeach; ?>
                        </div>

                        <!-- Hero -->
                        <div id="prevHero" data-editable data-panel="hero" data-label="البانر الرئيسي"
                             style="background:<?=sv($ds,'hero_bg','linear-gradient(135deg,#1E3A8A,#1E40AF,#1D4ED8)')?>;padding:40px 24px;display:flex;align-items:center;justify-content:space-between;gap:24px;overflow:hidden;">
                            <div style="color:white;max-width:480px;">
                                <div id="prevBadge" style="display:inline-flex;align-items:center;gap:6px;background:rgba(255,255,255,.15);color:white;padding:5px 12px;border-radius:20px;font-size:11px;font-weight:700;margin-bottom:14px;border:1px solid rgba(255,255,255,.25);">
                                    ⚡ <span id="prevBadgeText"><?=sv($ds,'hero_badge_text','متجرك المفضل دائماً')?></span>
                                </div>
                                <div id="prevTitle" style="font-size:clamp(18px,3vw,32px);font-weight:900;line-height:1.3;margin-bottom:10px;">
                                    <?=svRaw($ds,'hero_title','اكتشف أفضل المنتجات<br>بأسعار <span style="color:#F59E0B">لا تُقاوَم</span>')?>
                                </div>
                                <div id="prevSubtitle" style="font-size:13px;color:rgba(255,255,255,.82);margin-bottom:18px;line-height:1.7;">
                                    <?=sv($ds,'hero_subtitle','تسوّق بثقة وراحة، توصيل سريع')?>
                                </div>
                                <div style="display:flex;gap:10px;flex-wrap:wrap;">
                                    <button id="prevHeroBtn1" style="background:white;color:<?=sv($ds,'color_primary','#1E40AF')?>;padding:9px 18px;border:none;border-radius:8px;font-size:12px;font-weight:800;cursor:pointer;font-family:'Tajawal',sans-serif;">
                                        🛍️ <span id="prevHeroBtn1Txt"><?=sv($ds,'hero_btn_primary_text','تسوّق الآن')?></span>
                                    </button>
                                    <button id="prevHeroBtn2" style="background:rgba(255,255,255,.15);color:white;padding:9px 18px;border:1.5px solid rgba(255,255,255,.35);border-radius:8px;font-size:12px;font-weight:700;cursor:pointer;font-family:'Tajawal',sans-serif;">
                                        <span id="prevHeroBtn2Txt"><?=sv($ds,'hero_btn_sec_text','تتبع طلبك')?></span>
                                    </button>
                                </div>
                            </div>
                            <div id="prevEmoji" style="font-size:72px;width:140px;height:140px;background:rgba(255,255,255,.1);border-radius:50%;display:flex;align-items:center;justify-content:center;border:2px solid rgba(255,255,255,.2);flex-shrink:0;animation:float 3s ease-in-out infinite;">
                                <?=sv($ds,'hero_emoji','🛒')?>
                            </div>
                        </div>

                        <!-- Products -->
                        <div id="prevProducts" data-editable data-panel="products" data-label="قسم المنتجات"
                             style="padding:20px 20px 28px;background:<?=sv($ds,'color_bg','#F8FAFF')?>;">
                            <div style="font-size:16px;font-weight:900;margin-bottom:6px;">
                                جميع <span id="prevAccent" style="color:<?=sv($ds,'color_primary','#1E40AF')?>">المنتجات</span>
                            </div>
                            <div id="prevDivider" style="width:36px;height:3px;border-radius:3px;margin-bottom:16px;background:linear-gradient(90deg,<?=sv($ds,'color_primary','#1E40AF')?>,<?=sv($ds,'color_primary_light','#3B82F6')?>)"></div>

                            <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:14px;">
                                <?php
                                $ob = $btn['order_btn']??[];
                                for($ci=0;$ci<3;$ci++):
                                    $sp=$sample_products[$ci]??null;
                                    $img=(!empty($sp['image']))?BASE_URL.'admin/'.htmlspecialchars($sp['image']):'';
                                    $price=$sp?(($sp['discounted_price']?:$sp['price'])):(1200+$ci*300);
                                    $oldPrice=$sp?($sp['discounted_price']?$sp['price']:null):($price*1.25);
                                    $title=$sp?$sp['name']:'منتج رائع للعرض '.($ci+1);
                                    $cardRadius=sv($ds,'card_radius','14');
                                    $imgH=sv($ds,'card_img_height','210');
                                    $btnBg=htmlspecialchars($ob['background_color']??'#1E40AF');
                                    $btnColor=htmlspecialchars($ob['text_color']??'#fff');
                                    $btnRadius=htmlspecialchars($ob['border_radius']??'8px');
                                    $btnFs=htmlspecialchars($ob['font_size']??'14px');
                                    $btnFw=htmlspecialchars($ob['font_weight']??'700');
                                    $btnTxt=htmlspecialchars($ob['button_text']??'اطلب الآن');
                                    $btnIcon=htmlspecialchars($ob['icon_class']??'');
                                ?>
                                <div class="prev-card" data-editable data-panel="products" data-label="بطاقة منتج"
                                     style="background:white;border-radius:<?=$cardRadius?>px;border:1.5px solid #E2E8F0;overflow:hidden;box-shadow:0 1px 4px rgba(0,0,0,.06);transition:all .2s;"
                                     onmouseenter="this.style.transform='translateY(-4px)';this.style.boxShadow='0 8px 24px rgba(0,0,0,.12)'"
                                     onmouseleave="this.style.transform='';this.style.boxShadow='0 1px 4px rgba(0,0,0,.06)'">
                                    <div class="prev-card-img-<?=$ci?>" style="height:<?=$imgH?>px;background:#F1F5F9;overflow:hidden;position:relative;display:flex;align-items:center;justify-content:center;">
                                        <?php if($img): ?>
                                        <img src="<?=$img?>" style="width:100%;height:100%;object-fit:cover;" onerror="this.parentElement.innerHTML='<div style=\'font-size:40px;color:#CBD5E0\'>📦</div>'">
                                        <?php else: ?>
                                        <div style="font-size:40px;color:#CBD5E0">📦</div>
                                        <?php endif; ?>
                                        <div style="position:absolute;top:8px;right:8px;background:#EF4444;color:white;padding:2px 7px;border-radius:12px;font-size:9px;font-weight:800;">خصم 20%</div>
                                    </div>
                                    <div style="padding:12px;">
                                        <div style="display:inline-block;background:#F1F5F9;color:#94A3B8;padding:2px 7px;border-radius:10px;font-size:9px;font-weight:700;border:1px solid #E2E8F0;margin-bottom:6px;">إلكترونيات</div>
                                        <div style="font-size:12px;font-weight:800;margin-bottom:8px;line-height:1.4;color:#0F172A;"><?=htmlspecialchars(mb_substr($title,0,40))?></div>
                                        <div style="display:flex;align-items:center;gap:7px;margin-bottom:10px;">
                                            <span class="prev-price-now" style="font-size:16px;font-weight:900;color:<?=sv($ds,'color_primary','#1E40AF')?>"><?=number_format($price,2)?> دج</span>
                                            <?php if($oldPrice): ?>
                                            <span style="font-size:11px;color:#94A3B8;text-decoration:line-through;"><?=number_format($oldPrice,2)?> دج</span>
                                            <?php endif; ?>
                                        </div>
                                        <button class="prev-order-btn" data-editable data-panel="order-btn" data-label="زر الطلب"
                                                style="width:100%;padding:8px;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:6px;font-size:<?=$btnFs?>;font-weight:<?=$btnFw?>;font-family:'Tajawal',sans-serif;border-radius:<?=$btnRadius?>;background:<?=$btnBg?>;color:<?=$btnColor?>;transition:all .2s;"
                                                onmouseenter="this.style.filter='brightness(1.1)';this.style.transform='translateY(-1px)'"
                                                onmouseleave="this.style.filter='';this.style.transform=''">
                                            <?php if($btnIcon): ?><i class="<?=$btnIcon?>"></i><?php endif; ?>
                                            <?=$btnTxt?>
                                        </button>
                                    </div>
                                </div>
                                <?php endfor; ?>
                            </div>
                        </div>

                        <!-- Footer -->
                        <div id="prevFooter" data-editable data-panel="footer" data-label="الفوتر"
                             style="padding:24px 24px 16px;color:white;background:<?=sv($ds,'footer_bg','linear-gradient(135deg,#0F172A,#1E293B)')?>;">
                            <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:16px;">
                                <div>
                                    <div style="font-size:13px;font-weight:800;margin-bottom:8px;">🏪 <?=htmlspecialchars($store['name']??'المتجر')?></div>
                                    <div style="font-size:11px;color:rgba(255,255,255,.6);line-height:1.7;"><?=htmlspecialchars(mb_substr($store['description']??'متجرنا الإلكتروني',0,80))?></div>
                                </div>
                                <div>
                                    <div style="font-size:13px;font-weight:800;margin-bottom:8px;">📞 تواصل معنا</div>
                                    <div style="font-size:11px;color:rgba(255,255,255,.6);"><?=htmlspecialchars($store['phone']??'0555000000')?></div>
                                </div>
                            </div>
                            <div style="border-top:1px solid rgba(255,255,255,.1);padding-top:12px;text-align:center;font-size:11px;color:rgba(255,255,255,.4);">
                                © جميع الحقوق محفوظة <?=date('Y')?>
                            </div>
                        </div>

                    </div><!-- #prevRoot -->
                </div><!-- .preview-desktop-container -->

                <!-- PHONE FRAME: Real iframe -->
                <div class="phone-frame" id="phoneFrame">
                    <iframe id="phoneIframe" src="index33.php" title="معاينة الهاتف"></iframe>
                </div>

                <!-- TABLET FRAME: Real iframe -->
                <div class="tablet-frame" id="tabletFrame">
                    <iframe id="tabletIframe" src="index33.php" title="معاينة التابلت"></iframe>
                </div>

            </div><!-- .device-wrapper -->
        </div><!-- .preview-frame-wrap -->
    </div><!-- .preview-area -->
</div><!-- .editor-layout -->

<style>
@keyframes float { 0%,100%{transform:translateY(0)} 50%{transform:translateY(-10px)} }
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">

<script>
// ============================================================
//  STATE
// ============================================================
const state = {
    settings: {},
    buttons: {}
};

<?php foreach($ds as $key=>$row): ?>
state.settings[<?=json_encode($key)?>] = <?=json_encode($row['setting_value']??'')?>;
<?php endforeach; ?>

<?php foreach($btn as $btype=>$bdata): ?>
state.buttons[<?=json_encode($btype)?>] = {
    bg:          <?=json_encode($bdata['background_color']??'#1E40AF')?>,
    color:       <?=json_encode($bdata['text_color']??'#fff')?>,
    hover_bg:    <?=json_encode($bdata['hover_background']??'#1E3A8A')?>,
    radius:      <?=json_encode($bdata['border_radius']??'8px')?>,
    font_size:   <?=json_encode($bdata['font_size']??'14px')?>,
    font_weight: <?=json_encode($bdata['font_weight']??'700')?>,
    btn_text:    <?=json_encode($bdata['button_text']??'')?>,
    icon:        <?=json_encode($bdata['icon_class']??'')?>,
    shadow:      <?=json_encode($bdata['box_shadow']??'')?>,
    anim:        <?=json_encode($bdata['animation_type']??'none')?>
};
<?php endforeach; ?>

let hasUnsavedChanges = false;

// ============================================================
//  PANEL NAVIGATION
// ============================================================
function openPanel(name) {
    document.querySelectorAll('.edit-panel').forEach(p => p.classList.remove('active'));
    const panel = document.getElementById('panel-' + name);
    if (panel) {
        panel.classList.add('active');
        document.getElementById('selectedLabel').textContent = '→ ' + getPanelLabel(name);
    }
    // Highlight corresponding preview element
    clearHighlights();
    const target = document.querySelector(`[data-panel="${name}"]`);
    if (target) target.classList.add('selected');
}

function getPanelLabel(name) {
    const labels = {
        'colors':'الألوان','header-top':'الشريط العلوي','navbar':'التنقل',
        'hero':'البانر','products':'المنتجات','order-btn':'زر الطلب','footer':'الفوتر'
    };
    return labels[name] || name;
}

function backToDefault() {
    document.querySelectorAll('.edit-panel').forEach(p => p.classList.remove('active'));
    document.getElementById('panel-default').classList.add('active');
    document.getElementById('selectedLabel').textContent = '';
    clearHighlights();
}

function clearHighlights() {
    document.querySelectorAll('[data-editable].selected').forEach(el => el.classList.remove('selected'));
}

// ============================================================
//  CLICK TO EDIT — Attach click handlers on editable elements
// ============================================================
document.querySelectorAll('[data-editable]').forEach(el => {
    el.addEventListener('click', function(e) {
        e.stopPropagation();
        const panelName = this.getAttribute('data-panel');
        if (panelName) openPanel(panelName);
    });
});

// ============================================================
//  TOGGLE GROUP
// ============================================================
function toggleGroup(header) {
    header.classList.toggle('collapsed');
    header.nextElementSibling.classList.toggle('collapsed');
}

// ============================================================
//  DEVICE MODE
// ============================================================
let currentMode = 'desktop';
function setMode(mode, btn) {
    currentMode = mode;
    const wrapper = document.getElementById('deviceWrapper');
    wrapper.className = 'device-wrapper ' + (mode !== 'desktop' ? mode : '');

    document.querySelectorAll('.preview-mode-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');

    // Load iframe on first switch
    if (mode === 'mobile') {
        const iframe = document.getElementById('phoneIframe');
        if (!iframe.src || iframe.src === 'about:blank') iframe.src = 'index33.php';
    }
    if (mode === 'tablet') {
        const iframe = document.getElementById('tabletIframe');
        if (!iframe.src || iframe.src === 'about:blank') iframe.src = 'index33.php';
    }
}

// ============================================================
//  COLOR HELPERS
// ============================================================
function onColor(key, val) {
    const ch = document.getElementById('ch_' + key);
    const sw = document.getElementById('sw_' + key);
    if (ch) ch.value = val;
    if (sw) sw.style.background = val;
    state.settings[key] = val;
    markChanged();
    applyToPreview(key, val);
}

function onHex(key, val) {
    if (/^#[0-9a-fA-F]{6}$/.test(val)) {
        const sw = document.getElementById('sw_' + key);
        if (sw) sw.style.background = val;
        const cp = sw?.querySelector('input[type=color]');
        if (cp) cp.value = val;
        state.settings[key] = val;
        markChanged();
        applyToPreview(key, val);
    }
}

function onSetting(key, val) {
    state.settings[key] = val;
    markChanged();
    applyToPreview(key, val);
}

function applyDirect(selector, prop, val) {
    const el = document.querySelector(selector);
    if (el) el.style[prop] = val;
}

// ============================================================
//  APPLY COLOR TO PREVIEW — THE FIXED VERSION
// ============================================================
function applyToPreview(key, val) {
    const $ = id => document.getElementById(id);

    switch(key) {
        case 'color_primary':
            // Search button
            if ($('prevSearchBtn')) $('prevSearchBtn').style.background = val;
            // Accent text
            if ($('prevAccent')) $('prevAccent').style.color = val;
            // Divider
            updateDivider();
            // ALL price labels
            document.querySelectorAll('.prev-price-now').forEach(e => e.style.color = val);
            // Hero button 1 text color
            if ($('prevHeroBtn1')) $('prevHeroBtn1').style.color = val;
            break;

        case 'color_primary_light':
            updateDivider();
            break;

        case 'color_bg':
            if ($('prevProducts')) $('prevProducts').style.background = val;
            break;

        case 'color_surface':
            document.querySelectorAll('.prev-card').forEach(c => c.style.background = val);
            break;

        case 'navbar_bg':
            if ($('prevNavbar')) $('prevNavbar').style.background = val;
            // Also sync hex input in navbar panel
            const chNav = document.getElementById('ch_navbar_bg');
            const swNav = document.getElementById('sw_navbar_bg');
            if (chNav) chNav.value = val;
            if (swNav) swNav.style.background = val;
            break;

        case 'header_bg':
            if ($('prevHeaderMain')) $('prevHeaderMain').style.background = val;
            break;

        case 'header_top_bg':
            if ($('prevHeaderTop')) $('prevHeaderTop').style.background = val;
            break;

        case 'hero_bg':
            if ($('prevHero')) $('prevHero').style.background = val;
            break;

        case 'footer_bg':
            if ($('prevFooter')) $('prevFooter').style.background = val;
            break;
    }
}

function updateDivider() {
    const d = document.getElementById('prevDivider');
    if (d) {
        const p = state.settings['color_primary'] || '#1E40AF';
        const pl = state.settings['color_primary_light'] || '#3B82F6';
        d.style.background = `linear-gradient(90deg,${p},${pl})`;
    }
}

// ============================================================
//  TYPOGRAPHY & SHAPE
// ============================================================
function onFontSize(val) {
    document.getElementById('prevRoot').style.fontSize = val + 'px';
    state.settings['font_size_base'] = val + 'px';
    markChanged();
}

function onRadius(val) {
    document.querySelectorAll('.prev-card,[class^="prev-card"]').forEach(c => {
        c.style.borderRadius = val + 'px';
    });
    state.settings['card_radius'] = val + 'px';
    markChanged();
}

function onCardImgH(val) {
    document.querySelectorAll('[class*="prev-card-img"]').forEach(c => c.style.height = val + 'px');
    state.settings['card_img_height'] = val + 'px';
    markChanged();
}

// ============================================================
//  HERO
// ============================================================
function onHero(field, val) {
    const $ = id => document.getElementById(id);
    if (field === 'badge')    { if ($('prevBadgeText'))  $('prevBadgeText').textContent = val; state.settings['hero_badge_text'] = val; }
    if (field === 'title')    { if ($('prevTitle'))      $('prevTitle').innerHTML = val; state.settings['hero_title'] = val; }
    if (field === 'subtitle') { if ($('prevSubtitle'))   $('prevSubtitle').textContent = val; state.settings['hero_subtitle'] = val; }
    if (field === 'btn1')     { if ($('prevHeroBtn1Txt')) $('prevHeroBtn1Txt').textContent = val; state.settings['hero_btn_primary_text'] = val; }
    if (field === 'btn2')     { if ($('prevHeroBtn2Txt')) $('prevHeroBtn2Txt').textContent = val; state.settings['hero_btn_sec_text'] = val; }
    if (field === 'emoji')    { if ($('prevEmoji'))       $('prevEmoji').textContent = val; state.settings['hero_emoji'] = val; }
    markChanged();
}

function onHeroBg(val) {
    document.getElementById('prevHero').style.background = val;
    const inp = document.getElementById('hero_bg_input');
    if (inp) inp.value = val;
    state.settings['hero_bg'] = val;
    markChanged();
}

// ============================================================
//  HEADER TOP
// ============================================================
function applyHeaderTopBg(bg) {
    document.getElementById('prevHeaderTop').style.background = bg;
    state.settings['header_top_bg'] = bg;
    markChanged();
}

// ============================================================
//  BUTTONS
// ============================================================
function onBtnColor(type, field, val) {
    const ch = document.getElementById('ch_ob_' + field);
    const sw = document.getElementById('sw_ob_' + field);
    if (ch) ch.value = val;
    if (sw) sw.style.background = val;
    state.buttons[type][field] = val;
    markChanged();
    refreshOrderBtns();
}

function onBtnHex(type, field, val) {
    if (/^#[0-9a-fA-F]{6}$/.test(val)) {
        const sw = document.getElementById('sw_ob_' + field);
        if (sw) { sw.style.background = val; const cp = sw.querySelector('input[type=color]'); if(cp) cp.value=val; }
        state.buttons[type][field] = val;
        markChanged();
        refreshOrderBtns();
    }
}

function onBtnProp(type, prop, val) {
    state.buttons[type][prop] = val;
    markChanged();
    if (type === 'order_btn') refreshOrderBtns();
}

function refreshOrderBtns() {
    const b = state.buttons['order_btn'];
    if (!b) return;
    document.querySelectorAll('.prev-order-btn').forEach(btn => {
        btn.style.background    = b.bg;
        btn.style.color         = b.color;
        btn.style.borderRadius  = b.radius;
        btn.style.fontSize      = b.font_size;
        btn.style.fontWeight    = b.font_weight;
        // Rebuild inner HTML
        btn.innerHTML = (b.icon ? `<i class="${b.icon}" style="margin-left:4px"></i>` : '') + (b.btn_text || 'اطلب الآن');
    });
}

// ============================================================
//  PALETTES
// ============================================================
const palettes = {
    blue:   { color_primary:'#1E40AF', color_primary_light:'#3B82F6', color_primary_dark:'#1E3A8A', color_bg:'#F8FAFF', navbar_bg:'#1E40AF', header_top_bg:'linear-gradient(135deg,#1E3A8A,#1E40AF)' },
    green:  { color_primary:'#059669', color_primary_light:'#10B981', color_primary_dark:'#047857', color_bg:'#F0FDF9', navbar_bg:'#059669', header_top_bg:'linear-gradient(135deg,#047857,#059669)' },
    purple: { color_primary:'#7C3AED', color_primary_light:'#8B5CF6', color_primary_dark:'#6D28D9', color_bg:'#FAF5FF', navbar_bg:'#7C3AED', header_top_bg:'linear-gradient(135deg,#6D28D9,#7C3AED)' },
    red:    { color_primary:'#DC2626', color_primary_light:'#EF4444', color_primary_dark:'#B91C1C', color_bg:'#FFF5F5', navbar_bg:'#DC2626', header_top_bg:'linear-gradient(135deg,#B91C1C,#DC2626)' },
    orange: { color_primary:'#EA580C', color_primary_light:'#F97316', color_primary_dark:'#C2410C', color_bg:'#FFF7ED', navbar_bg:'#EA580C', header_top_bg:'linear-gradient(135deg,#C2410C,#EA580C)' },
    pink:   { color_primary:'#DB2777', color_primary_light:'#EC4899', color_primary_dark:'#9D174D', color_bg:'#FDF2F8', navbar_bg:'#DB2777', header_top_bg:'linear-gradient(135deg,#9D174D,#DB2777)' },
    gold:   { color_primary:'#D97706', color_primary_light:'#F59E0B', color_primary_dark:'#92400E', color_bg:'#FFFBEB', navbar_bg:'#D97706', header_top_bg:'linear-gradient(135deg,#92400E,#D97706)' },
    gray:   { color_primary:'#4B5563', color_primary_light:'#6B7280', color_primary_dark:'#374151', color_bg:'#F9FAFB', navbar_bg:'#4B5563', header_top_bg:'linear-gradient(135deg,#374151,#4B5563)' },
};

function applyPalette(name, dotEl) {
    const p = palettes[name];
    if (!p) return;
    Object.entries(p).forEach(([key, val]) => {
        state.settings[key] = val;
        // Update UI inputs
        const ch = document.getElementById('ch_' + key);
        const sw = document.getElementById('sw_' + key);
        if (ch && /^#/.test(val)) ch.value = val;
        if (sw) sw.style.background = val;
        // Apply to preview
        applyToPreview(key, val);
    });
    document.querySelectorAll('.palette-dot').forEach(d => d.classList.remove('active'));
    if (dotEl) dotEl.classList.add('active');
    markChanged();
    showToast('✅ تم تطبيق القالب!', 'success');
}

// ============================================================
//  SAVE ALL
// ============================================================
async function saveAll() {
    const btn = document.getElementById('saveBtn');
    btn.classList.add('saving');
    btn.textContent = '⏳ جاري الحفظ...';

    const payload = { settings: state.settings, buttons: state.buttons };

    try {
        const resp = await fetch('', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'ajax=1&action=save_all&data=' + encodeURIComponent(JSON.stringify(payload))
        });
        const data = await resp.json();
        if (data.ok) {
            showToast('✅ تم حفظ كل التغييرات!', 'success');
            hasUnsavedChanges = false;
            document.getElementById('saveDot').classList.remove('show');
            // Reload iframes to reflect saved changes
            const pi = document.getElementById('phoneIframe');
            const ti = document.getElementById('tabletIframe');
            if (pi && pi.src && pi.src !== 'about:blank') pi.contentWindow.location.reload();
            if (ti && ti.src && ti.src !== 'about:blank') ti.contentWindow.location.reload();
        } else {
            showToast('❌ خطأ: ' + (data.error || ''), 'error');
        }
    } catch(e) {
        showToast('❌ خطأ في الاتصال', 'error');
    }

    btn.classList.remove('saving');
    btn.innerHTML = '💾 حفظ الكل';
}

// ============================================================
//  HELPERS
// ============================================================
function markChanged() {
    hasUnsavedChanges = true;
    document.getElementById('saveDot').classList.add('show');
}

let toastTimer;
function showToast(msg, type='success') {
    const t = document.getElementById('toast');
    document.getElementById('toastMsg').textContent = msg;
    t.className = 'toast ' + type + ' show';
    clearTimeout(toastTimer);
    toastTimer = setTimeout(() => t.classList.remove('show'), 3000);
}

function confirmReset() {
    if (confirm('إلغاء كل التغييرات غير المحفوظة؟')) location.reload();
}

window.addEventListener('beforeunload', e => {
    if (hasUnsavedChanges) { e.preventDefault(); e.returnValue = ''; }
});

document.addEventListener('keydown', e => {
    if ((e.ctrlKey || e.metaKey) && e.key === 's') { e.preventDefault(); saveAll(); }
});
</script>
</body>
</html>