// ——— Don't Dig the Bomb! — screen sub-components ———
// Globals: DdbMenu, DdbStats, DdbGameOver, DdbPlay (referenced by DigBomb.jsx)

// Small reusable stat pill matched to the Lab's .pill-stat look
function DdbPill({ children, bg, color, big }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: big ? '8px 16px' : '7px 13px', borderRadius: 999,
      border: 'var(--border)', background: bg || 'var(--paper)',
      color: color || 'var(--ink)', fontFamily: 'var(--font-display)',
      fontWeight: 800, fontSize: big ? 15 : 13.5, whiteSpace: 'nowrap',
      boxShadow: '2px 2px 0 var(--ink)',
    }}>{children}</div>
  );
}

function DdbIconBtn({ label, onClick, title, bg }) {
  return (
    <button onClick={onClick} title={title} aria-label={title} style={{
      width: 44, height: 44, borderRadius: 14, border: 'var(--border)',
      background: bg || 'var(--paper)', cursor: 'pointer', fontSize: 19,
      display: 'grid', placeItems: 'center', boxShadow: '2px 2px 0 var(--ink)',
      lineHeight: 1, padding: 0,
    }}>{label}</button>
  );
}

// ——— MAIN MENU ———
function DdbMenu({ data, theme, txt, txtSoft, onStart, onContinue, onStats, onSelectTheme, onToggleSound, muted }) {
  const [diff, setDiff] = React.useState(data.difficulty || 'easy');
  return (
    <div style={{ textAlign: 'center', maxWidth: 520, margin: '0 auto' }}>
      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
        <DdbIconBtn label={muted ? '🔇' : '🔊'} onClick={onToggleSound} title={muted ? 'Sound off' : 'Sound on'} />
        <DdbIconBtn label="📊" onClick={onStats} title="Statistics" />
      </div>

      <div style={{ fontSize: 'clamp(54px, 16vw, 88px)', lineHeight: 1, marginTop: 4 }}>💣</div>
      <h1 style={{ color: txt, fontSize: 'clamp(28px, 8vw, 44px)', marginTop: 4, lineHeight: 1.05 }}>
        Don't Dig<br />the Bomb!
      </h1>
      <p style={{ color: txtSoft, fontWeight: 700, marginTop: 10, maxWidth: 360, marginInline: 'auto' }}>
        Dig up coins, gems &amp; treasure — but watch out for hidden bombs. Clear every safe tile to climb the explorer ranks!
      </p>

      {/* Quick stats */}
      <div style={{ display: 'flex', gap: 8, justifyContent: 'center', flexWrap: 'wrap', margin: '18px 0' }}>
        <DdbPill bg="var(--c-sun)">🏆 Best {data.highScore.toLocaleString()}</DdbPill>
        <DdbPill>🚩 Level {data.highLevel}</DdbPill>
        <DdbPill bg="var(--paper)">🪙 {data.coins}</DdbPill>
      </div>

      {/* Difficulty */}
      <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: '.08em', textTransform: 'uppercase', color: txtSoft, marginBottom: 8 }}>
        Choose difficulty
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, marginBottom: 18 }}>
        {Object.values(DDB_DIFFS).map((d) => {
          const on = diff === d.id;
          return (
            <button key={d.id} onClick={() => { setDiff(d.id); ddbPlay('ui', muted); }} style={{
              padding: '12px 6px', borderRadius: 16, cursor: 'pointer',
              border: 'var(--border)',
              background: on ? d.color : 'var(--paper)',
              color: on ? '#fff' : 'var(--ink)',
              boxShadow: on ? 'none' : '3px 3px 0 var(--ink)',
              transform: on ? 'translate(2px,2px)' : 'none',
              fontFamily: 'var(--font-display)', fontWeight: 800,
            }}>
              <div style={{ fontSize: 16 }}>{d.name}</div>
              <div style={{ fontSize: 11, fontWeight: 700, opacity: .85, marginTop: 2 }}>{d.blurb}</div>
            </button>
          );
        })}
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, alignItems: 'center' }}>
        {onContinue && (
          <button className="btn btn-green btn-lg" style={{ width: '100%', maxWidth: 320 }} onClick={onContinue}>
            ▶ Continue your dig
          </button>
        )}
        <button className="btn btn-primary btn-lg" style={{ width: '100%', maxWidth: 320 }} onClick={() => onStart(diff)}>
          {onContinue ? 'Start a new game' : '▶ Play'}
        </button>
      </div>

      {/* Theme picker */}
      <div style={{ marginTop: 26 }}>
        <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: '.08em', textTransform: 'uppercase', color: txtSoft, marginBottom: 10 }}>
          Themes
        </div>
        <div style={{ display: 'flex', gap: 8, justifyContent: 'center', flexWrap: 'wrap' }}>
          {DDB_THEME_ORDER.map((id) => {
            const t = DDB_THEMES[id];
            const unlocked = data.unlocked.includes(id);
            const active = data.theme === id;
            const affordable = data.coins >= t.cost;
            return (
              <button key={id} onClick={() => onSelectTheme(id)}
                disabled={!unlocked && !affordable}
                title={t.name}
                style={{
                  padding: '8px 8px 6px', borderRadius: 14, minWidth: 76,
                  border: active ? '3px solid ' + (theme.accent) : 'var(--border)',
                  background: 'var(--paper)', cursor: (unlocked || affordable) ? 'pointer' : 'not-allowed',
                  opacity: (unlocked || affordable) ? 1 : 0.55,
                  boxShadow: active ? 'none' : '2px 2px 0 var(--ink)',
                  fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 11, color: 'var(--ink)',
                }}>
                <div style={{ fontSize: 22, lineHeight: 1 }}>{t.icons.treasure}</div>
                <div style={{ marginTop: 4, lineHeight: 1.1 }}>{t.name.split(' ')[0]}</div>
                <div style={{ marginTop: 3, fontWeight: 800, color: active ? theme.accent : 'var(--ink-soft)' }}>
                  {active ? '✓ on' : unlocked ? 'Use' : '🪙 ' + t.cost}
                </div>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ——— STATISTICS ———
function DdbStats({ data, theme, txt, txtSoft, onBack }) {
  const s = data.stats;
  const items = [
    { icon: '🎮', label: 'Games played', val: s.played },
    { icon: '🚩', label: 'Highest level', val: s.highestLevel },
    { icon: '🏆', label: 'Best score', val: s.bestScore.toLocaleString() },
    { icon: '🪙', label: 'Coins collected', val: s.coinsTotal },
    { icon: '💣', label: 'Bombs avoided', val: s.bombsAvoided },
    { icon: '⛏️', label: 'Safe tiles dug', val: s.safeRevealed },
    { icon: '🎁', label: 'Treasures found', val: s.treasures },
    { icon: '⭐', label: 'Golden tiles', val: s.goldens },
  ];
  return (
    <div style={{ maxWidth: 520, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
        <DdbIconBtn label="←" onClick={onBack} title="Back" />
        <h1 style={{ color: txt, fontSize: 'clamp(24px,7vw,34px)' }}>Your stats</h1>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        {items.map((it) => (
          <div key={it.label} style={{
            background: theme.dark ? 'rgba(255,255,255,.08)' : 'var(--paper)',
            border: 'var(--border)', borderRadius: 18, padding: '16px 14px',
            boxShadow: '3px 3px 0 var(--ink)',
          }}>
            <div style={{ fontSize: 30, lineHeight: 1 }}>{it.icon}</div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 26, color: txt, marginTop: 8 }}>
              {it.val}
            </div>
            <div style={{ color: txtSoft, fontWeight: 700, fontSize: 13, marginTop: 2 }}>{it.label}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ——— GAME OVER ———
function DdbGameOver({ run, data, theme, txt, txtSoft, isHigh, onAgain, onHome }) {
  return (
    <div style={{ textAlign: 'center', maxWidth: 440, margin: '0 auto', paddingTop: 8 }}>
      {isHigh && (
        <div style={{ position: 'absolute', inset: 0, zIndex: 1, pointerEvents: 'none' }}>
          <DdbBurst kind="golden" />
        </div>
      )}
      <div style={{ position: 'relative', zIndex: 2 }}>
        <div style={{ fontSize: 'clamp(56px,15vw,84px)', lineHeight: 1 }}>{isHigh ? '🌟' : '⛏️'}</div>
        <h1 style={{ color: txt, fontSize: 'clamp(26px,8vw,40px)', marginTop: 4 }}>
          {isHigh ? 'New High Score!' : 'Good digging!'}
        </h1>
        <p style={{ color: txtSoft, fontWeight: 700, marginTop: 6 }}>
          You reached <strong style={{ color: theme.accent }}>{ddbRank(run.level)}</strong>
        </p>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, margin: '22px 0' }}>
          <DdbBox label="Final score" val={run.score.toLocaleString()} theme={theme} txt={txt} txtSoft={txtSoft} accent />
          <DdbBox label="Level reached" val={run.level} theme={theme} txt={txt} txtSoft={txtSoft} />
          <DdbBox label="Coins (total)" val={data.coins} theme={theme} txt={txt} txtSoft={txtSoft} />
          <DdbBox label="Best ever" val={data.highScore.toLocaleString()} theme={theme} txt={txt} txtSoft={txtSoft} />
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, alignItems: 'center' }}>
          <button className="btn btn-primary btn-lg" style={{ width: '100%', maxWidth: 300 }} onClick={onAgain}>Play again</button>
          <button className="btn btn-lg" style={{ width: '100%', maxWidth: 300 }} onClick={onHome}>Main menu</button>
        </div>
      </div>
    </div>
  );
}
function DdbBox({ label, val, theme, txt, txtSoft, accent }) {
  return (
    <div style={{
      background: accent ? 'var(--c-sun)' : (theme.dark ? 'rgba(255,255,255,.08)' : 'var(--paper)'),
      border: 'var(--border)', borderRadius: 16, padding: '14px 10px',
      boxShadow: '3px 3px 0 var(--ink)',
    }}>
      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 26, color: accent ? 'var(--ink)' : txt }}>{val}</div>
      <div style={{ color: accent ? 'var(--ink)' : txtSoft, fontWeight: 700, fontSize: 12, marginTop: 2 }}>{label}</div>
    </div>
  );
}

// ——— PLAY (board + HUD) ———
function DdbPlay({ run, data, theme, txt, txtSoft, boom, showBombs, paused, muted, onDig, onHint, onPause, onRestart, onHome, onToggleSound }) {
  const grid = run.grid;
  const cellFont = `calc(min(92vw, 440px) / ${grid} * 0.46)`;
  const hearts = Array.from({ length: 3 }, (_, i) => i < run.hearts);

  return (
    <div style={{ maxWidth: 520, margin: '0 auto' }}>
      {/* Top HUD */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10, flexWrap: 'wrap' }}>
        <div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(18px,5vw,24px)', color: txt }}>
            Level {run.level}
          </div>
          <div style={{ color: theme.accent, fontWeight: 800, fontSize: 13 }}>{ddbRank(run.level)}</div>
        </div>
        <div style={{ display: 'flex', gap: 7, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
          <DdbPill bg="var(--c-sun)">🏆 {run.score.toLocaleString()}</DdbPill>
          <DdbPill>Best {data.highScore.toLocaleString()}</DdbPill>
        </div>
      </div>

      {/* Secondary HUD: hearts / coins / hints */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10, margin: '12px 0 14px', flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', gap: 4 }}>
          {hearts.map((alive, i) => (
            <span key={i} style={{ fontSize: 24, filter: alive ? 'none' : 'grayscale(1)', opacity: alive ? 1 : 0.35 }}>❤️</span>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 7 }}>
          <DdbPill bg="var(--paper)">🪙 {data.coins}</DdbPill>
          <button onClick={onHint} disabled={run.hints <= 0} title="Use a hint" style={{
            display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 13px',
            borderRadius: 999, border: 'var(--border)',
            background: run.hints > 0 ? 'var(--c-grass)' : 'var(--paper)',
            color: run.hints > 0 ? '#fff' : 'var(--ink-soft)',
            boxShadow: '2px 2px 0 var(--ink)', cursor: run.hints > 0 ? 'pointer' : 'not-allowed',
            fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 13.5, opacity: run.hints > 0 ? 1 : 0.6, whiteSpace: 'nowrap',
          }}>💡 Hint {run.hints}</button>
        </div>
      </div>

      {/* Board */}
      <div style={{ display: 'grid', placeItems: 'center' }}>
        <div style={{
          width: 'min(100%, 440px)', display: 'grid',
          gridTemplateColumns: `repeat(${grid}, minmax(0, 1fr))`,
          gap: 'clamp(4px, 1.4vw, 9px)',
          padding: 'clamp(6px,2vw,12px)', borderRadius: 20,
          background: theme.board, border: 'var(--border-thick)',
          boxShadow: 'inset 0 3px 0 rgba(0,0,0,.08)',
        }}>
          {run.tiles.map((t) => {
            const isBoom = boom && boom.i === t.i;
            const revealBomb = t.bomb && (t.revealed || showBombs);
            const revealed = t.revealed && !t.bomb;
            const golden = revealed && t.type === 'golden';
            let bg, content, anim = '', border = '2px solid ' + theme.dirtEdge, glow = '';
            if (revealBomb) {
              bg = isBoom ? 'var(--c-coral)' : (theme.dark ? '#5a2a4a' : '#FFD9D2');
              content = theme.icons.bomb;
              anim = isBoom ? 'ddb-shake .5s ease' : '';
              border = '2px solid var(--ink)';
            } else if (revealed) {
              bg = theme.dark ? 'rgba(255,255,255,.92)' : 'var(--paper)';
              content = theme.icons[t.type] || theme.icons.coin;
              anim = 'ddb-reveal .35s ease';
              border = '2px solid ' + (golden ? '#E8B400' : theme.dirtEdge);
              if (golden) { glow = 'ddb-glow 1.2s ease infinite'; }
            } else {
              // covered dirt mound
              bg = `radial-gradient(circle at 50% 32%, ${theme.dirt}, ${theme.dirtEdge})`;
              content = '';
            }
            return (
              <button
                key={t.i}
                className="ddb-tile"
                onClick={() => onDig(t.i)}
                disabled={t.revealed || paused}
                aria-label={revealed ? 'revealed' : 'covered tile'}
                style={{
                  aspectRatio: '1', borderRadius: 'clamp(8px,2.4vw,14px)',
                  border, background: bg,
                  display: 'grid', placeItems: 'center',
                  fontSize: cellFont, lineHeight: 1, cursor: t.revealed ? 'default' : 'pointer',
                  padding: 0, boxShadow: (revealed || revealBomb) ? 'none' : 'inset 0 -3px 0 rgba(0,0,0,.14), 0 2px 0 rgba(0,0,0,.06)',
                  animation: [anim, glow].filter(Boolean).join(', '),
                  transition: 'transform .08s',
                }}
              >
                <span style={{ pointerEvents: 'none' }}>{content}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* Progress + controls */}
      <div style={{ display: 'flex', justifyContent: 'center', marginTop: 12 }}>
        <DdbPill bg={theme.dark ? 'rgba(255,255,255,.1)' : 'var(--paper)'} color={txt}>
          ⛏️ {run.revealedSafe} / {run.safeCount} safe tiles
        </DdbPill>
      </div>
      <div style={{ display: 'flex', gap: 8, justifyContent: 'center', marginTop: 14 }}>
        <DdbIconBtn label="⏸️" onClick={onPause} title="Pause" />
        <DdbIconBtn label="↻" onClick={onRestart} title="Restart level" />
        <DdbIconBtn label={muted ? '🔇' : '🔊'} onClick={onToggleSound} title="Sound" />
        <DdbIconBtn label="🏠" onClick={onHome} title="Main menu" />
      </div>
    </div>
  );
}

Object.assign(window, { DdbMenu, DdbStats, DdbGameOver, DdbPlay, DdbPill, DdbIconBtn, DdbBox });
