/* Main App — splash → onboarding → crisis → coaching + demo guide. */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "sarthiPalette": ["#FF8A3D", "#FC8019", "#E8731A"],
  "mood": "warm",
  "presence": "balanced"
}/*EDITMODE-END*/;

const SARTHI_PALETTES = [
  ['#FF8A3D', '#FC8019', '#E8731A'],
  ['#8B5CF6', '#EC4899', '#6D28D9'],
  ['#F97316', '#FBBF24', '#C2410C'],
  ['#10B981', '#06B6D4', '#047857'],
  ['#4F46E5', '#D946EF', '#3730A3'],
  ['#0EA5E9', '#A78BFA', '#1E3A8A'],
];

function TweakStyles({ palette, mood, presence }) {
  const [from, to, deep] = palette;
  _ue(() => {
    document.body.dataset.mood = mood;
    document.body.dataset.presence = presence;
  }, [mood, presence]);

  return (
    <style>{`
      :root { --s-from: ${from}; --s-to: ${to}; --s-deep: ${deep}; }
      .orb-grad {
        background-image: linear-gradient(135deg, var(--s-from) 0%,
          color-mix(in srgb, var(--s-from), var(--s-to)) 50%, var(--s-to) 100%) !important;
      }
      .shadow-orb {
        box-shadow: 0 12px 32px -8px color-mix(in srgb, var(--s-from) 60%, transparent),
          0 6px 16px -6px color-mix(in srgb, var(--s-to) 45%, transparent) !important;
      }
      .bg-sarthi-50  { background-color: color-mix(in srgb, var(--s-from) 6%, #FFF) !important; }
      .bg-sarthi-100 { background-color: color-mix(in srgb, var(--s-from) 14%, #FFF) !important; }
      .border-sarthi-100 { border-color: color-mix(in srgb, var(--s-from) 22%, #FFF) !important; }
      .text-sarthi-deep { color: var(--s-deep) !important; }
      .text-sarthi-from { color: var(--s-from) !important; }
      @keyframes orbPulse {
        0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--s-from) 55%, transparent); }
        70% { box-shadow: 0 0 0 18px transparent; }
        100% { box-shadow: 0 0 0 0 transparent; }
      }
      .orb-pulse { animation: orbPulse 2.2s ease-out infinite; }
      .orb-pulse-lg { animation: orbPulse 1.6s ease-out infinite; }
      body[data-mood="warm"] .phone-host {
        background: radial-gradient(1200px 600px at 15% 0%, rgba(252,128,25,0.08) 0%, transparent 60%),
          linear-gradient(180deg, #F8FAFC 0%, #EEF2F7 100%) !important;
      }
      :root { --fab-size: 64px; --fab-icon: 26px; }
      .sarthi-fab { width: var(--fab-size); height: var(--fab-size); }
      .sarthi-fab .sarthi-fab-icon svg { width: var(--fab-icon); height: var(--fab-icon); }
    `}</style>
  );
}

const DEV_MODE = typeof window !== 'undefined' && (
  new URLSearchParams(window.location.search).get('dev') === '1' ||
  window.localStorage?.getItem('sarthi_dev') === '1'
);

const INITIAL_B2 = { status: 'idle', words: [], wordCount: 0, thinking: false, barLevels: [] };
const MIN_HOLD_MS = 550;
/** Screens that start TTS on mount — parent must not cancel them. */
const VOICE_AUTO_SCREENS = new Set(['SPLASH', 'A1', 'A2', 'A3', 'A4', 'A5', 'B3', 'C2']);

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [screen, setScreen] = _us('SPLASH');
  const [toast, setToast] = _us(null);
  const [crossSell, setCrossSell] = _us(false);
  const [showFabLabel, setShowFabLabel] = _us(true);
  const [scenarioIdx, setScenarioIdx] = _us(0);
  const [scenarioResults, setScenarioResults] = _us([]);
  const [orderState, setOrderState] = _us('picked');
  const [sarthiHolding, setSarthiHolding] = _us(false);
  const [b2, setB2] = _us(INITIAL_B2);
  const [guideDismissed, setGuideDismissed] = _us({});
  const [b3Guide, setB3Guide] = _us(false);
  const [voicePhase, setVoicePhase] = _us('idle');
  const [splashIntroDone, setSplashIntroDone] = _us(false);

  const b2RecordingRef = React.useRef(false);
  const b2RafRef = React.useRef(null);
  const holdStartMsRef = React.useRef(0);
  const finishingB2Ref = React.useRef(false);

  const showGuide = (key) => GUIDE_STEPS[key] && GUIDE_STEPS[key].title && !guideDismissed[key];

  const dismissGuide = (key) => {
    setGuideDismissed((d) => ({ ...d, [key]: true }));
  };

  _ue(() => Voice.subscribe(({ phase }) => setVoicePhase(phase)), []);

  _ue(() => {
    window.__toast = (text, sub, tone) => {
      setToast({ text, sub, tone });
      clearTimeout(window.__toastTimer);
      window.__toastTimer = setTimeout(() => setToast(null), 2400);
    };
    return () => { window.__toast = () => {}; };
  }, []);

  _ue(() => {
    if (!VOICE_AUTO_SCREENS.has(screen)) Voice.stopSpeaking();
    if (screen === 'B1' || screen === 'B2') Voice.preload([DEMO.B3_SPEECH]);
    if (screen === 'C1' || screen === 'C2') Voice.preload([DEMO.C2_COACHING]);
    if (screen === 'A3') {
      const sc = SCENARIO_TTS[scenarioIdx];
      Voice.preload([sc?.question, sc?.explainRight, sc?.explainWrong].filter(Boolean));
    }
  }, [screen, scenarioIdx]);

  _ue(() => {
    const unlock = () => Voice.unlockAudio();
    document.addEventListener('pointerdown', unlock, { once: true, passive: true });
    return () => document.removeEventListener('pointerdown', unlock);
  }, []);

  const animateWords = (words, onComplete) => {
    setB2((s) => ({ ...s, status: 'transcript', words, wordCount: 0, thinking: false }));
    let i = 0;
    const tick = () => {
      i += 1;
      setB2((s) => ({ ...s, wordCount: i }));
      if (i < words.length) setTimeout(tick, 150);
      else {
        setTimeout(() => {
          setB2((s) => ({ ...s, thinking: true }));
          setTimeout(() => {
            finishingB2Ref.current = false;
            onComplete();
          }, 1100);
        }, 350);
      }
    };
    tick();
  };

  const goToB3 = () => {
    Voice.preload([DEMO.B3_SPEECH]);
    setB2(INITIAL_B2);
    setSarthiHolding(false);
    setB3Guide(true);
    setScreen('B3');
  };

  const runB2Fallback = () => {
    animateWords(DEMO.B2_FALLBACK_WORDS, goToB3);
  };

  const finishB2Hold = async () => {
    if (finishingB2Ref.current) return;
    finishingB2Ref.current = true;

    setSarthiHolding(false);
    if (b2RafRef.current) cancelAnimationFrame(b2RafRef.current);

    const heldMs = Date.now() - holdStartMsRef.current;
    if (heldMs < MIN_HOLD_MS) {
      finishingB2Ref.current = false;
      window.__toast?.('Button dabaye rakho', 'Hold while you speak the demo line', 'sarthi');
      cancelB2();
      return;
    }

    if (!b2RecordingRef.current) {
      runB2Fallback();
      return;
    }

    b2RecordingRef.current = false;
    setB2((s) => ({ ...s, status: 'processing', barLevels: [] }));

    try {
      const { blob, mimeType } = await Voice.stopListening();
      let words = DEMO.B2_FALLBACK_WORDS;
      try {
        const { transcript, fallback } = await Voice.transcribe(blob, mimeType);
        if (transcript && !fallback) {
          words = Voice.splitWords(transcript);
          if (words.length < 2) words = DEMO.B2_FALLBACK_WORDS;
        }
      } catch { /* fallback */ }
      animateWords(words, goToB3);
    } catch {
      runB2Fallback();
    }
  };

  const handleSarthiHoldStart = async (e) => {
    e?.preventDefault?.();
    dismissGuide('B1');
    setShowFabLabel(false);
    setSarthiHolding(true);
    holdStartMsRef.current = Date.now();
    finishingB2Ref.current = false;
    setScreen('B2');
    setB2({ status: 'recording', words: [], wordCount: 0, thinking: false, barLevels: [] });

    const onUp = () => {
      window.removeEventListener('pointerup', onUp);
      window.removeEventListener('pointercancel', onUp);
      finishB2Hold();
    };
    window.addEventListener('pointerup', onUp, { once: true });
    window.addEventListener('pointercancel', onUp, { once: true });

    const tickBars = () => {
      setB2((s) => (s.status === 'recording' || s.status === 'processing')
        ? { ...s, barLevels: Voice.getAnalyserLevels(7) }
        : s);
      b2RafRef.current = requestAnimationFrame(tickBars);
    };
    b2RafRef.current = requestAnimationFrame(tickBars);

    try {
      await Voice.startListening();
      b2RecordingRef.current = true;
    } catch {
      b2RecordingRef.current = false;
    }
  };

  const cancelB2 = () => {
    finishingB2Ref.current = false;
    setSarthiHolding(false);
    if (b2RafRef.current) cancelAnimationFrame(b2RafRef.current);
    Voice.cancelListening();
    b2RecordingRef.current = false;
    setB2(INITIAL_B2);
    setScreen('B1');
  };

  const goto = (s) => {
    Voice.stopSpeaking();
    setToast(null);
    setCrossSell(false);
    setSarthiHolding(false);
    setB2(INITIAL_B2);
    finishingB2Ref.current = false;
    if (s === 'SPLASH') setSplashIntroDone(false);
    setScreen(s);
    if (s === 'A3') { setScenarioIdx(0); setScenarioResults([]); }
    if (s === 'B1') setOrderState('picked');
    if (s === 'B1' || s === 'C1') setShowFabLabel(true);
  };

  const next = () => {
    Voice.stopSpeaking();
    const flow = {
      SPLASH: 'A1',
      A1: 'A2', A2: 'A3', A3: 'A4', A4: 'A5', A5: 'B1',
      B1: 'B1', B2: 'B3', B3: 'B1',
      C1: 'C2', C2: 'C1',
    };
    setScreen(flow[screen] || 'A1');
  };

  const startFromSplash = () => {
    Voice.unlockAudio();
    setGuideDismissed((d) => ({ ...d, SPLASH: true }));
    setScreen('A1');
  };

  const dismissB3 = () => {
    Voice.stopSpeaking();
    setB3Guide(false);
    setScreen('B1');
    window.__toast('Sarthi handle kar raha hai', 'Sarthi is handling it for you', 'sarthi');
  };

  const onScenarioAnswered = (r) => setScenarioResults([...scenarioResults, r]);
  const onScenarioNext = () => {
    if (scenarioIdx < 2) setScenarioIdx(scenarioIdx + 1);
    else next();
  };

  const isB = screen.startsWith('B');
  const isC = screen.startsWith('C');
  const isFlowScreen = screen !== 'SPLASH';

  const activeGuideScreen = (() => {
    if (screen === 'SPLASH' && splashIntroDone && !guideDismissed.SPLASH) return 'SPLASH';
    if (screen === 'A1' && showGuide('A1')) return 'A1';
    if (screen === 'A3' && showGuide('A3')) return 'A3';
    if (screen === 'B1' && showGuide('B1')) return 'B1';
    if (screen === 'B3' && b3Guide && showGuide('B3')) return 'B3';
    if (screen === 'C1' && showGuide('C1')) return 'C1';
    return null;
  })();

  return (
    <>
      <TweakStyles palette={t.sarthiPalette} mood={t.mood} presence={t.presence}/>

      <AppLayout
        screen={screen}
        side={isFlowScreen ? <StoryboardPanel screen={screen} scenarioIdx={scenarioIdx}/> : null}
        mobileStory={isFlowScreen ? <StoryboardMobileStrip screen={screen} scenarioIdx={scenarioIdx}/> : null}
      >
        <PhoneFrame>
          {screen === 'SPLASH' && (
            <ScreenSplash
              onStart={startFromSplash}
              onIntroComplete={() => setSplashIntroDone(true)}
            />
          )}

          {screen === 'A1' && <ScreenA1 next={() => { dismissGuide('A1'); next(); }}/>}
          {screen === 'A2' && <ScreenA2 next={next}/>}
          {screen === 'A3' && (
            <ScreenA3 idx={scenarioIdx} results={scenarioResults}
                     onAnswer={onScenarioAnswered} onNext={onScenarioNext}/>
          )}
          {screen === 'A4' && <ScreenA4 next={next} results={scenarioResults}/>}
          {screen === 'A5' && <ScreenA5 next={next}/>}

          {isB && (
            <ScreenB1
              onSarthiHoldStart={handleSarthiHoldStart}
              showFabLabel={showFabLabel && screen === 'B1'}
              holding={sarthiHolding}
              orderState={orderState}
              setOrderState={setOrderState}
              guideFab={showGuide('B1')}
            />
          )}
          {screen === 'B2' && <ScreenB2Overlay b2={b2} onCancel={cancelB2}/>}
          {screen === 'B3' && (
            <ScreenB3Sheet
              onDismiss={dismissB3}
              onGuideDone={() => dismissGuide('B3')}
            />
          )}

          {isC && (
            <>
              <ScreenC1
                onSarthiHoldStart={handleSarthiHoldStart}
                openCoach={() => {
                  Voice.stopSpeaking();
                  Voice.preload([DEMO.C2_COACHING]);
                  if (showGuide('C1')) dismissGuide('C1');
                  setScreen('C2');
                }}
                showFabLabel={screen === 'C1' && showFabLabel}
                holding={sarthiHolding}
              />
              {screen === 'C2' && (
                <ScreenC2Sheet
                  onDismiss={() => setScreen('C1')}
                  onCrossSell={() => {
                    setCrossSell(true);
                    setScreen('C1');
                    setTimeout(() => setCrossSell(false), 2400);
                  }}
                />
              )}
            </>
          )}

          {toast && <Toast text={toast.text} sub={toast.sub} tone={toast.tone}/>}
          {crossSell && (
            <div className="absolute top-14 left-1/2 -translate-x-1/2 z-40 toast-in">
              <div className="bg-ink-900 text-white text-[12px] font-medium px-3 py-2 rounded-full shadow-lift flex items-center gap-2">
                <Bolt size={12} stroke="#FBBF24"/> Coming in Phase 3 — Sarthi Grow
              </div>
            </div>
          )}
        </PhoneFrame>

        {isFlowScreen && <DemoNavigator screen={screen} goto={goto}/>}
      </AppLayout>

      <SarthiVoicePanel phase={voicePhase}/>
      {activeGuideScreen && (
        <DemoCoachLayer
          screen={activeGuideScreen}
          show
          onDismiss={() => dismissGuide(activeGuideScreen)}
          onCta={() => {
            if (activeGuideScreen === 'SPLASH') startFromSplash();
            else dismissGuide(activeGuideScreen);
          }}
        />
      )}

      {DEV_MODE && <TweaksPanel>
        <TweakSection label="Sarthi character"/>
        <TweakColor label="Personality" value={t.sarthiPalette} options={SARTHI_PALETTES}
          onChange={(v) => setTweak('sarthiPalette', v)}/>
      </TweaksPanel>}
    </>
  );
}

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