// battle.jsx — Game Boy style battle preview with HP bars + move log

function Battle() {
  const enemy = POKEDEX[93];
  const friend = POKEDEX[24];
  const eName = (enemy?.name || 'ENEMY').toUpperCase();
  const fName = (friend?.name || 'ALLY').toUpperCase();
  const [enemyHP, setEnemyHP] = React.useState(100);
  const [friendHP, setFriendHP] = React.useState(100);
  const [log, setLog] = React.useState([`A wild ${eName} appeared!`, `Go! ${fName}!`]);
  const [thinking, setThinking] = React.useState(false);
  const [eShake, setEShake] = React.useState(false);
  const [fShake, setFShake] = React.useState(false);

  const moves = [
    { name: 'SPARK',     pwr: 18, type: friend.types[0] },
    { name: 'QUICK ZAP', pwr: 12, type: friend.types[0] },
    { name: 'IRON TAIL', pwr: 28, type: { color: '#c9c9c9' } },
    { name: 'GROWL',     pwr: 0,  type: { color: '#fff' } },
  ];

  function pushLog(line) {
    setLog(L => [...L.slice(-6), line]);
  }

  function attack(m) {
    if (thinking || enemyHP <= 0 || friendHP <= 0) return;
    setThinking(true);
    pushLog(`${fName} used ${m.name}!`);
    setTimeout(() => {
      setEShake(true);
      const dmg = m.pwr + Math.floor(Math.random() * 8);
      setEnemyHP(h => Math.max(0, h - dmg));
      setTimeout(() => setEShake(false), 300);
      if (enemyHP - dmg <= 0) {
        pushLog(`${eName} fainted! +280 EXP`);
        pushLog(`${fName} grew to LV.26!`);
        setThinking(false);
        return;
      }
      setTimeout(() => {
        // Enemy turn
        pushLog(`${eName} used SHADOW BALL!`);
        setFShake(true);
        const ed = 8 + Math.floor(Math.random() * 14);
        setFriendHP(h => Math.max(0, h - ed));
        setTimeout(() => setFShake(false), 300);
        setTimeout(() => setThinking(false), 400);
      }, 700);
    }, 500);
  }

  function reset() {
    setEnemyHP(100); setFriendHP(100); setThinking(false);
    setLog([`A wild ${eName} appeared!`, `Go! ${fName}!`]);
  }

  const ep = enemy.types[0].color;
  const fp = friend.types[0].color;

  return (
    <section id="battle" className="section grid-bg">
      <div className="pd-wrap">
        <Reveal>
          <div className="section-label">Battle Arena</div>
          <div className="row between" style={{ alignItems: 'flex-end', marginBottom: 28, flexWrap: 'wrap', gap: 20 }}>
            <h2 className="pd-h2" style={{ margin: 0, color: 'var(--pd-paper)', maxWidth: 700 }}>
              EVERY CREATURE YOU HOLD<br/>
              <span style={{ color: 'var(--pd-red)' }}>CAN FIGHT.</span>
            </h2>
            <p style={{ fontSize: 16, color: 'rgba(241,233,210,.7)', maxWidth: 460 }}>
              Turn-based battles, on-chain wagers, EXP that levels your token. Higher level = bigger flex (and bigger bag).
            </p>
          </div>
        </Reveal>

        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24 }}>
          {/* Battle screen */}
          <Reveal delay={0.1}><div className="pd-card" style={{
            padding: 0, background: '#a8c8a0', overflow: 'hidden',
            display: 'flex', flexDirection: 'column',
          }}>
            {/* Battlefield */}
            <div className="battle-screen-field" style={{
              position: 'relative',
              flex: 1, minHeight: 380,
              background: 'linear-gradient(180deg, #87b5b0 0%, #a8c8a0 55%, #8eb275 100%)',
              padding: 24,
              backgroundImage: `
                linear-gradient(180deg, #87b5b0 0%, #a8c8a0 55%, #8eb275 100%),
                repeating-linear-gradient(0deg, transparent 0 7px, rgba(0,0,0,.04) 7px 8px)
              `,
            }}>
              {/* Enemy info */}
              <div className="pd-card battle-screen-info" style={{
                background: '#f1e9d2', padding: '10px 14px', display: 'inline-block',
                position: 'absolute', top: 24, left: 24, minWidth: 280,
              }}>
                <div className="row between">
                  <span className="pixel" style={{ fontSize: 11 }}>{enemy.name.toUpperCase()}</span>
                  <span className="pixel" style={{ fontSize: 11 }}>L43</span>
                </div>
                <div className="row" style={{ gap: 8, alignItems: 'center', marginTop: 6 }}>
                  <span className="pixel" style={{ fontSize: 9, color: '#c92a2a' }}>HP</span>
                  <div className="hpbar" style={{ flex: 1 }}>
                    <div className={`hpbar__fill ${enemyHP < 50 ? 'low' : ''} ${enemyHP < 20 ? 'crit' : ''}`} style={{ width: `${enemyHP}%` }} />
                  </div>
                </div>
              </div>

              {/* Enemy sprite */}
              <div className="battle-screen-sprite" style={{
                position: 'absolute', top: 30, right: 60,
                transform: eShake ? 'translateX(8px) rotate(2deg)' : 'translateX(0)',
                transition: 'transform .1s',
                opacity: enemyHP <= 0 ? 0 : 1,
              }}>
                <Sprite seed={enemy.seed} n={enemy.n} primary={ep} secondary={enemy.types[1]?.color} size={100} />
              </div>

              {/* Friend info */}
              <div className="pd-card battle-screen-info" style={{
                background: '#f1e9d2', padding: '10px 14px',
                position: 'absolute', bottom: 24, right: 24, minWidth: 320,
              }}>
                <div className="row between">
                  <span className="pixel" style={{ fontSize: 11 }}>{friend.name.toUpperCase()}</span>
                  <span className="pixel" style={{ fontSize: 11 }}>L25</span>
                </div>
                <div className="row" style={{ gap: 8, alignItems: 'center', marginTop: 6 }}>
                  <span className="pixel" style={{ fontSize: 9, color: '#c92a2a' }}>HP</span>
                  <div className="hpbar" style={{ flex: 1 }}>
                    <div className={`hpbar__fill ${friendHP < 50 ? 'low' : ''} ${friendHP < 20 ? 'crit' : ''}`} style={{ width: `${friendHP}%` }} />
                  </div>
                  <span className="mono" style={{ fontSize: 14 }}>{friendHP}/100</span>
                </div>
                <div className="row" style={{ gap: 8, alignItems: 'center', marginTop: 4 }}>
                  <span className="pixel" style={{ fontSize: 9 }}>EXP</span>
                  <div style={{ flex: 1, height: 6, background: '#1a1d3a', border: '2px solid #14172b' }}>
                    <div style={{ height: '100%', width: '64%', background: '#5ad8ff' }} />
                  </div>
                </div>
              </div>

              {/* Friend sprite */}
              <div className="battle-screen-sprite" style={{
                position: 'absolute', bottom: 130, left: 60,
                transform: fShake ? 'translateX(-8px) rotate(-2deg)' : 'translateX(0)',
                transition: 'transform .1s',
                opacity: friendHP <= 0 ? 0 : 1,
              }}>
                <Sprite seed={friend.seed} n={friend.n} primary={fp} secondary={friend.types[1]?.color} size={120} />
              </div>
            </div>

            {/* Move log + actions */}
            <div className="battle-screen-bottom" style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', borderTop: '4px solid var(--pd-line)' }}>
              <div style={{
                padding: 14, background: '#f1e9d2', borderRight: '4px solid var(--pd-line)',
                minHeight: 130,
              }}>
                {log.slice(-3).map((line, i) => (
                  <div key={i} className="pixel" style={{ fontSize: 11, marginBottom: 6, color: '#14172b' }}>
                    {line}
                  </div>
                ))}
              </div>
              <div style={{
                padding: 12, background: '#f1e9d2',
                display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6,
              }}>
                {(enemyHP <= 0 || friendHP <= 0) ? (
                  <button className="pd-btn" style={{ gridColumn: '1 / -1' }} onClick={reset}>↻ NEW BATTLE</button>
                ) : moves.map(m => (
                  <button key={m.name} className="pd-btn pd-btn--sm" onClick={() => attack(m)} disabled={thinking}
                    style={{
                      background: m.type.color, color: '#14172b',
                      fontSize: 10, padding: 10, opacity: thinking ? .5 : 1,
                    }}>
                    {m.name}
                  </button>
                ))}
              </div>
            </div>
          </div>

          </Reveal>

          {/* Right column: stats + tournament info */}
          <Reveal delay={0.2}><div className="col" style={{ gap: 16 }}>
            <div className="pd-card pd-card--dark" style={{ padding: 20 }}>
              <div className="pixel" style={{ fontSize: 11, color: 'var(--pd-yellow)', letterSpacing: '.14em', marginBottom: 14 }}>WAGER POOL</div>
              <div className="row between" style={{ alignItems: 'baseline' }}>
                <span className="mono" style={{ fontSize: 36, color: 'var(--pd-paper)' }}>2.40</span>
                <span className="pixel" style={{ fontSize: 12, color: 'var(--pd-yellow)' }}>◎ SOL</span>
              </div>
              <div className="mono" style={{ fontSize: 13, color: 'rgba(241,233,210,.5)' }}>
                +0.12 SOL per round to winner
              </div>
              <div className="row" style={{ gap: 8, marginTop: 14 }}>
                <button className="pd-btn pd-btn--sm" style={{ flex: 1 }}>STAKE 0.5</button>
                <button className="pd-btn pd-btn--sm pd-btn--yellow" style={{ flex: 1 }}>STAKE 2.0</button>
              </div>
            </div>

            <div className="pd-card pd-card--dark" style={{ padding: 20 }}>
              <div className="pixel" style={{ fontSize: 11, color: 'var(--pd-yellow)', letterSpacing: '.14em', marginBottom: 14 }}>BATTLE TYPES</div>
              <div className="col" style={{ gap: 10 }}>
                {[
                  { n: '1v1',  d: 'Quick duel, no stakes', c: 'var(--pd-cyan)' },
                  { n: 'PvP',  d: 'Wager SOL, winner takes 90%', c: 'var(--pd-yellow)' },
                  { n: '3v3',  d: 'Team battle, type advantages stack', c: 'var(--pd-pink)' },
                  { n: 'RAID', d: 'Co-op vs legendary, weekly drop', c: 'var(--pd-red)' },
                ].map(b => (
                  <div key={b.n} className="row between" style={{ alignItems: 'center', padding: '8px 0', borderBottom: '1px dashed rgba(241,233,210,.15)' }}>
                    <div className="row" style={{ gap: 12, alignItems: 'center' }}>
                      <span className="pixel" style={{ fontSize: 11, color: b.c, minWidth: 50 }}>{b.n}</span>
                      <span style={{ fontSize: 13, color: 'rgba(241,233,210,.7)' }}>{b.d}</span>
                    </div>
                    <span style={{ color: 'var(--pd-paper)' }}>›</span>
                  </div>
                ))}
              </div>
            </div>

            <div className="pd-card pd-card--dark" style={{ padding: 20 }}>
              <div className="row between" style={{ alignItems: 'center', marginBottom: 12 }}>
                <span className="pixel" style={{ fontSize: 11, color: 'var(--pd-yellow)' }}>NEXT TOURNAMENT</span>
                <span className="pulse-dot"></span>
              </div>
              <div className="mono" style={{ fontSize: 30, color: 'var(--pd-paper)' }}>02:14:33</div>
              <div className="mono" style={{ fontSize: 13, color: 'rgba(241,233,210,.55)', marginTop: 4 }}>
                Prize pool: 142 SOL · 1,204 entries
              </div>
            </div>
          </div></Reveal>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Battle });
