// duel-lobby.jsx — GTO Duel match setup / lobby screen (portrait + landscape split).
// Exports (to window): DuelLobby({ mode, setMode, onStart, onProfile, landscape })

function VsRow({ mode, big = true }) {
  const left = mode === 'ai' ? 'YOU' : 'PLAYER 1';
  const right = mode === 'ai' ? 'AI' : 'PLAYER 2';
  const sub = mode === 'ai' ? 'ADVANCED' : null;
  const fs = big ? 20 : 18;
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 16 }}>
      <span style={{ fontFamily: 'var(--op-font-display)', fontWeight: 700, fontSize: fs, color: '#fff' }}>{left}</span>
      <span style={{
        width: 42, height: 42, borderRadius: 999, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        background: 'rgba(108,92,231,0.18)', boxShadow: '0 0 22px rgba(108,92,231,0.45)',
        fontFamily: 'var(--op-font-display)', fontWeight: 700, fontStyle: 'italic', fontSize: 16, color: 'var(--op-exodus-50)',
      }}>VS</span>
      <span style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', lineHeight: 1 }}>
        <span style={{ fontFamily: 'var(--op-font-display)', fontWeight: 700, fontSize: fs, color: '#fff' }}>{right}</span>
        {sub && <span style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 9.5, letterSpacing: '0.16em', color: 'rgba(255,255,255,0.45)', marginTop: 3 }}>{sub}</span>}
      </span>
    </div>
  );
}

function SettingRow({ title, desc, on, onChange }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 14, padding: '4px 0' }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 15, color: '#fff' }}>{title}</div>
        <div style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 400, fontSize: 12.5, color: 'rgba(255,255,255,0.45)', marginTop: 2 }}>{desc}</div>
      </div>
      <Toggle on={on} onChange={onChange} />
    </div>
  );
}

function Gear({ size = 22 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.6)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3" /><path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 11-2.83 2.83l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 11-2.83-2.83l.06-.06a1.65 1.65 0 00.33-1.82 1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 112.83-2.83l.06.06a1.65 1.65 0 001.82.33H9a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 112.83 2.83l-.06.06a1.65 1.65 0 00-.33 1.82V9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z" /></svg>
  );
}

function LobbySlider({ label, value, set, min, max, step, fmt }) {
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
        <span style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 15, color: '#fff' }}>{label}</span>
        <span style={{ fontFamily: 'var(--op-font-display)', fontWeight: 700, fontSize: 15, color: 'var(--op-exodus-50)' }}>{fmt ? fmt(value) : value}</span>
      </div>
      <input type="range" min={min} max={max} step={step} value={value} onChange={(e) => set(parseFloat(e.target.value))} style={{ width: '100%', accentColor: '#6C5CE7', height: 4, cursor: 'pointer' }} />
    </div>
  );
}

function NumberBox({ value, set, w = 70 }) {
  return (
    <input value={value} inputMode="decimal" onChange={(e) => set(e.target.value)} style={{
      width: w, boxSizing: 'border-box', textAlign: 'center',
      background: 'rgba(10,11,17,0.55)', border: '1px solid rgba(255,255,255,0.14)', borderRadius: 8,
      padding: '11px 6px', fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 15, color: '#fff', outline: 'none',
    }} />
  );
}

function DistTier({ title, d, on }) {
  const cell = (label, key) => (
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 600, fontSize: 11, color: 'rgba(255,255,255,0.5)', marginBottom: 5 }}>{label}</div>
      <NumberBox value={d[key]} set={(x) => on(key, x)} w="100%" />
    </div>
  );
  return (
    <div style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.07)', borderRadius: 12, padding: 14, marginBottom: 12 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12, gap: 8 }}>
        <span style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 13.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: '#fff' }}>{title}</span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 600, fontSize: 11.5, color: 'rgba(255,255,255,0.5)' }}>From decision</span>
          <NumberBox value={d.from} set={(x) => on('from', x)} w={58} />
        </span>
      </div>
      <div style={{ display: 'flex', gap: 8 }}>
        {cell('Heal', 'heal')}{cell('Shield', 'shield')}{cell('Offensive', 'off')}
      </div>
    </div>
  );
}

const ADV_DEFAULTS = {
  hp: 1000, rounds: 20, decTime: 25, bank: 60, threshold: 5,
  dist: {
    early: { from: 0, heal: 0.6, shield: 0.2, off: 0.2 },
    mid: { from: 30, heal: 0.4, shield: 0.2, off: 0.4 },
    late: { from: 60, heal: 0.2, shield: 0.2, off: 0.6 },
  },
};

function AdvancedSettings() {
  const [v, setV] = React.useState(ADV_DEFAULTS);
  const set = (k, val) => setV((s) => ({ ...s, [k]: val }));
  const setDist = (tier, key, val) => setV((s) => ({ ...s, dist: { ...s.dist, [tier]: { ...s.dist[tier], [key]: val } } }));
  return (
    <DarkCard pad={18}>
      <Eyebrow style={{ marginBottom: 18 }}>Match</Eyebrow>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
        <LobbySlider label="Starting HP" value={v.hp} set={(x) => set('hp', x)} min={200} max={2000} step={50} />
        <LobbySlider label="Round length" value={v.rounds} set={(x) => set('rounds', x)} min={5} max={40} step={1} fmt={(x) => `${x} decisions`} />
        <LobbySlider label="Per-decision time" value={v.decTime} set={(x) => set('decTime', x)} min={5} max={60} step={1} fmt={(x) => `${x}s`} />
        <LobbySlider label="Reserve time bank" value={v.bank} set={(x) => set('bank', x)} min={0} max={120} step={5} fmt={(x) => `${x}s`} />
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 14 }}>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 15, color: '#fff' }}>Power-up streak threshold</div>
            <div style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 400, fontSize: 12, color: 'rgba(255,255,255,0.45)', marginTop: 2 }}>Tier 1 at 5, tier 2 at multiples (10, 15, &hellip;)</div>
          </div>
          <NumberBox value={v.threshold} set={(x) => set('threshold', x)} w={70} />
        </div>
      </div>
      <div style={{ height: 1, background: 'rgba(255,255,255,0.07)', margin: '20px 0 16px' }}></div>
      <Eyebrow style={{ marginBottom: 14 }}>Power-up distribution</Eyebrow>
      <DistTier title="Early" d={v.dist.early} on={(k, x) => setDist('early', k, x)} />
      <DistTier title="Mid" d={v.dist.mid} on={(k, x) => setDist('mid', k, x)} />
      <DistTier title="Late" d={v.dist.late} on={(k, x) => setDist('late', k, x)} />
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 6 }}>
        <button onClick={() => setV(ADV_DEFAULTS)} className="op-tap" style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', background: 'none', border: '1px solid rgba(255,255,255,0.2)', borderRadius: 10, padding: '12px 18px', fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 12.5, letterSpacing: '0.06em', color: '#fff' }}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12a9 9 0 11-3-6.7L21 8" /><path d="M21 3v5h-5" /></svg>
          RESET ALL TO DEFAULTS
        </button>
      </div>
    </DarkCard>
  );
}

function DuelLobby({ mode, setMode, onStart, onProfile, landscape }) {
  const [gameType, setGameType] = React.useState('MTT, 8-Max');
  const [stage, setStage] = React.useState('Chip EV');
  const [street, setStreet] = React.useState('Postflop');
  const [difficulty, setDifficulty] = React.useState('Advanced');
  const [p1, setP1] = React.useState('Player 1');
  const [p2, setP2] = React.useState('Player 2');
  const [rng, setRng] = React.useState(false);
  const [timer, setTimer] = React.useState(true);
  const [advanced, setAdvanced] = React.useState(false);

  const diffStars = { Beginner: 1, Intermediate: 2, Advanced: 3, Expert: 4, GTO: 5 };
  const subtitle = mode === 'ai'
    ? 'Play a single-player match against an AI opponent. Each mistake takes HP. Last one standing wins.'
    : 'Two players, one screen. Take turns making GTO decisions — each mistake costs HP. Last one standing wins.';

  const profileBtn = (
    <button onClick={onProfile} className="op-tap" style={{
      cursor: 'pointer', background: 'none', border: '1px solid rgba(255,255,255,0.18)', borderRadius: 8,
      padding: '7px 12px', fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 11, letterSpacing: '0.12em', color: '#fff',
    }}>PROFILE</button>
  );
  const gearBtn = <button onClick={() => setAdvanced((a) => !a)} aria-pressed={advanced} className="op-tap" style={{ cursor: 'pointer', background: advanced ? 'rgba(108,92,231,0.22)' : 'none', border: 'none', borderRadius: 8, padding: 6 }}><Gear /></button>;

  const tutorialBtn = (
    <button className="op-tap" style={{
      flex: '0 0 38%', cursor: 'pointer', background: 'none', border: '1px solid rgba(255,255,255,0.2)', borderRadius: 12,
      padding: '15px 0', fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 13, letterSpacing: '0.1em', color: '#fff',
    }}>TUTORIAL</button>
  );
  const startBtn = (
    <button onClick={onStart} className="op-tap" style={{
      flex: 1, cursor: 'pointer', border: 'none', borderRadius: 12,
      background: 'linear-gradient(180deg, #7C6BF0, #6C5CE7)', color: '#fff',
      padding: '15px 0', fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 14, letterSpacing: '0.1em',
      boxShadow: '0 10px 28px rgba(108,92,231,0.5)',
    }}>START MATCH</button>
  );

  const scenarioCard = (
    <DarkCard pad={18}>
      <Eyebrow style={{ marginBottom: 16 }}>Scenario</Eyebrow>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <SelectField label="Game Type" options={['MTT, 8-Max', 'MTT, 6-Max', 'MTT, Heads-Up', 'Cash, 6-Max']} value={gameType} onChange={setGameType} />
        <SelectField label="Stage" options={['Chip EV', 'ICM', 'Final Table', 'Bubble']} value={stage} onChange={setStage} />
        <SelectField label="Street" options={['Postflop', 'Preflop', 'Flop', 'Turn', 'River']} value={street} onChange={setStreet} />
      </div>
    </DarkCard>
  );

  const settingsCard = (
    <DarkCard pad={18}>
      <Eyebrow style={{ marginBottom: 16 }}>Match Settings</Eyebrow>
      <div style={{ marginBottom: 16 }}>
        <Segmented options={[{ value: 'ai', label: 'VS AI' }, { value: 'local', label: 'VS Local Player' }]} value={mode} onChange={setMode} />
      </div>
      {mode === 'ai' ? (
        <div style={{ marginBottom: 18 }}>
          <SelectField label="AI Difficulty" options={['Beginner', 'Intermediate', 'Advanced', 'Expert', 'GTO']} value={difficulty} onChange={setDifficulty} adornment={<Stars filled={diffStars[difficulty]} />} />
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 18 }}>
          <TextField label="Player 1" value={p1} onChange={setP1} />
          <TextField label="Player 2" value={p2} onChange={setP2} />
        </div>
      )}
      <div style={{ height: 1, background: 'rgba(255,255,255,0.06)', margin: '2px 0 10px' }}></div>
      <SettingRow title="RNG mode" desc="Sample actions from the GTO mix" on={rng} onChange={setRng} />
      <div style={{ height: 1, background: 'rgba(255,255,255,0.06)', margin: '6px 0' }}></div>
      <SettingRow title="Timer" desc="Limit how long each decision can take" on={timer} onChange={setTimer} />
    </DarkCard>
  );

  // ---------- Landscape: split rail (brand + actions) | scrolling settings ----------
  if (landscape) {
    const sidebar = (
      <React.Fragment>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>{profileBtn}{gearBtn}</div>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', textAlign: 'center', padding: '8px 0' }}>
          <div style={{
            fontFamily: 'var(--op-font-display)', fontWeight: 700, fontSize: 40, lineHeight: 1, letterSpacing: '-0.01em',
            background: 'linear-gradient(180deg, #ABA2F1, #6C5CE7)', WebkitBackgroundClip: 'text', backgroundClip: 'text', WebkitTextFillColor: 'transparent',
          }}>GTO DUEL</div>
          <p style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 400, fontSize: 12.5, lineHeight: 1.45, color: 'rgba(255,255,255,0.6)', margin: '12px auto 16px', maxWidth: 280, textWrap: 'pretty' }}>{subtitle}</p>
          <VsRow mode={mode} />
        </div>
        <div style={{ display: 'flex', gap: 12 }}>{tutorialBtn}{startBtn}</div>
      </React.Fragment>
    );
    return (
      <ScreenShell landscape sidebar={sidebar}>
        {advanced ? <AdvancedSettings /> : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            {scenarioCard}
            {settingsCard}
          </div>
        )}
      </ScreenShell>
    );
  }

  // ---------- Portrait ----------
  const header = (
    <div style={{ padding: '44px 16px 4px', boxSizing: 'border-box' }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>{profileBtn}{gearBtn}</div>
    </div>
  );
  const footer = (
    <div style={{ display: 'flex', gap: 12, padding: '14px 16px 22px', borderTop: '1px solid rgba(255,255,255,0.06)', background: 'rgba(11,12,19,0.6)', backdropFilter: 'blur(8px)' }}>
      {tutorialBtn}{startBtn}
    </div>
  );
  return (
    <ScreenShell header={header} footer={footer} padBody={16}>
      {advanced ? <AdvancedSettings /> : (
        <React.Fragment>
          <div style={{ textAlign: 'center', marginBottom: 8 }}>
            <div style={{
              fontFamily: 'var(--op-font-display)', fontWeight: 700, fontSize: 52, lineHeight: 1, letterSpacing: '-0.01em',
              background: 'linear-gradient(180deg, #ABA2F1, #6C5CE7)', WebkitBackgroundClip: 'text', backgroundClip: 'text', WebkitTextFillColor: 'transparent',
            }}>GTO<br />DUEL</div>
            <p style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 400, fontSize: 13.5, lineHeight: 1.5, color: 'rgba(255,255,255,0.6)', margin: '14px auto 0', maxWidth: 320, textWrap: 'pretty' }}>{subtitle}</p>
          </div>
          <div style={{ margin: '20px 0 22px' }}><VsRow mode={mode} /></div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            {scenarioCard}
            {settingsCard}
          </div>
        </React.Fragment>
      )}
    </ScreenShell>
  );
}

Object.assign(window, { DuelLobby });
