// Playbook app shell, wires phases together

function PlaybookApp() {
  const [state, setState] = usePlaybookState();
  // 'hero' shows the landing; otherwise this tracks the highest phase revealed so far.
  // Phases accumulate vertically: hitting Continue on Phase N reveals Phase N+1 below.
  const [started, setStarted] = React.useState(false);
  const [highestPhase, setHighestPhase] = React.useState(() => {
    // Resume at the highest completed phase + 1 if returning to the page
    const c = state.completedPhases || {};
    if (c.p3) return 4;
    if (c.p2) return 3;
    if (c.p1) return 2;
    return 1;
  });

  // Nav uses 'p1'..'p4' ids; map to/from our phase number internally.
  const currentPhase = started ? `p${highestPhase}` : 'hero';

  const scrollToPhase = (n) => {
    setTimeout(() => {
      const el = document.getElementById(`phase${n}`);
      if (el) {
        const top = el.getBoundingClientRect().top + window.pageYOffset - 80; // sticky nav offset
        window.scrollTo({ top, behavior: 'smooth' });
      }
    }, 60);
  };

  const jumpTo = (phaseId) => {
    if (!phaseId || phaseId === 'hero') return;
    // Accept 'p1' (from PlaybookNav) or 'phase1' (legacy)
    const m = String(phaseId).match(/(\d+)/);
    const n = m ? parseInt(m[1], 10) : NaN;
    if (!Number.isFinite(n)) return;
    if (n > highestPhase) setHighestPhase(n);
    scrollToPhase(n);
  };

  const reveal = (n) => {
    if (n > highestPhase) setHighestPhase(n);
    scrollToPhase(n);
  };

  // Safe analytics wrapper: never lets a tracking failure block the user flow.
  // (Hit a real bug where analytics was undefined → TypeError → reveal()
  // never ran → user stuck on Continue. Defense in depth from here on out.)
  const safeTrack = (eventName, params) => {
    try {
      if (window.bluemoso && window.bluemoso.analytics && window.bluemoso.analytics.track) {
        window.bluemoso.analytics.track(eventName, params);
      }
    } catch (e) {
      if (window.console && console.warn) {
        console.warn('[bluemoso/analytics] track failed:', eventName, e);
      }
    }
  };

  const startPlaybook = () => {
    setStarted(true);
    setHighestPhase(h => Math.max(h, 1));
    scrollToPhase(1);
    safeTrack('playbook_started', {
      resumed_from_phase: highestPhase > 1 ? highestPhase : null,
    });
  };

  // Fires after a phase is completed (user pressed Continue on phase N).
  // Wraps reveal(N+1) so every phase advancement is tracked uniformly.
  // IMPORTANT: reveal() runs BEFORE analytics so even a tracking failure
  // can't strand the user on the current phase.
  const completePhase = (n) => {
    reveal(n + 1);
    safeTrack('playbook_phase_completed', { phase: n });
  };

  return (
    <>
      <Nav baseHref="index.html" />
      {started && (
        <PlaybookNav currentPhase={currentPhase} onJump={jumpTo} completed={state.completedPhases} />
      )}
      {!started && <Hero onStart={startPlaybook} />}
      {/* Phases stack vertically. Each one reveals the next when Continue is pressed. */}
      {started && highestPhase >= 1 && (
        <Phase1 state={state} setState={setState} onComplete={() => completePhase(1)} />
      )}
      {started && highestPhase >= 2 && (
        <Phase2 state={state} setState={setState} onComplete={() => completePhase(2)} onBack={() => scrollToPhase(1)} />
      )}
      {started && highestPhase >= 3 && (
        <Phase3 state={state} setState={setState} onComplete={() => completePhase(3)} onBack={() => scrollToPhase(2)} />
      )}
      {started && highestPhase >= 4 && (
        <Phase4 state={state} setState={setState} onBack={() => scrollToPhase(3)} />
      )}
      <Footer baseHref="index.html" />
    </>
  );
}

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