// ============================================================================
// Title / Character Select / Tutorial / Victory screens
// ============================================================================

const { useState: sUseState, useEffect: sUseEffect } = React;

// ------------------ Title ------------------
function TitleScreen({ onPlay, onTutorial, onSelect }) {
  return (
    <div className="screen" style={{justifyContent:'center', alignItems:'center', padding:'40px 28px', gap:18}}>
      <div className="candle-glow" style={{top: 60, left: '50%', marginLeft: -100}}></div>

      <div style={{textAlign:'center', position:'relative'}}>
        <div className="mono" style={{fontSize:11, letterSpacing:'.4em', color:'var(--brass-2)', marginBottom:6}}>
          A POKER DUEL
        </div>
        <div className="display" style={{
          fontSize: 56,
          color: 'var(--brass-1)',
          textShadow: '0 0 22px rgba(255,138,31,0.55), 0 4px 0 #2a1810, 0 5px 0 #1a0f08, 0 8px 12px rgba(0,0,0,0.7)',
          lineHeight: 0.95,
          letterSpacing: '0.01em',
        }}>
          POKER
        </div>
        <div className="display" style={{
          fontSize: 56,
          color: 'var(--blood)',
          textShadow: '0 0 22px rgba(139,26,26,0.6), 0 4px 0 #2a0a0a, 0 5px 0 #1a0606, 0 8px 12px rgba(0,0,0,0.7)',
          lineHeight: 0.95,
          letterSpacing: '0.01em',
        }}>
          MANIA
        </div>
        <Ornament width={220} />
        <div style={{fontFamily:'var(--font-body)', fontStyle:'italic', fontSize:14, color:'var(--parch-dim)', marginTop:-4}}>
          Hold'em with knives
        </div>
      </div>

      {/* Card fan decoration */}
      <div style={{position:'relative', height:115, margin:'10px 0'}}>
        <style>{`
          ${[0,1,2,3,4].map(i => {
            const a = (i-2)*11;
            const aStart = a + (a >= 0 ? 12 : -12);
            return `@keyframes titleFan${i}{from{opacity:0;transform:translateX(-50%) rotate(${aStart}deg) translateY(-22px);}to{opacity:1;transform:translateX(-50%) rotate(${a}deg);}}`;
          }).join('')}
        `}</style>
        {[null, null, 'As', null, null].map((c, i) => (
          <PCard
            key={i}
            card={c}
            size="lg"
            style={{
              position:'absolute',
              left:`calc(50% + ${(i-2)*12}px)`,
              bottom:0,
              transformOrigin:'bottom center',
              zIndex: 5 - Math.abs(i - 2),
              animation:`titleFan${i} .5s ${i*80}ms cubic-bezier(.3,1.4,.5,1) both`,
            }}
          />
        ))}
      </div>

      <div style={{display:'flex', flexDirection:'column', gap:10, width:'100%', maxWidth:280}}>
        <button className="btn btn-primary" onClick={onSelect} style={{padding:'14px 16px', fontSize:18}}>
          Sit at the Table
        </button>
        <button className="btn" onClick={onTutorial}>Tutorial</button>
      </div>

      <div className="mono" style={{position:'absolute', bottom:18, fontSize:9, color:'var(--parch-faded)', letterSpacing:'.3em', whiteSpace:'nowrap'}}>
        DEAL · DRAW · BLEED
      </div>
    </div>
  );
}

// ------------------ Character Select ------------------
const CHARS = [
  { key: 'drifter',  name: 'The Drifter',  title: 'cold hand, colder eye',         avatar: '🎩', perk: 'Balanced — no quirks, no excuses.',     statline: { agg: 2, read: 3, luck: 2 } },
  { key: 'preacher', name: 'The Preacher', title: 'speaks softly, holds two pair',  avatar: '✝', perk: 'Reads the room as well as the cards.',   statline: { agg: 1, read: 3, luck: 3 } },
  { key: 'gunhand',  name: 'The Gunhand',  title: 'shoots first, shuffles later',   avatar: '🔫', perk: 'Strikes early and often.',              statline: { agg: 4, read: 1, luck: 2 } },
  { key: 'widow',    name: 'The Widow',    title: 'wore black before the funeral',  avatar: '🕷', perk: 'Patient. Lets others bleed first.',     statline: { agg: 2, read: 3, luck: 3 } },
];

const OPPONENTS = [
  { key: 'greenhorn', name: 'Greenhorn Pete', sub: 'first time off the homestead', hp: 80, diff: 'Easy' },
  { key: 'gambler',   name: 'Lady Diamond',   sub: 'never seen her lose a hand sober', hp: 100, diff: 'Medium' },
  { key: 'marshal',   name: 'Marshal Crane',  sub: 'reads tells like a sermon', hp: 110, diff: 'Hard' },
  { key: 'outlaw',    name: 'Black Jack Roy', sub: 'bluffs like he means it', hp: 100, diff: 'Hard' },
];

function CharacterSelectScreen({ onStart, onBack }) {
  const [charIx, setCharIx] = sUseState(0);
  const [oppIx, setOppIx] = sUseState(1);
  const char = CHARS[charIx];
  const opp = OPPONENTS[oppIx];
  return (
    <div className="screen" style={{padding:'18px 14px 14px', gap:12}}>
      <Header title="Choose Your Hand" onBack={onBack} />

      {/* Player picker */}
      <div className="panel" style={{padding:'12px', display:'flex', flexDirection:'column', gap:8}}>
        <div style={{display:'flex', alignItems:'center', gap:12}}>
          <div style={{
            width:72, height:60, flexShrink:0,
            borderRadius:2, border:'1px solid var(--brass-2)',
            background: 'radial-gradient(ellipse at 50% 35%, rgba(255,179,71,0.2), transparent 70%), linear-gradient(180deg,#2a1810,#0a0604)',
            display:'grid', placeItems:'end center', overflow:'hidden',
            boxShadow:'inset 0 0 8px rgba(0,0,0,0.7)',
          }}>
            <Silhouette kind={char.key} size={66} color="#4a2e1e" />
          </div>
          <div style={{flex:1, minWidth:0}}>
            <div className="head" style={{fontSize:20, color:'var(--brass-1)'}}>{char.name}</div>
            <div style={{fontSize:12, color:'var(--parch-dim)', fontStyle:'italic'}}>{char.title}</div>
            <div style={{fontFamily:'var(--font-body)', fontSize:13, color:'var(--parch)', marginTop:4, lineHeight:1.3}}>
              {char.perk}
            </div>
          </div>
        </div>
        <div style={{display:'flex', gap:14, justifyContent:'center', marginTop:4}}>
          <StatLine label="Aggression" value={char.statline.agg} />
          <StatLine label="Read" value={char.statline.read} />
          <StatLine label="Luck" value={char.statline.luck} />
        </div>
        <div style={{display:'flex', gap:6, marginTop:4}}>
          {CHARS.map((c, i) => (
            <button
              key={c.key}
              className={`btn btn-sm ${i === charIx ? 'btn-brass' : ''}`}
              style={{padding:'4px 4px', fontSize:11, minWidth:0, flex:'1 1 0', display:'grid', placeItems:'end center', height: 56, overflow:'hidden'}}
              onClick={() => setCharIx(i)}
            >
              <Silhouette kind={c.key} size={50} color={i === charIx ? '#4a2e1e' : '#2a1810'} />
            </button>
          ))}
        </div>
      </div>

      {/* VS */}
      <div className="display" style={{textAlign:'center', fontSize:16, color:'var(--blood)', letterSpacing:'.4em'}}>
        — VS —
      </div>

      {/* Opponent picker */}
      <div className="panel" style={{padding:'12px', display:'flex', flexDirection:'column', gap:8}}>
        <div style={{display:'flex', alignItems:'center', gap:12}}>
          <div style={{
            width:72, height:60, flexShrink:0,
            borderRadius:2, border:'1px solid var(--blood-deep)',
            background: 'radial-gradient(ellipse at 50% 35%, rgba(139,26,26,0.3), transparent 70%), linear-gradient(180deg,#2a1010,#0a0606)',
            display:'grid', placeItems:'end center', overflow:'hidden',
          }}>
            <Silhouette kind={opp.key} size={66} color="#3a1818" />
          </div>
          <div style={{flex:1, minWidth:0}}>
            <div className="head" style={{fontSize:18, color:'var(--blood)'}}>{opp.name}</div>
            <div style={{fontSize:12, color:'var(--parch-dim)', fontStyle:'italic'}}>{opp.sub}</div>
            <div className="mono" style={{fontSize:11, color:'var(--parch-faded)', marginTop:4, letterSpacing:'.1em'}}>
              {opp.diff.toUpperCase()} · {opp.hp} HP
            </div>
          </div>
        </div>
        <div style={{display:'flex', gap:6, marginTop:4}}>
          {OPPONENTS.map((o, i) => (
            <button
              key={o.key}
              className={`btn btn-sm ${i === oppIx ? 'btn-brass' : ''}`}
              style={{padding:'4px 4px', fontSize:10, minWidth:0, flex:'1 1 0', display:'flex', flexDirection:'column', gap:2, alignItems:'center', height: 70, overflow:'hidden'}}
              onClick={() => setOppIx(i)}
            >
              <div style={{flex:1, display:'grid', placeItems:'end center', overflow:'hidden', width:'100%'}}>
                <Silhouette kind={o.key} size={44} color={i === oppIx ? '#3a1818' : '#1a1010'} />
              </div>
              <div style={{fontSize:9}}>{o.diff.toUpperCase()}</div>
            </button>
          ))}
        </div>
      </div>

      <button className="btn btn-primary" style={{padding:'14px', fontSize:18}} onClick={() => onStart(char, opp)}>
        Ante Up
      </button>
    </div>
  );
}

function StatLine({ label, value }) {
  return (
    <div style={{textAlign:'center'}}>
      <div style={{display:'flex', gap:2, justifyContent:'center'}}>
        {[1,2,3,4,5].map(i => (
          <span key={i} style={{
            width:8, height:8, borderRadius:'50%',
            background: i <= value ? 'var(--brass-1)' : 'rgba(234,214,168,0.15)',
            boxShadow: i <= value ? '0 0 4px rgba(255,138,31,0.6)' : 'none',
          }}></span>
        ))}
      </div>
      <div className="mono" style={{fontSize:9, color:'var(--parch-faded)', letterSpacing:'.1em', marginTop:3}}>
        {label.toUpperCase()}
      </div>
    </div>
  );
}

function Header({ title, onBack }) {
  return (
    <div style={{display:'flex', alignItems:'center', gap:8}}>
      {onBack && (
        <button className="btn btn-ghost btn-sm" style={{padding:'6px 10px'}} onClick={onBack}>‹</button>
      )}
      <div className="display" style={{fontSize:22, color:'var(--brass-1)', flex:1, textAlign:'center', textShadow:'0 0 10px rgba(255,138,31,0.4)'}}>
        {title}
      </div>
      {onBack && <div style={{width:36}}></div>}
    </div>
  );
}

// ------------------ Tutorial ------------------

const TUTORIAL_DECK = ['3s', '4h', 'Qs', 'Kd', 'Ac', '7d', '2c', 'Kh', 'As'];
// Pop order → player: As Kh | cpu: 2c 7d | flop: Ac Kd Qs | turn: 4h | river: 3s

const TUTORIAL_CPU_SCRIPT = [
  { phase: 'preFlop', attack: false, block: false },
  { phase: 'flop',    attack: false, block: false, betResponse: 'call' },
  { phase: 'turn',    attack: true,  block: false },
  { phase: 'river',   attack: false, block: false },
];

const TUTORIAL_STEPS = [
  { highlight: 'deal-btn',     message: 'A new hand begins. Click DEAL.',                                                                                      waitFor: 'deal-click'    },
  { highlight: 'hole-cards',   message: 'Your hole cards — only you see these.',                                                                              waitFor: 'tap'           },
  { highlight: 'energy-bar',   message: 'Win hands to fill your candles. Six lit candles unlock CHALLENGE — a direct HP wager, separate from your two actions.', waitFor: 'auto'        },
  { highlight: 'center-stage', message: 'Three cards land on the table. The Flop.',                                                                           waitFor: 'tap'           },
  { highlight: 'challenge-btn',message: 'Six candles. Click CHALLENGE to call out your opponent.',                                                             waitFor: 'challenge-click'},
  { highlight: null,           message: 'Pick your wager. They must Call, Fold, or Raise — same as a real saloon.',                                           waitFor: 'bet-commit'    },
  { highlight: null,           message: 'They called. The pot sits between you — winner takes it at showdown.',                                               waitFor: 'auto'          },
  { highlight: 'action-area',  message: 'The Action Window opens each street. You have 2 actions per hand.',                                                  waitFor: 'tap'           },
  { highlight: 'attack-btn',   message: 'Your hand is stronger. Click ATTACK to deal damage.',                                                                waitFor: 'attack-click'  },
  { highlight: 'timer-ring',   message: 'Both moves are secret until the clock runs out.',                                                                    waitFor: 'auto'          },
  { highlight: 'center-stage', message: 'A fourth card hits the table. The Turn.',                                                                            waitFor: 'tap'           },
  { highlight: 'block-btn',    message: 'Your enemy is about to strike. Click BLOCK to reflect it.',                                                         waitFor: 'block-click'   },
  { highlight: 'hp-bars',      message: 'Their attack bounced back. Block works.',                                                                            waitFor: 'tap'           },
  { highlight: 'center-stage', message: 'The final card. The River. The action window closes.',                                                              waitFor: 'auto'          },
  { highlight: 'damage-display',message: 'Damage is the gap between hand strengths. Winner takes the pot.',                                                   waitFor: 'tap'           },
  { highlight: null,           message: "Now you know the table. Good luck, stranger.",                                                                       waitFor: 'done'          },
];

function TutorialScreen({ onBack }) {
  const [step, setStep] = sUseState(0);
  const currentStep = TUTORIAL_STEPS[step];
  const advance = () => setStep(s => Math.min(s + 1, TUTORIAL_STEPS.length - 1));
  const isDone = currentStep?.waitFor === 'done';

  sUseEffect(() => {
    if (!currentStep || currentStep.waitFor !== 'auto') return;
    const t = setTimeout(advance, 1500);
    return () => clearTimeout(t);
  }, [step]);

  const isTap = currentStep?.waitFor === 'tap';

  return (
    <div style={{ position: 'relative', width: '100%', height: '100%' }}>
      <CombatScreen
        persona="greenhorn"
        playerProfile={{ name: 'You', title: 'The Drifter', key: 'drifter' }}
        onGameOver={() => {}}
        onExit={onBack}
        scriptedDeck={TUTORIAL_DECK}
        scriptedPlayerEnergy={100}
        scriptedCpuEnergy={0}
        cpuScript={TUTORIAL_CPU_SCRIPT}
        tutorialStep={currentStep}
        onTutorialAdvance={advance}
      />
      <div style={{
        position: 'absolute', inset: 0,
        pointerEvents: 'none',
      }}>
        <div
          className="panel-parch"
          onClick={isTap ? advance : undefined}
          style={{
            position: 'absolute', bottom: 8, left: 8, right: 8,
            padding: '12px 16px', zIndex: 52,
            pointerEvents: (isTap || isDone) ? 'auto' : 'none',
            cursor: isTap ? 'pointer' : 'default',
            display: 'flex', flexDirection: 'column', gap: 8,
          }}
        >
          <div className="mono" style={{
            fontSize: 9, letterSpacing: '.3em', color: 'var(--parch-faded)',
            textAlign: 'center', marginBottom: 2,
          }}>
            TUTORIAL · {step + 1} / {TUTORIAL_STEPS.length}
          </div>
          <div style={{
            fontFamily: 'var(--font-body)', fontSize: 14,
            lineHeight: 1.5, color: '#2a1810',
          }}>
            {currentStep?.message}
          </div>
          {isTap && (
            <div className="mono" style={{
              fontSize: 10, color: 'var(--parch-faded)',
              letterSpacing: '.2em', textAlign: 'center',
            }}>
              CLICK TO CONTINUE
            </div>
          )}
          {isDone && (
            <button className="btn btn-primary" onClick={e => { e.stopPropagation(); onBack(); }} style={{ marginTop: 4 }}>
              Back to Saloon
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// ------------------ Victory / Defeat ------------------
function GameOverScreen({ winner, state, onRematch, onMenu }) {
  const youWon = winner === 'player';
  return (
    <div className="screen" style={{padding:'30px 18px', gap:16, justifyContent:'center', alignItems:'center'}}>
      <div className="candle-glow" style={{top: 40, left: '50%', marginLeft: -100}}></div>

      <div style={{textAlign:'center'}}>
        <div className="mono" style={{fontSize:11, letterSpacing:'.4em', color:'var(--parch-faded)', marginBottom:4}}>
          {youWon ? 'THE TABLE IS YOURS' : 'YOU LEAVE BLEEDING'}
        </div>
        <div className="display" style={{
          fontSize: 56,
          color: youWon ? 'var(--brass-1)' : 'var(--blood)',
          textShadow: `0 0 22px ${youWon ? 'rgba(255,138,31,0.6)' : 'rgba(139,26,26,0.6)'}, 0 4px 0 #1a0f08, 0 8px 12px rgba(0,0,0,0.7)`,
          lineHeight: 1,
        }}>
          {youWon ? 'VICTORY' : 'DEFEAT'}
        </div>
        <Ornament width={240} />
        <div style={{fontFamily:'var(--font-body)', fontStyle:'italic', color:'var(--parch-dim)', fontSize:14}}>
          {youWon
            ? 'You rake the pot and walk out alive. The brass clock keeps ticking.'
            : 'They count your chips. Someone closes your eyes.'}
        </div>
      </div>

      <div className="panel-parch" style={{padding:'14px 18px', minWidth:260}}>
        <div style={{display:'grid', gridTemplateColumns:'1fr auto 1fr', gap:8, alignItems:'center'}}>
          <Stat label="Rounds played" value={Math.max(1, state.round)} />
          <div style={{color:'#5a4a30'}}>·</div>
          <Stat label="Best hand" value={bestHandSeen(state)} />
        </div>
      </div>

      <div style={{display:'flex', flexDirection:'column', gap:8, width:'100%', maxWidth:260}}>
        <button className="btn btn-primary" onClick={onRematch}>Rematch</button>
        <button className="btn" onClick={onMenu}>Back to Saloon</button>
      </div>
    </div>
  );
}

function Stat({ label, value }) {
  return (
    <div style={{textAlign:'center'}}>
      <div className="display" style={{fontSize:24, color:'var(--ink-stamp)'}}>{value}</div>
      <div className="mono" style={{fontSize:9, color:'#5a4a30', letterSpacing:'.1em', textTransform:'uppercase'}}>{label}</div>
    </div>
  );
}

function bestHandSeen(state) {
  if (state.lastEval?.winnerEval) return Poker.HAND_NAME[state.lastEval.winnerEval.rank];
  return '—';
}

Object.assign(window, {
  TitleScreen, CharacterSelectScreen, TutorialScreen, GameOverScreen,
  CHARS, OPPONENTS,
});
