/* UnifiedRouter.jsx — top-level router that stitches the five flows into one
   continuous prototype: onboarding → questionnaire → capture → AI processing →
   tier result → tier pathway. Owns persona/tier selection (demo sheet + URL
   deep-links), reset, and clean-URL-on-completion.
   Exports window.MunaUnified = { UnifiedApp, DeepLinkRegistry }. */

const { Splash, ValueProp, SignUp, SignIn, Done, Stage: UStage } = window.MunaFlow;
const { Questionnaire } = window.MunaQuestionnaire;
const { CaptureFlow } = window.MunaCapture;
const { HealthyApp } = window.MunaHealthyApp;
const { ModerateApp } = window.MunaModerateApp;
const { HighApp } = window.MunaHighApp;
const { PERSONAS, TIER_TO_PERSONA, PERSONA_ANSWERS, personaByTier, randomPersona, PersonaSheet } = window.MunaPersonas;

const APP_BY_TIER = { healthy: HealthyApp, moderate: ModerateApp, high: HighApp };

// ── Deep-link registry: screen-id → pathway init (per persona) ──────────
//   stage 'pathway' entries carry { route, tab?, clinicStep?, prescribed? }.
const PATHWAY_SCREENS = {
  // shared
  result:     { route: 'result' },
  nextstep:   { route: 'nextstep' },
  dashboard:  { route: 'app', tab: 'home' },
  care:       { route: 'app', tab: 'care' },
  profile:    { route: 'app', tab: 'profile' },
  // healthy
  challenges: { route: 'app', tab: 'challenges' },
  booking:    { route: 'booking' },
  // moderate
  learn:      { route: 'app', tab: 'learn' },
  reversal:   { route: 'reversal' },
  // high
  'video-consult':        { route: 'consult' },
  prescription:           { route: 'rx' },
  summary:                { route: 'summary', prescribed: true },
  'clinic-booking-step-1':{ route: 'clinic', clinicStep: 0 },
  'clinic-booking-step-2':{ route: 'clinic', clinicStep: 1 },
  'clinic-booking-step-3':{ route: 'clinic', clinicStep: 2 },
  'clinic-booking-step-4':{ route: 'clinic', clinicStep: 3 },
};
const SECTION_NUM_TO_ID = { 1: 'personal', 2: 'general', 3: 'oral', 4: 'diabetes', 5: 'cardio', 6: 'lifestyle', 7: 'mental', 8: 'family', 9: 'women', 10: 'optional' };

// Human-readable registry for the dev "Deep links" card.
const DeepLinkRegistry = [
  { group: 'Demo', links: ['#demo=chioma', '#demo=bisola', '#demo=fatima', '#demo=random', '#reset'] },
  { group: 'Chioma · healthy', links: ['chioma/result', 'chioma/nextstep', 'chioma/dashboard', 'chioma/challenges', 'chioma/care', 'chioma/profile', 'chioma/booking'] },
  { group: 'Bisola · moderate', links: ['bisola/result', 'bisola/dashboard', 'bisola/reversal', 'bisola/learn', 'bisola/care', 'bisola/profile', 'bisola/booking'] },
  { group: 'Fatima · high-risk', links: ['fatima/result', 'fatima/dashboard', 'fatima/care', 'fatima/profile', 'fatima/video-consult', 'fatima/prescription', 'fatima/clinic-booking-step-3', 'fatima/summary'] },
  { group: 'Flow stages', links: ['questionnaire/section-3', 'questionnaire/section-6', 'capture/photo-3'] },
];

// Navigate to a registry deep link by writing the hash and reloading so the app
// re-resolves from scratch. Bare entries (e.g. 'chioma/result') are screen
// paths; entries that already start with '#' (e.g. '#demo=chioma', '#reset') are
// full hashes. dev=true is preserved so the links panel stays reachable.
function navToDeepLink(link) {
  let hash = link.startsWith('#') ? link : '#screen=' + link;
  if (!/[?&]dev=|#dev=/.test(hash)) hash += '&dev=true';
  window.location.hash = hash;
  window.location.reload();
}

function parseHash() {
  const raw = (window.location.hash || '').replace(/^#/, '');
  if (!raw) return {};
  const out = {};
  raw.split('&').forEach(part => {
    const [k, v] = part.split('=');
    if (v === undefined) out[k] = true; else out[k] = decodeURIComponent(v);
  });
  return out;
}

// Resolve initial state from the URL hash.
function resolveInitial() {
  const h = parseHash();
  if (h.reset !== undefined) return { stage: 'onboarding', tier: null, dev: !!h.dev };
  const dev = h.dev !== undefined && h.dev !== 'false';

  if (h.screen) {
    const [who, screenId] = String(h.screen).split('/');
    // questionnaire / capture stage deep-links (persona-agnostic)
    if (who === 'questionnaire') {
      const m = /section-(\d+)/.exec(screenId || '');
      const sectionId = m ? SECTION_NUM_TO_ID[Number(m[1])] : screenId;
      return { stage: 'questionnaire', tier: null, dev, startSectionId: sectionId };
    }
    if (who === 'capture') {
      const m = /photo-(\d+)/.exec(screenId || '');
      const n = m ? Math.max(1, Math.min(4, Number(m[1]))) : 1;
      return { stage: 'capture', tier: null, dev, initHist: ['intro', 'cap-' + (n - 1)] };
    }
    // pathway deep-links
    const persona = PERSONAS[who];
    const screen = PATHWAY_SCREENS[screenId];
    if (persona && screen) {
      return { stage: 'pathway', tier: persona.tier, dev, pathwayInit: screen };
    }
  }
  if (h.demo) {
    const d = String(h.demo);
    const persona = d === 'random' ? randomPersona() : PERSONAS[d];
    if (persona) return { stage: 'onboarding', tier: persona.tier, dev, fromDemoHash: true };
  }
  return { stage: 'onboarding', tier: null, dev };
}

// ── Onboarding sub-flow (splash → value props → sign up/in → you're all set) ──
function Onboarding({ onComplete, onLongPressMark }) {
  const [key, setKey] = React.useState('splash');
  const [dir, setDir] = React.useState(1);
  const ORD = { splash: 0, v0: 1, v1: 2, v2: 3, signup: 4, signin: 5, done: 6 };
  const go = (n) => { setDir(ORD[n] >= ORD[key] ? 1 : -1); setKey(n); };
  const render = (k) => {
    if (k === 'splash') return <Splash onContinue={() => go('v0')} grain auto={false} onLongPressMark={onLongPressMark}/>;
    if (k === 'v0') return <ValueProp index={0} heroStyle="photo" grain onNext={() => go('v1')} onSkip={() => go('signup')}/>;
    if (k === 'v1') return <ValueProp index={1} heroStyle="photo" grain onNext={() => go('v2')} onBack={() => go('v0')} onSkip={() => go('signup')}/>;
    if (k === 'v2') return <ValueProp index={2} heroStyle="photo" grain onNext={() => go('signup')} onBack={() => go('v1')} onSkip={() => go('signup')}/>;
    if (k === 'signup') return <SignUp onBack={() => go('v2')} onSwitch={() => go('signin')} onDone={() => go('done')}/>;
    if (k === 'signin') return <SignIn onBack={() => go('signup')} onSwitch={() => go('signup')} onDone={() => go('done')}/>;
    if (k === 'done') return <Done onRestart={onComplete}/>;
    return null;
  };
  return <UStage activeKey={key} direction={dir} render={render}/>;
}

function seedAnswers(tier) {
  if (!tier) return {};
  const p = personaByTier(tier);
  return p ? { ...(PERSONA_ANSWERS[p.id] || {}) } : {};
}

function UnifiedApp() {
  const initial = React.useRef(resolveInitial()).current;
  const [stage, setStage] = React.useState(initial.stage);
  const [dir, setDir] = React.useState(1);
  const [tier, setTier] = React.useState(initial.tier);
  const [answers, setAnswers] = React.useState(() => seedAnswers(initial.tier));
  const [pathwayInit, setPathwayInit] = React.useState(initial.pathwayInit || null);
  const [sheetOpen, setSheetOpen] = React.useState(false);
  const [showJumpExtras, setShowJumpExtras] = React.useState(false); // sheet opened from the inner-page jump button
  const [pathwayNonce, setPathwayNonce] = React.useState(0);          // forces the pathway app to remount on a same-tier jump
  const [dev] = React.useState(!!initial.dev);
  const [showLinks, setShowLinks] = React.useState(false);
  const pendingAfterPick = React.useRef(null);
  const STAGE_ORD = { onboarding: 0, questionnaire: 1, capture: 2, pathway: 3 };

  const goStage = (s) => { setDir(STAGE_ORD[s] >= STAGE_ORD[stage] ? 1 : -1); setStage(s); };

  // clean URL once a pathway result is reached (shareable final state)
  React.useEffect(() => {
    if (stage === 'pathway' && tier) {
      const pid = TIER_TO_PERSONA[tier];
      const screenId = pathwayInit && Object.keys(PATHWAY_SCREENS).find(k => PATHWAY_SCREENS[k] === pathwayInit) || 'result';
      history.replaceState(null, '', '#screen=' + pid + '/' + screenId + (dev ? '&dev=true' : ''));
    }
  }, [stage, tier]);

  const choosePersona = (id) => {
    const p = PERSONAS[id];
    setTier(p.tier);
    setAnswers(a => ({ ...(PERSONA_ANSWERS[p.id] || {}), ...a }));
    setSheetOpen(false);
    setShowJumpExtras(false);
    const after = pendingAfterPick.current;
    pendingAfterPick.current = null;
    if (after) after(p.tier);
  };
  const chooseRandom = () => choosePersona(randomPersona().id);

  // Inner-page demo jump: open the persona sheet from any dashboard. Picking a
  // persona lands on that flow's dashboard; "Back to the questionnaire" returns.
  const openJumpSheet = () => {
    pendingAfterPick.current = () => { setPathwayInit(PATHWAY_SCREENS.dashboard); setPathwayNonce(n => n + 1); goStage('pathway'); };
    setShowJumpExtras(true);
    setSheetOpen(true);
  };
  const goToQuestionnaire = () => {
    pendingAfterPick.current = null;
    setShowJumpExtras(false);
    setSheetOpen(false);
    goStage('questionnaire');
  };

  // request a tier before proceeding (used at AI processing / first dev-skip)
  const requireTier = (proceed) => {
    if (tier) { proceed(tier); return; }
    pendingAfterPick.current = proceed;
    setSheetOpen(true);
  };

  const restart = () => {
    history.replaceState(null, '', window.location.pathname + window.location.search);
    setTier(null); setAnswers({}); setPathwayInit(null); setSheetOpen(false);
    setDir(-1); setStage('onboarding');
  };

  // capture complete → AI processing already shown inside; gate on tier then enter pathway
  const afterCapture = () => requireTier((t) => { setPathwayInit({ route: 'result' }); goStage('pathway'); });

  const render = (s) => {
    if (s === 'onboarding') return <Onboarding onComplete={() => goStage('questionnaire')} onLongPressMark={() => setSheetOpen(true)}/>;
    if (s === 'questionnaire') return <Questionnaire answers={answers} setAnswers={setAnswers} startSectionId={initial.startSectionId}
      onDevSkip={() => {
        // DEV · skip → always open the persona sheet; picking a persona jumps straight to their outcome.
        pendingAfterPick.current = () => { setPathwayInit({ route: 'result' }); goStage('pathway'); };
        setSheetOpen(true);
      }}
      onComplete={() => goStage('capture')} onExit={() => goStage('onboarding')}/>;
    if (s === 'capture') return <CaptureFlow initHist={initial.initHist} onComplete={afterCapture} onBack={() => goStage('questionnaire')}/>;
    if (s === 'pathway') {
      const App = APP_BY_TIER[tier] || HealthyApp;
      return <App key={tier + ':' + pathwayNonce} init={pathwayInit || { route: 'result' }}/>;
    }
    return null;
  };

  return (
    <React.Fragment>
      <UStage activeKey={stage} direction={dir} render={render}/>

      {/* Restart affordance — invisible long-press strip over the status bar */}
      <RestartStrip onRestart={restart}/>

      {/* Inner-page demo jump button — appears on every tier dashboard/care/profile/etc. */}
      {stage === 'pathway' && <JumpButton onClick={openJumpSheet}/>}

      {/* Demo persona sheet */}
      <PersonaSheet open={sheetOpen} onPick={choosePersona} onRandom={chooseRandom}
        onClose={() => { pendingAfterPick.current = null; setShowJumpExtras(false); setSheetOpen(false); }}
        onQuestionnaire={showJumpExtras ? goToQuestionnaire : null}/>

      {/* Dev-only deep-links reference card */}
      {dev && <DeepLinksButton open={showLinks} onToggle={() => setShowLinks(v => !v)}/>}
    </React.Fragment>
  );
}

// Long-press the top status-bar area to restart the demo.
function RestartStrip({ onRestart }) {
  const timer = React.useRef(null);
  const start = () => { timer.current = setTimeout(onRestart, 650); };
  const end = () => { if (timer.current) clearTimeout(timer.current); timer.current = null; };
  return (
    <div onPointerDown={start} onPointerUp={end} onPointerLeave={end}
      title="Long-press to restart demo"
      style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 40, zIndex: 70 }}/>
  );
}

// Inner-page demo jump — right-edge tab that opens the persona sheet so a demo
// viewer can hop between flows (or back to the questionnaire) from any page.
function JumpButton({ onClick }) {
  // Collapsed icon-only nub tucked on the right edge — minimal footprint.
  // Tapping it opens the demo sheet (persona jump / back to questionnaire).
  return (
    <button onClick={onClick} aria-label="Demo — jump to another flow" title="Demo — jump to another flow" style={{
      position: 'absolute', right: 0, top: '50%', transform: 'translateY(-50%)', zIndex: 55, cursor: 'pointer',
      background: 'var(--stone-800)', color: '#fff', border: 0,
      borderRadius: 'var(--radius-pill) 0 0 var(--radius-pill)',
      width: 30, height: 38, display: 'flex', alignItems: 'center', justifyContent: 'center',
      paddingLeft: 2, boxShadow: 'var(--shadow-m)', opacity: 0.9,
    }}>
      <Icon name="shuffle" size={15}/>
    </button>
  );
}

// Dev deep-links reference card (only when #dev=true).
function DeepLinksButton({ open, onToggle }) {
  return (
    <React.Fragment>
      <button onClick={onToggle} style={{
        position: 'absolute', bottom: 14, right: 14, zIndex: 71, cursor: 'pointer',
        background: 'var(--stone-800)', color: '#fff', border: 0, borderRadius: 'var(--radius-pill)',
        padding: '8px 14px', font: 'var(--type-overline)', letterSpacing: 'var(--tracking-loose)', textTransform: 'uppercase',
        boxShadow: 'var(--shadow-m)',
      }}>Dev · links</button>
      {open && (
        <div onClick={onToggle} style={{ position: 'absolute', inset: 0, zIndex: 72, background: 'var(--bg-overlay)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
          <div onClick={e => e.stopPropagation()} style={{ background: '#fff', borderRadius: 'var(--radius-l)', padding: 20, maxHeight: '80%', overflowY: 'auto', boxShadow: 'var(--shadow-l)', width: '100%' }}>
            <div style={{ font: 'var(--type-h2)', color: 'var(--fg-1)', marginBottom: 4 }}>Deep links</div>
            <p style={{ font: 'var(--type-body-s)', color: 'var(--fg-3)', marginBottom: 16 }}>Tap any link to jump straight there — the page reloads into that screen.</p>
            {DeepLinkRegistry.map(g => (
              <div key={g.group} style={{ marginBottom: 14 }}>
                <div className="overline" style={{ color: 'var(--amber-600)', marginBottom: 6 }}>{g.group}</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {g.links.map(l => (
                    <button key={l} onClick={() => navToDeepLink(l)} style={{
                      font: '12px/1.4 var(--font-mono)', color: 'var(--amber-700)', background: 'var(--stone-100)',
                      padding: '4px 9px', borderRadius: 'var(--radius-s)', border: '1px solid var(--border-subtle)', cursor: 'pointer',
                    }}>{l}</button>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </React.Fragment>
  );
}

window.MunaUnified = { UnifiedApp, DeepLinkRegistry };
