<?php
session_start();
$ADMIN_USER = 'admin';
$ADMIN_PASS = 'Alarcade123#';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
    if ($_POST['username'] === $ADMIN_USER && $_POST['password'] === $ADMIN_PASS) {
        $_SESSION['branding_auth'] = true;
    }
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['logout'])) {
    unset($_SESSION['branding_auth']);
}

if (!($_SESSION['branding_auth'] ?? false)) {
    ?><!DOCTYPE html><html lang="en" dir="ltr"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>EL3AB Branding Admin</title>
    <style>body{background:#0a0a1a;color:#f8fafc;font-family:'IBM Plex Sans Arabic',sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0}form{background:#1a1a2e;padding:40px;border-radius:16px;width:320px;text-align:center}input{width:100%;padding:12px;margin:8px 0;background:#2a2a4a;border:1px solid #333;border-radius:8px;color:#fff;font-size:14px}button{width:100%;padding:12px;margin-top:16px;background:linear-gradient(135deg,#E4AC38,#FFCC66);border:none;border-radius:8px;color:#1a1a1a;font-weight:700;font-size:15px;cursor:pointer}h2{color:#E4AC38;margin-bottom:16px}</style></head><body>
    <form method="POST"><h2>EL3AB Branding</h2><input name="username" placeholder="Username" required><input name="password" type="password" placeholder="Password" required><button name="login" value="1">Login</button></form></body></html><?php
    exit;
}

$BRAND_DIR = __DIR__ . '/../public/assets/brand/';
if (!is_dir($BRAND_DIR)) mkdir($BRAND_DIR, 0777, true);

$THEME_FILE = __DIR__ . '/../public/assets/brand/theme.json';

// Load theme from Supabase first (persistent), fallback to local file
require_once __DIR__ . '/../includes/supabase.php';
$sdb = supabaseService();
$themeRows = $sdb->get('platform_theme', ['select' => 'id,value']);
$theme = [];
if (is_array($themeRows) && !isset($themeRows['error'])) {
    foreach ($themeRows as $row) {
        $theme[$row['id']] = $row['value'];
    }
}
// Load assets from platform_assets table
$assetRows = $sdb->get('platform_assets', ['select' => 'id,asset_url']);
if (is_array($assetRows) && !isset($assetRows['error'])) {
    if (!isset($theme['assets'])) $theme['assets'] = [];
    foreach ($assetRows as $row) {
        if ($row['asset_url']) {
            $theme['assets'][$row['id']] = $row['asset_url'];
        }
    }
}
// Merge local file on top (for assets that are still local)
if (file_exists($THEME_FILE)) {
    $localTheme = json_decode(file_get_contents($THEME_FILE), true) ?: [];
    $theme = array_merge($theme, $localTheme);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_theme'])) {
    $theme = array_merge($theme, $_POST['theme'] ?? []);
    file_put_contents($THEME_FILE, json_encode($theme, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    // Also save to Supabase (persistent across deploys)
    require_once __DIR__ . '/../includes/supabase.php';
    $sdb = supabaseService();
    foreach ($_POST['theme'] ?? [] as $key => $value) {
        if (empty($key) || $value === null) continue;
        $existing = $sdb->get('platform_theme', ['id' => 'eq.' . $key, 'select' => 'id', 'limit' => 1]);
        if (!empty($existing) && !isset($existing['error'])) {
            $sdb->update('platform_theme', ['value' => $value], ['id' => 'eq.' . $key]);
        } else {
            $cat = 'color';
            if (strpos($key, 'anim_') === 0 || strpos($key, 'btn_') === 0) $cat = 'animation';
            if (strpos($key, 'ludo_') === 0 || strpos($key, 'board_') === 0) $cat = 'game';
            if (strpos($key, 'juice_') === 0) $cat = 'juice';
            $sdb->insert('platform_theme', ['id' => $key, 'category' => $cat, 'group_name' => 'player_app', 'label' => $key, 'value' => $value, 'default_value' => $value, 'value_type' => (strpos($value, '#') === 0) ? 'hex' : 'string']);
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['asset'])) {
    $slot = $_POST['slot'] ?? '';
    $expectedW = intval($_POST['expected_w'] ?? 64);
    $expectedH = intval($_POST['expected_h'] ?? 64);
    $file = $_FILES['asset'];
    if ($file['error'] === 0 && $slot) {
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $fileName = 'branding/' . $slot . '.' . $ext;
        $fileContent = file_get_contents($file['tmp_name']);

        // Upload to Supabase Storage (persistent across deploys)
        $storageUrl = SUPABASE_URL . '/storage/v1/object/profile-images/' . $fileName;
        $ch = curl_init($storageUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent);
        $mimeTypes = ['svg' => 'image/svg+xml', 'png' => 'image/png', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'webp' => 'image/webp', 'gif' => 'image/gif', 'mp3' => 'audio/mpeg', 'ogg' => 'audio/ogg', 'wav' => 'audio/wav', 'm4a' => 'audio/mp4', 'webm' => 'audio/webm'];
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'apikey: ' . SUPABASE_SERVICE_KEY,
            'Authorization: Bearer ' . SUPABASE_SERVICE_KEY,
            'Content-Type: ' . ($mimeTypes[$ext] ?? 'application/octet-stream'),
            'x-upsert: true'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $uploadResult = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode >= 200 && $httpCode < 300) {
            // Public URL with anon key for browser access
            $anonKey = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlzcyI6InN1cGFiYXNlIiwiaWF0IjoxNzM1Njg5NjAwLCJleHAiOjE4OTM0NTYwMDB9.31PF6PvP-pSrvRuQwLFptQoejR0W1A7o53lZhEbnz84';
            $publicUrl = SUPABASE_URL . '/storage/v1/object/public/profile-images/' . $fileName . '?apikey=' . $anonKey . '&v=' . time();
            $theme['assets'][$slot] = $publicUrl;

            // Save asset URL to Supabase platform_assets table (upsert)
            $existing = $sdb->get('platform_assets', ['id' => 'eq.' . $slot, 'select' => 'id', 'limit' => 1]);
            if (!empty($existing) && !isset($existing['error'])) {
                $result = $sdb->update('platform_assets', ['asset_url' => $publicUrl, 'dimensions' => $expectedW . 'x' . $expectedH], ['id' => 'eq.' . $slot]);
            } else {
                $result = $sdb->insert('platform_assets', ['id' => $slot, 'category' => 'custom', 'label' => $slot, 'asset_url' => $publicUrl, 'dimensions' => $expectedW . 'x' . $expectedH]);
            }
            if (isset($result['error'])) {
                error_log('[branding] platform_assets save failed: ' . json_encode($result));
            }

            // Also save locally for immediate preview
            @mkdir($BRAND_DIR, 0777, true);
            file_put_contents($BRAND_DIR . $slot . '.' . $ext, $fileContent);
            file_put_contents($THEME_FILE, json_encode($theme, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>EL3AB — Branding Admin</title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { background: #0a0a1a; color: #f8fafc; font-family: 'IBM Plex Sans Arabic', 'Inter', sans-serif; line-height: 1.6; }
        .container { max-width: 900px; margin: 0 auto; padding: 24px 16px; }
        h1 { color: #E4AC38; font-size: 24px; margin-bottom: 8px; }
        h2 { color: #94a3b8; font-size: 18px; margin: 32px 0 12px; border-bottom: 1px solid #1a1a2e; padding-bottom: 8px; }
        h3 { color: #64748b; font-size: 14px; margin: 16px 0 8px; }
        .logout { float: left; background: none; border: 1px solid #333; color: #94a3b8; padding: 6px 14px; border-radius: 6px; cursor: pointer; font-size: 12px; }
        .section { background: #1a1a2e; border-radius: 12px; padding: 20px; margin-bottom: 16px; }
        .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
        @media(max-width:600px) { .grid { grid-template-columns: 1fr; } }
        .field { margin-bottom: 12px; }
        .field label { display: block; font-size: 12px; color: #94a3b8; margin-bottom: 4px; font-weight: 600; }
        .field .hint { font-size: 10px; color: #64748b; margin-top: 2px; }
        input[type="color"] { width: 48px; height: 36px; border: 1px solid #333; border-radius: 6px; background: #2a2a4a; cursor: pointer; }
        input[type="text"], input[type="number"], select { width: 100%; padding: 8px 12px; background: #2a2a4a; border: 1px solid #333; border-radius: 6px; color: #fff; font-size: 13px; }
        .color-row { display: flex; align-items: center; gap: 8px; }
        .color-row input[type="text"] { flex: 1; }
        .upload-box { border: 2px dashed #333; border-radius: 8px; padding: 16px; text-align: center; cursor: pointer; transition: border-color 0.2s; }
        .upload-box:hover { border-color: #E4AC38; }
        .upload-box .size-hint { font-size: 11px; color: #E4AC38; font-weight: 600; margin-top: 4px; }
        .upload-box .current { margin-top: 8px; }
        .upload-box img { max-width: 80px; max-height: 80px; border-radius: 4px; }
        button[type="submit"] { background: linear-gradient(135deg, #E4AC38, #FFCC66); color: #1a1a1a; border: none; padding: 12px 32px; border-radius: 8px; font-weight: 700; font-size: 14px; cursor: pointer; margin-top: 16px; }
        .saved { background: #34D399; color: #000; padding: 8px 16px; border-radius: 6px; margin: 8px 0; font-size: 13px; font-weight: 600; }
        .range-row { display:flex; align-items:center; gap:8px; }
        .range-row input[type="range"] { flex:1; height:6px; -webkit-appearance:none; background:#2a2a4a; border-radius:3px; outline:none; }
        .range-row input[type="range"]::-webkit-slider-thumb { -webkit-appearance:none; width:16px; height:16px; border-radius:50%; background:#E4AC38; cursor:pointer; }
        .range-row .range-val { min-width:40px; text-align:right; font-size:12px; color:#E4AC38; font-family:'IBM Plex Mono',monospace; }
    </style>
</head>
<body>
<div class="container">
    <form method="POST" style="display:inline;"><button class="logout" name="logout" value="1">Logout</button></form>
    <h1>🎨 EL3AB Branding Admin</h1>
    <p style="color:#64748b;font-size:13px;margin-bottom:24px;">Visual identity management — colors, icons, and assets appear as defaults for all players</p>

    <?php if (isset($_POST['save_theme'])): ?><div class="saved">✓ Changes saved</div><?php endif; ?>

    <form method="POST">
    <input type="hidden" name="save_theme" value="1">

    <!-- COLORS -->
    <h2>🎨 Core Colors</h2>
    <div class="section">
        <div class="grid">
            <?php
            $colors = [
                ['key' => 'bg_deep', 'label' => 'Deep Background', 'default' => '#050810', 'hint' => 'Darkest layer in the app'],
                ['key' => 'bg_base', 'label' => 'Base Background', 'default' => '#0A1020', 'hint' => 'Screen background'],
                ['key' => 'bg_card', 'label' => 'Card Background', 'default' => '#121A2E', 'hint' => 'Card surfaces'],
                ['key' => 'bg_elevated', 'label' => 'Elevated Background', 'default' => '#1A2440', 'hint' => 'Inputs & elevated elements'],
                ['key' => 'gold', 'label' => 'Gold (Brand)', 'default' => '#E4AC38', 'hint' => 'Primary brand, buttons, rewards'],
                ['key' => 'gold_soft', 'label' => 'Gold Light', 'default' => '#FFCC66', 'hint' => 'Gold button gradient end'],
                ['key' => 'blue', 'label' => 'Blue', 'default' => '#2082F0', 'hint' => 'Links, competitive actions'],
                ['key' => 'cyan', 'label' => 'Cyan', 'default' => '#00FFFF', 'hint' => 'Glow effects'],
                ['key' => 'purple', 'label' => 'Purple', 'default' => '#6834BE', 'hint' => 'Rare/Legendary tier'],
                ['key' => 'success', 'label' => 'Success / Win', 'default' => '#34D399', 'hint' => 'Win & success states'],
                ['key' => 'error', 'label' => 'Error / Loss', 'default' => '#EF4444', 'hint' => 'Loss & error states'],
                ['key' => 'text_primary', 'label' => 'Primary Text', 'default' => '#F8FAFC', 'hint' => 'Main text color'],
                ['key' => 'text_secondary', 'label' => 'Secondary Text', 'default' => '#94A3B8', 'hint' => 'Muted/secondary text'],
            ];
            foreach ($colors as $c):
                $val = $theme[$c['key']] ?? $c['default'];
            ?>
            <div class="field">
                <label><?= $c['label'] ?></label>
                <div class="color-row">
                    <input type="color" name="theme[<?= $c['key'] ?>]" value="<?= $val ?>">
                    <input type="text" name="theme[<?= $c['key'] ?>]" value="<?= $val ?>" pattern="#[0-9A-Fa-f]{6}">
                </div>
                <div class="hint"><?= $c['hint'] ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- LAYOUT: HUD BAR -->
    <h2>📐 HUD Bar Layout</h2>
    <div class="section">
        <div class="grid">
            <?php
            $hudLayout = [
                ['key' => 'hud_height', 'label' => 'HUD Height', 'default' => '56', 'min' => 40, 'max' => 80, 'hint' => 'Top bar height (px)'],
                ['key' => 'hud_avatar_size', 'label' => 'Avatar Size', 'default' => '34', 'min' => 24, 'max' => 56, 'hint' => 'Profile avatar circle'],
                ['key' => 'hud_avatar_border', 'label' => 'Avatar Border', 'default' => '2', 'min' => 0, 'max' => 6, 'hint' => 'Gold ring width'],
                ['key' => 'hud_icon_size', 'label' => 'Coin/Gem Icon', 'default' => '16', 'min' => 10, 'max' => 28, 'hint' => 'HUD emoji icon size'],
                ['key' => 'hud_bell_size', 'label' => 'Bell Icon', 'default' => '18', 'min' => 12, 'max' => 32, 'hint' => 'Notification bell'],
                ['key' => 'hud_stat_font', 'label' => 'Stat Font Size', 'default' => '14', 'min' => 10, 'max' => 22, 'hint' => 'Coin/gem numbers'],
                ['key' => 'hud_stat_gap', 'label' => 'Stats Gap', 'default' => '16', 'min' => 4, 'max' => 32, 'hint' => 'Space between coin & gem'],
                ['key' => 'hud_btn_size', 'label' => 'Action Button', 'default' => '44', 'min' => 32, 'max' => 64, 'hint' => 'Bell button size'],
                ['key' => 'hud_badge_size', 'label' => 'Badge Size', 'default' => '16', 'min' => 10, 'max' => 24, 'hint' => 'Notification dot'],
                ['key' => 'hud_badge_font', 'label' => 'Badge Font', 'default' => '9', 'min' => 7, 'max' => 14, 'hint' => 'Badge number size'],
                ['key' => 'hud_padding_x', 'label' => 'Horizontal Padding', 'default' => '16', 'min' => 8, 'max' => 32, 'hint' => 'Left/right padding'],
            ];
            foreach ($hudLayout as $s):
                $val = $theme[$s['key']] ?? $s['default'];
            ?>
            <div class="field">
                <label><?= $s['label'] ?></label>
                <div class="range-row">
                    <input type="range" name="theme[<?= $s['key'] ?>]" value="<?= $val ?>" min="<?= $s['min'] ?>" max="<?= $s['max'] ?>" oninput="this.nextElementSibling.textContent=this.value+'px'">
                    <span class="range-val"><?= $val ?>px</span>
                </div>
                <div class="hint"><?= $s['hint'] ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- LAYOUT: TAB BAR -->
    <h2>📐 Tab Bar Layout</h2>
    <div class="section">
        <div class="grid">
            <?php
            $tabLayout = [
                ['key' => 'tab_height', 'label' => 'Tab Bar Height', 'default' => '64', 'min' => 48, 'max' => 88, 'hint' => 'Bottom bar height'],
                ['key' => 'tab_icon_size', 'label' => 'Tab Icon Size', 'default' => '24', 'min' => 16, 'max' => 36, 'hint' => 'Icon width/height'],
                ['key' => 'tab_label_font', 'label' => 'Tab Label Font', 'default' => '11', 'min' => 8, 'max' => 16, 'hint' => 'Text under icons'],
                ['key' => 'tab_item_gap', 'label' => 'Icon-Label Gap', 'default' => '3', 'min' => 0, 'max' => 12, 'hint' => 'Between icon & text'],
                ['key' => 'tab_item_padding_x', 'label' => 'Item Padding X', 'default' => '12', 'min' => 4, 'max' => 24, 'hint' => 'Horizontal padding'],
                ['key' => 'tab_item_padding_y', 'label' => 'Item Padding Y', 'default' => '8', 'min' => 2, 'max' => 20, 'hint' => 'Vertical padding'],
                ['key' => 'tab_item_min_size', 'label' => 'Touch Target', 'default' => '48', 'min' => 36, 'max' => 64, 'hint' => 'Min tap area'],
            ];
            foreach ($tabLayout as $s):
                $val = $theme[$s['key']] ?? $s['default'];
            ?>
            <div class="field">
                <label><?= $s['label'] ?></label>
                <div class="range-row">
                    <input type="range" name="theme[<?= $s['key'] ?>]" value="<?= $val ?>" min="<?= $s['min'] ?>" max="<?= $s['max'] ?>" oninput="this.nextElementSibling.textContent=this.value+'px'">
                    <span class="range-val"><?= $val ?>px</span>
                </div>
                <div class="hint"><?= $s['hint'] ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- LAYOUT: HOME PAGE -->
    <h2>📐 Home Page Layout</h2>
    <div class="section">
        <div class="grid">
            <?php
            $homeLayout = [
                ['key' => 'home_padding', 'label' => 'Page Padding', 'default' => '16', 'min' => 8, 'max' => 32, 'hint' => 'Content edge spacing'],
                ['key' => 'home_max_width', 'label' => 'Content Max Width', 'default' => '340', 'min' => 280, 'max' => 500, 'hint' => 'Grid/widget max width'],
                ['key' => 'home_greeting_font', 'label' => 'Greeting Font', 'default' => '16', 'min' => 12, 'max' => 24, 'hint' => 'Welcome text size'],
                ['key' => 'home_greeting_margin', 'label' => 'Greeting Margin', 'default' => '12', 'min' => 4, 'max' => 32, 'hint' => 'Space below greeting'],
            ];
            foreach ($homeLayout as $s):
                $val = $theme[$s['key']] ?? $s['default'];
            ?>
            <div class="field">
                <label><?= $s['label'] ?></label>
                <div class="range-row">
                    <input type="range" name="theme[<?= $s['key'] ?>]" value="<?= $val ?>" min="<?= $s['min'] ?>" max="<?= $s['max'] ?>" oninput="this.nextElementSibling.textContent=this.value+'px'">
                    <span class="range-val"><?= $val ?>px</span>
                </div>
                <div class="hint"><?= $s['hint'] ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- LAYOUT: QUICK ACTIONS -->
    <h2>📐 Quick Action Buttons</h2>
    <div class="section">
        <div class="grid">
            <?php
            $quickLayout = [
                ['key' => 'quick_btn_icon_size', 'label' => 'Icon Box Size', 'default' => '42', 'min' => 28, 'max' => 64, 'hint' => 'Circle icon container'],
                ['key' => 'quick_btn_icon_radius', 'label' => 'Icon Radius', 'default' => '12', 'min' => 4, 'max' => 32, 'hint' => 'Corner rounding'],
                ['key' => 'quick_btn_icon_font', 'label' => 'Icon Font Size', 'default' => '20', 'min' => 12, 'max' => 36, 'hint' => 'Emoji/icon in circle'],
                ['key' => 'quick_btn_label_font', 'label' => 'Label Font', 'default' => '10', 'min' => 7, 'max' => 16, 'hint' => 'Text under icon'],
                ['key' => 'quick_btn_gap', 'label' => 'Icon-Label Gap', 'default' => '8', 'min' => 0, 'max' => 16, 'hint' => 'Space inside button'],
                ['key' => 'quick_btn_padding', 'label' => 'Button Padding', 'default' => '6', 'min' => 0, 'max' => 16, 'hint' => 'Outer padding'],
                ['key' => 'quick_row_gap', 'label' => 'Row Gap', 'default' => '8', 'min' => 4, 'max' => 24, 'hint' => 'Between buttons'],
                ['key' => 'quick_row_margin', 'label' => 'Row Bottom Margin', 'default' => '16', 'min' => 4, 'max' => 32, 'hint' => 'Below quick actions'],
            ];
            foreach ($quickLayout as $s):
                $val = $theme[$s['key']] ?? $s['default'];
            ?>
            <div class="field">
                <label><?= $s['label'] ?></label>
                <div class="range-row">
                    <input type="range" name="theme[<?= $s['key'] ?>]" value="<?= $val ?>" min="<?= $s['min'] ?>" max="<?= $s['max'] ?>" oninput="this.nextElementSibling.textContent=this.value+'px'">
                    <span class="range-val"><?= $val ?>px</span>
                </div>
                <div class="hint"><?= $s['hint'] ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- LAYOUT: GAME TILES -->
    <h2>📐 Game Tiles</h2>
    <div class="section">
        <div class="grid">
            <?php
            $tileLayout = [
                ['key' => 'game_tile_radius', 'label' => 'Tile Radius', 'default' => '18', 'min' => 0, 'max' => 40, 'hint' => 'Corner rounding'],
                ['key' => 'game_tile_gap', 'label' => 'Grid Gap', 'default' => '12', 'min' => 4, 'max' => 24, 'hint' => 'Space between tiles'],
                ['key' => 'game_tile_icon_size', 'label' => 'Icon Size (asset)', 'default' => '48', 'min' => 24, 'max' => 80, 'hint' => 'Game icon img size'],
                ['key' => 'game_tile_icon_font', 'label' => 'Icon Size (emoji)', 'default' => '42', 'min' => 20, 'max' => 72, 'hint' => 'Fallback emoji size'],
                ['key' => 'game_tile_name_font', 'label' => 'Name Font', 'default' => '16', 'min' => 10, 'max' => 24, 'hint' => 'Game title text'],
                ['key' => 'game_tile_content_gap', 'label' => 'Content Gap', 'default' => '8', 'min' => 0, 'max' => 20, 'hint' => 'Icon to name space'],
            ];
            foreach ($tileLayout as $s):
                $val = $theme[$s['key']] ?? $s['default'];
            ?>
            <div class="field">
                <label><?= $s['label'] ?></label>
                <div class="range-row">
                    <input type="range" name="theme[<?= $s['key'] ?>]" value="<?= $val ?>" min="<?= $s['min'] ?>" max="<?= $s['max'] ?>" oninput="this.nextElementSibling.textContent=this.value+'px'">
                    <span class="range-val"><?= $val ?>px</span>
                </div>
                <div class="hint"><?= $s['hint'] ?></div>
            </div>
            <?php endforeach; ?>
            <div class="field">
                <label>Tile Aspect Ratio</label>
                <div class="range-row">
                    <input type="range" name="theme[game_tile_aspect]" value="<?= $theme['game_tile_aspect'] ?? '1.1' ?>" min="0.7" max="1.6" step="0.05" oninput="this.nextElementSibling.textContent=this.value">
                    <span class="range-val"><?= $theme['game_tile_aspect'] ?? '1.1' ?></span>
                </div>
                <div class="hint">Width:height ratio (1.0 = square)</div>
            </div>
        </div>
    </div>

    <!-- LAYOUT: GAME MENU SHEET -->
    <h2>📐 Game Menu (Bottom Sheet)</h2>
    <div class="section">
        <div class="grid">
            <?php
            $sheetLayout = [
                ['key' => 'sheet_radius', 'label' => 'Sheet Radius', 'default' => '28', 'min' => 0, 'max' => 48, 'hint' => 'Top corner rounding'],
                ['key' => 'sheet_padding_x', 'label' => 'Padding X', 'default' => '20', 'min' => 8, 'max' => 40, 'hint' => 'Left/right space'],
                ['key' => 'sheet_padding_top', 'label' => 'Padding Top', 'default' => '28', 'min' => 12, 'max' => 48, 'hint' => 'Top space'],
                ['key' => 'menu_close_size', 'label' => 'Close Button Size', 'default' => '36', 'min' => 24, 'max' => 56, 'hint' => 'X button circle'],
                ['key' => 'menu_close_font', 'label' => 'Close Icon Font', 'default' => '20', 'min' => 12, 'max' => 32, 'hint' => 'X character size'],
                ['key' => 'menu_header_icon_size', 'label' => 'Header Icon Size', 'default' => '42', 'min' => 28, 'max' => 64, 'hint' => 'Game icon box'],
                ['key' => 'menu_header_icon_radius', 'label' => 'Header Icon Radius', 'default' => '12', 'min' => 0, 'max' => 32, 'hint' => 'Icon corner rounding'],
                ['key' => 'menu_header_icon_font', 'label' => 'Header Icon Font', 'default' => '22', 'min' => 12, 'max' => 36, 'hint' => 'Emoji size in icon'],
                ['key' => 'menu_header_title_font', 'label' => 'Title Font', 'default' => '22', 'min' => 14, 'max' => 32, 'hint' => 'Game name size'],
                ['key' => 'menu_header_gap', 'label' => 'Header Gap', 'default' => '10', 'min' => 4, 'max' => 24, 'hint' => 'Icon to title space'],
                ['key' => 'menu_header_margin', 'label' => 'Header Margin', 'default' => '20', 'min' => 8, 'max' => 40, 'hint' => 'Below header space'],
            ];
            foreach ($sheetLayout as $s):
                $val = $theme[$s['key']] ?? $s['default'];
            ?>
            <div class="field">
                <label><?= $s['label'] ?></label>
                <div class="range-row">
                    <input type="range" name="theme[<?= $s['key'] ?>]" value="<?= $val ?>" min="<?= $s['min'] ?>" max="<?= $s['max'] ?>" oninput="this.nextElementSibling.textContent=this.value+'px'">
                    <span class="range-val"><?= $val ?>px</span>
                </div>
                <div class="hint"><?= $s['hint'] ?></div>
            </div>
            <?php endforeach; ?>
            <div class="field">
                <label>Max Height</label>
                <div class="range-row">
                    <input type="range" name="theme[sheet_max_height]" value="<?= $theme['sheet_max_height'] ?? '75' ?>" min="40" max="95" oninput="this.nextElementSibling.textContent=this.value+'vh'">
                    <span class="range-val"><?= $theme['sheet_max_height'] ?? '75' ?>vh</span>
                </div>
                <div class="hint">Sheet max viewport height</div>
            </div>
            <div class="field">
                <label>Sheet Background</label>
                <input type="color" name="theme[sheet_bg]" value="<?= $theme['sheet_bg'] ?? '#0f0f1e' ?>" class="color-input">
                <div class="hint">Bottom sheet bg color</div>
            </div>
        </div>
    </div>

    <!-- LAYOUT: MENU BUTTONS -->
    <h2>📐 Menu Play Buttons</h2>
    <div class="section">
        <div class="grid">
            <?php
            $gmBtnLayout = [
                ['key' => 'gm_btn_padding_y', 'label' => 'Button Padding Y', 'default' => '18', 'min' => 8, 'max' => 32, 'hint' => 'Top/bottom space'],
                ['key' => 'gm_btn_padding_x', 'label' => 'Button Padding X', 'default' => '16', 'min' => 8, 'max' => 32, 'hint' => 'Left/right space'],
                ['key' => 'gm_btn_gap', 'label' => 'Icon-Body Gap', 'default' => '14', 'min' => 4, 'max' => 28, 'hint' => 'Between icon & text'],
                ['key' => 'gm_btn_radius', 'label' => 'Button Radius', 'default' => '16', 'min' => 0, 'max' => 32, 'hint' => 'Corner rounding'],
                ['key' => 'gm_btn_margin_bottom', 'label' => 'Button Spacing', 'default' => '10', 'min' => 4, 'max' => 24, 'hint' => 'Between buttons'],
                ['key' => 'gm_btn_icon_size', 'label' => 'Icon Size', 'default' => '52', 'min' => 32, 'max' => 72, 'hint' => 'Gradient icon box'],
                ['key' => 'gm_btn_icon_radius', 'label' => 'Icon Radius', 'default' => '14', 'min' => 0, 'max' => 36, 'hint' => 'Icon corner rounding'],
                ['key' => 'gm_btn_icon_font', 'label' => 'Icon Font', 'default' => '26', 'min' => 14, 'max' => 40, 'hint' => 'Emoji in icon box'],
                ['key' => 'gm_btn_title_font', 'label' => 'Title Font', 'default' => '17', 'min' => 12, 'max' => 24, 'hint' => 'Button title text'],
                ['key' => 'gm_btn_sub_font', 'label' => 'Subtitle Font', 'default' => '11', 'min' => 8, 'max' => 16, 'hint' => 'Description text'],
                ['key' => 'gm_btn_arrow_font', 'label' => 'Arrow Font', 'default' => '22', 'min' => 12, 'max' => 32, 'hint' => 'Chevron size'],
            ];
            foreach ($gmBtnLayout as $s):
                $val = $theme[$s['key']] ?? $s['default'];
            ?>
            <div class="field">
                <label><?= $s['label'] ?></label>
                <div class="range-row">
                    <input type="range" name="theme[<?= $s['key'] ?>]" value="<?= $val ?>" min="<?= $s['min'] ?>" max="<?= $s['max'] ?>" oninput="this.nextElementSibling.textContent=this.value+'px'">
                    <span class="range-val"><?= $val ?>px</span>
                </div>
                <div class="hint"><?= $s['hint'] ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- LAYOUT: MENU CHIPS -->
    <h2>📐 Menu Chips (Secondary)</h2>
    <div class="section">
        <div class="grid">
            <?php
            $chipLayout = [
                ['key' => 'gm_chip_padding_y', 'label' => 'Chip Padding Y', 'default' => '14', 'min' => 4, 'max' => 28, 'hint' => 'Top/bottom'],
                ['key' => 'gm_chip_padding_x', 'label' => 'Chip Padding X', 'default' => '8', 'min' => 4, 'max' => 24, 'hint' => 'Left/right'],
                ['key' => 'gm_chip_gap', 'label' => 'Icon-Label Gap', 'default' => '4', 'min' => 0, 'max' => 16, 'hint' => 'Inside chip'],
                ['key' => 'gm_chip_radius', 'label' => 'Chip Radius', 'default' => '12', 'min' => 0, 'max' => 24, 'hint' => 'Corner rounding'],
                ['key' => 'gm_chip_font', 'label' => 'Chip Font', 'default' => '11', 'min' => 8, 'max' => 16, 'hint' => 'Label text size'],
                ['key' => 'gm_chip_icon_font', 'label' => 'Chip Icon', 'default' => '18', 'min' => 12, 'max' => 32, 'hint' => 'Emoji size'],
                ['key' => 'gm_chips_grid_gap', 'label' => 'Grid Gap', 'default' => '8', 'min' => 4, 'max' => 20, 'hint' => 'Between chips'],
                ['key' => 'gm_chips_margin_top', 'label' => 'Top Margin', 'default' => '14', 'min' => 4, 'max' => 32, 'hint' => 'Above chip row'],
            ];
            foreach ($chipLayout as $s):
                $val = $theme[$s['key']] ?? $s['default'];
            ?>
            <div class="field">
                <label><?= $s['label'] ?></label>
                <div class="range-row">
                    <input type="range" name="theme[<?= $s['key'] ?>]" value="<?= $val ?>" min="<?= $s['min'] ?>" max="<?= $s['max'] ?>" oninput="this.nextElementSibling.textContent=this.value+'px'">
                    <span class="range-val"><?= $val ?>px</span>
                </div>
                <div class="hint"><?= $s['hint'] ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- LAYOUT: BOT CARDS -->
    <h2>📐 Bot Selection Cards</h2>
    <div class="section">
        <div class="grid">
            <?php
            $botLayout = [
                ['key' => 'bot_card_avatar_size', 'label' => 'Avatar Size', 'default' => '56', 'min' => 32, 'max' => 80, 'hint' => 'Bot portrait circle'],
                ['key' => 'bot_card_avatar_border', 'label' => 'Avatar Border', 'default' => '2', 'min' => 0, 'max' => 6, 'hint' => 'Color ring width'],
                ['key' => 'bot_card_name_font', 'label' => 'Name Font', 'default' => '14', 'min' => 10, 'max' => 20, 'hint' => 'Bot name size'],
                ['key' => 'bot_card_sub_font', 'label' => 'Subtitle Font', 'default' => '11', 'min' => 8, 'max' => 16, 'hint' => 'Style & ELO text'],
                ['key' => 'bot_card_accent_height', 'label' => 'Top Accent Bar', 'default' => '3', 'min' => 0, 'max' => 8, 'hint' => 'Colored bar height'],
                ['key' => 'bot_grid_gap', 'label' => 'Grid Gap', 'default' => '12', 'min' => 4, 'max' => 24, 'hint' => 'Between cards'],
                ['key' => 'bot_back_btn_size', 'label' => 'Back Button Size', 'default' => '44', 'min' => 32, 'max' => 56, 'hint' => 'Arrow button'],
                ['key' => 'bot_back_btn_font', 'label' => 'Back Button Font', 'default' => '18', 'min' => 12, 'max' => 28, 'hint' => 'Arrow character size'],
                ['key' => 'bot_title_font', 'label' => 'Page Title Font', 'default' => '18', 'min' => 14, 'max' => 28, 'hint' => 'Select bot heading'],
            ];
            foreach ($botLayout as $s):
                $val = $theme[$s['key']] ?? $s['default'];
            ?>
            <div class="field">
                <label><?= $s['label'] ?></label>
                <div class="range-row">
                    <input type="range" name="theme[<?= $s['key'] ?>]" value="<?= $val ?>" min="<?= $s['min'] ?>" max="<?= $s['max'] ?>" oninput="this.nextElementSibling.textContent=this.value+'px'">
                    <span class="range-val"><?= $val ?>px</span>
                </div>
                <div class="hint"><?= $s['hint'] ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- GAME COLORS -->
    <h2>🎮 Game Colors</h2>
    <div class="section">
        <div class="grid">
            <?php
            $gameColors = [
                ['key' => 'chess_primary', 'label' => 'Chess — Primary', 'default' => '#2563EB'],
                ['key' => 'chess_secondary', 'label' => 'Chess — Secondary', 'default' => '#F5B731'],
                ['key' => 'domino_primary', 'label' => 'Domino — Primary', 'default' => '#10B981'],
                ['key' => 'domino_secondary', 'label' => 'Domino — Secondary', 'default' => '#06B6D4'],
                ['key' => 'ludo_primary', 'label' => 'Ludo — Primary', 'default' => '#8B5CF6'],
                ['key' => 'ludo_secondary', 'label' => 'Ludo — Secondary', 'default' => '#EC4899'],
                ['key' => 'backgammon_primary', 'label' => 'Backgammon — Primary', 'default' => '#F59E0B'],
                ['key' => 'backgammon_secondary', 'label' => 'Backgammon — Secondary', 'default' => '#EF4444'],
            ];
            foreach ($gameColors as $c):
                $val = $theme[$c['key']] ?? $c['default'];
            ?>
            <div class="field">
                <label><?= $c['label'] ?></label>
                <div class="color-row">
                    <input type="color" name="theme[<?= $c['key'] ?>]" value="<?= $val ?>">
                    <input type="text" name="theme[<?= $c['key'] ?>]" value="<?= $val ?>">
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- CHESS BOARD -->
    <h2>♟ Chess Board Colors</h2>
    <div class="section">
        <div class="grid">
            <?php
            $boardColors = [
                ['key' => 'board_light', 'label' => 'Light Square', 'default' => '#F0D9B5', 'hint' => 'Light squares on the board'],
                ['key' => 'board_dark', 'label' => 'Dark Square', 'default' => '#B58863', 'hint' => 'Dark squares on the board'],
                ['key' => 'board_highlight_light', 'label' => 'Move Highlight (Light)', 'default' => '#CDD16A', 'hint' => 'Last move — light square'],
                ['key' => 'board_highlight_dark', 'label' => 'Move Highlight (Dark)', 'default' => '#AAA23A', 'hint' => 'Last move — dark square'],
                ['key' => 'board_check', 'label' => 'King in Check', 'default' => '#FF6B6B', 'hint' => 'When the king is under attack'],
            ];
            foreach ($boardColors as $c):
                $val = $theme[$c['key']] ?? $c['default'];
            ?>
            <div class="field">
                <label><?= $c['label'] ?></label>
                <div class="color-row">
                    <input type="color" name="theme[<?= $c['key'] ?>]" value="<?= $val ?>">
                    <input type="text" name="theme[<?= $c['key'] ?>]" value="<?= $val ?>">
                </div>
                <div class="hint"><?= $c['hint'] ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- LUDO BOARD COLORS -->
    <h2>🎲 Ludo Board Colors</h2>
    <div class="section">
        <div class="grid">
            <?php
            $ludoBoardColors = [
                ['key' => 'ludo_red', 'label' => 'Ludo Red', 'default' => '#E53935', 'hint' => 'Red player zone'],
                ['key' => 'ludo_blue', 'label' => 'Ludo Blue', 'default' => '#1E88E5', 'hint' => 'Blue player zone'],
                ['key' => 'ludo_green', 'label' => 'Ludo Green', 'default' => '#43A047', 'hint' => 'Green player zone'],
                ['key' => 'ludo_yellow', 'label' => 'Ludo Yellow', 'default' => '#FDD835', 'hint' => 'Yellow player zone'],
                ['key' => 'ludo_board_bg', 'label' => 'Board Background', 'default' => '#FAFAFA', 'hint' => 'Main board surface'],
                ['key' => 'ludo_path', 'label' => 'Path Color', 'default' => '#FFFFFF', 'hint' => 'Walking path tiles'],
                ['key' => 'ludo_safe', 'label' => 'Safe Spot', 'default' => '#FFD700', 'hint' => 'Star/safe zone marker'],
                ['key' => 'ludo_piece_border', 'label' => 'Piece Border', 'default' => '#FFFFFF', 'hint' => 'Ring around pieces'],
                ['key' => 'ludo_grid_line', 'label' => 'Grid Lines', 'default' => '#E0E0E0', 'hint' => 'Board grid lines'],
            ];
            foreach ($ludoBoardColors as $c):
                $val = $theme[$c['key']] ?? $c['default'];
            ?>
            <div class="field">
                <label><?= $c['label'] ?></label>
                <div class="color-row">
                    <input type="color" name="theme[<?= $c['key'] ?>]" value="<?= $val ?>">
                    <input type="text" name="theme[<?= $c['key'] ?>]" value="<?= $val ?>">
                </div>
                <div class="hint"><?= $c['hint'] ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- BACKGAMMON BOARD COLORS -->
    <h2>🎯 Backgammon Board Colors</h2>
    <div class="section">
        <div class="grid">
            <?php
            $bgBoardColors = [
                ['key' => 'bg_board_border', 'label' => 'Board Border', 'default' => '#5C3A0E', 'hint' => 'Outer frame'],
                ['key' => 'bg_board_light', 'label' => 'Board Light', 'default' => '#3D6B1E', 'hint' => 'Light felt area'],
                ['key' => 'bg_board_dark', 'label' => 'Board Dark', 'default' => '#2D5016', 'hint' => 'Dark felt area'],
                ['key' => 'bg_bar_dark', 'label' => 'Bar Dark', 'default' => '#2A1800', 'hint' => 'Center bar dark'],
                ['key' => 'bg_bar_light', 'label' => 'Bar Light', 'default' => '#3D2B1A', 'hint' => 'Center bar light'],
                ['key' => 'bg_bearoff', 'label' => 'Bear-off Area', 'default' => '#1A0E00', 'hint' => 'Bear-off tray'],
                ['key' => 'bg_point_dark', 'label' => 'Dark Point', 'default' => '#8B4513', 'hint' => 'Dark triangle base'],
                ['key' => 'bg_point_dark_tip', 'label' => 'Dark Point Tip', 'default' => '#5C2D0A', 'hint' => 'Dark triangle tip'],
                ['key' => 'bg_point_light', 'label' => 'Light Point', 'default' => '#D2691E', 'hint' => 'Light triangle base'],
                ['key' => 'bg_point_light_tip', 'label' => 'Light Point Tip', 'default' => '#A0522D', 'hint' => 'Light triangle tip'],
                ['key' => 'bg_checker_white', 'label' => 'White Checker', 'default' => '#F5E6D3', 'hint' => 'White player pieces'],
                ['key' => 'bg_checker_black', 'label' => 'Black Checker', 'default' => '#2A2A2A', 'hint' => 'Black player pieces'],
                ['key' => 'bg_highlight', 'label' => 'Move Highlight', 'default' => '#10B981', 'hint' => 'Valid move indicator'],
                ['key' => 'bg_selected', 'label' => 'Selected Piece', 'default' => '#FFD700', 'hint' => 'Selected checker glow'],
            ];
            foreach ($bgBoardColors as $c):
                $val = $theme[$c['key']] ?? $c['default'];
            ?>
            <div class="field">
                <label><?= $c['label'] ?></label>
                <div class="color-row">
                    <input type="color" name="theme[<?= $c['key'] ?>]" value="<?= $val ?>">
                    <input type="text" name="theme[<?= $c['key'] ?>]" value="<?= $val ?>">
                </div>
                <div class="hint"><?= $c['hint'] ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- CHESS PIECES -->
    <h2>♟ Chess Pieces</h2>
    <p style="color:#64748b;font-size:12px;margin-bottom:16px;">Upload PNG or SVG images for each piece — they appear on the board immediately</p>
    <div class="section">
        <h3 style="color:#f8fafc;margin-bottom:12px;">⬜ White Pieces</h3>
        <div class="grid">
            <?php
            $whitePieces = [
                ['slot' => 'chess_piece_wK', 'label' => 'White King ♔', 'w' => 128, 'h' => 128, 'hint' => 'White King'],
                ['slot' => 'chess_piece_wQ', 'label' => 'White Queen ♕', 'w' => 128, 'h' => 128, 'hint' => 'White Queen'],
                ['slot' => 'chess_piece_wR', 'label' => 'White Rook ♖', 'w' => 128, 'h' => 128, 'hint' => 'White Rook'],
                ['slot' => 'chess_piece_wB', 'label' => 'White Bishop ♗', 'w' => 128, 'h' => 128, 'hint' => 'White Bishop'],
                ['slot' => 'chess_piece_wN', 'label' => 'White Knight ♘', 'w' => 128, 'h' => 128, 'hint' => 'White Knight'],
                ['slot' => 'chess_piece_wP', 'label' => 'White Pawn ♙', 'w' => 128, 'h' => 128, 'hint' => 'White Pawn'],
            ];
            foreach ($whitePieces as $a):
                $current = $theme['assets'][$a['slot']] ?? null;
            ?>
            <div class="field">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="slot" value="<?= $a['slot'] ?>">
                    <input type="hidden" name="expected_w" value="<?= $a['w'] ?>">
                    <input type="hidden" name="expected_h" value="<?= $a['h'] ?>">
                    <label><?= $a['label'] ?></label>
                    <div class="upload-box" onclick="this.querySelector('input[type=file]').click()">
                        <input type="file" name="asset" accept=".svg,.png,.webp" style="display:none" onchange="this.form.submit()">
                        <?php if ($current): ?>
                        <div class="current"><img src="<?= $current ?>" style="width:64px;height:64px;object-fit:contain;background:#F0D9B5;border-radius:8px;padding:4px;"></div>
                        <div style="font-size:10px;color:#34D399;margin-top:4px;">✓ Uploaded</div>
                        <?php else: ?>
                        📤 Click to upload
                        <?php endif; ?>
                        <div class="size-hint"><?= $a['w'] ?>×<?= $a['h'] ?>px — <?= $a['hint'] ?></div>
                    </div>
                </form>
            </div>
            <?php endforeach; ?>
        </div>

        <h3 style="color:#f8fafc;margin:20px 0 12px;">⬛ Black Pieces</h3>
        <div class="grid">
            <?php
            $blackPieces = [
                ['slot' => 'chess_piece_bK', 'label' => 'Black King ♚', 'w' => 128, 'h' => 128, 'hint' => 'Black King'],
                ['slot' => 'chess_piece_bQ', 'label' => 'Black Queen ♛', 'w' => 128, 'h' => 128, 'hint' => 'Black Queen'],
                ['slot' => 'chess_piece_bR', 'label' => 'Black Rook ♜', 'w' => 128, 'h' => 128, 'hint' => 'Black Rook'],
                ['slot' => 'chess_piece_bB', 'label' => 'Black Bishop ♝', 'w' => 128, 'h' => 128, 'hint' => 'Black Bishop'],
                ['slot' => 'chess_piece_bN', 'label' => 'Black Knight ♞', 'w' => 128, 'h' => 128, 'hint' => 'Black Knight'],
                ['slot' => 'chess_piece_bP', 'label' => 'Black Pawn ♟', 'w' => 128, 'h' => 128, 'hint' => 'Black Pawn'],
            ];
            foreach ($blackPieces as $a):
                $current = $theme['assets'][$a['slot']] ?? null;
            ?>
            <div class="field">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="slot" value="<?= $a['slot'] ?>">
                    <input type="hidden" name="expected_w" value="<?= $a['w'] ?>">
                    <input type="hidden" name="expected_h" value="<?= $a['h'] ?>">
                    <label><?= $a['label'] ?></label>
                    <div class="upload-box" onclick="this.querySelector('input[type=file]').click()">
                        <input type="file" name="asset" accept=".svg,.png,.webp" style="display:none" onchange="this.form.submit()">
                        <?php if ($current): ?>
                        <div class="current"><img src="<?= $current ?>" style="width:64px;height:64px;object-fit:contain;background:#B58863;border-radius:8px;padding:4px;"></div>
                        <div style="font-size:10px;color:#34D399;margin-top:4px;">✓ Uploaded</div>
                        <?php else: ?>
                        📤 Click to upload
                        <?php endif; ?>
                        <div class="size-hint"><?= $a['w'] ?>×<?= $a['h'] ?>px — <?= $a['hint'] ?></div>
                    </div>
                </form>
            </div>
            <?php endforeach; ?>
        </div>
    </div>


    <!-- BACKGAMMON SETTINGS -->
    <h2>🎲 Backgammon Settings</h2>
    <div class="section">
        <div class="grid">
            <?php
            $bgSettings = [
                ['key' => 'bg_move_duration', 'label' => 'Move Duration (ms)', 'default' => '320', 'hint' => 'Piece travel speed (300-500)', 'type' => 'number'],
                ['key' => 'bg_dice_duration', 'label' => 'Dice Roll Duration (ms)', 'default' => '700', 'hint' => 'Dice animation length (500-900)', 'type' => 'number'],
                ['key' => 'bg_bot_delay', 'label' => 'Bot Delay (ms)', 'default' => '700', 'hint' => 'Delay before bot moves', 'type' => 'number'],
                ['key' => 'bg_particle_count', 'label' => 'Hit Particles', 'default' => '12', 'hint' => 'Particles on hit (0=disable)', 'type' => 'number'],
                ['key' => 'bg_arc_height', 'label' => 'Move Arc Height', 'default' => '0.4', 'hint' => 'Arc ratio (0-1)', 'type' => 'text'],
                ['key' => 'bg_turn_timeout', 'label' => 'Turn Timeout (sec)', 'default' => '30', 'hint' => 'Online play timeout', 'type' => 'number'],
                ['key' => 'bg_confetti_count', 'label' => 'Win Confetti Count', 'default' => '30', 'hint' => 'Confetti particles on win', 'type' => 'number'],
            ];
            foreach ($bgSettings as $s):
                $val = $theme[$s['key']] ?? $s['default'];
            ?>
            <div class="field">
                <label><?= $s['label'] ?></label>
                <input type="<?= $s['type'] ?>" name="theme[<?= $s['key'] ?>]" value="<?= $val ?>">
                <div class="hint"><?= $s['hint'] ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- ANIMATIONS -->
    <h2>⚡ Animations & Motion</h2>
    <div class="section">
        <div class="grid">
            <?php
            $anims = [
                ['key' => 'anim_speed', 'label' => 'Transition Speed (ms)', 'default' => '250', 'hint' => 'Default transition duration', 'type' => 'number'],
                ['key' => 'anim_fast', 'label' => 'Fast Speed (ms)', 'default' => '150', 'hint' => 'Buttons, feedback', 'type' => 'number'],
                ['key' => 'anim_slow', 'label' => 'Slow Speed (ms)', 'default' => '400', 'hint' => 'Scene transitions', 'type' => 'number'],
                ['key' => 'btn_scale', 'label' => 'Button Press Scale', 'default' => '0.92', 'hint' => '0.9 = strong press, 0.97 = soft press', 'type' => 'text'],
                ['key' => 'border_radius', 'label' => 'Border Radius (px)', 'default' => '12', 'hint' => 'Button corner radius', 'type' => 'number'],
                ['key' => 'card_radius', 'label' => 'Card Radius (px)', 'default' => '20', 'hint' => 'Card & modal corner radius', 'type' => 'number'],
            ];
            foreach ($anims as $a):
                $val = $theme[$a['key']] ?? $a['default'];
            ?>
            <div class="field">
                <label><?= $a['label'] ?></label>
                <input type="<?= $a['type'] ?>" name="theme[<?= $a['key'] ?>]" value="<?= $val ?>">
                <div class="hint"><?= $a['hint'] ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- BUTTON SHAPES -->
    <h2>🔘 Button Shapes</h2>
    <div class="section">
        <div class="grid">
            <?php
            $shapes = [
                ['key' => 'btn_radius', 'label' => 'Primary Button Radius (px)', 'default' => '9999', 'hint' => '9999 = pill, 12 = soft rect, 0 = sharp', 'type' => 'number'],
                ['key' => 'btn_secondary_radius', 'label' => 'Secondary Button Radius (px)', 'default' => '9999', 'hint' => 'Cancel & option buttons', 'type' => 'number'],
                ['key' => 'btn_height', 'label' => 'Button Height (px)', 'default' => '44', 'hint' => 'Min button height — 44 for touch', 'type' => 'number'],
                ['key' => 'btn_font_weight', 'label' => 'Button Font Weight', 'default' => '700', 'hint' => '400=normal, 600=semi, 700=bold, 800=extra', 'type' => 'number'],
                ['key' => 'btn_shadow', 'label' => 'Primary Button Shadow', 'default' => '0 4px 16px rgba(228,172,56,0.3)', 'hint' => 'Full CSS box-shadow', 'type' => 'text'],
                ['key' => 'card_border_width', 'label' => 'Card Border Width (px)', 'default' => '1', 'hint' => '0 = none, 1 = subtle, 2 = visible', 'type' => 'number'],
                ['key' => 'input_radius', 'label' => 'Input Field Radius (px)', 'default' => '12', 'hint' => 'Text & password fields', 'type' => 'number'],
            ];
            foreach ($shapes as $s):
                $val = $theme[$s['key']] ?? $s['default'];
            ?>
            <div class="field">
                <label><?= $s['label'] ?></label>
                <input type="<?= $s['type'] ?>" name="theme[<?= $s['key'] ?>]" value="<?= $val ?>">
                <div class="hint"><?= $s['hint'] ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <button type="submit">💾 Save All Changes</button>
    </form>

    <!-- JUICE SETTINGS -->
    <h2>🧃 Juice Effects</h2>
    <div class="section">
        <div class="grid">
            <?php
            $juiceSettings = [
                ['key' => 'juice_particles', 'label' => 'Enable Particles', 'default' => '1', 'hint' => '1=enabled, 0=disabled', 'type' => 'number'],
                ['key' => 'juice_shake_intensity', 'label' => 'Shake Intensity', 'default' => '4', 'hint' => '0=none, 2=light, 4=normal, 8=strong', 'type' => 'number'],
                ['key' => 'juice_haptic', 'label' => 'Enable Haptic', 'default' => '1', 'hint' => '1=enabled, 0=disabled', 'type' => 'number'],
                ['key' => 'juice_confetti_count', 'label' => 'Confetti Particles', 'default' => '30', 'hint' => 'On win — 0 to disable', 'type' => 'number'],
                ['key' => 'juice_coin_fly_count', 'label' => 'Flying Coins Count', 'default' => '5', 'hint' => 'Coins flying to HUD', 'type' => 'number'],
                ['key' => 'juice_bounce_scale', 'label' => 'Bounce Scale', 'default' => '1.08', 'hint' => '1.0=none, 1.05=subtle, 1.15=exaggerated', 'type' => 'text'],
                ['key' => 'juice_slam_scale', 'label' => 'Slam Scale', 'default' => '1.5', 'hint' => 'Result screen impact', 'type' => 'text'],
                ['key' => 'juice_float_amount', 'label' => 'Float Distance (px)', 'default' => '5', 'hint' => 'Home page tile hover motion', 'type' => 'number'],
            ];
            foreach ($juiceSettings as $j):
                $val = $theme[$j['key']] ?? $j['default'];
            ?>
            <div class="field">
                <label><?= $j['label'] ?></label>
                <input type="<?= $j['type'] ?>" name="theme[<?= $j['key'] ?>]" value="<?= $val ?>">
                <div class="hint"><?= $j['hint'] ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- LUDO PAWNS -->
    <h2>🎯 Ludo Pawns</h2>
    <p style="color:#64748b;font-size:12px;margin-bottom:16px;">Upload PNG or SVG for Ludo pawns — they animate with the same bounce on the board. Default is geometric shape.</p>
    <div class="section">
        <div class="grid">
            <?php
            $ludoPawns = [
                ['slot' => 'ludo_pawn_red', 'label' => '🔴 Red Pawn', 'w' => 64, 'h' => 64, 'hint' => 'Player 1 — Red pawn sprite'],
                ['slot' => 'ludo_pawn_green', 'label' => '🟢 Green Pawn', 'w' => 64, 'h' => 64, 'hint' => 'Player 2 — Green pawn sprite'],
                ['slot' => 'ludo_pawn_yellow', 'label' => '🟡 Yellow Pawn', 'w' => 64, 'h' => 64, 'hint' => 'Player 3 — Yellow pawn sprite'],
                ['slot' => 'ludo_pawn_blue', 'label' => '🔵 Blue Pawn', 'w' => 64, 'h' => 64, 'hint' => 'Player 4 — Blue pawn sprite'],
            ];
            foreach ($ludoPawns as $a):
                $current = $theme['assets'][$a['slot']] ?? null;
            ?>
            <div class="field">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="slot" value="<?= $a['slot'] ?>">
                    <input type="hidden" name="expected_w" value="<?= $a['w'] ?>">
                    <input type="hidden" name="expected_h" value="<?= $a['h'] ?>">
                    <label><?= $a['label'] ?></label>
                    <div class="upload-box" onclick="this.querySelector('input[type=file]').click()">
                        <input type="file" name="asset" accept=".svg,.png,.webp" style="display:none" onchange="this.form.submit()">
                        <?php if ($current): ?>
                        <div class="current"><img src="<?= $current ?>" style="width:48px;height:48px;object-fit:contain;background:#2a2a4a;border-radius:8px;padding:4px;"></div>
                        <div style="font-size:10px;color:#34D399;margin-top:4px;">✓ Uploaded</div>
                        <?php else: ?>
                        📤 Click to upload
                        <?php endif; ?>
                        <div class="size-hint"><?= $a['w'] ?>×<?= $a['h'] ?>px — <?= $a['hint'] ?></div>
                    </div>
                </form>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- SOUND EFFECTS -->
    <h2>🔊 Sound Effects</h2>
    <p style="color:#64748b;font-size:12px;margin-bottom:16px;">Upload MP3/OGG/WAV to replace generated sounds. Default is synthesized electronic audio.</p>
    <div class="section">
        <div class="grid">
            <?php
            $soundSlots = [
                ['slot' => 'sfx_click', 'label' => '🖱️ Click', 'hint' => 'UI buttons — very short'],
                ['slot' => 'sfx_move', 'label' => '♟ Move', 'hint' => 'Chess/Ludo piece move'],
                ['slot' => 'sfx_capture', 'label' => '⚔️ Capture', 'hint' => 'Capturing a piece'],
                ['slot' => 'sfx_check', 'label' => '⚠️ Check', 'hint' => 'King under attack'],
                ['slot' => 'sfx_castle', 'label' => '🏰 Castle', 'hint' => 'Chess castling move'],
                ['slot' => 'sfx_gameOver', 'label' => '🏁 Game Over', 'hint' => 'Match end'],
                ['slot' => 'sfx_win', 'label' => '🏆 Win', 'hint' => 'Victory sound'],
                ['slot' => 'sfx_lose', 'label' => '💀 Lose', 'hint' => 'Defeat sound'],
                ['slot' => 'sfx_coin', 'label' => '🪙 Coin', 'hint' => 'Earn coins — short metallic'],
                ['slot' => 'sfx_levelUp', 'label' => '⬆️ Level Up', 'hint' => 'Level up fanfare'],
                ['slot' => 'sfx_notification', 'label' => '🔔 Notification', 'hint' => 'Incoming notification'],
                ['slot' => 'sfx_dice', 'label' => '🎲 Dice Roll', 'hint' => 'Ludo dice roll'],
                ['slot' => 'sfx_place', 'label' => '📍 Place', 'hint' => 'Domino tile placed'],
                ['slot' => 'sfx_reward', 'label' => '🎁 Reward', 'hint' => 'Daily reward open'],
                ['slot' => 'sfx_match_found', 'label' => '🎯 Match Found', 'hint' => 'Opponent paired'],
                ['slot' => 'sfx_dice_shake', 'label' => '🎲 Dice Shake', 'hint' => 'Shake before throw — Ludo'],
                ['slot' => 'sfx_boost', 'label' => '🚀 Boost / Six', 'hint' => 'Rolled 6 — extra turn — Ludo'],
                ['slot' => 'sfx_piece_home', 'label' => '🏠 Piece Home', 'hint' => 'Piece reached center — Ludo'],
                ['slot' => 'sfx_turn_start', 'label' => '🔔 Turn Start', 'hint' => 'Your turn alert — Ludo/Domino'],
                ['slot' => 'sfx_emote', 'label' => '💬 Emote', 'hint' => 'Sending emoji/social phrase'],
                ['slot' => 'sfx_bg_dice_roll', 'label' => '🎲 BG Dice Roll', 'hint' => 'Backgammon dice roll'],
                ['slot' => 'sfx_bg_piece_move', 'label' => '♟️ BG Piece Move', 'hint' => 'Move piece on board — Backgammon'],
                ['slot' => 'sfx_bg_piece_hit', 'label' => '💥 BG Hit', 'hint' => 'Send opponent to bar — Backgammon'],
                ['slot' => 'sfx_bg_bear_off', 'label' => '✅ BG Bear Off', 'hint' => 'Bear off piece — Backgammon'],
                ['slot' => 'sfx_bg_double', 'label' => '⬆️ BG Double', 'hint' => 'Doubling cube — Backgammon'],
                ['slot' => 'sfx_bg_win_game', 'label' => '🎉 BG Win Game', 'hint' => 'Win a single game — Backgammon'],
                ['slot' => 'sfx_bg_win_match', 'label' => '🏆 BG Win Match', 'hint' => 'Win the match — Backgammon'],
            ];
            foreach ($soundSlots as $s):
                $current = $theme['assets'][$s['slot']] ?? null;
            ?>
            <div class="field">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="slot" value="<?= $s['slot'] ?>">
                    <input type="hidden" name="expected_w" value="0">
                    <input type="hidden" name="expected_h" value="0">
                    <label><?= $s['label'] ?></label>
                    <div class="upload-box" onclick="this.querySelector('input[type=file]').click()">
                        <input type="file" name="asset" accept=".mp3,.ogg,.wav,.m4a,.webm" style="display:none" onchange="this.form.submit()">
                        <?php if ($current): ?>
                        <div style="font-size:11px;color:#34D399;">✓ Uploaded</div>
                        <audio controls src="<?= $current ?>" style="width:100%;height:28px;margin-top:4px;"></audio>
                        <?php else: ?>
                        🔊 Click to upload audio
                        <?php endif; ?>
                        <div class="size-hint"><?= $s['hint'] ?></div>
                    </div>
                </form>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- EMOJI REPLACEMENTS -->
    <h2>😀 Emoji Replacements</h2>
    <p style="color:#64748b;font-size:12px;margin-bottom:16px;">Replace any emoji with SVG or PNG — shown at the same size without distortion</p>
    <div class="section">
        <div class="grid">
            <?php
            $emojiSlots = [
                ['key' => 'trophy', 'emoji' => '🏆', 'label' => 'Win Trophy', 'size' => 72, 'hint' => 'Win result screen'],
                ['key' => 'skull', 'emoji' => '💀', 'label' => 'Loss Icon', 'size' => 72, 'hint' => 'Loss result screen'],
                ['key' => 'handshake', 'emoji' => '🤝', 'label' => 'Draw Icon', 'size' => 72, 'hint' => 'Draw result screen'],
                ['key' => 'gift', 'emoji' => '🎁', 'label' => 'Reward Box', 'size' => 48, 'hint' => 'Daily reward screen'],
                ['key' => 'robot', 'emoji' => '🤖', 'label' => 'Bot Icon', 'size' => 32, 'hint' => 'Next to bot opponent name'],
                ['key' => 'star', 'emoji' => '⭐', 'label' => 'Rating Star', 'size' => 20, 'hint' => 'Review screen'],
                ['key' => 'dice', 'emoji' => '🎲', 'label' => 'Dice Icon', 'size' => 48, 'hint' => 'Ludo tile + roll button'],
                ['key' => 'gamepad', 'emoji' => '🎮', 'label' => 'Single Player', 'size' => 24, 'hint' => 'Game menu — vs bot'],
                ['key' => 'swords', 'emoji' => '⚔️', 'label' => 'Multiplayer', 'size' => 24, 'hint' => 'Game menu — online'],
                ['key' => 'medal_gold', 'emoji' => '🥇', 'label' => 'Gold Medal', 'size' => 20, 'hint' => '#1 in leaderboard'],
                ['key' => 'medal_silver', 'emoji' => '🥈', 'label' => 'Silver Medal', 'size' => 20, 'hint' => '#2 in leaderboard'],
                ['key' => 'medal_bronze', 'emoji' => '🥉', 'label' => 'Bronze Medal', 'size' => 20, 'hint' => '#3 in leaderboard'],
                ['key' => 'coin', 'emoji' => '🪙', 'label' => 'Coin', 'size' => 16, 'hint' => 'Next to shop prices'],
                ['key' => 'gem', 'emoji' => '💎', 'label' => 'Gem', 'size' => 16, 'hint' => 'Next to gem prices'],
                ['key' => 'person', 'emoji' => '👤', 'label' => 'Default Avatar', 'size' => 32, 'hint' => 'Default player avatar'],
                ['key' => 'people', 'emoji' => '👥', 'label' => 'Friends Icon', 'size' => 32, 'hint' => 'Empty friends screen'],
                ['key' => 'bell', 'emoji' => '🔔', 'label' => 'Notification Bell', 'size' => 18, 'hint' => 'Header notifications icon'],
                ['key' => 'speaker_on', 'emoji' => '🔊', 'label' => 'Sound On', 'size' => 20, 'hint' => 'Sound settings'],
                ['key' => 'speaker_off', 'emoji' => '🔇', 'label' => 'Sound Off', 'size' => 20, 'hint' => 'Sound settings'],
                ['key' => 'art', 'emoji' => '🎨', 'label' => 'Shop Icon', 'size' => 24, 'hint' => 'Shop cards'],
                ['key' => 'puzzle', 'emoji' => '🧩', 'label' => 'Puzzles', 'size' => 16, 'hint' => 'Puzzles menu button'],
                ['key' => 'chart', 'emoji' => '📊', 'label' => 'Analysis', 'size' => 16, 'hint' => 'Analysis button'],
                ['key' => 'clipboard', 'emoji' => '📋', 'label' => 'My Games', 'size' => 16, 'hint' => 'Match history button'],
                ['key' => 'share', 'emoji' => '📤', 'label' => 'Share', 'size' => 16, 'hint' => 'Share button'],
                ['key' => 'checkmark', 'emoji' => '✅', 'label' => 'Success mark', 'size' => 20, 'hint' => 'Operation success feedback'],
                ['key' => 'cross', 'emoji' => '❌', 'label' => 'Error mark', 'size' => 20, 'hint' => 'Operation failure feedback'],
                ['key' => 'flag', 'emoji' => '⚐', 'label' => 'Resign flag', 'size' => 16, 'hint' => 'Chess resign button'],
                ['key' => 'book', 'emoji' => '📖', 'label' => 'Book/Theory', 'size' => 14, 'hint' => 'Move classification: book move'],
                // HUD icons
                ['key' => 'hud_coin', 'emoji' => '●', 'label' => 'HUD coin dot', 'size' => 16, 'hint' => 'Coin indicator in top HUD bar'],
                ['key' => 'hud_gem', 'emoji' => '◆', 'label' => 'HUD gem diamond', 'size' => 16, 'hint' => 'Gem indicator in top HUD bar'],
                ['key' => 'hud_level', 'emoji' => '⬡', 'label' => 'HUD level hex', 'size' => 16, 'hint' => 'Level indicator in top HUD bar'],
                // Game specific
                ['key' => 'lightning', 'emoji' => '⚡', 'label' => 'Puzzle rating bolt', 'size' => 16, 'hint' => 'Puzzle difficulty indicator'],
                ['key' => 'best_move_star', 'emoji' => '★', 'label' => 'Best move star', 'size' => 14, 'hint' => 'Move classification: best move'],
                ['key' => 'particle_star', 'emoji' => '✦', 'label' => 'Particle star', 'size' => 10, 'hint' => 'Star burst particle effect'],
                ['key' => 'backgammon_icon', 'emoji' => '◎', 'label' => 'Backgammon game icon', 'size' => 48, 'hint' => 'Home screen backgammon tile'],
                ['key' => 'domino_tile', 'emoji' => '⬚', 'label' => 'Domino game icon', 'size' => 48, 'hint' => 'Home screen domino tile'],
                ['key' => 'ludo_hex', 'emoji' => '⬡', 'label' => 'Ludo game icon', 'size' => 48, 'hint' => 'Home screen ludo tile (if not using dice)'],
                ['key' => 'chess_pawn', 'emoji' => '♟', 'label' => 'Chess pawn', 'size' => 48, 'hint' => 'Home screen chess tile'],
                // Social
                ['key' => 'challenge_swords', 'emoji' => '⚔️', 'label' => 'Challenge swords', 'size' => 20, 'hint' => 'Challenge friend to game'],
                ['key' => 'search_icon', 'emoji' => '🔍', 'label' => 'Search icon', 'size' => 16, 'hint' => 'Search button in social'],
                ['key' => 'online_dot', 'emoji' => '🟢', 'label' => 'Online indicator', 'size' => 12, 'hint' => 'Online status dot'],
                // Dice faces
                ['key' => 'dice_1', 'emoji' => '⚀', 'label' => 'Dice face 1', 'size' => 56, 'hint' => 'Ludo dice — shown when rolled 1'],
                ['key' => 'dice_2', 'emoji' => '⚁', 'label' => 'Dice face 2', 'size' => 56, 'hint' => 'Ludo dice — shown when rolled 2'],
                ['key' => 'dice_3', 'emoji' => '⚂', 'label' => 'Dice face 3', 'size' => 56, 'hint' => 'Ludo dice — shown when rolled 3'],
                ['key' => 'dice_4', 'emoji' => '⚃', 'label' => 'Dice face 4', 'size' => 56, 'hint' => 'Ludo dice — shown when rolled 4'],
                ['key' => 'dice_5', 'emoji' => '⚄', 'label' => 'Dice face 5', 'size' => 56, 'hint' => 'Ludo dice — shown when rolled 5'],
                ['key' => 'dice_6', 'emoji' => '⚅', 'label' => 'Dice face 6', 'size' => 56, 'hint' => 'Ludo dice — shown when rolled 6 (golden glow)'],
                // Puzzle themes
                ['key' => 'theme_fork', 'emoji' => '🔱', 'label' => 'Fork theme', 'size' => 16, 'hint' => 'Puzzle theme: fork'],
                ['key' => 'theme_pin', 'emoji' => '📌', 'label' => 'Pin theme', 'size' => 16, 'hint' => 'Puzzle theme: pin'],
                ['key' => 'theme_castle', 'emoji' => '🏰', 'label' => 'Back rank theme', 'size' => 16, 'hint' => 'Puzzle theme: back rank mate'],
                ['key' => 'theme_crown', 'emoji' => '👑', 'label' => 'Promotion theme', 'size' => 16, 'hint' => 'Puzzle theme: promotion'],
                ['key' => 'theme_sacrifice', 'emoji' => '💥', 'label' => 'Sacrifice theme', 'size' => 16, 'hint' => 'Puzzle theme: sacrifice'],
                // Tournaments
                ['key' => 'tournament_cup', 'emoji' => '🏆', 'label' => 'Tournament trophy', 'size' => 20, 'hint' => 'Tournament list & leaderboard button'],
                ['key' => 'money_bag', 'emoji' => '💰', 'label' => 'Entry fee', 'size' => 14, 'hint' => 'Tournament entry fee indicator'],
                // Misc
                ['key' => 'thinking_dots', 'emoji' => '●●●', 'label' => 'Bot thinking dots', 'size' => 14, 'hint' => 'Chess bot thinking indicator'],
                ['key' => 'building', 'emoji' => '🏛️', 'label' => 'Organization', 'size' => 32, 'hint' => 'Organization/club icon'],
                // Social & Navigation
                ['key' => 'crown', 'emoji' => '👑', 'label' => 'Crown/Owner', 'size' => 16, 'hint' => 'Group owner / top rank badge'],
                ['key' => 'mute', 'emoji' => '🔇', 'label' => 'Muted user', 'size' => 16, 'hint' => 'Muted player indicator'],
                ['key' => 'block', 'emoji' => '🚫', 'label' => 'Blocked', 'size' => 16, 'hint' => 'Blocked user indicator'],
                ['key' => 'hourglass', 'emoji' => '⏳', 'label' => 'Waiting', 'size' => 24, 'hint' => 'Matchmaking / waiting state'],
                ['key' => 'play', 'emoji' => '▶️', 'label' => 'Play button', 'size' => 24, 'hint' => 'Start/play action'],
                ['key' => 'exit', 'emoji' => '🚪', 'label' => 'Exit', 'size' => 20, 'hint' => 'Leave game / exit'],
                ['key' => 'clock', 'emoji' => '⏱️', 'label' => 'Timer', 'size' => 16, 'hint' => 'Turn timer / time control'],
                ['key' => 'live', 'emoji' => '🔴', 'label' => 'Live dot', 'size' => 12, 'hint' => 'Live match indicator'],
                ['key' => 'calendar', 'emoji' => '📅', 'label' => 'Calendar', 'size' => 16, 'hint' => 'Tournament date/schedule'],
                ['key' => 'news', 'emoji' => '📢', 'label' => 'News', 'size' => 20, 'hint' => 'Announcements/news feed'],
                ['key' => 'group', 'emoji' => '👥', 'label' => 'Group', 'size' => 20, 'hint' => 'Groups/team section'],
                ['key' => 'inbox', 'emoji' => '📥', 'label' => 'Inbox', 'size' => 20, 'hint' => 'Messages inbox'],
                ['key' => 'sleeping', 'emoji' => '💤', 'label' => 'Offline/Sleeping', 'size' => 14, 'hint' => 'Player is offline'],
                ['key' => 'send', 'emoji' => '✉️', 'label' => 'Send message', 'size' => 16, 'hint' => 'Send button in chat'],
                ['key' => 'wave', 'emoji' => '👋', 'label' => 'Wave/Hello', 'size' => 20, 'hint' => 'Friend request greeting'],
                ['key' => 'camera', 'emoji' => '📷', 'label' => 'Camera', 'size' => 20, 'hint' => 'Upload photo button'],
                ['key' => 'arrow_back', 'emoji' => '←', 'label' => 'Back arrow', 'size' => 16, 'hint' => 'Navigation back button'],
                ['key' => 'globe', 'emoji' => '🌐', 'label' => 'Globe/Language', 'size' => 16, 'hint' => 'Language selector'],
                ['key' => 'save', 'emoji' => '💾', 'label' => 'Save', 'size' => 16, 'hint' => 'Save settings button'],
                ['key' => 'lock', 'emoji' => '🔒', 'label' => 'Lock', 'size' => 16, 'hint' => 'Locked/premium content'],
                ['key' => 'document', 'emoji' => '📄', 'label' => 'Document', 'size' => 16, 'hint' => 'Terms / policy docs'],
                ['key' => 'target', 'emoji' => '🎯', 'label' => 'Target/Challenge', 'size' => 20, 'hint' => 'Daily challenge objective'],
                ['key' => 'green_circle', 'emoji' => '🟢', 'label' => 'Online dot', 'size' => 10, 'hint' => 'Player is online'],
                ['key' => 'gray_circle', 'emoji' => '⚫', 'label' => 'Offline dot', 'size' => 10, 'hint' => 'Player is offline'],
                ['key' => 'check', 'emoji' => '✓', 'label' => 'Checkmark', 'size' => 14, 'hint' => 'Selection/completion mark'],
            ];
            foreach ($emojiSlots as $e):
                $current = $theme['assets']['emoji_' . $e['key']] ?? null;
            ?>
            <div class="field">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="slot" value="emoji_<?= $e['key'] ?>">
                    <input type="hidden" name="expected_w" value="<?= $e['size'] ?>">
                    <input type="hidden" name="expected_h" value="<?= $e['size'] ?>">
                    <label><?= $e['emoji'] ?> <?= $e['label'] ?></label>
                    <div class="upload-box" onclick="this.querySelector('input[type=file]').click()">
                        <input type="file" name="asset" accept=".svg,.png,.jpg,.webp" style="display:none" onchange="this.form.submit()">
                        <?php if ($current): ?>
                        <div class="current"><img src="<?= $current ?>" style="width:<?= min($e['size'], 48) ?>px;height:<?= min($e['size'], 48) ?>px;object-fit:contain;"></div>
                        <?php else: ?>
                        <span style="font-size:24px;"><?= $e['emoji'] ?></span> → Upload replacement
                        <?php endif; ?>
                        <div class="size-hint"><?= $e['size'] ?>×<?= $e['size'] ?>px — <?= $e['hint'] ?></div>
                    </div>
                </form>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- ASSET UPLOADS -->
    <h2>📦 Visual Assets</h2>
    <p style="color:#64748b;font-size:12px;margin-bottom:16px;">Upload SVG or PNG — appears immediately as default for all players</p>

    <div class="section">
        <div class="grid">
            <?php
            $assetSlots = [
                ['slot' => 'logo', 'label' => 'Platform Logo', 'w' => 200, 'h' => 60, 'hint' => 'Header logo — transparent SVG preferred'],
                ['slot' => 'logo_icon', 'label' => 'Logo Icon (Square)', 'w' => 64, 'h' => 64, 'hint' => 'Compact logo icon'],
                ['slot' => 'splash_bg', 'label' => 'Splash Background', 'w' => 1080, 'h' => 1920, 'hint' => 'Full background on app launch'],
                ['slot' => 'favicon', 'label' => 'Favicon', 'w' => 32, 'h' => 32, 'hint' => 'Browser tab icon'],
                ['slot' => 'coin_icon', 'label' => 'Coin Icon (HUD)', 'w' => 24, 'h' => 24, 'hint' => 'Next to coin count in header'],
                ['slot' => 'gem_icon', 'label' => 'Gem Icon (HUD)', 'w' => 24, 'h' => 24, 'hint' => 'Next to gem count in header'],
                ['slot' => 'xp_icon', 'label' => 'Level Icon (HUD)', 'w' => 24, 'h' => 24, 'hint' => 'Next to level number'],
                ['slot' => 'chess_icon', 'label' => 'Chess Icon', 'w' => 64, 'h' => 64, 'hint' => 'Chess tile on home screen'],
                ['slot' => 'domino_icon', 'label' => 'Domino Icon', 'w' => 64, 'h' => 64, 'hint' => 'Domino tile on home screen'],
                ['slot' => 'ludo_icon', 'label' => 'Ludo Icon', 'w' => 64, 'h' => 64, 'hint' => 'Ludo tile on home screen'],
                ['slot' => 'backgammon_icon', 'label' => 'Backgammon Icon', 'w' => 64, 'h' => 64, 'hint' => 'Backgammon tile on home screen'],
                ['slot' => 'win_trophy', 'label' => 'Win Trophy', 'w' => 128, 'h' => 128, 'hint' => 'Match result — win'],
                ['slot' => 'loss_icon', 'label' => 'Loss Icon', 'w' => 128, 'h' => 128, 'hint' => 'Match result — loss'],
                ['slot' => 'draw_icon', 'label' => 'Draw Icon', 'w' => 128, 'h' => 128, 'hint' => 'Match result — draw'],
                ['slot' => 'daily_reward', 'label' => 'Daily Reward Box', 'w' => 128, 'h' => 128, 'hint' => 'Daily reward screen'],
                ['slot' => 'rank_gold', 'label' => 'Gold Medal (#1)', 'w' => 32, 'h' => 32, 'hint' => 'Next to #1 in leaderboard'],
                ['slot' => 'rank_silver', 'label' => 'Silver Medal (#2)', 'w' => 32, 'h' => 32, 'hint' => 'Next to #2 in leaderboard'],
                ['slot' => 'rank_bronze', 'label' => 'Bronze Medal (#3)', 'w' => 32, 'h' => 32, 'hint' => 'Next to #3 in leaderboard'],
                ['slot' => 'default_avatar', 'label' => 'Default Player Avatar', 'w' => 128, 'h' => 128, 'hint' => 'Shown if player has no photo'],
                ['slot' => 'notification_bell', 'label' => 'Notification Bell', 'w' => 24, 'h' => 24, 'hint' => 'Header notification icon'],
                ['slot' => 'tab_play', 'label' => 'Tab Icon: Play', 'w' => 24, 'h' => 24, 'hint' => 'Bottom navigation bar'],
                ['slot' => 'tab_rank', 'label' => 'Tab Icon: Leaderboard', 'w' => 24, 'h' => 24, 'hint' => 'Bottom navigation bar'],
                ['slot' => 'tab_social', 'label' => 'Tab Icon: Friends', 'w' => 24, 'h' => 24, 'hint' => 'Bottom navigation bar'],
                ['slot' => 'tab_shop', 'label' => 'Tab Icon: Shop', 'w' => 24, 'h' => 24, 'hint' => 'Bottom navigation bar'],
                ['slot' => 'tab_profile', 'label' => 'Tab Icon: Profile', 'w' => 24, 'h' => 24, 'hint' => 'Bottom navigation bar'],
            ];
            foreach ($assetSlots as $a):
                $current = $theme['assets'][$a['slot']] ?? null;
                $displayW = min($a['w'], 80);
                $displayH = min($a['h'], 80);
            ?>
            <div class="field">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="slot" value="<?= $a['slot'] ?>">
                    <input type="hidden" name="expected_w" value="<?= $a['w'] ?>">
                    <input type="hidden" name="expected_h" value="<?= $a['h'] ?>">
                    <label><?= $a['label'] ?></label>
                    <div class="upload-box" onclick="this.querySelector('input[type=file]').click()">
                        <input type="file" name="asset" accept=".svg,.png,.jpg,.jpeg,.webp,.gif,.ico" style="display:none" onchange="this.form.submit()">
                        <?php if ($current): ?>
                        <div class="current"><img src="<?= $current ?>" style="width:<?= $displayW ?>px;height:<?= $displayH ?>px;object-fit:contain;image-rendering:auto;"></div>
                        <div style="font-size:10px;color:#64748b;margin-top:4px;">✓ Uploaded</div>
                        <?php else: ?>
                        📤 Click to upload
                        <?php endif; ?>
                        <div class="size-hint"><?= $a['w'] ?>×<?= $a['h'] ?>px — <?= $a['hint'] ?></div>
                    </div>
                </form>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

</div>

<!-- Sticky save bar -->
<div id="save-bar" style="position:fixed;bottom:0;left:0;right:0;background:#0f0f1e;border-top:1px solid rgba(255,255,255,0.1);padding:12px 20px;display:flex;align-items:center;justify-content:space-between;z-index:999;">
  <span id="save-status" style="font-size:12px;color:#64748b;">No unsaved changes</span>
  <button id="save-btn" onclick="saveAll()" style="background:linear-gradient(135deg,#E4AC38,#FFCC66);color:#1a1a1a;border:none;padding:10px 28px;border-radius:8px;font-weight:700;font-size:14px;cursor:pointer;opacity:0.5;pointer-events:none;transition:opacity 0.2s;">💾 Save All</button>
</div>

<script>
let hasChanges = false;
const saveBtn = document.getElementById('save-btn');
const saveStatus = document.getElementById('save-status');

function markDirty() {
  if (!hasChanges) {
    hasChanges = true;
    saveBtn.style.opacity = '1';
    saveBtn.style.pointerEvents = 'auto';
    saveStatus.textContent = '⚠️ Unsaved changes';
    saveStatus.style.color = '#FBBF24';
  }
}

function saveAll() {
  saveBtn.textContent = 'Saving...';
  saveBtn.style.opacity = '0.6';

  // Collect all theme values from inputs
  const values = {};
  document.querySelectorAll('input[name^="theme["]').forEach(input => {
    const match = input.name.match(/theme\[(.+?)\]/);
    if (match && input.value) {
      values[match[1]] = input.value;
    }
  });

  // Save directly to Supabase via API (reliable, no session dependency)
  fetch('/api/branding.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ action: 'save_theme', values })
  })
    .then(r => r.json())
    .then(data => {
      if (data.success) {
        hasChanges = false;
        saveBtn.textContent = '✓ Saved!';
        saveBtn.style.opacity = '0.5';
        saveBtn.style.pointerEvents = 'none';
        saveStatus.textContent = '✓ All changes saved to database';
        saveStatus.style.color = '#34D399';
        setTimeout(() => {
          saveBtn.textContent = '💾 Save All';
          saveStatus.textContent = 'No unsaved changes';
          saveStatus.style.color = '#64748b';
        }, 2000);
      } else {
        saveBtn.textContent = '❌ Error: ' + (data.error || 'unknown');
        saveBtn.style.opacity = '1';
      }
    })
    .catch((err) => {
      saveBtn.textContent = '❌ Network error — retry';
      saveBtn.style.opacity = '1';
    });
}

// Mark dirty on any input change (NO auto-save)
document.querySelectorAll('input[name^="theme["]').forEach(input => {
  input.addEventListener('input', markDirty);
  input.addEventListener('change', markDirty);
});

// Sync color picker ↔ text input (no save, just sync visuals)
document.querySelectorAll('.color-row').forEach(row => {
  const colorInput = row.querySelector('input[type="color"]');
  const textInput = row.querySelector('input[type="text"]');
  if (colorInput && textInput) {
    colorInput.addEventListener('input', () => { textInput.value = colorInput.value; markDirty(); });
    textInput.addEventListener('input', () => { if (/^#[0-9A-Fa-f]{6}$/.test(textInput.value)) { colorInput.value = textInput.value; markDirty(); } });
  }
});

// Warn before leaving with unsaved changes
window.addEventListener('beforeunload', (e) => {
  if (hasChanges) { e.preventDefault(); e.returnValue = ''; }
});
</script>
</body>
</html>
