// game.jsx — Algebra Invaders main game.
// Globals expected: React, AlgebraQuestions, AlgebraSprites, useTweaks, TweaksPanel,
// TweakSection, TweakRadio, TweakToggle, TweakColor, TweakSelect, TweakSlider, TweakButton.

const { useState, useEffect, useRef, useCallback, useMemo } = React;
const { PixelSprite, PixelBurst, MONSTER_ORDER, MONSTER_HP, MONSTER_NAMES } = window.AlgebraSprites;
const { generate: generateQ, TOPICS } = window.AlgebraQuestions;

// ─── Themes ────────────────────────────────────────────────
const THEMES = {
  neon:    { bg:"#0a0a14", panel:"#13132a", border:"#00ff88", accent:"#00ff88", accent2:"#ff3bd1", text:"#e8f7ff", dim:"#5b6b8a", danger:"#ff3b6b", warn:"#ffd83b", name:"NEON" },
  gameboy: { bg:"#0f380f", panel:"#306230", border:"#9bbc0f", accent:"#9bbc0f", accent2:"#e0f8d0", text:"#e0f8d0", dim:"#306230", danger:"#9bbc0f", warn:"#e0f8d0", name:"GAMEBOY" },
  pinkpop: { bg:"#1a0a1a", panel:"#2a1430", border:"#ff3bd1", accent:"#ff3bd1", accent2:"#ffd83b", text:"#fff0fa", dim:"#7a3a7a", danger:"#ff3b6b", warn:"#ffd83b", name:"BUBBLEGUM" },
  amber:   { bg:"#0a0500", panel:"#1f1408", border:"#ffaa00", accent:"#ffaa00", accent2:"#ff6b00", text:"#ffe8b8", dim:"#7a4a18", danger:"#ff3b6b", warn:"#ffd83b", name:"CRT AMBER" },
};

// ─── Sound (tiny WebAudio blips) ───────────────────────────
let _ac = null;
const ac = () => { if (!_ac) _ac = new (window.AudioContext || window.webkitAudioContext)(); return _ac; };
function blip(freq, dur = 0.08, type = "square", vol = 0.08, slide = 0) {
  try {
    const a = ac();
    if (a.state === "suspended") a.resume();
    const o = a.createOscillator(); const g = a.createGain();
    o.type = type; o.frequency.value = freq;
    if (slide) o.frequency.exponentialRampToValueAtTime(Math.max(40, freq + slide), a.currentTime + dur);
    g.gain.value = vol; g.gain.exponentialRampToValueAtTime(0.0001, a.currentTime + dur);
    o.connect(g); g.connect(a.destination);
    o.start(); o.stop(a.currentTime + dur);
  } catch (e) {}
}
const sfx = {
  click: (on) => on && blip(440, 0.04, "square", 0.05),
  correct: (on) => { if (!on) return; blip(660, 0.07, "square", 0.07); setTimeout(() => blip(880, 0.1, "square", 0.07), 60); setTimeout(() => blip(1320, 0.12, "square", 0.07), 120); },
  wrong: (on) => { if (!on) return; blip(220, 0.16, "sawtooth", 0.07, -120); },
  combo: (on, n) => on && blip(880 + n * 80, 0.06, "triangle", 0.06),
  explode: (on) => { if (!on) return; blip(120, 0.18, "sawtooth", 0.09, -60); setTimeout(() => blip(80, 0.22, "sawtooth", 0.09, -40), 80); },
  start: (on) => { if (!on) return; [440, 554, 659, 880].forEach((f, i) => setTimeout(() => blip(f, 0.08, "square", 0.06), i * 80)); },
  win: (on) => { if (!on) return; [523, 659, 784, 1047].forEach((f, i) => setTimeout(() => blip(f, 0.12, "square", 0.07), i * 100)); },
  lose: (on) => { if (!on) return; [392, 311, 247, 196].forEach((f, i) => setTimeout(() => blip(f, 0.18, "sawtooth", 0.07), i * 140)); },
  hover: (on) => on && blip(880, 0.02, "square", 0.025),
};

// ─── HUD pieces ────────────────────────────────────────────
function PixelText({ children, size = 16, color, style, ...p }) {
  return (
    <span style={{
      fontFamily: '"Press Start 2P", monospace',
      fontSize: size, color, lineHeight: 1.15, letterSpacing: ".5px", ...style,
    }} {...p}>{children}</span>
  );
}

function ChunkyButton({ children, onClick, color, fg, big, disabled, sound }) {
  const [down, setDown] = useState(false);
  const [hover, setHover] = useState(false);
  const shadow = down ? 0 : 6;
  return (
    <button
      onClick={() => { if (!disabled) { sfx.click(sound); onClick && onClick(); } }}
      onMouseDown={() => setDown(true)}
      onMouseUp={() => setDown(false)}
      onMouseLeave={() => { setDown(false); setHover(false); }}
      onMouseEnter={() => setHover(true)}
      disabled={disabled}
      style={{
        fontFamily:'"Press Start 2P", monospace',
        fontSize: big ? 18 : 12,
        padding: big ? "18px 28px" : "12px 18px",
        background: color,
        color: fg || "#0a0a14",
        border: `3px solid ${fg || "#0a0a14"}`,
        borderRadius: 0,
        cursor: disabled ? "not-allowed" : "pointer",
        opacity: disabled ? 0.4 : 1,
        boxShadow: `${shadow}px ${shadow}px 0 ${fg || "#0a0a14"}`,
        transform: down ? "translate(6px,6px)" : "translate(0,0)",
        transition: "transform 60ms steps(1), box-shadow 60ms steps(1)",
        textTransform: "uppercase",
        letterSpacing: "1px",
        filter: hover && !down && !disabled ? "brightness(1.1)" : "none",
      }}
    >{children}</button>
  );
}

function HpBar({ value, max, color, bg }) {
  const pct = Math.max(0, value / max);
  const cells = 20;
  const filled = Math.round(cells * pct);
  return (
    <div style={{ display: "flex", gap: 2, padding: 3, background: "#0a0a14", border: `2px solid ${bg}` }}>
      {Array.from({ length: cells }).map((_, i) => (
        <div key={i} style={{
          width: 10, height: 14,
          background: i < filled ? color : "transparent",
        }} />
      ))}
    </div>
  );
}

function Hearts({ n, max = 3 }) {
  return (
    <div style={{ display:"flex", gap: 4 }}>
      {Array.from({ length: max }).map((_, i) => (
        <div key={i} style={{ opacity: i < n ? 1 : 0.18, filter: i < n ? "none" : "grayscale(1)" }}>
          <PixelSprite name="heart" scale={3} />
        </div>
      ))}
    </div>
  );
}

// ─── Title screen ──────────────────────────────────────────
function TitleScreen({ theme, onStart, onSwitchPlayer, profile, leaderboard, sound }) {
  const [blink, setBlink] = useState(true);
  useEffect(() => { const t = setInterval(() => setBlink(b => !b), 500); return () => clearInterval(t); }, []);
  return (
    <div style={{ display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", height:"100%", gap: 22, position:"relative" }}>
      <div style={{ display:"flex", flexDirection:"column", alignItems:"center", gap: 6 }}>
        <PixelText size={14} color={theme.accent2}>★ MIDDLE-SCHOOL ARCADE ★</PixelText>
        <PixelText size={52} color={theme.accent} style={{ textShadow: `4px 4px 0 ${theme.accent2}, 8px 8px 0 #000` }}>ALGEBRA</PixelText>
        <PixelText size={52} color={theme.text} style={{ textShadow: `4px 4px 0 ${theme.accent}, 8px 8px 0 #000` }}>INVADERS</PixelText>
      </div>

      {/* monster row */}
      <div style={{ display:"flex", gap: 24, alignItems:"flex-end" }}>
        {MONSTER_ORDER.map((m, i) => (
          <div key={m} style={{ animation: `bob 1.4s steps(2) infinite`, animationDelay: `${i * 0.1}s` }}>
            <PixelSprite name={m} scale={3} />
          </div>
        ))}
      </div>

      <div style={{ height: 24, display:"flex", alignItems:"center" }}>
        {blink && <PixelText size={16} color={theme.warn}>▶ PRESS START ◀</PixelText>}
      </div>

      <ChunkyButton onClick={onStart} color={theme.accent} fg={theme.bg} big sound={sound}>START GAME</ChunkyButton>

      {/* Player badge (bottom-left) */}
      <div style={{ position:"absolute", bottom: 20, left: 20, display:"flex", flexDirection:"column", gap: 6 }}>
        <PixelText size={9} color={theme.dim}>NOW PLAYING</PixelText>
        <button onClick={() => { sfx.click(sound); onSwitchPlayer(); }}
          style={{
            display:"flex", alignItems:"center", gap: 10,
            background: theme.panel, border:`2px solid ${theme.accent}`,
            padding:"6px 10px", cursor:"pointer",
            boxShadow:`3px 3px 0 ${theme.accent2}`,
          }}>
          <PixelSprite name={profile?.avatar || "knight"} scale={2} />
          <div style={{ display:"flex", flexDirection:"column", alignItems:"flex-start", gap: 2 }}>
            <PixelText size={11} color={theme.text}>{(profile?.name || "PLAYER").toUpperCase()}</PixelText>
            <PixelText size={8} color={theme.dim}>LV{profile?.level || 1} · {String(profile?.hi || 0).padStart(6,"0")} HI</PixelText>
          </div>
          <PixelText size={9} color={theme.accent2} style={{ marginLeft: 4 }}>▶ SWITCH</PixelText>
        </button>
      </div>

      {/* Leaderboard (bottom-right) */}
      {leaderboard && leaderboard.length > 0 && (
        <div style={{ position:"absolute", bottom: 20, right: 20, minWidth: 230,
                      background: theme.panel, border:`2px solid ${theme.accent}`,
                      padding:"8px 12px", boxShadow:`3px 3px 0 ${theme.accent2}` }}>
          <PixelText size={9} color={theme.accent2}>★ HI-SCORES ★</PixelText>
          <div style={{ display:"flex", flexDirection:"column", gap: 4, marginTop: 6 }}>
            {leaderboard.map((p, i) => (
              <div key={p.id} style={{ display:"flex", alignItems:"center", gap: 8 }}>
                <PixelText size={10} color={i === 0 ? theme.warn : theme.dim} style={{ width: 18 }}>{i + 1}.</PixelText>
                <PixelSprite name={p.avatar} scale={1.5} />
                <PixelText size={10} color={theme.text} style={{ flex: 1 }}>{p.name.toUpperCase()}</PixelText>
                <PixelText size={10} color={i === 0 ? theme.warn : theme.accent}>{String(p.hi || 0).padStart(6,"0")}</PixelText>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Profile select ───────────────────────────────────────
function ProfileSelectScreen({ theme, profiles, activeId, onPick, onNew, onDelete, onRename, sound }) {
  const [editing, setEditing] = useState(null); // profile id being renamed
  const [draft, setDraft] = useState("");
  const startRename = (p) => { setEditing(p.id); setDraft(p.name); };
  const saveRename = () => { if (editing) { onRename(editing, draft.trim() || "Player"); setEditing(null); } };

  return (
    <div style={{ display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", height:"100%", gap: 22, padding: 30 }}>
      <PixelText size={28} color={theme.accent}>WHO'S PLAYING?</PixelText>
      <PixelText size={10} color={theme.dim}>EACH PLAYER KEEPS THEIR OWN SCORE & XP</PixelText>

      <div style={{ display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap: 14, marginTop: 4, maxWidth: 900 }}>
        {profiles.map(p => {
          const isActive = p.id === activeId;
          const isEditing = editing === p.id;
          return (
            <div key={p.id} style={{
              background: isActive ? theme.accent : theme.panel,
              border: `3px solid ${isActive ? theme.warn : theme.accent}`,
              padding: "14px 10px",
              boxShadow: `4px 4px 0 ${isActive ? theme.accent2 : theme.accent}`,
              display:"flex", flexDirection:"column", alignItems:"center", gap: 8,
              cursor: "pointer", position:"relative", minHeight: 200,
            }} onClick={() => { if (!isEditing) { sfx.click(sound); onPick(p.id); } }}>
              <div style={{ animation: isActive ? "bob 1.2s steps(2) infinite" : "none" }}>
                <PixelSprite name={p.avatar} scale={3} />
              </div>
              {isEditing ? (
                <input autoFocus value={draft}
                  onChange={(e) => setDraft(e.target.value.slice(0, 12))}
                  onBlur={saveRename}
                  onKeyDown={(e) => { if (e.key === "Enter") saveRename(); if (e.key === "Escape") setEditing(null); }}
                  onClick={(e) => e.stopPropagation()}
                  style={{
                    fontFamily:'"Press Start 2P", monospace', fontSize: 11,
                    background: theme.bg, color: theme.text,
                    border:`2px solid ${theme.warn}`, padding: "4px 6px",
                    width: "100%", textAlign:"center", textTransform:"uppercase",
                  }} />
              ) : (
                <PixelText size={12} color={isActive ? theme.bg : theme.text} style={{ textAlign:"center" }}>
                  {p.name.toUpperCase()}
                </PixelText>
              )}
              <div style={{ display:"flex", flexDirection:"column", gap: 3, alignItems:"center" }}>
                <PixelText size={8} color={isActive ? theme.bg : theme.dim}>LV {p.level} · {p.plays || 0} ROUNDS</PixelText>
                <PixelText size={9} color={isActive ? theme.bg : theme.warn}>{String(p.hi || 0).padStart(6,"0")}</PixelText>
                <PixelText size={8} color={isActive ? theme.bg : theme.dim}>${p.coins || 0}</PixelText>
              </div>
              {/* edit/delete */}
              <div style={{ position:"absolute", top: 4, right: 4, display:"flex", gap: 2 }}>
                <button onClick={(e) => { e.stopPropagation(); sfx.click(sound); startRename(p); }} style={miniBtn(theme)}>✎</button>
                <button onClick={(e) => {
                  e.stopPropagation();
                  if (confirm(`Delete profile "${p.name}"? This wipes their score.`)) onDelete(p.id);
                }} style={miniBtn(theme)}>✕</button>
              </div>
              {isActive && (
                <div style={{ position:"absolute", top: -10, left: "50%", transform:"translateX(-50%)",
                              background: theme.warn, padding:"2px 8px", border:`2px solid ${theme.bg}` }}>
                  <PixelText size={8} color={theme.bg}>ACTIVE</PixelText>
                </div>
              )}
            </div>
          );
        })}

        {/* + new */}
        <button onClick={() => { sfx.click(sound); onNew(); }}
          style={{
            background: theme.bg, border: `3px dashed ${theme.accent}`,
            padding: "14px 10px", cursor:"pointer", minHeight: 200,
            display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", gap: 10,
          }}>
          <PixelText size={32} color={theme.accent}>+</PixelText>
          <PixelText size={11} color={theme.accent}>NEW PLAYER</PixelText>
        </button>
      </div>
    </div>
  );
}
function miniBtn(theme) {
  return {
    width: 18, height: 18, padding: 0,
    background: theme.bg, color: theme.text,
    border: `1px solid ${theme.dim}`,
    fontFamily:'"Press Start 2P", monospace', fontSize: 9,
    cursor:"pointer", lineHeight: 1,
  };
}

// ─── New profile (name + avatar) ─────────────────────────
function NewProfileScreen({ theme, onCreate, onBack, sound, canBack }) {
  const { AVATARS } = window.AlgebraSprites;
  const [name, setName] = useState("");
  const [avatar, setAvatar] = useState(AVATARS[0]);
  const submit = () => {
    const n = name.trim() || "Player";
    sfx.start(sound);
    onCreate(n, avatar);
  };
  return (
    <div style={{ display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", height:"100%", gap: 22, padding: 30 }}>
      <PixelText size={26} color={theme.accent}>NEW PLAYER</PixelText>
      <PixelText size={10} color={theme.dim}>PICK A NAME & AN AVATAR</PixelText>

      {/* big preview */}
      <div style={{
        display:"flex", alignItems:"center", gap: 22,
        padding: "18px 28px", background: theme.panel,
        border:`3px solid ${theme.accent}`, boxShadow:`6px 6px 0 ${theme.accent2}`,
      }}>
        <div style={{ animation: "bob 1.2s steps(2) infinite" }}>
          <PixelSprite name={avatar} scale={5} />
        </div>
        <div style={{ display:"flex", flexDirection:"column", gap: 8 }}>
          <PixelText size={9} color={theme.dim}>NAME</PixelText>
          <input autoFocus value={name} placeholder="ENTER NAME"
            onChange={(e) => setName(e.target.value.slice(0, 12))}
            onKeyDown={(e) => { if (e.key === "Enter") submit(); }}
            style={{
              fontFamily:'"Press Start 2P", monospace', fontSize: 16,
              background: theme.bg, color: theme.text,
              border:`3px solid ${theme.warn}`, padding: "10px 12px",
              width: 240, textTransform:"uppercase", letterSpacing:"2px",
              caretColor: theme.warn, outline:"none",
            }} />
        </div>
      </div>

      {/* avatar grid */}
      <div style={{ display:"flex", gap: 10, flexWrap:"wrap", justifyContent:"center", maxWidth: 720 }}>
        {AVATARS.map(a => {
          const picked = a === avatar;
          return (
            <button key={a} onClick={() => { sfx.click(sound); setAvatar(a); }}
              onMouseEnter={() => sfx.hover(sound)}
              style={{
                background: picked ? theme.accent : theme.panel,
                border: `3px solid ${picked ? theme.warn : theme.dim}`,
                padding: 10, cursor:"pointer",
                boxShadow: picked ? `3px 3px 0 ${theme.accent2}` : "none",
                width: 76, height: 76,
                display:"flex", alignItems:"center", justifyContent:"center",
              }}>
              <PixelSprite name={a} scale={2} />
            </button>
          );
        })}
      </div>

      <div style={{ display:"flex", gap: 14, marginTop: 6 }}>
        {canBack && <ChunkyButton onClick={onBack} color={theme.panel} fg={theme.text} sound={sound}>← BACK</ChunkyButton>}
        <ChunkyButton onClick={submit} color={theme.accent} fg={theme.bg} big sound={sound}>LET'S GO</ChunkyButton>
      </div>
    </div>
  );
}

// ─── Topic select ──────────────────────────────────────────
function TopicSelect({ theme, allowed, onPick, onBack, sound }) {
  const list = TOPICS.filter(t => allowed.includes(t.id));
  return (
    <div style={{ display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", height:"100%", gap: 24, padding: 32 }}>
      <PixelText size={28} color={theme.accent}>SELECT YOUR MISSION</PixelText>
      <PixelText size={11} color={theme.dim}>CHOOSE A TOPIC OR FIGHT THE FULL GAUNTLET</PixelText>

      <div style={{ display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap: 14, marginTop: 12, maxWidth: 880 }}>
        <button
          onClick={() => { sfx.click(sound); onPick("ALL"); }}
          style={tileStyle(theme, true)}
        >
          <PixelText size={12} color={theme.bg}>★ GAUNTLET ★</PixelText>
          <PixelText size={9} color={theme.bg} style={{ marginTop: 8, opacity: 0.75 }}>ALL TOPICS</PixelText>
        </button>
        {list.map(t => (
          <button key={t.id}
            onClick={() => { sfx.click(sound); onPick(t.id); }}
            onMouseEnter={() => sfx.hover(sound)}
            style={tileStyle(theme)}
          >
            <PixelText size={11} color={theme.text}>{t.name}</PixelText>
            <PixelText size={9} color={theme.accent} style={{ marginTop: 10, fontFamily: '"VT323", monospace', fontSize: 22 }}>{t.glyph}</PixelText>
            <div style={{ display:"flex", gap: 2, marginTop: 10 }}>
              {[1,2,3,4,5].map(n => (
                <div key={n} style={{ width: 8, height: 8, background: n <= t.baseLevel ? theme.warn : theme.dim }} />
              ))}
            </div>
          </button>
        ))}
      </div>

      <div style={{ marginTop: 16 }}>
        <ChunkyButton onClick={onBack} color={theme.panel} fg={theme.text} sound={sound}>← BACK</ChunkyButton>
      </div>
    </div>
  );
}
function tileStyle(theme, primary) {
  return {
    fontFamily:'"Press Start 2P", monospace',
    background: primary ? theme.accent : theme.panel,
    border: `3px solid ${primary ? theme.bg : theme.accent}`,
    padding: "20px 12px",
    minHeight: 130,
    display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
    cursor: "pointer", color: theme.text, textAlign:"center",
    boxShadow: `4px 4px 0 ${primary ? theme.accent2 : theme.accent}`,
    imageRendering:"pixelated",
  };
}

window.__algebraScreens = { TitleScreen, TopicSelect, ProfileSelectScreen, NewProfileScreen, ChunkyButton, PixelText, HpBar, Hearts, sfx, THEMES };
