<?php
$route = $_GET['route'] ?? '';
$route = trim($route, '/');

// API passthrough
if (str_starts_with($route, 'api/')) {
    $apiFile = str_replace('api/', '', $route);
    $apiPath = __DIR__ . '/api/' . basename($apiFile) . '.php';
    if (file_exists($apiPath)) { require $apiPath; } else { http_response_code(404); echo json_encode(['error' => 'not found']); }
    exit;
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
  <meta name="theme-color" content="#030A12">
  <title>EL3AB</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+Arabic:wght@400;500;600;700;800&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="/app/styles/el3ab.css">
  <link rel="stylesheet" href="/public/css/chessboard.css">
</head>
<body>
<div class="shell" id="shell">

  <header class="hdr" id="hdr">
    <a href="/" class="hdr-brand" onclick="return route(event,'/')">EL3AB</a>
    <div class="hdr-mid">
      <span class="hdr-stat" id="hdr-level" style="color:var(--gold)">Lv 1</span>
      <span class="hdr-stat"><svg style="color:var(--gold)" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="12" r="10"/></svg><span id="hdr-coins">0</span></span>
      <span class="hdr-stat"><svg style="color:var(--purple)" viewBox="0 0 24 24" fill="currentColor"><polygon points="12,2 15,10 24,10 17,15 19,23 12,18 5,23 7,15 0,10 9,10"/></svg><span id="hdr-gems">0</span></span>
    </div>
    <div class="hdr-end">
      <button class="hdr-btn" onclick="route(event,'/notifications')">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 01-3.46 0"/></svg>
      </button>
    </div>
  </header>

  <div class="main" id="main"></div>

  <nav class="nav" id="nav">
    <a href="/" class="nav-item active" data-route="/" onclick="return route(event,'/')">
      <svg viewBox="0 0 24 24"><path d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-4 0v-6a1 1 0 011-1h2a1 1 0 011 1v6m-6 0h6"/></svg>
      <span>الرئيسية</span>
    </a>
    <a href="/games" class="nav-item" data-route="/games" onclick="return route(event,'/games')">
      <svg viewBox="0 0 24 24"><rect x="2" y="2" width="20" height="20" rx="5"/><circle cx="8" cy="8" r="1.5" fill="currentColor"/><circle cx="16" cy="16" r="1.5" fill="currentColor"/></svg>
      <span>العاب</span>
    </a>
    <a href="/leaderboard" class="nav-item" data-route="/leaderboard" onclick="return route(event,'/leaderboard')">
      <svg viewBox="0 0 24 24"><path d="M8 21V11M12 21V3M16 21v-5"/></svg>
      <span>ترتيب</span>
    </a>
    <a href="/friends" class="nav-item" data-route="/friends" onclick="return route(event,'/friends')">
      <svg viewBox="0 0 24 24"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/></svg>
      <span>اجتماعي</span>
    </a>
    <a href="/profile" class="nav-item" data-route="/profile" onclick="return route(event,'/profile')">
      <svg viewBox="0 0 24 24"><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
      <span>حسابي</span>
    </a>
  </nav>

</div>

<!-- Compatibility: game engines need window.App -->
<script src="/public/js/app.js"></script>

<!-- JUICE: Global interaction feedback -->
<script>
// Haptics
const H = { tap:()=>navigator.vibrate&&navigator.vibrate(8), heavy:()=>navigator.vibrate&&navigator.vibrate(25), success:()=>navigator.vibrate&&navigator.vibrate([15,40,15]), error:()=>navigator.vibrate&&navigator.vibrate([40,20,40,20,40]) };

// Audio (Web Audio API synth)
let _ac;
function beep(freq,dur,type='sine',vol=0.1){try{if(!_ac)_ac=new(window.AudioContext||window.webkitAudioContext)();if(_ac.state==='suspended')_ac.resume();const o=_ac.createOscillator(),g=_ac.createGain();o.type=type;o.frequency.value=freq;g.gain.value=vol;g.gain.exponentialRampToValueAtTime(0.001,_ac.currentTime+dur);o.connect(g).connect(_ac.destination);o.start();o.stop(_ac.currentTime+dur);}catch(e){}}
const SFX = {
  tap(){beep(600,0.04,'sine',0.06)},
  click(){beep(900,0.03,'sine',0.08)},
  coin(){beep(1200,0.08,'sine',0.1);setTimeout(()=>beep(1500,0.08,'sine',0.08),60)},
  win(){beep(523,0.12,'triangle',0.12);setTimeout(()=>beep(659,0.12,'triangle',0.12),80);setTimeout(()=>beep(784,0.2,'triangle',0.14),160)},
  error(){beep(200,0.15,'square',0.06)},
};

// Global tap feedback on all interactive elements
document.addEventListener('pointerdown', function(e) {
  const t = e.target.closest('.btn, .chip, .game-card, .nav-item, .hdr-btn, .streak-btn, .activity-item, .stat-pill');
  if (!t) return;

  // Set ripple position
  const rect = t.getBoundingClientRect();
  t.style.setProperty('--ripple-x', ((e.clientX - rect.left) / rect.width * 100) + '%');
  t.style.setProperty('--ripple-y', ((e.clientY - rect.top) / rect.height * 100) + '%');

  // Haptic
  H.tap();

  // Sound (only for buttons/chips/cards — not every single element)
  if (t.matches('.btn, .game-card, .streak-btn')) SFX.click();
  else if (t.matches('.chip')) SFX.tap();
});

// Coin counter tick animation
function tickCounter(elId, newVal) {
  const el = document.getElementById(elId);
  if (!el) return;
  el.classList.add('tick');
  el.textContent = typeof newVal === 'number' ? newVal.toLocaleString() : newVal;
  setTimeout(() => el.classList.remove('tick'), 200);
}
</script>

<!-- SPA Router -->
<script>
const main = document.getElementById('main');
const screens = {};
let current = null;

// Simple screen registry
function defineScreen(path, renderFn) { screens[path] = renderFn; }

function route(e, path) {
  if (e) { e.preventDefault(); e.stopPropagation(); }
  history.pushState({}, '', path);
  render(path);
  return false;
}

function render(path) {
  // Update nav active state
  document.querySelectorAll('.nav-item').forEach(item => {
    const r = item.dataset.route;
    item.classList.toggle('active', r === path || (r !== '/' && path.startsWith(r)));
  });

  // Find screen
  const screen = screens[path] || screens['/'];
  if (!screen) { main.innerHTML = '<div class="empty">الصفحة غير موجودة</div>'; return; }

  // Render
  main.innerHTML = '';
  main.style.opacity = '0';
  main.style.transform = 'translateY(8px)';
  screen();
  requestAnimationFrame(() => {
    main.style.transition = 'opacity 0.2s, transform 0.2s';
    main.style.opacity = '1';
    main.style.transform = 'translateY(0)';
  });
}

// Handle back/forward
window.addEventListener('popstate', () => render(location.pathname));

// Handle link clicks
document.addEventListener('click', (e) => {
  const a = e.target.closest('a[href]');
  if (!a) return;
  const href = a.getAttribute('href');
  if (!href || href.startsWith('http') || href.startsWith('#') || href.startsWith('/api/')) return;
  e.preventDefault();
  route(null, href);
});

// === SCREENS ===

defineScreen('/', async function homeScreen() {
  if (!App.isLoggedIn()) { route(null, '/login'); return; }

  main.innerHTML = `
    <div class="sec">
      <div class="streak" id="streak">
        <span class="streak-fire">🔥</span>
        <div class="streak-info">
          <p class="streak-day" id="streak-day">اليوم 0</p>
          <p class="streak-reward" id="streak-reward">+50 عملة</p>
        </div>
        <button class="streak-btn" id="streak-btn">اجمع</button>
      </div>
    </div>

    <div class="sec">
      <div class="sec-hdr"><h2 class="sec-title">العب</h2></div>
      <div class="game-grid">
        <a href="/play" class="game-card"><div class="game-card-hero game-card-hero--chess"><span class="game-card-hero-icon">♟️</span></div><div class="game-card-body"><span class="game-card-name">شطرنج</span><span class="game-card-dot"></span></div></a>
        <a href="/ludo" class="game-card"><div class="game-card-hero game-card-hero--ludo"><span class="game-card-hero-icon">🎲</span></div><div class="game-card-body"><span class="game-card-name">لودو</span><span class="game-card-dot"></span></div></a>
        <a href="/domino" class="game-card"><div class="game-card-hero game-card-hero--domino"><span class="game-card-hero-icon">🁣</span></div><div class="game-card-body"><span class="game-card-name">دومينو</span><span class="game-card-dot"></span></div></a>
        <a href="/backgammon" class="game-card"><div class="game-card-hero game-card-hero--backgammon"><span class="game-card-hero-icon">🎯</span></div><div class="game-card-body"><span class="game-card-name">طاولة</span><span class="game-card-dot"></span></div></a>
      </div>
    </div>

    <div class="sec" id="ratings-sec" style="display:none">
      <div class="sec-hdr"><h2 class="sec-title">تصنيفاتي</h2></div>
      <div class="stats-scroll" id="ratings-row"></div>
    </div>

    <div class="sec">
      <div class="sec-hdr"><h2 class="sec-title">اخر المباريات</h2></div>
      <div class="card" id="recent"><div class="empty">لم تلعب بعد</div></div>
    </div>
  `;

  // Load profile
  const data = await App.fetch('/api/profile');
  if (data && data.profile) {
    const p = data.profile;
    document.getElementById('hdr-level').textContent = 'Lv ' + (p.level || 1);
    document.getElementById('hdr-coins').textContent = (p.coins || 0).toLocaleString();
    document.getElementById('hdr-gems').textContent = p.gems || 0;

    const streak = p.daily_streak || 0;
    document.getElementById('streak-day').textContent = 'اليوم ' + streak;
    document.getElementById('streak-reward').textContent = '+' + (50 + streak * 10) + ' عملة';

    const today = new Date().toISOString().slice(0, 10);
    if (p.last_daily_reward === today) {
      document.getElementById('streak-btn').textContent = 'تم ✓';
      document.getElementById('streak-btn').disabled = true;
    }
  }

  // Streak claim with juice
  document.getElementById('streak-btn').onclick = async function() {
    this.disabled = true;
    H.tap();
    const res = await App.fetch('/api/daily-reward', { method: 'POST' });
    if (res && res.ok) {
      // Celebration!
      SFX.coin();
      H.success();
      this.textContent = 'تم ✓';
      this.classList.add('claimed');
      document.getElementById('streak-day').textContent = 'اليوم ' + res.streak;
      tickCounter('hdr-coins', res.coins);
      App.toast('+' + res.reward + ' عملة!', 'success');
    } else {
      this.disabled = false;
      SFX.error();
      H.error();
      App.toast(res?.error === 'already_claimed' ? 'جمعتها اليوم' : 'خطأ', 'error');
    }
  };

  // Ratings
  try {
    const rd = await App.fetch('/api/ratings.php?action=player');
    if (rd && rd.ratings && rd.ratings.length) {
      document.getElementById('ratings-sec').style.display = '';
      const names = {chess:'شطرنج',ludo:'لودو',backgammon:'طاولة',domino:'دومينو'};
      const modes = {bullet:'بوليت',blitz:'بليتز',rapid:'رابيد',classical:'كلاسيك',default:''};
      document.getElementById('ratings-row').innerHTML = rd.ratings.map(r => {
        const lbl = (modes[r.mode]||'') ? names[r.game_key]+' '+modes[r.mode] : names[r.game_key];
        return '<div class="stat-pill"><span class="stat-pill-val">'+r.rating+'</span><span class="stat-pill-lbl">'+lbl+'</span></div>';
      }).join('');
    }
  } catch(e) {}

  // Recent games
  const gd = await App.fetch('/api/game?action=recent');
  if (gd && gd.games && gd.games.length) {
    document.getElementById('recent').innerHTML = '<div class="activity">' + gd.games.slice(0,5).map(g => {
      const cls = g.result==='win'?'win':'loss';
      const icon = g.result==='win'?'✓':g.result==='loss'?'✗':'=';
      const txt = g.result==='win'?'فوز':g.result==='loss'?'خسارة':'تعادل';
      return '<div class="activity-item"><div class="activity-icon '+cls+'">'+icon+'</div><div class="activity-text">مباراة شطرنج</div><span class="activity-result" style="color:var(--'+cls+')">'+txt+'</span></div>';
    }).join('') + '</div>';
  }
});

defineScreen('/login', function loginScreen() {
  document.getElementById('hdr').classList.add('hide');
  document.getElementById('nav').classList.add('hide');
  main.innerHTML = `
    <div class="login-wrap">
      <div class="login-card">
        <h1 class="login-brand">EL3AB</h1>
        <p class="login-sub">سجل دخولك وابدأ اللعب</p>
        <form id="login-form">
          <div class="mb-4"><label style="display:block;font-size:13px;color:var(--text-2);margin-bottom:6px;">البريد</label><input type="email" class="input" id="l-email" placeholder="email@example.com" required dir="ltr"></div>
          <div class="mb-5"><label style="display:block;font-size:13px;color:var(--text-2);margin-bottom:6px;">كلمة المرور</label><input type="password" class="input" id="l-pass" placeholder="••••••••" required dir="ltr"></div>
          <button type="submit" class="btn btn-gold btn-block btn-lg" id="l-btn">تسجيل الدخول</button>
        </form>
        <p style="text-align:center;margin-top:20px;font-size:13px;color:var(--text-3);">ما عندك حساب؟ <a href="/register" style="color:var(--cyan)">انشئ حساب</a></p>
        <div id="l-err" style="display:none" class="login-err"></div>
      </div>
    </div>
  `;
  document.getElementById('login-form').onsubmit = async function(e) {
    e.preventDefault();
    const btn = document.getElementById('l-btn');
    const err = document.getElementById('l-err');
    err.style.display = 'none';
    btn.disabled = true; btn.textContent = 'جاري...';
    try {
      const res = await fetch('/api/auth', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({action:'login', email:document.getElementById('l-email').value, password:document.getElementById('l-pass').value}) });
      const data = await res.json();
      if (data.error) { err.textContent = data.error; err.style.display = 'block'; }
      else { App.setAuth(data.access_token, data.user); location.href = '/'; }
    } catch { err.textContent = 'خطأ في الاتصال'; err.style.display = 'block'; }
    btn.disabled = false; btn.textContent = 'تسجيل الدخول';
  };
});

defineScreen('/play', function chessLobby() {
  main.innerHTML = `
    <h2 class="text-center mb-5" style="font-size:20px;font-weight:700;">♟️ شطرنج</h2>
    <div class="card card-pad mb-4">
      <p style="font-size:15px;font-weight:700;margin-bottom:12px;">🤖 ضد البوت</p>
      <div class="chips mb-3" id="tc-chips">
        <button class="chip on" data-t="300" data-i="0">5+0</button>
        <button class="chip" data-t="180" data-i="0">3+0</button>
        <button class="chip" data-t="600" data-i="0">10+0</button>
        <button class="chip" data-t="60" data-i="1">1+1</button>
      </div>
      <div class="mb-3"><select class="input" id="bot-sel" dir="ltr" style="background:var(--bg-2);border:1px solid var(--border);border-radius:var(--radius-sm);height:44px;padding:0 16px;"><option>Loading...</option></select></div>
      <div class="chips mb-4" id="color-chips">
        <button class="chip on" data-c="w">⬜ ابيض</button>
        <button class="chip" data-c="b">⬛ اسود</button>
        <button class="chip" data-c="random">🎲 عشوائي</button>
      </div>
      <button class="btn btn-gold btn-block btn-lg" id="btn-play">ابدأ</button>
    </div>
  `;
  // Chip logic
  document.querySelectorAll('.chips').forEach(group => {
    group.querySelectorAll('.chip').forEach(c => {
      c.onclick = () => { group.querySelectorAll('.chip').forEach(x => x.classList.remove('on')); c.classList.add('on'); };
    });
  });
  // Load bots
  App.fetch('/api/bots.php').then(d => {
    if (!d || !d.bots) return;
    document.getElementById('bot-sel').innerHTML = d.bots.map(b => '<option value="'+b.id+'">'+b.name+' ('+Math.round((b.elo_min+b.elo_max)/2)+')</option>').join('');
  });
  // Start game
  document.getElementById('btn-play').onclick = () => {
    const tc = document.querySelector('#tc-chips .on');
    let color = document.querySelector('#color-chips .on').dataset.c;
    if (color === 'random') color = Math.random() < 0.5 ? 'w' : 'b';
    const bot = document.getElementById('bot-sel').value;
    location.href = '/game?bot='+bot+'&color='+color+'&time='+tc.dataset.t+'&inc='+tc.dataset.i+'&rated=true';
  };
});

defineScreen('/game', function gameScreen() {
  document.getElementById('shell').classList.add('immersive');
  const params = Object.fromEntries(new URLSearchParams(location.search));

  main.innerHTML = `
    <div class="chess-game-wrap">
      <div class="chess-top-bar">
        <div class="chess-player-bar">
          <span class="chess-player-name" id="opp-name">🤖</span>
          <span class="chess-clock" id="clock-top">--:--</span>
        </div>
      </div>

      <div class="board-wrapper" style="width:min(calc(100vw - 24px), 400px);margin:0 auto;">
        <div id="board"></div>
      </div>

      <div class="chess-bottom-bar">
        <div class="chess-player-bar">
          <span class="chess-player-name" id="player-name">انت</span>
          <span class="chess-clock" id="clock-bottom">--:--</span>
        </div>
      </div>

      <div id="opening-display" style="text-align:center;font-size:12px;color:var(--text-2);min-height:18px;margin:4px 0;"></div>
      <div id="opening-display-mobile" style="display:none;"></div>

      <div id="thinking-indicator" style="text-align:center;font-size:12px;color:var(--gold);min-height:18px;"></div>

      <div id="game-status" style="text-align:center;font-size:13px;font-weight:600;min-height:20px;margin:4px 0;"></div>
      <div id="game-status-mobile" style="display:none;"></div>

      <div class="chess-move-list-wrap">
        <div id="move-list" class="chess-move-list"></div>
        <div id="move-list-mobile" style="display:none;"></div>
      </div>

      <div class="chess-actions">
        <button class="btn btn-ghost btn-sm" id="btn-resign" onclick="if(Game&&Game.resign)Game.resign()">استسلام</button>
        <button class="btn btn-ghost btn-sm" id="btn-draw" onclick="if(Game&&Game.offerDraw)Game.offerDraw()">تعادل</button>
        <button class="btn btn-ghost btn-sm" id="btn-flip" onclick="if(Board&&Board.flip)Board.flip()">🔄</button>
        <button class="btn btn-ghost btn-sm" id="btn-pgn" style="display:none;">PGN</button>
        <button class="btn btn-ghost btn-sm" id="btn-fen" style="display:none;">FEN</button>
        <button class="btn btn-ghost btn-sm" id="btn-rematch" style="display:none;">اعادة</button>
      </div>
    </div>
  `;

  function loadS(src){return new Promise((r,j)=>{
    const existing = document.querySelector('script[src="'+src+'"]');
    if(existing){existing.remove();} // Remove old script to force re-execute
    const s=document.createElement('script');s.src=src;s.onload=r;s.onerror=j;document.body.appendChild(s);
  });}

  // Wait for DOM to settle, then load scripts sequentially
  requestAnimationFrame(() => {
    loadS('/public/js/chess.min.js')
      .then(() => loadS('/public/js/openings.js'))
      .then(() => loadS('/public/js/board.js'))
      .then(() => loadS('/public/js/game.js'))
      .then(() => {
        // Verify #board exists before init
        const boardEl = document.getElementById('board');
        if (!boardEl) { console.error('Board element not found!'); return; }
        if (window.Board) Board.init('board', { flipped: params.color === 'b', playerColor: params.color || 'w' });
        if (window.Game) Game.start({
          color: params.color || 'w',
          botId: params.bot || 'nour',
          time: parseInt(params.time) || 300,
          increment: parseInt(params.inc) || 0,
          rated: params.rated !== 'false'
        });
      })
      .catch(e => console.error('Script load error:', e));
  });
});

defineScreen('/game-live', function gameLiveScreen() {
  document.getElementById('shell').classList.add('immersive');
  const params = Object.fromEntries(new URLSearchParams(location.search));

  main.innerHTML = `
    <div class="chess-game-wrap">
      <div class="chess-top-bar"><div class="chess-player-bar"><span class="chess-player-name" id="opp-name">خصم</span><span class="chess-clock" id="clock-top">--:--</span></div></div>
      <div class="board-wrapper" style="width:min(calc(100vw - 24px), 400px);margin:0 auto;"><div id="board"></div></div>
      <div class="chess-bottom-bar"><div class="chess-player-bar"><span class="chess-player-name" id="player-name">انت</span><span class="chess-clock" id="clock-bottom">--:--</span></div></div>
      <div id="opening-display" style="text-align:center;font-size:12px;color:var(--text-2);min-height:18px;margin:4px 0;"></div>
      <div id="opening-display-mobile" style="display:none;"></div>
      <div id="thinking-indicator" style="text-align:center;font-size:12px;color:var(--gold);min-height:18px;"></div>
      <div id="game-status" style="text-align:center;font-size:13px;font-weight:600;min-height:20px;margin:4px 0;"></div>
      <div id="game-status-mobile" style="display:none;"></div>
      <div class="chess-move-list-wrap"><div id="move-list" class="chess-move-list"></div><div id="move-list-mobile" style="display:none;"></div></div>
      <div class="chess-actions">
        <button class="btn btn-ghost btn-sm" id="btn-resign">استسلام</button>
        <button class="btn btn-ghost btn-sm" id="btn-draw">عرض تعادل</button>
        <button class="btn btn-ghost btn-sm" id="btn-flip" onclick="if(Board&&Board.flip)Board.flip()">🔄</button>
        <button class="btn btn-ghost btn-sm" id="btn-rematch" style="display:none;">اعادة</button>
      </div>
      <div id="draw-offer-banner" style="display:none;text-align:center;padding:8px;background:var(--gold-dim);border-radius:var(--radius-sm);margin:8px 0;">
        <span>خصمك يعرض تعادل</span>
        <button class="btn btn-sm btn-gold" id="btn-accept-draw" style="margin-right:8px;">قبول</button>
        <button class="btn btn-sm btn-ghost" id="btn-decline-draw">رفض</button>
      </div>
    </div>
  `;

  function loadS(src){return new Promise((r,j)=>{if(document.querySelector('script[src="'+src+'"]')){r();return;}const s=document.createElement('script');s.src=src;s.onload=r;s.onerror=j;document.body.appendChild(s);});}

  Promise.all([
    loadS('/public/js/chess.min.js'),
    loadS('/public/js/openings.js'),
    loadS('/public/js/board.js'),
    loadS('/public/js/realtime.js'),
    loadS('/public/js/game-live.js')
  ]).then(() => {
    if (window.LiveGame) LiveGame.init(params.match_id);
  });
});

defineScreen('/analysis', function analysisScreen() {
  const params = Object.fromEntries(new URLSearchParams(location.search));

  main.innerHTML = `
    <h2 class="text-center mb-4" style="font-size:18px;font-weight:700;">📊 تحليل المباراة</h2>
    <div id="analysis-loading" class="text-center" style="color:var(--text-2);">جاري التحميل...</div>
    <div id="analysis-content" style="display:none;">
      <div style="display:flex;gap:12px;margin-bottom:12px;justify-content:center;">
        <div style="text-align:center;"><span id="analysis-player-name" style="font-size:13px;font-weight:600;">انت</span><br><span id="analysis-player-accuracy" style="font-size:18px;font-weight:700;color:var(--win);">--%</span></div>
        <div style="text-align:center;"><span id="analysis-opponent-name" style="font-size:13px;font-weight:600;">خصم</span><br><span id="analysis-opponent-accuracy" style="font-size:18px;font-weight:700;color:var(--loss);">--%</span></div>
      </div>
      <div id="eval-bar" style="height:24px;background:var(--bg-3);border-radius:var(--radius-sm);overflow:hidden;margin-bottom:8px;position:relative;">
        <div id="eval-bar-fill" style="height:100%;width:50%;background:var(--text-1);transition:width 0.3s;"></div>
        <span id="eval-bar-value" style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);font-size:11px;font-weight:700;mix-blend-mode:difference;">0.0</span>
      </div>
      <div class="board-wrapper" style="width:min(calc(100vw - 24px), 400px);margin:0 auto 12px;"><div id="board"></div></div>
      <canvas id="eval-graph" width="320" height="60" style="width:100%;height:60px;background:var(--bg-2);border-radius:var(--radius-sm);margin-bottom:8px;"></canvas>
      <div id="analysis-opening" style="text-align:center;font-size:12px;color:var(--text-2);margin-bottom:8px;"></div>
      <div style="display:flex;gap:8px;justify-content:center;margin-bottom:12px;">
        <button class="btn btn-ghost btn-sm" id="btn-first">⏮</button>
        <button class="btn btn-ghost btn-sm" id="btn-prev">◀</button>
        <button class="btn btn-ghost btn-sm" id="btn-next">▶</button>
        <button class="btn btn-ghost btn-sm" id="btn-last">⏭</button>
      </div>
      <div id="analysis-moves" class="chess-move-list" style="max-height:120px;overflow-y:auto;margin-bottom:12px;"></div>
      <div id="critical-moments" style="margin-bottom:12px;"></div>
      <button class="btn btn-gold btn-block" id="btn-analyze">🔍 تحليل بالمحرك</button>
      <canvas id="time-graph" width="320" height="60" style="width:100%;height:60px;background:var(--bg-2);border-radius:var(--radius-sm);margin-top:8px;display:none;"></canvas>
    </div>
  `;

  function loadS(src){return new Promise((r,j)=>{if(document.querySelector('script[src="'+src+'"]')){r();return;}const s=document.createElement('script');s.src=src;s.onload=r;s.onerror=j;document.body.appendChild(s);});}

  Promise.all([
    loadS('/public/js/chess.min.js'),
    loadS('/public/js/openings.js'),
    loadS('/public/js/board.js'),
    loadS('/public/js/analysis.js')
  ]).then(() => {
    if (window.Analysis) Analysis.init(params.id);
  });
});

defineScreen('/puzzles', function puzzlesScreen() {
  main.innerHTML = `
    <h2 class="text-center mb-4" style="font-size:20px;font-weight:700;">🧩 تمارين شطرنج</h2>
    <div id="puzzle-tabs" class="chips mb-4" style="justify-content:center;">
      <button class="chip on" data-tab="daily">اليومية</button>
      <button class="chip" data-tab="streak">سلسلة</button>
      <button class="chip" data-tab="rush">سباق</button>
    </div>
    <div id="tab-daily">
      <div class="daily-dots" style="display:flex;gap:8px;justify-content:center;margin-bottom:12px;">
        <span class="daily-dot" style="width:12px;height:12px;border-radius:50%;background:var(--bg-3);border:2px solid var(--border);"></span>
        <span class="daily-dot" style="width:12px;height:12px;border-radius:50%;background:var(--bg-3);border:2px solid var(--border);"></span>
        <span class="daily-dot" style="width:12px;height:12px;border-radius:50%;background:var(--bg-3);border:2px solid var(--border);"></span>
        <span class="daily-dot" style="width:12px;height:12px;border-radius:50%;background:var(--bg-3);border:2px solid var(--border);"></span>
        <span class="daily-dot" style="width:12px;height:12px;border-radius:50%;background:var(--bg-3);border:2px solid var(--border);"></span>
      </div>
    </div>
    <div id="puzzle-board-area">
      <div style="text-align:center;margin-bottom:8px;">
        <span id="current-puzzle-rating" style="font-size:12px;color:var(--text-2);"></span>
        <span id="puzzle-turn" style="font-size:12px;color:var(--gold);margin-right:12px;"></span>
      </div>
      <div class="board-wrapper" style="width:min(calc(100vw - 24px), 400px);margin:0 auto;"><div id="board"></div></div>
      <div id="puzzle-status" style="text-align:center;font-size:14px;font-weight:600;margin:12px 0;min-height:20px;"></div>
      <div id="puzzle-result" style="display:none;text-align:center;margin:12px 0;">
        <span id="puzzle-result-icon" style="font-size:32px;"></span>
        <p id="puzzle-result-text" style="font-size:14px;font-weight:600;margin-top:4px;"></p>
      </div>
      <button class="btn btn-gold btn-block" onclick="if(Puzzles&&Puzzles.nextPuzzle)Puzzles.nextPuzzle()">التالي ▶</button>
    </div>
    <div id="rush-timer" style="display:none;text-align:center;margin:12px 0;">
      <span id="rush-time" style="font-size:24px;font-weight:700;font-variant-numeric:tabular-nums;">3:00</span>
      <span id="rush-count" style="display:block;font-size:13px;color:var(--text-2);">0 حل</span>
    </div>
    <button class="btn btn-ghost btn-block" id="btn-start-rush" style="display:none;" onclick="if(Puzzles&&Puzzles.startRush)Puzzles.startRush()">ابدأ السباق</button>
  `;

  // Chip tabs
  document.querySelectorAll('#puzzle-tabs .chip').forEach(c => {
    c.onclick = () => {
      document.querySelectorAll('#puzzle-tabs .chip').forEach(x => x.classList.remove('on'));
      c.classList.add('on');
    };
  });

  function loadS(src){return new Promise((r,j)=>{if(document.querySelector('script[src="'+src+'"]')){r();return;}const s=document.createElement('script');s.src=src;s.onload=r;s.onerror=j;document.body.appendChild(s);});}

  Promise.all([
    loadS('/public/js/chess.min.js'),
    loadS('/public/js/board.js'),
    loadS('/public/js/puzzles.js')
  ]).then(() => {
    if (window.Puzzles) Puzzles.init();
  });
});

defineScreen('/matchmaking', function matchmakingScreen() {
  const params = Object.fromEntries(new URLSearchParams(location.search));
  main.innerHTML = `
    <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:60vh;text-align:center;">
      <div class="matchmaking-radar">
        <div class="radar-ring"></div>
        <div class="radar-ring r2"></div>
        <div class="radar-ring r3"></div>
        <span style="font-size:32px;position:relative;z-index:1;">⚔️</span>
      </div>
      <p style="font-size:16px;font-weight:700;margin-top:20px;">جاري البحث عن خصم...</p>
      <p style="font-size:13px;color:var(--text-2);margin-top:8px;" id="mm-status">الانتظار: <span id="mm-timer">0</span> ثانية</p>
      <button class="btn btn-ghost" style="margin-top:24px;" id="mm-cancel">الغاء</button>
    </div>
  `;

  let seconds = 0;
  let polling = null;
  const timerEl = document.getElementById('mm-timer');

  const timerInterval = setInterval(() => { seconds++; if(timerEl) timerEl.textContent = seconds; }, 1000);

  // Join queue
  App.fetch('/api/matchmaking', { method:'POST', body: JSON.stringify({ action:'join', game_key:'chess', time_control: params.tc, rating: 1200 }) });

  // Poll for match
  polling = setInterval(async () => {
    const res = await App.fetch('/api/matchmaking?action=status');
    if (res && res.status === 'matched' && res.match_id) {
      clearInterval(timerInterval);
      clearInterval(polling);
      SFX.win();
      H.success();
      location.href = '/game-live?match_id=' + res.match_id;
    }
  }, 2000);

  document.getElementById('mm-cancel').onclick = () => {
    clearInterval(timerInterval);
    clearInterval(polling);
    App.fetch('/api/matchmaking', { method:'POST', body: JSON.stringify({ action:'cancel' }) });
    route(null, '/play');
  };
});

defineScreen('/ludo', function ludoLobby() {
  main.innerHTML = `
    <h2 class="text-center mb-5" style="font-size:20px;font-weight:700;">🎲 لودو</h2>
    <div class="card card-pad mb-4">
      <p style="font-size:15px;font-weight:700;margin-bottom:12px;">مباراة سريعة</p>
      <div class="chips mb-3" id="ludo-count"><button class="chip" data-n="2">2</button><button class="chip on" data-n="3">3</button><button class="chip" data-n="4">4</button></div>
      <div class="chips mb-4" id="ludo-diff"><button class="chip on" data-d="easy">سهل</button><button class="chip" data-d="hard">صعب</button></div>
      <button class="btn btn-gold btn-block btn-lg" id="btn-ludo">ابدأ</button>
    </div>
  `;
  document.querySelectorAll('.chips').forEach(g => g.querySelectorAll('.chip').forEach(c => { c.onclick=()=>{g.querySelectorAll('.chip').forEach(x=>x.classList.remove('on'));c.classList.add('on');}; }));
  document.getElementById('btn-ludo').onclick = async () => {
    const count = parseInt(document.querySelector('#ludo-count .on').dataset.n);
    const diff = document.querySelector('#ludo-diff .on').dataset.d;
    const bots = []; for(let i=1;i<count;i++) bots.push({name:'بوت '+i, difficulty:diff});
    const res = await App.fetch('/api/ludo', {method:'POST', body:JSON.stringify({action:'create', player_count:count, bots})});
    if(res&&res.ok) { const sr = await App.fetch('/api/ludo',{method:'POST',body:JSON.stringify({action:'start',match_id:res.match.id})}); if(sr&&sr.ok) location.href='/ludo-game?match_id='+sr.match.id; }
  };
});

defineScreen('/domino', function dominoLobby() {
  main.innerHTML = `
    <h2 class="text-center mb-5" style="font-size:20px;font-weight:700;">🁣 دومينو</h2>
    <div class="card card-pad mb-4">
      <div class="chips mb-3" id="dom-mode"><button class="chip on" data-m="2p">فردي</button><button class="chip" data-m="4p_teams">فرق</button></div>
      <div class="chips mb-4" id="dom-diff"><button class="chip on" data-d="easy">سهل</button><button class="chip" data-d="medium">متوسط</button><button class="chip" data-d="hard">صعب</button></div>
      <button class="btn btn-gold btn-block btn-lg" id="btn-dom">ابدأ</button>
    </div>
  `;
  document.querySelectorAll('.chips').forEach(g => g.querySelectorAll('.chip').forEach(c => { c.onclick=()=>{g.querySelectorAll('.chip').forEach(x=>x.classList.remove('on'));c.classList.add('on');}; }));
  document.getElementById('btn-dom').onclick = async () => {
    const mode = document.querySelector('#dom-mode .on').dataset.m;
    const diff = document.querySelector('#dom-diff .on').dataset.d;
    const res = await App.fetch('/api/domino',{method:'POST',body:JSON.stringify({action:'create',mode,difficulty:diff})});
    if(res&&res.ok&&res.match){const sr=await App.fetch('/api/domino',{method:'POST',body:JSON.stringify({action:'start',match_id:res.match.id})});if(sr&&sr.ok)location.href='/domino-game?match_id='+sr.match.id;}
  };
});

defineScreen('/backgammon', function bgLobby() {
  main.innerHTML = `
    <h2 class="text-center mb-5" style="font-size:20px;font-weight:700;">🎯 طاولة</h2>
    <div class="card card-pad mb-4">
      <div class="chips mb-4" id="bg-len"><button class="chip on" data-l="1">1 نقطة</button><button class="chip" data-l="3">3</button><button class="chip" data-l="5">5</button></div>
      <button class="btn btn-gold btn-block btn-lg" id="btn-bg">انشئ غرفة</button>
    </div>
  `;
  document.querySelectorAll('.chips').forEach(g => g.querySelectorAll('.chip').forEach(c => { c.onclick=()=>{g.querySelectorAll('.chip').forEach(x=>x.classList.remove('on'));c.classList.add('on');}; }));
  document.getElementById('btn-bg').onclick = async () => {
    const len = parseInt(document.querySelector('#bg-len .on').dataset.l);
    const res = await App.fetch('/api/backgammon',{method:'POST',body:JSON.stringify({action:'create',match_length:len})});
    if(res&&res.ok&&res.match) location.href='/backgammon-game?match_id='+res.match.id;
  };
});

defineScreen('/profile', async function profileScreen() {
  main.innerHTML = '<div class="skel" style="height:200px;margin-bottom:16px;"></div><div class="skel" style="height:100px;"></div>';
  const data = await App.fetch('/api/profile');
  if(!data||!data.profile){main.innerHTML='<div class="empty">خطأ</div>';return;}
  const p = data.profile;
  main.innerHTML = `
    <div class="card card-pad text-center mb-4" style="padding:24px;">
      <div style="width:64px;height:64px;border-radius:50%;background:var(--bg-3);margin:0 auto 12px;display:flex;align-items:center;justify-content:center;box-shadow:0 0 0 3px var(--gold);">
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--text-2)" stroke-width="2"><circle cx="12" cy="7" r="4"/><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/></svg>
      </div>
      <h2 style="font-size:18px;font-weight:700;">${p.display_name||p.username}</h2>
      <p style="font-size:13px;color:var(--text-2);">@${p.username}</p>
      <div style="display:flex;gap:8px;justify-content:center;margin-top:12px;">
        <span class="stat-pill"><span class="stat-pill-val" style="color:var(--gold)">Lv ${p.level||1}</span></span>
        <span class="stat-pill"><span class="stat-pill-val">${p.total_games_played||0}</span><span class="stat-pill-lbl">مباراة</span></span>
        <span class="stat-pill"><span class="stat-pill-val" style="color:var(--win)">${p.total_wins||0}</span><span class="stat-pill-lbl">فوز</span></span>
      </div>
    </div>
    <div class="card card-pad mb-4" style="display:flex;justify-content:space-around;">
      <div class="text-center"><p style="font-size:18px;font-weight:700;color:var(--gold)">${(p.coins||0).toLocaleString()}</p><p style="font-size:10px;color:var(--text-2)">عملات</p></div>
      <div class="text-center"><p style="font-size:18px;font-weight:700;color:var(--purple)">${p.gems||0}</p><p style="font-size:10px;color:var(--text-2)">جواهر</p></div>
      <div class="text-center"><p style="font-size:18px;font-weight:700;">🔥 ${p.daily_streak||0}</p><p style="font-size:10px;color:var(--text-2)">ايام</p></div>
    </div>
    <button class="btn btn-ghost btn-block mb-3" onclick="route(event,'/settings')">⚙️ الاعدادات</button>
    <button class="btn btn-block" style="color:var(--loss);border:1px solid var(--loss-dim);" onclick="App.logout()">تسجيل خروج</button>
  `;
});

defineScreen('/leaderboard', async function lbScreen() {
  main.innerHTML = '<h2 class="text-center mb-4" style="font-size:20px;font-weight:700;">🏆 المتصدرين</h2><div class="card"><div class="skel" style="height:200px;"></div></div>';
  const data = await App.fetch('/api/leaderboard?mode=blitz');
  if(!data||!data.players||!data.players.length){main.querySelector('.card').innerHTML='<div class="empty">لا لاعبين بعد</div>';return;}
  main.querySelector('.card').innerHTML = '<div class="activity">'+data.players.map((p,i)=>{
    const medal = i===0?'🥇':i===1?'🥈':i===2?'🥉':(i+1);
    return '<div class="activity-item"><span style="min-width:28px;text-align:center;font-weight:700;">'+medal+'</span><div class="activity-text">'+(p.display_name||p.username)+'</div><span style="font-weight:700;font-variant-numeric:tabular-nums;">'+(p.elo_blitz||1200)+'</span></div>';
  }).join('')+'</div>';
});

defineScreen('/friends', async function friendsScreen() {
  main.innerHTML = '<h2 class="text-center mb-4" style="font-size:20px;font-weight:700;">👥 الاصدقاء</h2><div class="card"><div class="skel" style="height:150px;"></div></div>';
  const data = await App.fetch('/api/friends?action=list');
  if(!data||!data.friends||!data.friends.length){main.querySelector('.card').innerHTML='<div class="empty">لا اصدقاء بعد</div>';return;}
  main.querySelector('.card').innerHTML = '<div class="activity">'+data.friends.map(f=>'<div class="activity-item"><span style="width:8px;height:8px;border-radius:50%;background:'+(f.is_online?'var(--online)':'var(--text-3)')+'"></span><div class="activity-text">'+(f.display_name||f.username)+'</div><span style="font-size:11px;color:var(--text-2);">'+(f.is_online?'متصل':'غير متصل')+'</span></div>').join('')+'</div>';
});

defineScreen('/settings', function settingsScreen() {
  main.innerHTML = `
    <h2 class="text-center mb-5" style="font-size:20px;font-weight:700;">⚙️ الاعدادات</h2>
    <div class="card card-pad mb-3" style="display:flex;align-items:center;justify-content:space-between;">
      <span>🔊 الصوت</span>
      <button class="btn btn-ghost" id="snd-btn" style="min-height:36px;padding:6px 14px;font-size:12px;">${App.isMuted&&App.isMuted()?'مكتوم':'مفعل'}</button>
    </div>
    <button class="btn btn-block" style="color:var(--loss);border:1px solid var(--loss-dim);" onclick="App.logout()">تسجيل خروج</button>
  `;
  const btn = document.getElementById('snd-btn');
  if(btn) btn.onclick = () => { if(App.toggleMute) App.toggleMute(); btn.textContent = App.isMuted&&App.isMuted()?'مكتوم':'مفعل'; };
});

defineScreen('/games', function(){route(null,'/');});
defineScreen('/notifications', function(){main.innerHTML='<div class="empty">لا اشعارات جديدة</div>';});
defineScreen('/shop', async function(){main.innerHTML='<h2 class="text-center mb-4" style="font-size:20px;font-weight:700;">🛍️ المتجر</h2><div class="empty">قريبا</div>';});
defineScreen('/achievements', async function(){main.innerHTML='<h2 class="text-center mb-4" style="font-size:20px;font-weight:700;">🏅 الانجازات</h2><div class="empty">قريبا</div>';});

// === GAME PAGES (load via full page reload to ensure game engines get clean DOM) ===
defineScreen('/ludo-game', function(){ location.reload(); });
defineScreen('/domino-game', function(){ location.reload(); });
defineScreen('/backgammon-game', function(){ location.reload(); });

// === BOOT ===
(function boot() {
  const path = location.pathname;
  if (!App.isLoggedIn() && path !== '/login' && path !== '/register') {
    render('/login');
    return;
  }
  if (App.isLoggedIn() && path === '/login') { history.replaceState({},'','/'); render('/'); return; }

  // Show/hide header+nav for login
  if (path !== '/login') {
    document.getElementById('hdr').classList.remove('hide');
    document.getElementById('nav').classList.remove('hide');
  }

  // Exit immersive if not on /game
  if (path !== '/game') document.getElementById('shell').classList.remove('immersive');

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