// app.jsx — Main shell + routing + tournament detail + tweaks panel

const { useState: uS, useEffect: uE } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "gold",
  "andrewTone": "hybrid",
  "showFriends": true,
  "responsibleProminence": "all"
}/*EDITMODE-END*/;

function App() {
  const [tab, setTab] = uS('home');
  const [sub, setSub] = uS(null); // sub-screen id or 'doyle'
  const [tournament, setTournament] = uS(null);
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  // Profile is optional — set when user wants to save a draft. Map is open to all.
  const [profile, setProfile] = uS(() => {
    try { const raw = localStorage.getItem('plr_profile'); return raw ? JSON.parse(raw) : null; } catch (e) { return null; }
  });

  // Apply accent tweak
  uE(() => {
    const root = document.querySelector('.app');
    if (!root) return;
    const map = { gold: '#d4af37', red: '#c8312b', green: '#3a8a5c', white: '#f4f1ea' };
    root.style.setProperty('--gold', map[tweaks.accent] || '#d4af37');
  }, [tweaks.accent]);

  const goDoyle = () => setSub('doyle');

  // Sub-screen routing
  if (sub === 'coach') return <CoachScreen onClose={() => setSub(null)}/>;
  if (sub === 'history')  return <HistoryScreen  onBack={() => setSub(null)}/>;
  if (sub === 'mind')     return <MindScreen onCoach={goDoyle} onBack={() => setSub(null)}/>;
  if (sub === 'rankings') return <RankingsScreen onBack={() => setSub(null)}/>;
  if (sub === 'recap')    return <RecapScreen    onBack={() => setSub(null)}/>;
  if (sub === 'news')     return <NewsScreen     onBack={() => setSub(null)}/>;
  if (sub === 'bustout')  return <BustoutScreen  onBack={() => setSub(null)} onCoach={goDoyle}/>;
  if (sub === 'settings') return <SettingsScreen onBack={() => setSub(null)}/>;
  if (sub === 'latereg')  return <PokerLateRegScreen  onBack={() => setSub(null)} onTournamentTap={setTournament}/>;
  if (sub === 'draft')    return <DraftRoomScreen onClose={() => setSub(null)}/>;
  if (tournament)         return <TournamentDetail t={tournament} onBack={() => setTournament(null)} onCoach={goDoyle}/>;

  return (
    <>
      <div style={{ height: '100%', position: 'relative' }}>
        {tab === 'home'    && <HomeScreen onTab={setTab} onTournamentTap={setTournament} onCoach={goDoyle} onSubScreen={setSub}/>}
        {tab === 'coach'  && <CoachScreen onClose={() => setTab('home')}/>}
        {tab === 'friends' && <FriendsScreen/>}
        {tab === 'fantasy' && <FantasyScreen onBack={() => setTab('home')} fullscreen onSubScreen={setSub}/>}
        {tab === 'me'      && <MeScreen onTab={setTab} onSubScreen={setSub}/>}
        <BottomNav active={tab} onTab={setTab}/>
      </div>
    </>
  );
}

// ─── Tournament Detail ──────────────────────────────────────────────────
function TournamentDetail({ t, onBack, onCoach }) {
  return (
    <div style={{ height: '100%', overflowY: 'auto', paddingBottom: 100 }}>
      <SubHeader title={t.title} eyebrow={`${t.casino} · ${t.tag}`} onBack={onBack}/>
      <div style={{ padding: 20 }}>
        {/* Big countdown */}
        <div style={{ marginBottom: 20 }}>
          <div className="eyebrow" style={{ color: 'var(--red-bright)', marginBottom: 4 }}>● LATE REG CLOSES IN</div>
          <Countdown target={t.regClose} big/>
          <div className="mono" style={{ fontSize: 12, color: 'var(--paper-d)', marginTop: 8 }}>
            CLOSES AT LEVEL {t.level} · {t.startTime} START · {t.room.toUpperCase()}
          </div>
        </div>

        {/* Walk strip */}
        <div className="card card-gold" style={{ marginBottom: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div>
              <div className="num serif" style={{ fontSize: 42, color: 'var(--gold)', lineHeight: 1 }}>{t.walkMin}</div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--muted-d)', marginTop: 2 }}>MIN WALK</div>
            </div>
            <div style={{ flex: 1 }}>
              <div className="serif" style={{ fontSize: 17, lineHeight: 1.2 }}>You can make it.</div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--paper-d)', marginTop: 3 }}>{t.distance} · via Strip walkway</div>
              <div style={{ display: 'flex', gap: 6, marginTop: 8, alignItems: 'center' }}>
                <div style={{ flex: 1, height: 3, background: 'var(--felt-3)', position: 'relative' }}>
                  <div style={{ height: '100%', width: '15%', background: 'var(--gold)' }}/>
                </div>
                <div className="mono" style={{ fontSize: 9, color: 'var(--muted-d)' }}>YOU → {t.casino.toUpperCase()}</div>
              </div>
            </div>
          </div>
        </div>

        {/* Doyle's full take */}
        <div className="card" style={{ marginBottom: 16, border: '1px solid var(--line-gold)' }}>
          <div style={{ display: 'flex', gap: 12, marginBottom: 8 }}>
            <CoachAvatar size={32} mode="sharp"/>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                <AndrewTake take={t.doyle.take}/>
                <div className="mono" style={{ fontSize: 10, color: 'var(--muted-d)' }}>2:14 PM · sharp mode</div>
              </div>
              <div className="serif" style={{ fontSize: 17, lineHeight: 1.3 }}>"{t.doyle.note}"</div>
            </div>
          </div>
          <button onClick={onCoach} className="btn btn-ghost" style={{ width: '100%', marginTop: 4 }}>
            Ask follow-up →
          </button>
        </div>

        {/* Stats grid */}
        <div className="section-num" style={{ marginBottom: 8 }}>EVENT INTEL</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1, background: 'var(--line-d)', border: '1px solid var(--line-d)' }}>
          {[
            ['Buy-in', `$${t.buyin.toLocaleString()}`],
            ['Field',  t.field.toLocaleString()],
            ['Chip avg', `${(t.chipAvg/1000).toFixed(1)}k`],
            ['Structure', t.structureGrade],
            ['Prize pool', `$${(t.prizePool/1000).toFixed(0)}k`],
            ['Current level', `L${t.level}`],
          ].map(([k, v]) => (
            <div key={k} style={{ padding: 14, background: 'var(--felt)' }}>
              <div className="eyebrow" style={{ marginBottom: 4 }}>{k}</div>
              <div className="num serif" style={{ fontSize: 22 }}>{v}</div>
            </div>
          ))}
        </div>

        {/* Friends */}
        {t.friends.length > 0 && (
          <>
            <div className="section-num" style={{ marginTop: 24, marginBottom: 8 }}>YOUR CREW · {t.friends.length} IN</div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {t.friends.map((f, i) => (
                <div key={i} className="card" style={{ padding: '8px 12px', display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontSize: 14 }}>{f.avatar}</span>
                  <span className="serif" style={{ fontSize: 14 }}>{f.name}</span>
                </div>
              ))}
            </div>
          </>
        )}

        {/* Big register button */}
        <div style={{ position: 'sticky', bottom: 90, marginTop: 32 }}>
          <button className="btn btn-gold" style={{ width: '100%', padding: '18px', fontSize: 16, fontWeight: 600 }}>
            Walk there now → reserve seat
          </button>
          <button className="btn btn-ghost" style={{ width: '100%', marginTop: 8 }}>Add to my watchlist</button>
        </div>
      </div>
    </div>
  );
}

// ─── Tweaks Panel ───────────────────────────────────────────────────────
function AppTweaks() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  return (
    <TweaksPanel>
      <TweakSection title="Look">
        <TweakRadio label="Accent color" value={tweaks.accent} options={[
          { value: 'gold', label: 'Gold' },
          { value: 'red', label: 'Red' },
          { value: 'green', label: 'Felt' },
          { value: 'white', label: 'Ivory' },
        ]} onChange={v => setTweak('accent', v)}/>
      </TweakSection>
      <TweakSection title="Coach Kyle">
        <TweakRadio label="Default tone" value={tweaks.andrewTone} options={[
          { value: 'hybrid', label: 'Hybrid' },
          { value: 'sharp', label: 'Sharp' },
          { value: 'mentor', label: 'Mentor' },
          { value: 'zen', label: 'Zen' },
        ]} onChange={v => setTweak('andrewTone', v)}/>
      </TweakSection>
      <TweakSection title="Map">
        <TweakToggle label="Show friends on map" value={tweaks.showFriends} onChange={v => setTweak('showFriends', v)}/>
      </TweakSection>
      <TweakSection title="Responsible play">
        <TweakRadio label="Prominence" value={tweaks.responsibleProminence} options={[
          { value: 'footer', label: 'Footer' },
          { value: 'header', label: 'Header' },
          { value: 'all', label: 'Everywhere' },
        ]} onChange={v => setTweak('responsibleProminence', v)}/>
      </TweakSection>
    </TweaksPanel>
  );
}

// ─── Mount ──────────────────────────────────────────────────────────────
function Root() {
  // Auto day/night by Pacific hour. Day: 7am–7pm.
  const hour = new Date().getHours();
  const mode = (hour >= 7 && hour < 19) ? 'day' : 'night';
  return (
    <div className="app" data-mode={mode} style={{ width: '100vw', height: '100vh', overflow: 'hidden' }}>
      <App/>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<Root/>);
