// Kill the King — scrapbook-styled clicker
// Smash SPACE (or click) to deal damage. Defeat enemies to advance stages.
// Final boss = King Trost. Time-limited; earn XP, level up between stages.

function KillTheKing({ T, F }) {
  const STAGES = 4;
  const PER_STAGE = 5;
  const TOTAL_TIME = 90; // seconds

  const [started, setStarted] = React.useState(false);
  const [intro, setIntro] = React.useState(false); // king dialog
  const [stage, setStage] = React.useState(1);
  const [defeated, setDefeated] = React.useState(0);
  const [enemyHP, setEnemyHP] = React.useState(20);
  const [enemyMax, setEnemyMax] = React.useState(20);
  const [enemyShake, setEnemyShake] = React.useState(0);
  const [killed, setKilled] = React.useState(false);
  const [xp, setXp] = React.useState(0);
  const [str, setStr] = React.useState(2);
  const [spd, setSpd] = React.useState(1);
  const [pressed, setPressed] = React.useState(false);
  const [popup, setPopup] = React.useState(null); // {dmg, key}
  const [shopping, setShopping] = React.useState(false);
  const [time, setTime] = React.useState(TOTAL_TIME);
  const [over, setOver] = React.useState(null); // 'win' | 'lose' | null
  const cooldownRef = React.useRef(0);

  const enemyName = stage >= STAGES ? '特罗斯特王 King Trost' : ['Goblin','Knight','Sorcerer'][stage-1] || 'Foe';
  const isBoss = stage >= STAGES && defeated === PER_STAGE - 1;

  // initialize enemy on stage / progress change
  React.useEffect(() => {
    if (!started || over) return;
    const baseHP = 18 + (stage - 1) * 14 + (defeated * 4);
    const hp = isBoss ? baseHP * 3 : baseHP;
    setEnemyMax(hp);
    setEnemyHP(hp);
    setKilled(false);
  }, [stage, defeated, started, over, isBoss]);

  // timer
  React.useEffect(() => {
    if (!started || over || shopping) return;
    const id = setInterval(() => {
      setTime(t => {
        if (t <= 0.1) { setOver('lose'); return 0; }
        return +(t - 0.1).toFixed(1);
      });
    }, 100);
    return () => clearInterval(id);
  }, [started, over, shopping]);

  // press handler (space or click)
  function attack() {
    if (!started || over || shopping || killed) return;
    const now = performance.now();
    const cd = Math.max(80, 220 - spd * 25);
    if (now - cooldownRef.current < cd) return;
    cooldownRef.current = now;

    const dmg = str + Math.floor(Math.random() * 3);
    setPressed(true);
    setEnemyShake(s => s + 1);
    setPopup({ dmg, key: now });
    setTimeout(() => setPressed(false), 80);

    setEnemyHP(hp => {
      const next = hp - dmg;
      if (next <= 0) {
        setKilled(true);
        const gained = isBoss ? 50 : 8 + stage * 3;
        setXp(x => x + gained);
        if (window.__sp_playSound) window.__sp_playSound('pop');
        if (window.__sp_burstConfetti && isBoss) window.__sp_burstConfetti();
        setTimeout(() => {
          if (isBoss) { setOver('win'); return; }
          if (defeated + 1 >= PER_STAGE) {
            // stage cleared -> shop
            setShopping(true);
          } else {
            setDefeated(d => d + 1);
          }
        }, 600);
        return 0;
      }
      return next;
    });
  }

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.code === 'Space' && started && !shopping && !over) {
        e.preventDefault();
        attack();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  });

  function startGame() { setStarted(true); setIntro(true); }
  function dismissIntro() { setIntro(false); }
  function nextStage() {
    setShopping(false);
    setDefeated(0);
    setStage(s => s + 1);
  }
  function reset() {
    setStarted(false); setIntro(false); setStage(1); setDefeated(0);
    setStr(2); setSpd(1); setXp(0); setTime(TOTAL_TIME); setOver(null); setShopping(false);
  }

  // upgrades
  const strCost = 10 + str * 6;
  const spdCost = 12 + spd * 8;
  const buyStr = () => { if (xp >= strCost) { setXp(x => x - strCost); setStr(s => s + 1); if(window.__sp_playSound)window.__sp_playSound('pop'); } };
  const buySpd = () => { if (xp >= spdCost) { setXp(x => x - spdCost); setSpd(s => s + 1); if(window.__sp_playSound)window.__sp_playSound('pop'); } };

  const mins = String(Math.floor(time / 60)).padStart(2, '0');
  const secs = String(Math.floor(time) % 60).padStart(2, '0');
  const ms = String(Math.floor((time * 10) % 10));

  // visuals
  const enemyColor = isBoss ? T.ink : [T.accent2, T.accent, T.ink][stage - 1] || T.accent;

  return (
    <div style={{margin:'0 32px 56px'}}>
      <div style={{display:'flex', alignItems:'baseline', gap:14, marginBottom: 24, flexWrap:'wrap'}}>
        <h2 style={{fontFamily:F.display, fontWeight:F.dispWt, fontSize:72, margin:0, letterSpacing:'-0.04em'}}>kill the king</h2>
        <PeelSticker t={T} bg={T.accent2} color="#fff" rotate={-3} fontSize={11}>♥ SMASH SPACE</PeelSticker>
        <PeelSticker t={T} bg={T.accent} rotate={4} fontSize={11}>{TOTAL_TIME}s LIMIT</PeelSticker>
      </div>

      <ScrapBox t={T} bg={T.bg} rotate={-0.4} hoverable={false} style={{padding:'24px 28px', position:'relative'}}>
        <Tape rotate={-3} color={T.tape} w={120} style={{top:-12, left:'35%'}}/>
        <Tape rotate={4} color={T.tape} w={90} style={{top:-10, right:30}}/>

        <style>{`
          @keyframes ktk-shake { 0%,100%{transform:translateX(0)} 25%{transform:translate(-6px,-2px)} 50%{transform:translate(6px,2px)} 75%{transform:translate(-3px,1px)} }
          @keyframes ktk-pop { 0%{opacity:1; transform:translate(-50%,0) scale(.6)} 30%{transform:translate(-50%,-14px) scale(1.2)} 100%{opacity:0; transform:translate(-50%,-44px) scale(.9)} }
          @keyframes ktk-fall { 0%{opacity:1; transform:translateY(0) rotate(0)} 100%{opacity:0; transform:translateY(40px) rotate(60deg)} }
          @keyframes ktk-bob { 0%,100%{transform:translateY(0)} 50%{transform:translateY(-6px)} }
        `}</style>

        {/* HUD */}
        <div style={{display:'grid', gridTemplateColumns:'auto 1fr auto', gap:18, alignItems:'center', marginBottom:14}}>
          <div style={{
            fontFamily:F.display, fontWeight:F.dispWt, fontSize: 28, color: time < 15 ? T.accent2 : T.ink,
            background:T.tape, padding:'6px 14px', border:`2.5px solid ${T.ink}`, boxShadow:`3px 3px 0 0 ${T.ink}`,
          }}>
            {mins}:{secs}<span style={{opacity:0.5}}>.{ms}</span>
          </div>
          <div>
            <div style={{display:'flex', justifyContent:'space-between', fontSize:11, fontWeight:800, letterSpacing:'0.18em', textTransform:'uppercase', opacity:0.7, marginBottom:4}}>
              <span>STAGE {stage} / {STAGES}</span>
              <span>{defeated} / {PER_STAGE} defeated</span>
            </div>
            <div style={{height:14, background:`${T.ink}15`, border:`2px solid ${T.ink}`, position:'relative'}}>
              <div style={{
                width:`${((stage-1)*PER_STAGE + defeated) / (STAGES*PER_STAGE) * 100}%`,
                height:'100%', background: T.accent, transition:'width .3s',
              }}/>
            </div>
          </div>
          <div style={{
            fontFamily:F.display, fontWeight:F.dispWt, fontSize:24, color:T.accent,
            background:T.bg, padding:'6px 14px', border:`2.5px solid ${T.ink}`, boxShadow:`3px 3px 0 0 ${T.ink}`,
          }}>★ {xp} XP</div>
        </div>

        {/* arena */}
        <div style={{
          position:'relative',
          background: `linear-gradient(180deg, ${T.tape}66, ${T.bg})`,
          border:`2.5px solid ${T.ink}`,
          minHeight: 320,
          display:'flex', alignItems:'center', justifyContent:'space-around',
          padding:'24px 32px',
          overflow:'hidden',
        }}>
          {/* ground line */}
          <div style={{position:'absolute', left:0, right:0, bottom:60, borderTop:`2px dashed ${T.ink}55`}}/>

          {/* player */}
          <div style={{position:'relative', textAlign:'center'}}>
            <div style={{display:'flex', flexDirection:'column', gap:4, fontFamily:F.mono, fontSize:11, fontWeight:700, color:T.ink, marginBottom:8}}>
              <span>⚔ {str} STR</span>
              <span>⚡ {spd} SPD</span>
            </div>
            <div style={{
              width:90, height:120, position:'relative',
              transform: pressed ? 'translateX(40px) rotate(-8deg)' : 'translateX(0)',
              transition:'transform 80ms',
              animation: !pressed && !killed && !shopping ? 'ktk-bob 1.6s ease-in-out infinite' : 'none',
            }}>
              {/* hero body */}
              <svg viewBox="0 0 90 120" width="90" height="120">
                {/* sword */}
                <g transform={pressed ? "rotate(50 70 50)" : "rotate(-15 70 50)"}>
                  <line x1="70" y1="55" x2="70" y2="15" stroke={T.ink} strokeWidth="4" strokeLinecap="round"/>
                  <rect x="62" y="55" width="16" height="6" fill={T.ink}/>
                  <rect x="67" y="55" width="6" height="14" fill={T.accent}/>
                </g>
                {/* head */}
                <circle cx="40" cy="28" r="16" fill={T.bg} stroke={T.ink} strokeWidth="3"/>
                <circle cx="35" cy="28" r="2" fill={T.ink}/>
                <circle cx="46" cy="28" r="2" fill={T.ink}/>
                <path d="M 33 35 Q 40 39 46 35" stroke={T.ink} strokeWidth="2" fill="none" strokeLinecap="round"/>
                {/* helmet plume */}
                <path d="M 28 22 Q 40 8 52 22" stroke={T.accent2} strokeWidth="6" fill="none" strokeLinecap="round"/>
                {/* body */}
                <rect x="26" y="44" width="32" height="40" fill={T.accent} stroke={T.ink} strokeWidth="3"/>
                <rect x="26" y="50" width="32" height="4" fill={T.ink} opacity="0.4"/>
                {/* legs */}
                <rect x="28" y="84" width="10" height="28" fill={T.ink}/>
                <rect x="46" y="84" width="10" height="28" fill={T.ink}/>
              </svg>
            </div>
            <div style={{fontFamily:F.hand, fontSize:18, color:T.accent2, marginTop:6}}>YOU</div>
          </div>

          {/* attack arrow */}
          <div style={{
            fontFamily:F.display, fontWeight:F.dispWt, fontSize: 56, color: T.accent2,
            opacity: pressed ? 1 : 0.35, transform: pressed ? 'scale(1.2)' : 'scale(1)', transition:'all 80ms',
          }}>→</div>

          {/* enemy */}
          <div style={{position:'relative', textAlign:'center'}}>
            {popup && (
              <div key={popup.key} style={{
                position:'absolute', top:-20, left:'50%',
                fontFamily:F.display, fontWeight:F.dispWt, fontSize: 32, color:T.accent2,
                animation:'ktk-pop .6s ease-out forwards', pointerEvents:'none',
              }}>-{popup.dmg}</div>
            )}
            <div style={{
              width: isBoss ? 130 : 90, height: isBoss ? 160 : 120, position:'relative',
              animation: enemyShake && !killed ? 'ktk-shake .18s' : (!killed ? 'ktk-bob 2s ease-in-out infinite' : 'ktk-fall .6s forwards'),
            }} key={`${stage}-${defeated}-${enemyShake}`}>
              <svg viewBox="0 0 90 120" width={isBoss ? 130 : 90} height={isBoss ? 160 : 120}>
                {isBoss && (
                  <g>
                    {/* crown */}
                    <path d="M 22 10 L 28 22 L 36 10 L 44 22 L 52 10 L 60 22 L 66 10 L 66 28 L 22 28 Z"
                      fill={T.accent} stroke={T.ink} strokeWidth="3"/>
                    <circle cx="28" cy="22" r="3" fill={T.accent2}/>
                    <circle cx="44" cy="22" r="3" fill={T.accent2}/>
                    <circle cx="60" cy="22" r="3" fill={T.accent2}/>
                  </g>
                )}
                {/* head */}
                <circle cx="44" cy={isBoss ? 42 : 30} r={isBoss ? 18 : 16} fill={T.bg} stroke={T.ink} strokeWidth="3"/>
                {/* angry eyes */}
                <path d={`M 36 ${isBoss ? 38 : 26} L 42 ${isBoss ? 42 : 30}`} stroke={T.ink} strokeWidth="3" strokeLinecap="round"/>
                <path d={`M 52 ${isBoss ? 38 : 26} L 46 ${isBoss ? 42 : 30}`} stroke={T.ink} strokeWidth="3" strokeLinecap="round"/>
                <circle cx="40" cy={isBoss ? 44 : 32} r="1.6" fill={T.ink}/>
                <circle cx="48" cy={isBoss ? 44 : 32} r="1.6" fill={T.ink}/>
                {/* mouth */}
                <path d={`M 38 ${isBoss ? 52 : 38} Q 44 ${isBoss ? 48 : 34} 50 ${isBoss ? 52 : 38}`} stroke={T.ink} strokeWidth="2.5" fill="none" strokeLinecap="round"/>
                {/* body */}
                <rect x="26" y={isBoss ? 60 : 46} width="36" height={isBoss ? 60 : 40} fill={enemyColor} stroke={T.ink} strokeWidth="3"/>
                {isBoss && <rect x="32" y="68" width="24" height="6" fill={T.accent} stroke={T.ink} strokeWidth="2"/>}
                {/* arms */}
                <rect x="14" y={isBoss ? 64 : 50} width="12" height={isBoss ? 36 : 26} fill={enemyColor} stroke={T.ink} strokeWidth="3"/>
                <rect x="62" y={isBoss ? 64 : 50} width="12" height={isBoss ? 36 : 26} fill={enemyColor} stroke={T.ink} strokeWidth="3"/>
                {/* legs */}
                <rect x="28" y={isBoss ? 120 : 86} width="12" height={isBoss ? 30 : 26} fill={T.ink}/>
                <rect x="48" y={isBoss ? 120 : 86} width="12" height={isBoss ? 30 : 26} fill={T.ink}/>
                {/* weapon */}
                <line x1="74" y1={isBoss ? 80 : 60} x2="74" y2={isBoss ? 40 : 30} stroke={T.ink} strokeWidth="4" strokeLinecap="round"/>
                <rect x="68" y={isBoss ? 38 : 28} width="12" height="8" fill={T.accent2} stroke={T.ink} strokeWidth="2"/>
              </svg>
            </div>
            <div style={{fontFamily:F.hand, fontSize: isBoss ? 22 : 18, color:T.ink, marginTop:6, fontWeight:700}}>{enemyName}</div>
            {/* HP bar */}
            <div style={{width: 160, height:12, background:`${T.ink}15`, border:`2px solid ${T.ink}`, marginTop:6, position:'relative'}}>
              <div style={{
                width: `${Math.max(0, enemyHP / enemyMax * 100)}%`, height:'100%',
                background: T.accent2, transition:'width .15s',
              }}/>
              <div style={{
                position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center',
                fontFamily:F.mono, fontSize:10, fontWeight:700, color:T.bg, mixBlendMode:'difference',
              }}>{Math.max(0,enemyHP)} / {enemyMax}</div>
            </div>
          </div>

          {/* TAP button */}
          <button onClick={attack} disabled={!started || over || shopping}
            style={{
              position:'absolute', bottom: 14, left:'50%', transform:'translateX(-50%)',
              padding:'10px 28px', background: T.accent, color: T.ink,
              border:`2.5px solid ${T.ink}`, boxShadow:`4px 4px 0 0 ${T.ink}`,
              fontFamily: F.display, fontWeight: F.dispWt, fontSize: 16, letterSpacing:'0.08em', textTransform:'uppercase',
              cursor: started && !shopping && !over ? 'pointer' : 'not-allowed',
              opacity: started && !shopping && !over ? 1 : 0.4,
            }}>
            ⚔ ATTACK <span style={{opacity:0.6, fontSize:11, marginLeft:8}}>SPACE</span>
          </button>

          {/* INTRO overlay */}
          {!started && (
            <div style={{position:'absolute', inset:0, background:`${T.ink}f0`, color:T.bg, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:18, padding:24, textAlign:'center'}}>
              <div style={{fontFamily:F.display, fontWeight:F.dispWt, fontSize:64, letterSpacing:'-0.04em', color:T.accent}}>KILL THE KING</div>
              <div style={{fontFamily:F.hand, fontSize:24, color:T.bg, maxWidth:520}}>
                King Trost has 90 seconds left to live. Smash <kbd style={{padding:'2px 8px', background:T.bg, color:T.ink, border:`2px solid ${T.bg}`, fontFamily:F.mono}}>SPACE</kbd> as fast as you can.
              </div>
              <button onClick={startGame} style={{
                padding:'14px 28px', background:T.accent, color:T.ink,
                border:`2.5px solid ${T.bg}`, boxShadow:`4px 4px 0 0 ${T.accent2}`,
                fontFamily:F.display, fontWeight:F.dispWt, fontSize:16, letterSpacing:'0.08em', textTransform:'uppercase', cursor:'pointer',
              }}>▶ BEGIN GAME</button>
            </div>
          )}

          {/* King taunt */}
          {started && intro && (
            <div style={{position:'absolute', inset:0, background:`${T.ink}f0`, color:T.bg, display:'flex', alignItems:'center', justifyContent:'center', gap:32, padding:24}}>
              <div style={{maxWidth: 360}}>
                <div style={{fontFamily:F.display, fontWeight:F.dispWt, fontSize:18, letterSpacing:'0.12em', color:T.accent, marginBottom:8, textTransform:'uppercase'}}>KING TROST</div>
                <p style={{fontFamily:F.hand, fontSize:24, lineHeight:1.3, margin:0}}>"Hahaha — you really think you can beat me? My men will crush you, kid."</p>
                <button onClick={dismissIntro} style={{
                  marginTop:18, padding:'10px 22px', background:T.accent, color:T.ink,
                  border:`2.5px solid ${T.bg}`, boxShadow:`4px 4px 0 0 ${T.accent2}`,
                  fontFamily:F.display, fontWeight:F.dispWt, fontSize:13, letterSpacing:'0.08em', textTransform:'uppercase', cursor:'pointer',
                }}>CONTINUE →</button>
              </div>
              <svg viewBox="0 0 130 160" width="130" height="160">
                <path d="M 22 10 L 28 22 L 36 10 L 44 22 L 52 10 L 60 22 L 66 10 L 66 28 L 22 28 Z" fill={T.accent} stroke={T.bg} strokeWidth="3"/>
                <circle cx="44" cy="50" r="22" fill={T.bg} stroke={T.bg} strokeWidth="3"/>
                <circle cx="38" cy="50" r="2.5" fill={T.ink}/>
                <circle cx="50" cy="50" r="2.5" fill={T.ink}/>
                <path d="M 36 60 Q 44 56 52 60" stroke={T.ink} strokeWidth="2.5" fill="none" strokeLinecap="round"/>
                <rect x="24" y="74" width="40" height="60" fill={T.accent2} stroke={T.bg} strokeWidth="3"/>
                <rect x="30" y="84" width="28" height="6" fill={T.accent}/>
              </svg>
            </div>
          )}

          {/* Shop overlay */}
          {shopping && (
            <div style={{position:'absolute', inset:0, background:`${T.bg}f6`, padding:'20px 32px', overflow:'auto'}}>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:12}}>
                <h3 style={{fontFamily:F.display, fontWeight:F.dispWt, fontSize:36, margin:0, letterSpacing:'-0.03em'}}>STAGE {stage} CLEARED — UPGRADE</h3>
                <div style={{fontFamily:F.display, fontWeight:F.dispWt, fontSize:20, color:T.accent}}>★ {xp} XP</div>
              </div>
              <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:14}}>
                {[
                  {label:'STRENGTH +1', desc:`Deal more damage per hit (now ${str})`, cost: strCost, buy: buyStr, can: xp >= strCost},
                  {label:'SPEED +1', desc:`Lower attack cooldown (now ${spd})`, cost: spdCost, buy: buySpd, can: xp >= spdCost},
                ].map(u => (
                  <button key={u.label} onClick={u.buy} disabled={!u.can} style={{
                    textAlign:'left', padding:'14px 16px', background:u.can ? T.accent : `${T.ink}15`, color:T.ink,
                    border:`2.5px solid ${T.ink}`, boxShadow:u.can ? `4px 4px 0 0 ${T.ink}` : 'none',
                    cursor: u.can ? 'pointer' : 'not-allowed', opacity: u.can ? 1 : 0.5,
                  }}>
                    <div style={{fontFamily:F.display, fontWeight:F.dispWt, fontSize:18}}>{u.label}</div>
                    <div style={{fontFamily:F.hand, fontSize:18, marginTop:2}}>{u.desc}</div>
                    <div style={{fontFamily:F.mono, fontSize:11, marginTop:6, fontWeight:700}}>COST: {u.cost} XP</div>
                  </button>
                ))}
              </div>
              <button onClick={nextStage} style={{
                marginTop:18, padding:'12px 24px', background:T.accent2, color:'#fff',
                border:`2.5px solid ${T.ink}`, boxShadow:`4px 4px 0 0 ${T.ink}`,
                fontFamily:F.display, fontWeight:F.dispWt, fontSize:14, letterSpacing:'0.08em', textTransform:'uppercase', cursor:'pointer',
              }}>NEXT STAGE →</button>
            </div>
          )}

          {/* Game over */}
          {over && (
            <div style={{position:'absolute', inset:0, background:`${T.ink}f2`, color:T.bg, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:14}}>
              <div style={{fontFamily:F.display, fontWeight:F.dispWt, fontSize:68, letterSpacing:'-0.04em', color: over==='win' ? T.accent : T.accent2}}>
                {over === 'win' ? 'YOU WIN!' : 'TIMES UP'}
              </div>
              <div style={{fontFamily:F.hand, fontSize:24, maxWidth:520, textAlign:'center'}}>
                {over === 'win' ? 'King Trost has fallen. The kingdom is yours, kid.' : 'King Trost gloats. Refresh and try again.'}
              </div>
              <button onClick={reset} style={{
                marginTop:8, padding:'12px 24px', background:T.accent, color:T.ink,
                border:`2.5px solid ${T.bg}`, boxShadow:`4px 4px 0 0 ${T.bg}`,
                fontFamily:F.display, fontWeight:F.dispWt, fontSize:14, letterSpacing:'0.08em', textTransform:'uppercase', cursor:'pointer',
              }}>↻ TRY AGAIN</button>
            </div>
          )}
        </div>

        <div style={{textAlign:'center', marginTop:14, fontFamily:F.hand, fontSize:20, color:T.accent2}}>
          ↳ smash SPACE to attack — defeat 5 foes per stage, then face King Trost ⚔
        </div>
      </ScrapBox>
    </div>
  );
}

window.WindyLion = KillTheKing; // replace lion slot
window.KillTheKing = KillTheKing;
