<?php $pageTitle = 'EL3AB - Theme Editor'; ?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>EL3AB Admin - Theme Editor</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
  <style>
    * { margin:0; padding:0; box-sizing:border-box; }
    body { font-family:'Inter',sans-serif; background:#0a0f1a; color:#e2e8f0; min-height:100vh; }
    .login-screen { display:flex; align-items:center; justify-content:center; min-height:100vh; padding:20px; }
    .login-box { background:#1a2332; border:1px solid rgba(255,255,255,0.1); border-radius:12px; padding:32px; max-width:360px; width:100%; }
    .login-box h1 { font-size:20px; margin-bottom:20px; text-align:center; color:#e7a832; }
    .login-box input { width:100%; padding:12px; margin-bottom:12px; background:#0f1925; border:1px solid rgba(255,255,255,0.1); border-radius:8px; color:#e2e8f0; font-size:14px; }
    .login-box button { width:100%; padding:12px; background:#e7a832; color:#0f172a; border:none; border-radius:8px; font-weight:700; font-size:14px; cursor:pointer; }
    .login-box button:hover { background:#c48b1a; }
    .login-error { color:#ef4444; font-size:12px; text-align:center; margin-top:8px; display:none; }

    .admin-layout { display:flex; min-height:100vh; }
    .admin-sidebar { width:220px; background:#111827; border-right:1px solid rgba(255,255,255,0.08); padding:20px 0; flex-shrink:0; }
    .admin-sidebar h2 { font-size:14px; padding:0 16px; margin-bottom:16px; color:#e7a832; }
    .admin-sidebar .nav-item { display:block; padding:10px 16px; font-size:13px; cursor:pointer; color:#94a3b8; transition:all 0.15s; border-right:3px solid transparent; }
    .admin-sidebar .nav-item:hover { color:#e2e8f0; background:rgba(255,255,255,0.04); }
    .admin-sidebar .nav-item.active { color:#15d7ff; background:rgba(21,215,255,0.08); border-right-color:#15d7ff; }
    .admin-main { flex:1; padding:24px 32px; overflow-y:auto; max-height:100vh; }
    .admin-main h1 { font-size:22px; font-weight:700; margin-bottom:8px; }
    .admin-main .subtitle { color:#64748b; font-size:13px; margin-bottom:24px; }

    .section { margin-bottom:32px; }
    .section-title { font-size:15px; font-weight:600; margin-bottom:14px; padding-bottom:8px; border-bottom:1px solid rgba(255,255,255,0.08); display:flex; align-items:center; gap:8px; }
    .section-title .badge { font-size:10px; background:#7c4dff; padding:2px 6px; border-radius:4px; }

    .field-grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(260px, 1fr)); gap:12px; }
    .field { background:#1a2332; border:1px solid rgba(255,255,255,0.08); border-radius:8px; padding:14px; }
    .field label { display:block; font-size:11px; color:#94a3b8; margin-bottom:6px; font-weight:500; text-transform:uppercase; letter-spacing:0.5px; }
    .field .input-row { display:flex; gap:8px; align-items:center; }
    .field input[type="text"], .field input[type="color"] { flex:1; padding:8px 10px; background:#0f1925; border:1px solid rgba(255,255,255,0.1); border-radius:6px; color:#e2e8f0; font-size:13px; font-family:monospace; }
    .field input[type="color"] { width:40px; height:34px; padding:2px; cursor:pointer; flex:none; }
    .field input[type="file"] { font-size:12px; color:#94a3b8; }
    .field .preview { margin-top:8px; }
    .field .preview img { max-height:40px; border-radius:4px; }
    .field .remove-btn { font-size:11px; color:#ef4444; cursor:pointer; background:none; border:none; padding:4px 8px; }

    .save-bar { position:sticky; bottom:0; background:#111827; border-top:1px solid rgba(255,255,255,0.1); padding:16px 32px; display:flex; align-items:center; gap:12px; }
    .save-bar .btn-save { padding:10px 24px; background:#15d7ff; color:#0f172a; border:none; border-radius:8px; font-weight:700; font-size:13px; cursor:pointer; }
    .save-bar .btn-save:hover { background:#0ba8c9; }
    .save-bar .btn-reset { padding:10px 24px; background:transparent; color:#ef4444; border:1px solid #ef4444; border-radius:8px; font-size:13px; cursor:pointer; }
    .save-bar .status { font-size:12px; color:#34d399; }

    .upload-area { border:2px dashed rgba(255,255,255,0.1); border-radius:8px; padding:16px; text-align:center; cursor:pointer; transition:border-color 0.2s; }
    .upload-area:hover { border-color:rgba(21,215,255,0.4); }
    .upload-area p { font-size:12px; color:#64748b; }

    .rgba-picker { display:flex; gap:6px; align-items:center; }
    .rgba-picker input[type="color"] { width:40px; height:32px; border:none; cursor:pointer; }
    .rgba-picker .alpha-slider { width:80px; }
    .rgba-picker .alpha-label { font-size:11px; min-width:30px; }
    .rgba-picker .rgba-output { font-size:11px; width:160px; background:var(--bg-3); border:1px solid var(--border); border-radius:4px; padding:4px 6px; color:var(--text-2); }

    .theme-field { margin-bottom:12px; }
    .theme-field label { display:block; font-size:11px; color:#94a3b8; margin-bottom:6px; font-weight:500; }
    .spacing-slider { flex:1; }
    .slider-value { font-size:12px; color:#e2e8f0; min-width:48px; text-align:right; font-family:monospace; }

    .icon-grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(100px, 1fr)); gap:12px; }
    .icon-item { display:flex; flex-direction:column; align-items:center; gap:6px; padding:12px 8px; background:#1a2332; border-radius:8px; border:1px solid rgba(255,255,255,0.08); }
    .icon-item svg { width:24px; height:24px; color:#94a3b8; }
    .icon-item img { width:24px; height:24px; object-fit:contain; }
    .icon-item span { font-size:10px; color:#64748b; }
    .icon-item input[type="file"] { display:none; }
    .icon-item .icon-upload-btn { font-size:10px; padding:3px 8px; background:#15d7ff; color:#fff; border:none; border-radius:4px; cursor:pointer; }
    .icon-item .icon-reset-btn { font-size:10px; padding:3px 6px; background:#0f1925; color:#64748b; border:1px solid rgba(255,255,255,0.1); border-radius:4px; cursor:pointer; }

    .upload-hint { display:block; margin-top:4px; font-size:10px; color:#64748b; }

    @media (max-width: 768px) {
      .admin-layout { flex-direction:column; }
      .admin-sidebar { width:100%; border-right:none; border-bottom:1px solid rgba(255,255,255,0.08); padding:12px 0; display:flex; overflow-x:auto; gap:0; }
      .admin-sidebar h2 { display:none; }
      .admin-sidebar .nav-item { white-space:nowrap; border-right:none; border-bottom:3px solid transparent; padding:8px 14px; }
      .admin-sidebar .nav-item.active { border-bottom-color:#15d7ff; }
      .admin-main { padding:16px; max-height:none; }
      .field-grid { grid-template-columns:1fr; }
    }
  </style>
</head>
<body>

<!-- Login Screen -->
<div class="login-screen" id="login-screen">
  <div class="login-box">
    <h1>Theme Editor</h1>
    <input type="text" id="admin-user" placeholder="Username" autocomplete="username">
    <input type="password" id="admin-pass" placeholder="Password" autocomplete="current-password">
    <button onclick="doLogin()">Login</button>
    <p class="login-error" id="login-err">Invalid credentials</p>
  </div>
</div>

<!-- Admin Panel -->
<div class="admin-layout" id="admin-panel" style="display:none;">
  <aside class="admin-sidebar">
    <h2>Theme Editor</h2>
    <div class="nav-item active" data-section="colors">Colors</div>
    <div class="nav-item" data-section="board">Board Colors</div>
    <div class="nav-item" data-section="chess">♟ Chess Styling</div>
    <div class="nav-item" data-section="moves">Move Classes</div>
    <div class="nav-item" data-section="ui">UI / Overlays</div>
    <div class="nav-item" data-section="bots">Bot Avatars</div>
    <div class="nav-item" data-section="assets">Assets / Logo</div>
    <div class="nav-item" data-section="pieces">Chess Pieces</div>
    <div class="nav-item" data-section="ludo">Ludo</div>
    <div class="nav-item" data-section="icons">Icons</div>
    <div class="nav-item" data-section="spacing">Spacing</div>
    <div class="nav-item" data-section="domino">Domino</div>
    <div class="nav-item" data-section="backgammon">Backgammon</div>
    <div class="nav-item" data-section="icons-grid">Icons Grid</div>
  </aside>

  <div class="admin-main">
    <h1>Theme Customization</h1>
    <p class="subtitle">Changes apply globally to all players. Leave fields empty to use defaults.</p>

    <!-- Colors Section -->
    <div class="section" data-panel="colors">
      <div class="section-title">Background & Brand <span class="badge">CSS Vars</span></div>
      <div class="field-grid" id="fields-colors"></div>
    </div>

    <!-- Board Section -->
    <div class="section" data-panel="board">
      <div class="section-title">Board Theme</div>
      <div class="field-grid" id="fields-board"></div>
    </div>

    <!-- Move Classes -->
    <div class="section" data-panel="moves">
      <div class="section-title">Move Classifications</div>
      <div class="field-grid" id="fields-moves"></div>
    </div>

    <!-- UI -->
    <div class="section" data-panel="ui">
      <div class="section-title">UI / Overlays / Eval Bar</div>
      <div class="field-grid" id="fields-ui"></div>
    </div>

    <!-- Bots -->
    <div class="section" data-panel="bots">
      <div class="section-title">Bot Avatar Gradients</div>
      <div class="field-grid" id="fields-bots"></div>
    </div>

    <!-- Assets -->
    <div class="section" data-panel="assets">
      <div class="section-title">Assets / Logo / Favicon</div>
      <div class="field-grid" id="fields-assets"></div>
    </div>

    <!-- Chess Pieces -->
    <div class="section" data-panel="pieces">
      <div class="section-title">Chess Pieces (upload custom images)</div>
      <div class="field-grid" id="fields-pieces"></div>
    </div>

    <!-- Ludo -->
    <div class="section" data-panel="ludo" style="display:none;">
      <div class="section-title">Ludo Game Colors</div>
      <div class="field-grid" id="fields-ludo"></div>
    </div>

    <!-- Icons -->
    <div class="section" data-panel="icons">
      <div class="section-title">Custom SVG Sprite</div>
      <div class="field-grid" id="fields-icons"></div>
    </div>

    <!-- Spacing & Layout -->
    <div class="section" data-panel="spacing">
      <div class="section-title">&#x1F4D0; Spacing & Layout</div>
      <div id="fields-spacing"></div>
    </div>

    <!-- Domino -->
    <div class="section" data-panel="domino">
      <div class="section-title">&#x1F3B2; Domino</div>
      <div class="field-grid" id="fields-domino"></div>
    </div>

    <!-- Backgammon -->
    <div class="section" data-panel="backgammon">
      <div class="section-title">&#x1F3AF; Backgammon</div>
      <div class="field-grid" id="fields-backgammon"></div>
    </div>

    <!-- Icons Grid -->
    <div class="section" data-panel="icons-grid" id="section-icons-grid">
      <div class="section-title">&#x1F3A8; Icons (Individual)</div>
      <p style="color:#64748b;font-size:12px;margin-bottom:12px;">Replace any icon with an SVG or PNG file — required size: 24x24px</p>
      <div class="icon-grid"></div>
    </div>

    <div class="save-bar">
      <button class="btn-save" onclick="saveAll()">Save All Changes</button>
      <button class="btn-reset" onclick="clearCache()">Clear Cache</button>
      <span class="status" id="save-status"></span>
    </div>
  </div>
</div>

<script>
const THEME_FIELDS = {
  colors: [
    { key:'bg-0', label:'Background Base', type:'color', default:'#050D17' },
    { key:'bg-1', label:'Background Layer 1', type:'color', default:'#0A1525' },
    { key:'bg-2', label:'Background Layer 2', type:'color', default:'#142640' },
    { key:'bg-3', label:'Background Layer 3', type:'color', default:'#1C3254' },
    { key:'gold', label:'Gold (Brand)', type:'color', default:'#E7A832' },
    { key:'gold-dark', label:'Gold Dark', type:'color', default:'#C48B1A' },
    { key:'cyan', label:'Cyan (Brand)', type:'color', default:'#15D7FF' },
    { key:'cyan-dark', label:'Cyan Dark', type:'color', default:'#0BA8C9' },
    { key:'blue', label:'Blue', type:'color', default:'#2979FF' },
    { key:'purple', label:'Purple', type:'color', default:'#7C4DFF' },
    { key:'success', label:'Success', type:'color', default:'#34D399' },
    { key:'error', label:'Error', type:'color', default:'#EF4444' },
    { key:'warning', label:'Warning', type:'color', default:'#F59E0B' },
    { key:'online', label:'Online Indicator', type:'color', default:'#22C55E' },
    { key:'text-1', label:'Text Primary', type:'color', default:'#F1F5F9' },
    { key:'text-2', label:'Text Secondary', type:'color', default:'#94A3B8' },
    { key:'text-3', label:'Text Tertiary', type:'color', default:'#64748B' },
    { key:'text-inverse', label:'Text Inverse', type:'color', default:'#0F172A' },
  ],
  board: [
    { key:'board-light', label:'Light Square', type:'color', default:'#E8EDF9' },
    { key:'board-dark', label:'Dark Square', type:'color', default:'#7195D1' },
    { key:'board-selected', label:'Selected Square', type:'text', default:'rgba(21, 215, 255, 0.45)' },
    { key:'board-last-move', label:'Last Move Highlight', type:'text', default:'rgba(255, 199, 40, 0.35)' },
    { key:'board-check', label:'Check Highlight', type:'text', default:'rgba(239, 68, 68, 0.55)' },
    { key:'board-premove', label:'Premove Highlight', type:'text', default:'rgba(21, 180, 240, 0.3)' },
    { key:'board-legal', label:'Legal Move Dots', type:'text', default:'rgba(0, 0, 0, 0.18)' },
    { key:'board-highlight-green', label:'Highlight Green', type:'text', default:'rgba(21, 180, 90, 0.4)' },
    { key:'board-highlight-red', label:'Highlight Red', type:'text', default:'rgba(220, 50, 50, 0.4)' },
    { key:'board-highlight-yellow', label:'Highlight Yellow', type:'text', default:'rgba(220, 180, 30, 0.4)' },
  ],
  chess: [
    { key:'chess-board-radius', label:'Board Radius', type:'text', default:'4px' },
    { key:'chess-board-shadow', label:'Board Shadow', type:'text', default:'0 2px 10px rgba(0,0,0,0.4)' },
    { key:'chess-piece-size', label:'Piece Size', type:'text', default:'min(11vw, 62px)' },
    { key:'chess-piece-white', label:'White Piece Color', type:'color', default:'#ffffff' },
    { key:'chess-piece-white-stroke', label:'White Stroke', type:'text', default:'1px #555' },
    { key:'chess-piece-black', label:'Black Piece Color', type:'color', default:'#222222' },
    { key:'chess-piece-black-stroke', label:'Black Stroke', type:'text', default:'0.5px #000' },
    { key:'chess-piece-shadow', label:'Piece Shadow', type:'text', default:'0 1px 2px rgba(0,0,0,0.3)' },
    { key:'chess-piece-hover-scale', label:'Hover Scale', type:'text', default:'1.05' },
    { key:'chess-piece-drag-scale', label:'Drag Scale', type:'text', default:'1.15' },
    { key:'chess-legal-dot-size', label:'Legal Move Dot Size', type:'text', default:'28%' },
    { key:'chess-legal-capture-size', label:'Capture Ring Size', type:'text', default:'88%' },
    { key:'chess-legal-capture-border', label:'Capture Ring Border', type:'text', default:'4px' },
    { key:'chess-clock-bg', label:'Clock BG', type:'color', default:'#1C3254' },
    { key:'chess-clock-active-bg', label:'Clock Active BG', type:'color', default:'#E7A832' },
    { key:'chess-clock-radius', label:'Clock Radius', type:'text', default:'8px' },
    { key:'chess-clock-font-size', label:'Clock Font Size', type:'text', default:'20px' },
    { key:'chess-clock-padding', label:'Clock Padding', type:'text', default:'8px 14px' },
    { key:'chess-coords-size', label:'Coordinates Size', type:'text', default:'11px' },
    { key:'chess-coords-weight', label:'Coordinates Weight', type:'text', default:'700' },
    { key:'chess-panel-width', label:'Side Panel Width', type:'text', default:'260px' },
    { key:'chess-panel-bg', label:'Panel BG', type:'color', default:'#142640' },
    { key:'chess-panel-radius', label:'Panel Radius', type:'text', default:'12px' },
    { key:'chess-move-font-size', label:'Move List Font', type:'text', default:'13px' },
    { key:'chess-eval-width', label:'Eval Bar Width', type:'text', default:'18px' },
    { key:'chess-eval-radius', label:'Eval Bar Radius', type:'text', default:'4px' },
    { key:'chess-header-padding', label:'Header Padding', type:'text', default:'10px 14px' },
    { key:'chess-header-radius', label:'Header Radius', type:'text', default:'12px' },
    { key:'chess-header-bg', label:'Header BG', type:'color', default:'#142640' },
    { key:'chess-player-font-size', label:'Player Name Size', type:'text', default:'14px' },
    { key:'chess-rating-font-size', label:'Rating Font Size', type:'text', default:'11px' },
    { key:'chess-board-max', label:'Board Max Width', type:'text', default:'580px' },
  ],
  moves: [
    { key:'move-brilliant', label:'Brilliant', type:'color', default:'#26c6da' },
    { key:'move-great', label:'Great', type:'color', default:'#66bb6a' },
    { key:'move-good', label:'Good', type:'color', default:'#81c784' },
    { key:'move-book', label:'Book', type:'color', default:'#9e9e9e' },
    { key:'move-inaccuracy', label:'Inaccuracy', type:'color', default:'#fdd835' },
    { key:'move-mistake', label:'Mistake', type:'color', default:'#ef6c00' },
    { key:'move-blunder', label:'Blunder', type:'color', default:'#e53935' },
    { key:'move-text-brilliant', label:'Text Brilliant', type:'color', default:'#00bcd4' },
    { key:'move-text-great', label:'Text Great', type:'color', default:'#2196f3' },
    { key:'move-text-good', label:'Text Good', type:'color', default:'#4caf50' },
    { key:'move-text-inaccuracy', label:'Text Inaccuracy', type:'color', default:'#ff9800' },
    { key:'move-text-mistake', label:'Text Mistake', type:'color', default:'#f44336' },
    { key:'move-text-blunder', label:'Text Blunder', type:'color', default:'#d32f2f' },
  ],
  ui: [
    { key:'eval-bg', label:'Eval Bar BG', type:'color', default:'#1a1a2e' },
    { key:'eval-white', label:'Eval White Fill', type:'color', default:'#f0f0f0' },
    { key:'eval-label-light', label:'Eval Label Light', type:'color', default:'#ffffff' },
    { key:'eval-label-dark', label:'Eval Label Dark', type:'color', default:'#333333' },
    { key:'arrow-green', label:'Arrow Green', type:'text', default:'rgba(21, 180, 90, 0.7)' },
    { key:'arrow-red', label:'Arrow Red', type:'text', default:'rgba(220, 50, 50, 0.7)' },
    { key:'arrow-yellow', label:'Arrow Yellow', type:'text', default:'rgba(220, 180, 30, 0.7)' },
    { key:'graph-bg', label:'Graph Background', type:'color', default:'#0a1628' },
    { key:'graph-grid', label:'Graph Grid', type:'color', default:'#333333' },
    { key:'graph-accent', label:'Graph Accent Line', type:'color', default:'#15d7ff' },
    { key:'graph-error', label:'Graph Error Dots', type:'color', default:'#f44336' },
    { key:'overlay-dark', label:'Overlay Dark', type:'text', default:'rgba(0, 0, 0, 0.8)' },
    { key:'overlay-result', label:'Game Result Overlay', type:'text', default:'rgba(5, 13, 23, 0.92)' },
    { key:'overlay-error-bg', label:'Error Alert BG', type:'text', default:'rgba(239, 68, 68, 0.1)' },
    { key:'overlay-error-border', label:'Error Alert Border', type:'text', default:'rgba(239, 68, 68, 0.2)' },
  ],
  bots: [
    { key:'bot-amina', label:'Amina (Beginner)', type:'text', default:'#4ade80, #22c55e' },
    { key:'bot-tarek', label:'Tarek (Amateur)', type:'text', default:'#38bdf8, #0ea5e9' },
    { key:'bot-nour', label:'Nour (Intermediate)', type:'text', default:'#a78bfa, #7c3aed' },
    { key:'bot-omar', label:'Omar (Good)', type:'text', default:'#fb923c, #ea580c' },
    { key:'bot-layla', label:'Layla (Strong)', type:'text', default:'#f472b6, #db2777' },
    { key:'bot-ziad', label:'Ziad (Expert)', type:'text', default:'#f87171, #dc2626' },
    { key:'bot-gm', label:'Grandmaster', type:'text', default:'var(--gold), #b45309' },
  ],
  assets: [
    { key:'logo-text', label:'Logo Text Override', type:'text', default:'', category:'assets' },
    { key:'logo-image', label:'Logo Image', type:'file', category:'assets' },
    { key:'favicon', label:'Favicon', type:'file', category:'assets' },
  ],
  pieces: [
    { key:'piece-wK', label:'White King', type:'file', category:'pieces' },
    { key:'piece-wQ', label:'White Queen', type:'file', category:'pieces' },
    { key:'piece-wR', label:'White Rook', type:'file', category:'pieces' },
    { key:'piece-wB', label:'White Bishop', type:'file', category:'pieces' },
    { key:'piece-wN', label:'White Knight', type:'file', category:'pieces' },
    { key:'piece-wP', label:'White Pawn', type:'file', category:'pieces' },
    { key:'piece-bK', label:'Black King', type:'file', category:'pieces' },
    { key:'piece-bQ', label:'Black Queen', type:'file', category:'pieces' },
    { key:'piece-bR', label:'Black Rook', type:'file', category:'pieces' },
    { key:'piece-bB', label:'Black Bishop', type:'file', category:'pieces' },
    { key:'piece-bN', label:'Black Knight', type:'file', category:'pieces' },
    { key:'piece-bP', label:'Black Pawn', type:'file', category:'pieces' },
  ],
  ludo: [
    { key:'ludo-p1', label:'Player 1 (Red)', type:'color', default:'#E53935' },
    { key:'ludo-p2', label:'Player 2 (Green)', type:'color', default:'#43A047' },
    { key:'ludo-p3', label:'Player 3 (Yellow)', type:'color', default:'#FDD835' },
    { key:'ludo-p4', label:'Player 4 (Blue)', type:'color', default:'#1E88E5' },
    { key:'ludo-board-bg', label:'Board Background', type:'color', default:'#1a2332' },
    { key:'ludo-path', label:'Path Cell Color', type:'color', default:'#f5f5f5' },
    { key:'ludo-safe', label:'Safe Position Color', type:'color', default:'#FFD54F' },
    { key:'ludo-path-border', label:'Path Cell Border', type:'text', default:'rgba(0,0,0,0.1)' },
    { key:'ludo-home-p1', label:'Home Entrance P1', type:'text', default:'rgba(229,57,53,0.3)' },
    { key:'ludo-home-p2', label:'Home Entrance P2', type:'text', default:'rgba(67,160,71,0.3)' },
    { key:'ludo-home-p3', label:'Home Entrance P3', type:'text', default:'rgba(253,216,53,0.3)' },
    { key:'ludo-home-p4', label:'Home Entrance P4', type:'text', default:'rgba(30,136,229,0.3)' },
    { key:'ludo-dice-bg', label:'Dice Background', type:'text', default:'var(--bg-2)' },
    { key:'ludo-dice-dot', label:'Dice Dot Color', type:'text', default:'var(--text-inverse)' },
    { key:'ludo-chat-bg', label:'Chat Background', type:'text', default:'var(--bg-2)' },
  ],
  icons: [
    { key:'sprite-svg', label:'Custom SVG Sprite (replaces default)', type:'file', category:'icons' },
  ],
  domino: [
    { key:'domino-face', label:'Domino Face', type:'color', default:'#f5f0e8' },
    { key:'domino-pip', label:'Domino Pips', type:'color', default:'#1a1a1a' },
    { key:'domino-back', label:'Domino Back', type:'color', default:'#1a2a4a' },
    { key:'domino-board-bg', label:'Domino Board BG', type:'color', default:'#0a2a1a' },
    { key:'domino-playable-glow', label:'Playable Glow', type:'text', default:'rgba(255,200,50,0.4)' },
  ],
  backgammon: [
    { key:'bg-felt', label:'Felt Color', type:'color', default:'#1a5c32' },
    { key:'bg-point-light', label:'Light Point', type:'color', default:'#d4a76a' },
    { key:'bg-point-dark', label:'Dark Point', type:'color', default:'#8b4513' },
    { key:'bg-bar', label:'Bar Color', type:'color', default:'#3a2418' },
    { key:'bg-checker-white', label:'White Checker', type:'color', default:'#f0ebe0' },
    { key:'bg-checker-black', label:'Black Checker', type:'color', default:'#1a1a1a' },
    { key:'bg-board-wood', label:'Board Wood', type:'color', default:'#5c3d2e' },
    { key:'bg-frame', label:'Frame Color', type:'color', default:'#3a2418' },
  ],
};

let adminUser = '';
let adminPass = '';
let currentSettings = {};

function doLogin() {
  adminUser = document.getElementById('admin-user').value;
  adminPass = document.getElementById('admin-pass').value;
  if (adminUser === 'admin' && adminPass === 'Alarcade123#') {
    document.getElementById('login-screen').style.display = 'none';
    document.getElementById('admin-panel').style.display = 'flex';
    loadTheme();
  } else {
    document.getElementById('login-err').style.display = 'block';
  }
}

document.getElementById('admin-pass').addEventListener('keydown', e => { if(e.key==='Enter') doLogin(); });

async function loadTheme() {
  const res = await fetch('/api/theme');
  const data = await res.json();
  currentSettings = {};
  (data.settings || []).forEach(s => { currentSettings[s.key] = s.value; });
  renderAllFields();
}

function renderAllFields() {
  Object.keys(THEME_FIELDS).forEach(section => {
    const container = document.getElementById('fields-' + section);
    if (!container) return;
    container.innerHTML = '';
    THEME_FIELDS[section].forEach(f => {
      const saved = currentSettings[f.key] || '';
      container.innerHTML += renderField(f, saved);
    });
  });
}

function renderField(f, saved) {
  if (f.type === 'color') {
    const colorVal = saved || f.default;
    return `<div class="field">
      <label>${f.label} <code style="font-size:10px;color:#64748b;">(--${f.key})</code></label>
      <div class="input-row">
        <input type="color" value="${colorVal}" data-key="${f.key}" data-category="${f.category || 'colors'}" onchange="onColorChange(this)">
        <input type="text" value="${saved}" data-key="${f.key}" data-category="${f.category || 'colors'}" placeholder="${f.default}">
        ${saved ? '<button class="remove-btn" onclick="removeField(this,\'' + f.key + '\')">X</button>' : ''}
      </div>
    </div>`;
  } else if (f.type === 'text') {
    return `<div class="field">
      <label>${f.label} <code style="font-size:10px;color:#64748b;">(--${f.key})</code></label>
      <div class="input-row">
        <input type="text" value="${saved}" data-key="${f.key}" data-category="${f.category || 'colors'}" placeholder="${f.default}">
        ${saved ? '<button class="remove-btn" onclick="removeField(this,\'' + f.key + '\')">X</button>' : ''}
      </div>
    </div>`;
  } else if (f.type === 'file') {
    const hint = getUploadHint(f.key, f.category);
    return `<div class="field">
      <label>${f.label} <code style="font-size:10px;color:#64748b;">(${f.key})</code></label>
      <input type="file" accept="image/*,.svg" data-key="${f.key}" data-category="${f.category || 'assets'}" onchange="uploadFile(this)">
      ${hint ? '<small class="upload-hint">' + hint + '</small>' : ''}
      ${saved ? '<div class="preview"><img src="' + saved + '"><button class="remove-btn" onclick="removeAsset(this,\'' + f.key + '\')">Remove</button></div>' : ''}
    </div>`;
  }
  return '';
}

function onColorChange(colorInput) {
  const row = colorInput.closest('.input-row');
  const textInput = row.querySelector('input[type="text"]');
  textInput.value = colorInput.value;
}

async function uploadFile(input) {
  const file = input.files[0];
  if (!file) return;

  const fd = new FormData();
  fd.append('file', file);
  fd.append('key', input.dataset.key);
  fd.append('category', input.dataset.category);
  fd.append('admin_user', adminUser);
  fd.append('admin_pass', adminPass);
  fd.append('label', input.dataset.key);

  const res = await fetch('/api/theme-upload', { method:'POST', body:fd });
  const data = await res.json();
  if (data.ok) {
    currentSettings[input.dataset.key] = data.url;
    showStatus('Uploaded: ' + input.dataset.key);
    renderAllFields();
  } else {
    showStatus('Error: ' + (data.error || 'upload failed'), true);
  }
}

async function removeField(btn, key) {
  await fetch('/api/theme', {
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body:JSON.stringify({ admin_user:adminUser, admin_pass:adminPass, action:'delete', key })
  });
  delete currentSettings[key];
  renderAllFields();
  showStatus('Removed: ' + key);
}

async function removeAsset(btn, key) {
  await removeField(btn, key);
}

async function saveAll() {
  const inputs = document.querySelectorAll('.field input[type="text"][data-key]');
  const settings = [];

  inputs.forEach(input => {
    const key = input.dataset.key;
    const value = input.value.trim();
    const category = input.dataset.category || 'colors';
    if (value) {
      settings.push({ key, value, category, label:key });
    }
  });

  if (settings.length === 0) {
    showStatus('Nothing to save');
    return;
  }

  const res = await fetch('/api/theme', {
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body:JSON.stringify({ admin_user:adminUser, admin_pass:adminPass, action:'save', settings })
  });
  const data = await res.json();
  if (data.ok) {
    showStatus('Saved ' + settings.length + ' settings!');
    currentSettings = {};
    settings.forEach(s => { currentSettings[s.key] = s.value; });
  } else {
    showStatus('Error saving', true);
  }
}

async function clearCache() {
  showStatus('Cache cleared - next page load will fetch fresh data');
}

function showStatus(msg, isErr) {
  const el = document.getElementById('save-status');
  el.textContent = msg;
  el.style.color = isErr ? '#ef4444' : '#34d399';
  setTimeout(() => { el.textContent = ''; }, 4000);
}

// Sidebar nav
document.querySelectorAll('.admin-sidebar .nav-item').forEach(item => {
  item.addEventListener('click', () => {
    document.querySelectorAll('.admin-sidebar .nav-item').forEach(n => n.classList.remove('active'));
    item.classList.add('active');
    const section = item.dataset.section;
    document.querySelectorAll('.section').forEach(s => {
      s.style.display = s.dataset.panel === section ? 'block' : 'none';
    });
  });
});

// Show only first section on load
document.querySelectorAll('.section').forEach((s, i) => { s.style.display = i === 0 ? 'block' : 'none'; });

// Upload hint helper
function getUploadHint(key, category) {
  if (key.startsWith('piece-')) return '128×128px PNG أو SVG';
  if (key === 'logo-image') return '200×40px PNG/SVG (خلفية شفافة)';
  if (key === 'favicon') return '32×32px PNG أو ICO';
  if (key === 'sprite-svg') return 'ملف SVG — كل رمز 24px viewBox';
  if (category === 'icons') return '24×24px SVG مفضل';
  return '';
}

// Spacing & Layout sliders
const SPACING_FIELDS = [
  { key:'--radius-sm', label:'زوايا صغيرة', default:8, min:0, max:24, step:1, suffix:'px' },
  { key:'--radius-md', label:'زوايا متوسطة', default:12, min:0, max:32, step:1, suffix:'px' },
  { key:'--radius-lg', label:'زوايا كبيرة', default:16, min:0, max:40, step:1, suffix:'px' },
  { key:'--content-max', label:'عرض المحتوى', default:600, min:400, max:1200, step:10, suffix:'px' },
  { key:'--header-h', label:'ارتفاع الهيدر', default:52, min:40, max:80, step:1, suffix:'px' },
  { key:'--nav-bottom-h', label:'ارتفاع النافبار', default:56, min:40, max:72, step:1, suffix:'px' },
  { key:'--card-padding', label:'حشو الكرت', default:16, min:8, max:32, step:1, suffix:'px' },
  { key:'--section-gap', label:'مسافة الأقسام', default:16, min:8, max:40, step:1, suffix:'px' },
  { key:'--touch-min', label:'حجم اللمس', default:44, min:36, max:56, step:1, suffix:'px' },
];

function renderSpacingFields() {
  const container = document.getElementById('fields-spacing');
  if (!container) return;
  container.innerHTML = SPACING_FIELDS.map(f => {
    const saved = currentSettings[f.key] || '';
    const val = saved ? parseInt(saved) : f.default;
    return `<div class="theme-field">
      <label>${f.label} <code style="font-size:10px;color:#64748b;">(${f.key})</code></label>
      <div style="display:flex;gap:8px;align-items:center;">
        <input type="range" min="${f.min}" max="${f.max}" value="${val}" step="${f.step}" data-key="${f.key}" class="spacing-slider">
        <span class="slider-value">${val}${f.suffix || ''}</span>
      </div>
    </div>`;
  }).join('');
}

function initSpacingSliders() {
  document.querySelectorAll('.spacing-slider').forEach(slider => {
    const valueSpan = slider.parentElement.querySelector('.slider-value');
    slider.addEventListener('input', () => {
      const val = slider.value + 'px';
      valueSpan.textContent = val;
      document.documentElement.style.setProperty(slider.dataset.key, val);
    });
  });
}

// RGBA Picker
function initRgbaPickers() {
  document.querySelectorAll('.rgba-picker').forEach(picker => {
    const colorInput = picker.querySelector('input[type="color"]');
    const alphaSlider = picker.querySelector('.alpha-slider');
    const alphaLabel = picker.querySelector('.alpha-label');
    const output = picker.querySelector('.rgba-output');
    const key = picker.dataset.key;

    function update() {
      const hex = colorInput.value;
      const alpha = alphaSlider.value / 100;
      const r = parseInt(hex.slice(1,3), 16);
      const g = parseInt(hex.slice(3,5), 16);
      const b = parseInt(hex.slice(5,7), 16);
      const rgba = `rgba(${r}, ${g}, ${b}, ${alpha})`;
      output.value = rgba;
      alphaLabel.textContent = alphaSlider.value + '%';
      document.documentElement.style.setProperty(key, rgba);
    }

    colorInput.addEventListener('input', update);
    alphaSlider.addEventListener('input', update);
  });
}

// RGBA fields - detect which fields need RGBA pickers
const RGBA_KEYS = ['board-selected','board-last-move','board-check','board-premove','board-legal',
  'board-highlight-green','board-highlight-red','board-highlight-yellow',
  'overlay-dark','overlay-result','overlay-error-bg','overlay-error-border',
  'ludo-path-border','ludo-home-p1','ludo-home-p2','ludo-home-p3','ludo-home-p4',
  'domino-playable-glow'];

function parseRgba(str) {
  const m = str.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)/);
  if (m) {
    const r = parseInt(m[1]), g = parseInt(m[2]), b = parseInt(m[3]);
    const a = m[4] !== '' ? parseFloat(m[4]) : 1;
    const hex = '#' + [r,g,b].map(x => x.toString(16).padStart(2,'0')).join('');
    return { hex, alpha: Math.round(a * 100) };
  }
  return { hex:'#000000', alpha:100 };
}

// Override renderField for RGBA fields
const originalRenderField = renderField;
renderField = function(f, saved) {
  if (f.type === 'text' && RGBA_KEYS.includes(f.key)) {
    const val = saved || f.default;
    const parsed = parseRgba(val);
    return `<div class="field">
      <label>${f.label} <code style="font-size:10px;color:#64748b;">(--${f.key})</code></label>
      <div class="rgba-picker" data-key="--${f.key}">
        <input type="color" value="${parsed.hex}">
        <input type="range" class="alpha-slider" min="0" max="100" value="${parsed.alpha}">
        <span class="alpha-label">${parsed.alpha}%</span>
        <input type="text" class="rgba-output" value="${val}" data-key="${f.key}" data-category="${f.category || 'colors'}">
      </div>
    </div>`;
  }
  return originalRenderField(f, saved);
};

// Icon Grid
const ICONS = ['home','play','trophy','leaderboard','friends','shop','star','settings','profile','bell','coin','gem','dice','users','lock','games','domino','backgammon','cards','plus','check','x','arrow-left','arrow-right','flag','crown','clock','key','bot','search','lightning'];

function renderIconGrid() {
  const container = document.querySelector('.icon-grid');
  if (!container) return;
  container.innerHTML = ICONS.map(icon => `
    <div class="icon-item" data-icon="${icon}">
      <svg style="width:24px;height:24px;"><use href="/public/icons/sprite.svg#icon-${icon}"></use></svg>
      <span>icon-${icon}</span>
      <label class="icon-upload-btn">تغيير<input type="file" accept=".svg,.png" onchange="uploadIcon('${icon}', this.files[0])"></label>
    </div>
  `).join('');
}

async function uploadIcon(iconName, file) {
  if (!file) return;
  const fd = new FormData();
  fd.append('file', file);
  fd.append('key', 'icon-' + iconName);
  fd.append('category', 'icons');
  fd.append('admin_user', adminUser);
  fd.append('admin_pass', adminPass);
  fd.append('label', 'icon-' + iconName);

  const res = await fetch('/api/theme-upload', { method:'POST', body:fd });
  const data = await res.json();
  if (data.ok) {
    showStatus('Uploaded icon: ' + iconName);
  } else {
    showStatus('Error: ' + (data.error || 'upload failed'), true);
  }
}

// Extend saveAll to include spacing sliders
const originalSaveAll = saveAll;
saveAll = async function() {
  // Collect spacing slider values into hidden inputs before saving
  document.querySelectorAll('.spacing-slider').forEach(slider => {
    const key = slider.dataset.key;
    const val = slider.value + 'px';
    // Create a temporary text input so the save loop picks it up
    let existing = document.querySelector(`input[type="text"][data-key="${key}"]`);
    if (!existing) {
      const hidden = document.createElement('input');
      hidden.type = 'text';
      hidden.dataset.key = key;
      hidden.dataset.category = 'spacing';
      hidden.value = val;
      hidden.style.display = 'none';
      hidden.classList.add('spacing-hidden-input');
      document.querySelector('.admin-main').appendChild(hidden);
    } else {
      existing.value = val;
    }
  });
  // Also collect RGBA picker values
  document.querySelectorAll('.rgba-picker .rgba-output').forEach(output => {
    // These already have data-key and data-category, they'll be picked up by saveAll
  });
  await originalSaveAll();
  // Remove temp hidden inputs
  document.querySelectorAll('.spacing-hidden-input').forEach(el => el.remove());
};

// Extend loadTheme to also render spacing and icon grid
const originalLoadTheme = loadTheme;
loadTheme = async function() {
  await originalLoadTheme();
  renderSpacingFields();
  initSpacingSliders();
  initRgbaPickers();
  renderIconGrid();
};
</script>
</body>
</html>
