// Screens for Persian Backgammon — Splash, Home, Difficulty, Game, Settings, Results, Tutorial
// Each screen is a function returning JSX sized for IOSDevice content area (402×874 minus chrome).

const FONT = {
  serif: "'Cormorant Garamond', 'Garamond', 'Times New Roman', serif",
  sans: "'SF Pro Display', -apple-system, system-ui, sans-serif",
};

// ─────────────────────────────────────────────────────────────
// Top chrome — used by all non-splash screens
// ─────────────────────────────────────────────────────────────
// iOS 26 glass-pill nav, recolored with our brand glass tint.
function ScreenChrome({ dark, onBack, title, onSettings, largeTitle = false }) {
  const t = themeFor(dark);
  const muted = dark ? 'rgba(244,235,217,0.7)' : 'rgba(31,27,22,0.65)';
  const pill = (content, onClick) => (
    <div onClick={onClick} style={{
      height: 38, minWidth: 38, borderRadius: 9999, position: 'relative', overflow: 'hidden',
      display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: onClick ? 'pointer' : 'default',
      boxShadow: dark
        ? '0 2px 6px rgba(0,0,0,0.35), 0 6px 16px rgba(0,0,0,0.2)'
        : '0 1px 3px rgba(0,0,0,0.07), 0 3px 10px rgba(0,0,0,0.06)',
    }}>
      <div style={{
        position: 'absolute', inset: 0, borderRadius: 9999,
        backdropFilter: 'blur(12px) saturate(180%)', WebkitBackdropFilter: 'blur(12px) saturate(180%)',
        background: dark ? 'rgba(43,183,179,0.16)' : 'rgba(255,252,245,0.55)',
      }}/>
      <div style={{
        position: 'absolute', inset: 0, borderRadius: 9999,
        boxShadow: dark
          ? 'inset 1.5px 1.5px 1px rgba(255,255,255,0.12), inset -1px -1px 1px rgba(255,255,255,0.06)'
          : 'inset 1.5px 1.5px 1px rgba(255,255,255,0.7), inset -1px -1px 1px rgba(255,255,255,0.4)',
        border: dark ? '0.5px solid rgba(212,162,76,0.25)' : '0.5px solid rgba(31,27,22,0.06)',
      }}/>
      <div style={{ position: 'relative', zIndex: 1, padding: '0 10px', display: 'flex', alignItems: 'center', gap: 6, color: muted }}>
        {content}
      </div>
    </div>
  );
  return (
    <div style={{
      display: 'flex', flexDirection: 'column', gap: largeTitle ? 14 : 4,
      paddingTop: 56, paddingBottom: 8, position: 'relative', zIndex: 5,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 16px' }}>
        {onBack ? pill(
          <svg width="12" height="20" viewBox="0 0 12 20" fill="none">
            <path d="M10 2L2 10l8 8" stroke={muted} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>, onBack) : <div style={{ width: 38 }}/>}
        {!largeTitle && (
          <div style={{ fontFamily: FONT.serif, fontSize: 18, fontWeight: 500, letterSpacing: 0.3, color: t.fg }}>{title}</div>
        )}
        {onSettings ? pill(
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={muted} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <circle cx="12" cy="12" r="3"/>
            <path d="M19.4 15a1.7 1.7 0 00.3 1.8l.1.1a2 2 0 11-2.8 2.8l-.1-.1a1.7 1.7 0 00-1.8-.3 1.7 1.7 0 00-1 1.5V21a2 2 0 11-4 0v-.1a1.7 1.7 0 00-1.1-1.5 1.7 1.7 0 00-1.8.3l-.1.1a2 2 0 11-2.8-2.8l.1-.1a1.7 1.7 0 00.3-1.8 1.7 1.7 0 00-1.5-1H3a2 2 0 110-4h.1a1.7 1.7 0 001.5-1.1 1.7 1.7 0 00-.3-1.8l-.1-.1a2 2 0 112.8-2.8l.1.1a1.7 1.7 0 001.8.3H9a1.7 1.7 0 001-1.5V3a2 2 0 114 0v.1a1.7 1.7 0 001 1.5 1.7 1.7 0 001.8-.3l.1-.1a2 2 0 112.8 2.8l-.1.1a1.7 1.7 0 00-.3 1.8V9a1.7 1.7 0 001.5 1H21a2 2 0 110 4h-.1a1.7 1.7 0 00-1.5 1z"/>
          </svg>, onSettings) : <div style={{ width: 38 }}/>}
      </div>
      {largeTitle && (
        <div style={{ padding: '0 18px', fontFamily: FONT.serif, fontSize: 38, fontWeight: 500, lineHeight: '44px', color: t.fg, letterSpacing: 0.5 }}>
          {title}
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 1. SPLASH
// ─────────────────────────────────────────────────────────────
function SplashScreen({ dark }) {
  const t = themeFor(dark);
  return (
    <div style={{
      width: '100%', height: '100%', position: 'relative',
      background: dark
        ? `radial-gradient(circle at 50% 40%, #2A2520 0%, ${NARD.c.charcoal} 60%, ${NARD.c.charcoalDeep} 100%)`
        : `radial-gradient(circle at 50% 40%, ${NARD.c.paper} 0%, ${NARD.c.cream} 60%, #F0E6CF 100%)`,
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      overflow: 'hidden',
    }}>
      <GirihPattern color={dark ? NARD.c.gold : NARD.c.cobalt} opacity={dark ? 0.06 : 0.05} size={140}/>
      {/* Large unfurling girih in center, faded */}
      <div style={{
        position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%) scale(2.4)',
        opacity: 0.18,
      }}>
        <GirihTile size={180} stroke={dark ? NARD.c.gold : NARD.c.cobalt} strokeWidth={0.6}/>
      </div>
      <div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 22 }}>
        <Logo size={104} color={NARD.c.turquoise} accent={NARD.c.gold}/>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontFamily: FONT.serif, fontWeight: 500, fontSize: 52, color: t.fg, letterSpacing: 4, lineHeight: 1 }}>
            NARD
          </div>
          <div style={{ fontFamily: FONT.serif, fontSize: 16, color: t.fgMute, marginTop: 8, letterSpacing: 6, textTransform: 'uppercase' }}>
            تخته نرد
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 80, color: t.fgFaint, fontFamily: FONT.sans, fontSize: 11, letterSpacing: 2, textTransform: 'uppercase' }}>
          <div style={{ width: 24, height: 0.5, background: 'currentColor' }}/>
          since 3000 BCE
          <div style={{ width: 24, height: 0.5, background: 'currentColor' }}/>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 2. HOME
// ─────────────────────────────────────────────────────────────
function HomeScreen({ dark, onPlay, onStats, onSettings, onTutorial, difficulty, setDifficulty }) {
  const t = themeFor(dark);
  const levels = [
    { id: 'beginner', en: 'Beginner', fa: 'Tazeh-kar' },
    { id: 'intermediate', en: 'Intermediate', fa: 'Mian' },
    { id: 'master', en: 'Master', fa: 'Ostad' },
  ];

  return (
    <div style={{ width: '100%', minHeight: '100%', background: t.bg, position: 'relative', paddingBottom: 40 }}>
      <GirihPattern color={dark ? NARD.c.turquoise : NARD.c.cobalt} opacity={dark ? 0.05 : 0.04} size={120}/>
      <div style={{ position: 'relative', padding: '20px 24px 0' }}>
        {/* Header w/ logo and small icon row */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
          <Logo size={36} color={NARD.c.turquoise} accent={NARD.c.gold}/>
          <div style={{ display: 'flex', gap: 14, color: t.fgMute }}>
            <Icon name="stats" size={20}/>
            <Icon name="book" size={20}/>
            <Icon name="gear" size={20}/>
          </div>
        </div>

        {/* Hero title */}
        <div style={{ marginTop: 18 }}>
          <div style={{ fontFamily: FONT.serif, fontSize: 56, fontWeight: 500, lineHeight: 1, color: t.fg, letterSpacing: 1 }}>
            Nard
          </div>
          <div style={{ fontFamily: FONT.sans, fontSize: 13, color: t.fgMute, marginTop: 8, letterSpacing: 0.5 }}>
            A backgammon set for the heirs of Isfahan.
          </div>
        </div>

        {/* Primary CTA card */}
        <div onClick={onPlay} style={{
          marginTop: 28, borderRadius: 18, padding: 20,
          background: `linear-gradient(135deg, ${NARD.c.turquoise} 0%, ${NARD.c.turquoiseDeep} 100%)`,
          color: NARD.c.paper, position: 'relative', overflow: 'hidden',
          boxShadow: '0 8px 24px rgba(43,183,179,0.3)',
          cursor: 'pointer',
        }}>
          {/* faint girih on cta */}
          <div style={{ position: 'absolute', right: -20, top: -20, opacity: 0.2 }}>
            <GirihTile size={140} stroke={NARD.c.paper} strokeWidth={0.6}/>
          </div>
          <div style={{ position: 'relative' }}>
            <div style={{ fontFamily: FONT.sans, fontSize: 12, letterSpacing: 1.5, textTransform: 'uppercase', opacity: 0.8 }}>Play</div>
            <div style={{ fontFamily: FONT.serif, fontSize: 28, fontWeight: 500, marginTop: 4 }}>
              vs. Computer
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 18 }}>
              <div style={{ width: 36, height: 36, borderRadius: 18, background: 'rgba(255,255,255,0.18)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name="play" size={14} color={NARD.c.paper}/>
              </div>
              <div style={{ fontSize: 13 }}>Tap to start a match</div>
            </div>
          </div>
        </div>

        {/* Difficulty pills */}
        <div style={{ marginTop: 22 }}>
          <div style={{ fontFamily: FONT.sans, fontSize: 11, letterSpacing: 1.5, textTransform: 'uppercase', color: t.fgMute, marginBottom: 10 }}>
            Difficulty
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            {levels.map(l => {
              const sel = difficulty === l.id;
              return (
                <div key={l.id} onClick={() => setDifficulty(l.id)} style={{
                  flex: 1, borderRadius: 12, padding: '10px 8px', textAlign: 'center', cursor: 'pointer',
                  background: sel ? (dark ? NARD.c.gold : NARD.c.charcoal) : t.card,
                  color: sel ? (dark ? NARD.c.charcoal : NARD.c.paper) : t.fg,
                  border: sel ? 'none' : `0.5px solid ${t.line}`,
                  transition: 'all 160ms',
                }}>
                  <div style={{ fontFamily: FONT.sans, fontSize: 13, fontWeight: 600 }}>{l.en}</div>
                  <div style={{ fontFamily: FONT.serif, fontSize: 12, opacity: 0.7, marginTop: 2, fontStyle: 'italic' }}>{l.fa}</div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Secondary tiles */}
        <div style={{ marginTop: 20, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <Tile dark={dark} icon="trophy" label="Stats" sub="3 wins · 1 loss" onClick={onStats}/>
          <Tile dark={dark} icon="book" label="How to Play" sub="8 chapters" onClick={onTutorial}/>
        </div>

        {/* heritage note */}
        <div style={{ marginTop: 26, textAlign: 'center', fontFamily: FONT.serif, fontSize: 11, color: t.fgFaint, fontStyle: 'italic', letterSpacing: 0.5 }}>
          Backgammon · Persia · since 3000 BCE
        </div>
      </div>
    </div>
  );
}

function Tile({ dark, icon, label, sub, onClick }) {
  const t = themeFor(dark);
  return (
    <div onClick={onClick} style={{
      borderRadius: 12, padding: 14, background: t.card,
      border: `0.5px solid ${t.line}`, cursor: 'pointer',
      display: 'flex', flexDirection: 'column', gap: 6,
    }}>
      <div style={{ width: 30, height: 30, borderRadius: 8, background: dark ? 'rgba(43,183,179,0.15)' : 'rgba(43,183,179,0.12)', color: NARD.c.turquoise, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon name={icon} size={16} color={NARD.c.turquoise}/>
      </div>
      <div style={{ fontFamily: FONT.sans, fontSize: 14, fontWeight: 600, color: t.fg, marginTop: 4 }}>{label}</div>
      <div style={{ fontFamily: FONT.sans, fontSize: 11, color: t.fgMute }}>{sub}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 3. GAME
// ─────────────────────────────────────────────────────────────
function GameScreen({ dark, onBack, onSettings, checkerStyle }) {
  const game = useGameState();
  const t = themeFor(dark);
  return (
    <div style={{ width: '100%', minHeight: '100%', background: t.bg, position: 'relative' }}>
      <GirihPattern color={dark ? NARD.c.turquoise : NARD.c.cobalt} opacity={dark ? 0.04 : 0.03} size={140}/>
      <ScreenChrome dark={dark} title="Round 1 · 3 pts" onBack={onBack} onSettings={onSettings}/>

      {/* Top HUD: opponent (cobalt) */}
      <PlayerHUD dark={dark} side="cobalt" name="Ostad AI" pip={167} active={game.turn === 'cobalt'} bar={game.pos.bar.cobalt} off={game.pos.off.cobalt}/>

      {/* Board */}
      <div style={{ display: 'flex', justifyContent: 'center', padding: '8px 0' }}>
        <Board pos={game.pos} dice={game.dice} used={game.used} selected={game.selected}
          onPointTap={(idx) => game.setSelected(game.selected === idx ? null : idx)}
          dark={dark} checkerStyle={checkerStyle} cube={game.cube}
        />
      </div>

      {/* Bottom HUD: player (gold) */}
      <PlayerHUD dark={dark} side="gold" name="You" pip={167} active={game.turn === 'gold'} bar={game.pos.bar.gold} off={game.pos.off.gold}/>

      {/* Action row */}
      <div style={{ padding: '12px 24px 24px', display: 'flex', gap: 10, alignItems: 'center', justifyContent: 'space-between' }}>
        <ActionButton dark={dark} icon="undo" label="Undo" subtle onClick={() => {}}/>
        <RollButton dark={dark} onClick={game.roll} rolling={game.rolling}/>
        <ActionButton dark={dark} icon="chevron" label="Double" subtle onClick={() => game.setCube({ value: 2, owner: 'gold' })}/>
      </div>
    </div>
  );
}

function PlayerHUD({ dark, side, name, pip, active, bar, off }) {
  const t = themeFor(dark);
  const accent = side === 'gold' ? NARD.c.gold : NARD.c.cobalt;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '8px 24px',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{
          width: 30, height: 30, borderRadius: 15,
          background: side === 'gold'
            ? 'linear-gradient(135deg, #E8B963, #A87A2C)'
            : 'linear-gradient(135deg, #3457B0, #152969)',
          boxShadow: active ? `0 0 0 2px ${accent}, 0 0 12px ${accent}80` : 'none',
          transition: 'box-shadow 200ms',
        }}/>
        <div>
          <div style={{ fontFamily: FONT.sans, fontSize: 13, fontWeight: 600, color: t.fg }}>{name}</div>
          <div style={{ fontFamily: FONT.sans, fontSize: 10, color: t.fgMute, letterSpacing: 0.5 }}>
            {active ? 'YOUR TURN' : 'WAITING'}
          </div>
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, fontFamily: FONT.serif, fontSize: 14, color: t.fgMute }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
          <span style={{ fontSize: 10, letterSpacing: 1, textTransform: 'uppercase', color: t.fgFaint }}>Pip</span>
          <span style={{ fontSize: 18, fontWeight: 500, color: t.fg }}>{pip}</span>
        </div>
        {bar > 0 && <div style={{ fontSize: 11, padding: '2px 8px', borderRadius: 8, background: NARD.c.brick, color: NARD.c.paper }}>BAR · {bar}</div>}
        {off > 0 && <div style={{ fontSize: 11, color: NARD.c.gold }}>↗ {off}</div>}
      </div>
    </div>
  );
}

function RollButton({ dark, onClick, rolling }) {
  return (
    <div onClick={onClick} style={{
      flex: 1, padding: '12px 16px', borderRadius: 12,
      background: `linear-gradient(135deg, ${NARD.c.turquoise} 0%, ${NARD.c.turquoiseDeep} 100%)`,
      color: NARD.c.paper, textAlign: 'center', cursor: 'pointer',
      boxShadow: '0 6px 16px rgba(43,183,179,0.35)',
      fontFamily: FONT.sans, fontSize: 15, fontWeight: 600,
      letterSpacing: 0.5, transform: rolling ? 'scale(0.97)' : 'scale(1)',
      transition: 'transform 180ms',
    }}>
      {rolling ? 'Rolling…' : 'Roll Dice'}
    </div>
  );
}

function ActionButton({ dark, icon, label, subtle, onClick }) {
  const t = themeFor(dark);
  return (
    <div onClick={onClick} style={{
      width: 60, padding: '10px 8px', borderRadius: 12,
      background: t.card, border: `0.5px solid ${t.line}`,
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
      color: t.fgMute, cursor: 'pointer',
    }}>
      <Icon name={icon} size={16}/>
      <div style={{ fontFamily: FONT.sans, fontSize: 10, letterSpacing: 0.5 }}>{label}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 4. DIFFICULTY SELECT
// ─────────────────────────────────────────────────────────────
function DifficultyScreen({ dark, onBack, onPick }) {
  const t = themeFor(dark);
  const levels = [
    { id: 'beginner', en: 'Beginner', fa: 'Tazeh-kar', desc: 'Learning the game.', meter: 1, accent: NARD.c.turquoise },
    { id: 'intermediate', en: 'Intermediate', fa: 'Mian', desc: 'A worthy match.', meter: 2, accent: NARD.c.gold },
    { id: 'master', en: 'Master', fa: 'Ostad', desc: 'A true master.', meter: 3, accent: NARD.c.brick },
  ];
  return (
    <div style={{ width: '100%', minHeight: '100%', background: t.bg, position: 'relative' }}>
      <GirihPattern color={dark ? NARD.c.turquoise : NARD.c.cobalt} opacity={dark ? 0.04 : 0.03} size={120}/>
      <ScreenChrome dark={dark} title="Choose your match" onBack={onBack} largeTitle/>
      <div style={{ padding: '4px 20px 24px' }}>
        <div style={{ fontFamily: FONT.serif, fontSize: 22, fontWeight: 400, fontStyle: 'italic', color: t.fgMute, lineHeight: 1.2 }}>
          Find a worthy opponent.
        </div>
        <div style={{ fontFamily: FONT.sans, fontSize: 13, color: t.fgMute, marginTop: 8 }}>
          Each level adapts its play style to yours.
        </div>
        <div style={{ marginTop: 24, display: 'flex', flexDirection: 'column', gap: 12 }}>
          {levels.map(l => (
            <div key={l.id} onClick={() => onPick(l.id)} style={{
              borderRadius: 16, padding: 18, background: t.card,
              border: `0.5px solid ${t.line}`, cursor: 'pointer',
              position: 'relative', overflow: 'hidden',
              boxShadow: t.cardElev,
            }}>
              <div style={{ position: 'absolute', right: -10, top: -10, opacity: 0.1 }}>
                <GirihTile size={100} stroke={l.accent} strokeWidth={0.6}/>
              </div>
              <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                    <div style={{ fontFamily: FONT.serif, fontSize: 26, fontWeight: 500, color: t.fg }}>{l.en}</div>
                    <div style={{ fontFamily: FONT.serif, fontSize: 14, fontStyle: 'italic', color: t.fgMute }}>· {l.fa}</div>
                  </div>
                  <div style={{ fontFamily: FONT.sans, fontSize: 13, color: t.fgMute, marginTop: 4 }}>{l.desc}</div>
                  <div style={{ display: 'flex', gap: 4, marginTop: 12 }}>
                    {[1,2,3].map(n => (
                      <div key={n} style={{
                        width: 18, height: 4, borderRadius: 2,
                        background: n <= l.meter ? l.accent : t.line,
                      }}/>
                    ))}
                  </div>
                </div>
                <div style={{ color: t.fgMute }}><Icon name="chevron" size={20}/></div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 5. SETTINGS
// ─────────────────────────────────────────────────────────────
function SettingsScreen({ dark, onBack, settings, setSettings }) {
  const t = themeFor(dark);
  const set = (k, v) => setSettings({ ...settings, [k]: v });

  return (
    <div style={{ width: '100%', minHeight: '100%', background: t.bg, position: 'relative' }}>
      <GirihPattern color={dark ? NARD.c.turquoise : NARD.c.cobalt} opacity={dark ? 0.04 : 0.03} size={120}/>
      <ScreenChrome dark={dark} title="Settings" onBack={onBack} largeTitle/>
      <div style={{ padding: '4px 16px 32px' }}>
        <IOS26Group title="Audio" dark={dark}>
          <IOS26Row dark={dark} iconBg={NARD.c.turquoise} icon="sound" label="Sound effects" right={<Toggle on={settings.sfx} onClick={() => set('sfx', !settings.sfx)}/>}/>
          <IOS26Row dark={dark} iconBg={NARD.c.brick} icon="music" label="Background music" right={<Toggle on={settings.music} onClick={() => set('music', !settings.music)}/>}/>
          <IOS26Row dark={dark} iconBg={NARD.c.gold} icon="haptic" label="Haptics" right={<Toggle on={settings.haptics} onClick={() => set('haptics', !settings.haptics)}/>} isLast/>
        </IOS26Group>

        <IOS26Group title="Board theme" dark={dark}>
          {[
            { id: 'isfahan', name: 'Isfahan', sub: 'Turquoise tilework', unlocked: true, c1: NARD.c.turquoise, c2: NARD.c.cobalt },
            { id: 'khatam', name: 'Khatam', sub: 'Inlaid marquetry', unlocked: false, c1: NARD.c.gold, c2: NARD.c.brick },
            { id: 'garden', name: 'Persian Garden', sub: 'Rose & cypress', unlocked: false, c1: '#7BA068', c2: '#C44E4E' },
            { id: 'teahouse', name: 'Tea House', sub: 'Deep saffron', unlocked: false, c1: '#A87A2C', c2: '#3A2218' },
          ].map((th, i, arr) => (
            <IOS26ThemeRow key={th.id} dark={dark} th={th} isLast={i === arr.length - 1}/>
          ))}
        </IOS26Group>

        <IOS26Group title="Match" dark={dark}>
          <IOS26Row dark={dark} iconBg={NARD.c.cobalt} icon="info" label="Doubling cube" right={<Toggle on={settings.cube} onClick={() => set('cube', !settings.cube)}/>}/>
          <IOS26Row dark={dark} iconBg={NARD.c.charcoal} icon="trophy" label="Match length" right={
            <div style={{ display: 'flex', gap: 4 }}>
              {[1,3,5,7].map(n => (
                <div key={n} onClick={() => set('matchLen', n)} style={{
                  padding: '4px 10px', borderRadius: 8, fontFamily: FONT.serif, fontSize: 14, fontWeight: 500,
                  background: settings.matchLen === n ? NARD.c.turquoise : 'transparent',
                  color: settings.matchLen === n ? NARD.c.paper : (dark ? 'rgba(235,235,245,0.6)' : 'rgba(60,60,67,0.6)'),
                  border: `0.5px solid ${settings.matchLen === n ? NARD.c.turquoise : (dark ? 'rgba(84,84,88,0.5)' : 'rgba(60,60,67,0.18)')}`,
                  cursor: 'pointer',
                }}>{n}</div>
              ))}
            </div>
          } isLast/>
        </IOS26Group>

        <IOS26Group title="More" dark={dark}>
          <IOS26Row dark={dark} iconBg={NARD.c.turquoiseDeep} icon="book" label="Language" detail="English"/>
          <IOS26Row dark={dark} iconBg={NARD.c.gold} icon="info" label="About & credits" chevron isLast/>
        </IOS26Group>

        <div style={{ textAlign: 'center', marginTop: 24, fontFamily: FONT.serif, fontSize: 13, fontStyle: 'italic', color: t.fgFaint }}>
          Crafted with care · Version 1.0
        </div>
      </div>
    </div>
  );
}

// iOS 26 grouped list — inset card r:26, 52pt rows, 30×30 colored icon tiles
function IOS26Group({ title, dark, children }) {
  const hc = dark ? 'rgba(235,235,245,0.6)' : 'rgba(60,60,67,0.6)';
  const bg = dark ? '#1C1C1E' : '#fff';
  return (
    <div style={{ marginTop: 18 }}>
      {title && (
        <div style={{ fontFamily: FONT.serif, fontSize: 13, letterSpacing: 0.5, color: hc, padding: '8px 20px 6px', textTransform: 'uppercase' }}>
          {title}
        </div>
      )}
      <div style={{ background: bg, borderRadius: 26, overflow: 'hidden', boxShadow: dark ? 'none' : '0 1px 2px rgba(0,0,0,0.04)' }}>
        {children}
      </div>
    </div>
  );
}
function IOS26Row({ dark, icon, iconBg, label, detail, right, chevron, isLast }) {
  const text = dark ? '#fff' : '#000';
  const sec = dark ? 'rgba(235,235,245,0.6)' : 'rgba(60,60,67,0.6)';
  const ter = dark ? 'rgba(235,235,245,0.3)' : 'rgba(60,60,67,0.3)';
  const sep = dark ? 'rgba(84,84,88,0.5)' : 'rgba(60,60,67,0.12)';
  return (
    <div style={{ display: 'flex', alignItems: 'center', minHeight: 52, padding: '0 16px', position: 'relative', fontFamily: FONT.serif, fontSize: 17 }}>
      {icon && (
        <div style={{
          width: 30, height: 30, borderRadius: 7, background: iconBg || NARD.c.turquoise,
          marginRight: 14, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: '#fff',
        }}>
          <Icon name={icon} size={16} color="#fff" strokeWidth={1.8}/>
        </div>
      )}
      <div style={{ flex: 1, color: text }}>{label}</div>
      {detail && <span style={{ color: sec, marginRight: chevron ? 6 : 0, fontSize: 16 }}>{detail}</span>}
      {right}
      {chevron && (
        <svg width="8" height="14" viewBox="0 0 8 14" style={{ flexShrink: 0, marginLeft: 4 }}>
          <path d="M1 1l6 6-6 6" stroke={ter} strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      )}
      {!isLast && (
        <div style={{ position: 'absolute', bottom: 0, right: 0, left: icon ? 60 : 16, height: 0.5, background: sep }}/>
      )}
    </div>
  );
}
function IOS26ThemeRow({ dark, th, isLast }) {
  const text = dark ? '#fff' : '#000';
  const sec = dark ? 'rgba(235,235,245,0.6)' : 'rgba(60,60,67,0.6)';
  const sep = dark ? 'rgba(84,84,88,0.5)' : 'rgba(60,60,67,0.12)';
  const ter = dark ? 'rgba(235,235,245,0.3)' : 'rgba(60,60,67,0.3)';
  return (
    <div style={{ display: 'flex', alignItems: 'center', minHeight: 60, padding: '8px 16px', position: 'relative', opacity: th.unlocked ? 1 : 0.55, fontFamily: FONT.serif }}>
      <div style={{ width: 44, height: 36, borderRadius: 8, background: `linear-gradient(135deg, ${th.c1}, ${th.c2})`, position: 'relative', overflow: 'hidden', marginRight: 14, flexShrink: 0 }}>
        <div style={{ position: 'absolute', inset: 0, opacity: 0.35 }}>
          <GirihTile size={44} stroke={NARD.c.paper} strokeWidth={0.5}/>
        </div>
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 17, color: text, fontWeight: 500 }}>{th.name}</div>
        <div style={{ fontSize: 13, color: sec, fontStyle: 'italic', marginTop: 1 }}>{th.sub}</div>
      </div>
      {th.unlocked
        ? <div style={{ color: NARD.c.turquoise }}><Icon name="check" size={20}/></div>
        : <div style={{ color: ter }}><Icon name="lock" size={16}/></div>}
      {!isLast && <div style={{ position: 'absolute', bottom: 0, right: 0, left: 74, height: 0.5, background: sep }}/>}
    </div>
  );
}

function Toggle({ on, onClick }) {
  return (
    <div onClick={onClick} style={{
      width: 42, height: 26, borderRadius: 13, padding: 2,
      background: on ? NARD.c.turquoise : 'rgba(120,120,128,0.32)',
      transition: 'background 200ms', cursor: 'pointer',
    }}>
      <div style={{
        width: 22, height: 22, borderRadius: 11, background: '#fff',
        transform: `translateX(${on ? 16 : 0}px)`,
        transition: 'transform 200ms',
        boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
      }}/>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 6. RESULTS
// ─────────────────────────────────────────────────────────────
function ResultsScreen({ dark, onBack, won = true }) {
  const t = themeFor(dark);
  return (
    <div style={{ width: '100%', minHeight: '100%', background: t.bg, position: 'relative', overflow: 'hidden' }}>
      <GirihPattern color={won ? NARD.c.gold : NARD.c.cobalt} opacity={dark ? 0.06 : 0.05} size={120}/>
      {/* gold particles for win */}
      {won && Array.from({length: 24}).map((_, i) => {
        const a = (i / 24) * Math.PI * 2;
        const r = 80 + (i % 4) * 40;
        return <div key={i} style={{
          position: 'absolute', left: '50%', top: 200,
          width: 4, height: 4, borderRadius: 2, background: NARD.c.gold,
          transform: `translate(${Math.cos(a) * r}px, ${Math.sin(a) * r}px)`,
          opacity: 0.6, boxShadow: `0 0 8px ${NARD.c.gold}`,
        }}/>;
      })}
      <ScreenChrome dark={dark} onBack={onBack} title="Match summary"/>
      <div style={{ padding: '8px 24px', textAlign: 'center', position: 'relative' }}>
        <div style={{ fontFamily: FONT.sans, fontSize: 11, letterSpacing: 2, textTransform: 'uppercase', color: t.fgMute }}>
          {won ? 'Victory' : 'A close match'}
        </div>
        <div style={{ fontFamily: FONT.serif, fontSize: 56, fontWeight: 500, color: t.fg, marginTop: 8, lineHeight: 1 }}>
          {won ? 'You won.' : 'Well played.'}
        </div>
        {won && (
          <div style={{ marginTop: 14, display: 'inline-flex', padding: '6px 14px', borderRadius: 999, background: NARD.c.gold, color: NARD.c.charcoal, fontFamily: FONT.sans, fontSize: 12, fontWeight: 600, letterSpacing: 1 }}>
            GAMMON · 2 PTS
          </div>
        )}

        <div style={{ marginTop: 26 }}>
          <Logo size={64} color={won ? NARD.c.gold : NARD.c.turquoise} accent={won ? NARD.c.turquoise : NARD.c.gold}/>
        </div>

        {/* Stats grid */}
        <div style={{ marginTop: 28, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, textAlign: 'left' }}>
          {[
            { k: 'Match time', v: '12:48' },
            { k: 'Hits', v: '4' },
            { k: 'Doubles taken', v: '1' },
            { k: 'Best roll', v: '6·6' },
            { k: 'Final pip', v: '0 / 47' },
            { k: 'Avg. luck', v: '+2.1' },
          ].map(s => (
            <div key={s.k} style={{ borderRadius: 10, padding: 12, background: t.card, border: `0.5px solid ${t.line}` }}>
              <div style={{ fontFamily: FONT.sans, fontSize: 10, letterSpacing: 1, textTransform: 'uppercase', color: t.fgMute }}>{s.k}</div>
              <div style={{ fontFamily: FONT.serif, fontSize: 20, fontWeight: 500, color: t.fg, marginTop: 2 }}>{s.v}</div>
            </div>
          ))}
        </div>

        {/* Pip-count history sparkline */}
        <div style={{ marginTop: 18, padding: 14, borderRadius: 12, background: t.card, border: `0.5px solid ${t.line}`, textAlign: 'left' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
            <div style={{ fontFamily: FONT.sans, fontSize: 12, letterSpacing: 0.5, color: t.fgMute }}>Pip count</div>
            <div style={{ display: 'flex', gap: 10, fontFamily: FONT.sans, fontSize: 11 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 4, color: t.fg }}><div style={{ width: 8, height: 8, borderRadius: 4, background: NARD.c.gold }}/> You</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 4, color: t.fgMute }}><div style={{ width: 8, height: 8, borderRadius: 4, background: NARD.c.cobalt }}/> AI</div>
            </div>
          </div>
          <svg width="100%" height="60" viewBox="0 0 280 60">
            <polyline points="0,12 30,16 60,22 90,18 120,30 150,42 180,48 210,54 240,58 280,60"
              fill="none" stroke={NARD.c.gold} strokeWidth="2" strokeLinecap="round"/>
            <polyline points="0,16 30,18 60,28 90,26 120,32 150,38 180,42 210,48 240,52 280,54"
              fill="none" stroke={NARD.c.cobalt} strokeWidth="2" strokeLinecap="round" strokeOpacity="0.7"/>
          </svg>
        </div>

        <div style={{ marginTop: 22, display: 'flex', gap: 8 }}>
          <CTA label="Rematch" primary dark={dark}/>
          <CTA label="Home" dark={dark}/>
          <CTA label="Share" icon="share" dark={dark}/>
        </div>
      </div>
    </div>
  );
}

function CTA({ label, primary, icon, dark }) {
  const t = themeFor(dark);
  return (
    <div style={{
      flex: 1, padding: '12px 8px', borderRadius: 12,
      background: primary ? NARD.c.turquoise : t.card,
      color: primary ? NARD.c.paper : t.fg,
      border: primary ? 'none' : `0.5px solid ${t.line}`,
      fontFamily: FONT.sans, fontSize: 13, fontWeight: 600, textAlign: 'center',
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
      cursor: 'pointer',
    }}>
      {icon && <Icon name={icon} size={14} color="currentColor"/>}
      {label}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 7. TUTORIAL
// ─────────────────────────────────────────────────────────────
function TutorialScreen({ dark, onBack }) {
  const [page, setPage] = React.useState(0);
  const t = themeFor(dark);
  const cards = [
    { n: '۱', en: 'One', title: 'The board', body: 'Twenty-four points form a circuit. Your home board is the bottom-right; you bear off there at the end.', illust: 'board' },
    { n: '۲', en: 'Two', title: 'Roll & move', body: 'Roll two dice. Each die moves a checker that many points. Doubles let you play four moves of the same value.', illust: 'dice' },
    { n: '۳', en: 'Three', title: 'Hit & the bar', body: 'Land on a single opposing checker to hit it. The captured checker goes to the bar — you must re-enter it before any other move.', illust: 'hit' },
    { n: '۴', en: 'Four', title: 'Build a prime', body: 'Six points in a row form a prime — an unjumpable wall. Use it to block your opponent and gain tempo.', illust: 'prime' },
    { n: '۵', en: 'Five', title: 'Bear off', body: 'Once all your checkers are home, dice rolls remove them from the board. First to bear off all fifteen wins.', illust: 'off' },
    { n: '۶', en: 'Six', title: 'The cube', body: 'The doubling cube doubles the stakes. Offered before your roll; declined or accepted. A subtle psychological game within the game.', illust: 'cube' },
    { n: '۷', en: 'Seven', title: 'Gammon & backgammon', body: 'Win before your opponent bears off any checker for a gammon (2×). If they still have a checker on the bar or in your home board — backgammon (3×).', illust: 'gammon' },
    { n: '۸', en: 'Eight', title: 'A Persian heritage', body: 'Backgammon — تخته نرد — was played in the Sassanid courts of Persia over 1500 years ago. Boards have been found in Shahr-e Sukhteh dating back 5,000 years.', illust: 'heritage' },
  ];
  const card = cards[page];

  return (
    <div style={{ width: '100%', minHeight: '100%', background: t.bg, position: 'relative' }}>
      <GirihPattern color={dark ? NARD.c.turquoise : NARD.c.cobalt} opacity={dark ? 0.05 : 0.04} size={120}/>
      <ScreenChrome dark={dark} title={`How to play · ${page + 1} / ${cards.length}`} onBack={onBack} largeTitle/>
      <div style={{ padding: '12px 20px 24px' }}>
        <div style={{
          borderRadius: 18, overflow: 'hidden',
          background: t.card, border: `0.5px solid ${t.line}`,
          boxShadow: t.cardElev,
        }}>
          {/* Illustration */}
          <div style={{ height: 220, position: 'relative',
            background: dark
              ? `linear-gradient(135deg, ${NARD.c.charcoalDeep}, #2A2520)`
              : `linear-gradient(135deg, ${NARD.c.cream}, ${NARD.c.ivory})`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            overflow: 'hidden',
          }}>
            <GirihPattern color={NARD.c.turquoise} opacity={0.08} size={80}/>
            <TutorialIllustration kind={card.illust} dark={dark}/>
            <div style={{
              position: 'absolute', top: 14, left: 14,
              fontFamily: FONT.serif, fontSize: 36, fontWeight: 500,
              color: NARD.c.gold, opacity: 0.85,
            }}>{card.n}</div>
          </div>
          <div style={{ padding: 20 }}>
            <div style={{ fontFamily: FONT.sans, fontSize: 11, letterSpacing: 2, textTransform: 'uppercase', color: t.fgMute }}>
              Chapter {card.en}
            </div>
            <div style={{ fontFamily: FONT.serif, fontSize: 30, fontWeight: 500, color: t.fg, marginTop: 4 }}>
              {card.title}
            </div>
            <div style={{ fontFamily: FONT.serif, fontSize: 15, color: t.fg, lineHeight: 1.5, marginTop: 10, textWrap: 'pretty' }}>
              {card.body}
            </div>
          </div>
        </div>

        {/* dot pager */}
        <div style={{ display: 'flex', justifyContent: 'center', gap: 6, margin: '20px 0' }}>
          {cards.map((_, i) => (
            <div key={i} onClick={() => setPage(i)} style={{
              width: i === page ? 18 : 6, height: 6, borderRadius: 3,
              background: i === page ? NARD.c.turquoise : t.line,
              transition: 'all 200ms', cursor: 'pointer',
            }}/>
          ))}
        </div>

        <div style={{ display: 'flex', gap: 8 }}>
          <div onClick={() => setPage(Math.max(0, page - 1))} style={{
            flex: 1, padding: '12px', borderRadius: 12, background: t.card,
            border: `0.5px solid ${t.line}`, fontFamily: FONT.sans, fontSize: 14, fontWeight: 600,
            textAlign: 'center', color: page === 0 ? t.fgFaint : t.fg, cursor: 'pointer',
          }}>Previous</div>
          <div onClick={() => setPage(Math.min(cards.length - 1, page + 1))} style={{
            flex: 1, padding: '12px', borderRadius: 12,
            background: NARD.c.turquoise, color: NARD.c.paper,
            fontFamily: FONT.sans, fontSize: 14, fontWeight: 600,
            textAlign: 'center', cursor: 'pointer',
          }}>{page === cards.length - 1 ? 'Done' : 'Next'}</div>
        </div>
      </div>
    </div>
  );
}

function TutorialIllustration({ kind, dark }) {
  // Simple flat-but-textured illustrations using the design vocabulary
  const c = themeFor(dark);
  if (kind === 'dice') return (
    <div style={{ display: 'flex', gap: 12, transform: 'rotate(-6deg)' }}>
      <Die value={5} size={70}/><Die value={3} size={70}/>
    </div>
  );
  if (kind === 'cube') return <DoublingCube value={64} size={96}/>;
  if (kind === 'board' || kind === 'prime' || kind === 'off') return (
    <div style={{ transform: 'scale(0.42)' }}>
      <Board pos={START_POSITION} dark={dark} checkerStyle="khatam"/>
    </div>
  );
  if (kind === 'hit') return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
      <Checker size={56} side="cobalt" style="khatam" captured/>
      <div style={{ fontFamily: FONT.serif, fontSize: 36, color: NARD.c.brick }}>→</div>
      <div style={{
        width: 60, height: 110, borderRadius: 6,
        background: dark ? '#2A1F14' : '#B89060',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Checker size={48} side="cobalt" style="khatam"/>
      </div>
    </div>
  );
  if (kind === 'gammon') return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
      <div style={{ display: 'flex', gap: 4 }}>
        {Array.from({length: 8}).map((_, i) => <Checker key={i} size={20} side="gold" style="khatam"/>)}
      </div>
      <div style={{ fontFamily: FONT.serif, fontSize: 22, fontStyle: 'italic', color: NARD.c.gold }}>Gammon · ×2</div>
    </div>
  );
  if (kind === 'heritage') return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
      <Logo size={92} color={NARD.c.turquoise} accent={NARD.c.gold}/>
      <div style={{ fontFamily: FONT.serif, fontSize: 22, color: c.fg, letterSpacing: 4 }}>تخته نرد</div>
    </div>
  );
  return <Logo size={90} color={NARD.c.turquoise} accent={NARD.c.gold}/>;
}

Object.assign(window, { SplashScreen, HomeScreen, GameScreen, DifficultyScreen, SettingsScreen, ResultsScreen, TutorialScreen, FONT });
