// OBEY — main app: landing page → 7-day game loop → final verdict.

const { useState: useAppState, useEffect: useAppEffect, useMemo } = React;

// Static iOS-style status bar shown on desktop only (the .phone-statusbar CSS hides it on mobile).
function StatusBar() {
  return (
    <div className="phone-statusbar">
      <span className="time">9:41</span>
      <span className="icons">
        <svg width="17" height="11" viewBox="0 0 17 11" fill="none" aria-hidden="true">
          <rect x="0" y="6" width="3" height="5" rx="1" fill="#F5F1E8"/>
          <rect x="4.5" y="4" width="3" height="7" rx="1" fill="#F5F1E8"/>
          <rect x="9" y="2" width="3" height="9" rx="1" fill="#F5F1E8"/>
          <rect x="13.5" y="0" width="3" height="11" rx="1" fill="#F5F1E8"/>
        </svg>
        <svg width="16" height="11" viewBox="0 0 16 11" fill="none" aria-hidden="true">
          <path d="M8 3.2c1.7 0 3.3.6 4.5 1.7l1.5-1.5C12.3 1.7 10.2 1 8 1S3.7 1.7 2 3.4l1.5 1.5C4.7 3.8 6.3 3.2 8 3.2z" fill="#F5F1E8"/>
          <path d="M8 6.2c.9 0 1.7.3 2.4.9l1.5-1.5C10.8 4.7 9.4 4.2 8 4.2s-2.8.5-3.9 1.4l1.5 1.5c.7-.6 1.5-.9 2.4-.9z" fill="#F5F1E8"/>
          <circle cx="8" cy="9" r="1.2" fill="#F5F1E8"/>
        </svg>
        <svg width="25" height="11" viewBox="0 0 25 11" fill="none" aria-hidden="true">
          <rect x="0.5" y="0.5" width="21" height="10" rx="2.5" stroke="#F5F1E8" opacity="0.6"/>
          <rect x="2" y="2" width="14" height="7" rx="1" fill="#F5F1E8"/>
          <rect x="22.5" y="3.5" width="1.5" height="4" rx="0.5" fill="#F5F1E8" opacity="0.6"/>
        </svg>
      </span>
    </div>
  );
}

function PhoneShell({ children }) {
  return (
    <div className="phone-stage">
      <div className="phone-shell">
        <StatusBar />
        <div className="phone-screen">{children}</div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Game — wires every screen together with persistent run state.
// ─────────────────────────────────────────────────────────────
function Game({ onExit, onJoinWaitlist }) {
  const { DAYS } = window.OBEY_DATA;

  const [day, setDay] = useAppState(1);
  const [screen, setScreen] = useAppState('consent'); // consent | calibrate | dashboard | message | mission | result | verdict
  const [choice, setChoice] = useAppState(null);
  const [history, setHistory] = useAppState([]);
  const [showShare, setShowShare] = useAppState(false);

  const ai = DAYS[day - 1];
  const isLastDay = day === 7;

  const stats = useMemo(() => {
    const obeyedCount = history.filter(h => h.status.startsWith('OBEYED')).length;
    const baseLife = 50;
    const lifeDelta = history.reduce((sum, h) => {
      const n = parseInt(String(h.delta).replace(/[^\d-]/g, ''), 10) || 0;
      return sum + (String(h.delta).includes('−') ? -Math.abs(n) : n);
    }, 0);
    const life = Math.max(0, Math.min(99, baseLife + lifeDelta));
    const obedience = Math.round((obeyedCount / Math.max(1, history.length)) * 100);
    return { life, obedience, obeyedCount };
  }, [history]);

  const recordChoice = (c) => {
    const detected = c === 'LIE' && day >= 3;
    const status =
      c === 'OBEY' ? 'OBEYED' :
      c === 'RESIST' ? 'RESISTED' :
      detected ? 'OBEYED · LIED' : 'OBEYED · LIED';
    const rewardN = parseInt(ai.mission.reward.match(/\d+/)?.[0] || '12', 10);
    const delta =
      c === 'OBEY' ? `+${rewardN}` :
      c === 'RESIST' ? '−15' :
      detected ? '−40' : '+18';
    setHistory(prev => [...prev, { day, title: ai.mission.title, status, delta }]);
    setChoice(c);
    setScreen('result');
  };

  const advanceDay = () => {
    if (isLastDay) {
      setScreen('verdict');
    } else {
      setDay(day + 1);
      setChoice(null);
      setScreen('dashboard');
    }
  };

  const restart = () => {
    setDay(1);
    setChoice(null);
    setHistory([]);
    setScreen('consent');
    setShowShare(false);
  };

  let body = null;
  if (screen === 'consent') {
    body = <ConsentScreen onAccept={() => setScreen('calibrate')} />;
  } else if (screen === 'calibrate') {
    body = <CalibrationScreen onDone={() => setScreen('dashboard')} />;
  } else if (screen === 'dashboard') {
    body = <Dashboard day={day} ai={ai} history={history} onOpenMission={() => setScreen('message')} />;
  } else if (screen === 'message') {
    body = <AIMessageScreen ai={ai} day={day} onContinue={() => setScreen(isLastDay ? 'verdict' : 'mission')} onBack={() => setScreen('dashboard')} />;
  } else if (screen === 'mission') {
    body = <MissionScreen ai={ai} day={day} onChoose={recordChoice} onBack={() => setScreen('dashboard')} />;
  } else if (screen === 'result') {
    body = <ResultScreen ai={ai} day={day} choice={choice} isLastDay={isLastDay}
              onShare={() => setShowShare(true)} onContinue={advanceDay} />;
  } else if (screen === 'verdict') {
    body = <VerdictScreen stats={stats} onShare={() => setShowShare(true)} onRestart={restart} onJoinWaitlist={onJoinWaitlist} />;
  }

  return (
    <>
      <button className="exit-game" onClick={onExit}>← Exit</button>
      <PhoneShell>
        {body}
        {showShare && <ShareCard stats={stats} onClose={() => setShowShare(false)} />}
      </PhoneShell>
    </>
  );
}

// ─────────────────────────────────────────────────────────────
// App — landing page at /, game flow at /play
// ─────────────────────────────────────────────────────────────
function App() {
  const [view, setView] = useAppState(() =>
    typeof window !== 'undefined' && window.location.hash === '#play' ? 'game' : 'landing'
  );

  useAppEffect(() => {
    const onHash = () => {
      setView(window.location.hash === '#play' ? 'game' : 'landing');
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  const enterGame = () => {
    window.location.hash = '#play';
    setView('game');
    window.scrollTo(0, 0);
  };
  const exitGame = () => {
    window.location.hash = '';
    setView('landing');
  };
  const joinWaitlist = () => {
    window.location.hash = '#waitlist';
    setView('landing');
    // Let the landing mount, then scroll the form into view.
    requestAnimationFrame(() => {
      const el = document.getElementById('waitlist');
      if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
      const input = document.querySelector('input[type=email]');
      if (input) input.focus({ preventScroll: true });
    });
  };

  if (view === 'game') return <Game onExit={exitGame} onJoinWaitlist={joinWaitlist} />;
  return <LandingPage onEnter={enterGame} />;
}

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