/* global React, ReactDOM, IOSDevice, TweaksPanel, useTweaks, TweakSection, TweakColor, TweakRadio, TweakToggle,
   paosTokens, Header,
   Step1Welcome, Step2QuickInfo, VoiceStep, Step7WrapUp, Step8Booked,
   PAOS, resolveQuestions */
const { useState, useMemo } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "primary": "#294669",
  "surface": "warm",
  "showFrame": true
}/*EDITMODE-END*/;

const STEP_NAMES = ['Welcome', 'Basics', 'Story', 'Audience', 'Goals', 'Brand', 'Wrap-up'];
const VOICE_STEP_CONFIGS = { 2: 'STEP3', 3: 'STEP4', 4: 'STEP5', 5: 'STEP6' };
const isVoiceStep = (s) => s >= 2 && s <= 5;

// ─────────────────────────────────────────────────────────────
// Submit — bundle answers + audio blobs → POST /api/submit
// ─────────────────────────────────────────────────────────────
async function submitOnboarding({ clientId, step2Data, voiceAnswers }) {
  const fd = new FormData();
  const answers = {};

  Object.keys(voiceAnswers || {}).forEach((qid) => {
    const v = voiceAnswers[qid];
    if (!v) return;
    const entry = {};
    if (v.text) entry.text = v.text;
    if (v.scale != null) entry.scale = v.scale;
    if (v.ready != null) entry.ready = v.ready;
    if (v.audio && v.audio.blob) {
      const ext = window.extForMime ? window.extForMime(v.audio.mimeType) : 'webm';
      entry.audio = { duration: Math.round(v.audio.duration || 0), mime: v.audio.mimeType };
      fd.append(`audio_${qid}`, v.audio.blob, `${qid}.${ext}`);
    }
    answers[qid] = entry;
  });

  const payload = {
    clientId: clientId || null,
    submittedAt: new Date().toISOString(),
    step2: step2Data,
    answers,
  };
  fd.append('payload', JSON.stringify(payload));

  const res = await fetch('/api/submit', { method: 'POST', body: fd });
  if (!res.ok) {
    let msg = 'Submit failed. Please try again.';
    try { const j = await res.json(); if (j && j.error) msg = j.error; } catch (e) {}
    throw new Error(msg);
  }
  return res.json().catch(() => ({}));
}

function PaosApp() {
  const [tw, setTw] = useTweaks(TWEAK_DEFAULTS);

  // client id from the personalized link  ?c=<clientId>
  const clientId = useMemo(() => {
    try { return new URLSearchParams(window.location.search).get('c'); } catch (e) { return null; }
  }, []);

  // ── State ────────────────────────────────────────────
  const [step, setStep] = useState(0);
  const [subStep, setSubStep] = useState(0);
  const [done, setDone] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);

  const [step2Data, setStep2Data] = useState({
    name: '', email: '', phone: '', location: '',
    languages: [], tenure: '', companyDesc: '',
    revenueNow: '', revenueTarget: '', revenueConsistency: '',
    marketingOwner: '', teamSize: '',
    paidAds: '', adSpend: '',
    salesFunnel: '', caseStudies: '', caseStudiesDetail: '',
    platforms: [], formats: [], perception: [],
  });
  const [voiceAnswers, setVoiceAnswers] = useState({});

  const t = paosTokens(tw.primary, tw.surface);
  const TOTAL = 7;

  // ── Navigation ───────────────────────────────────────
  const goToStep = (s, subAtEnd = false) => {
    setStep(s);
    if (subAtEnd && isVoiceStep(s)) {
      const cfg = PAOS[VOICE_STEP_CONFIGS[s]];
      const visible = resolveQuestions(cfg.questions, step2Data);
      setSubStep(Math.max(0, visible.length - 1));
    } else {
      setSubStep(0);
    }
  };

  const next = () => {
    if (step < TOTAL - 1) goToStep(step + 1);
  };

  const back = () => {
    if (done) { setDone(false); return; }
    if (isVoiceStep(step) && subStep > 0) {
      setSubStep(subStep - 1);
      return;
    }
    if (step > 0) goToStep(step - 1, true);
  };

  // Final submit — POST everything, then show the booked screen
  const finish = async () => {
    if (submitting) return;
    setSubmitError(null);
    setSubmitting(true);
    try {
      await submitOnboarding({ clientId, step2Data, voiceAnswers });
      setSubmitting(false);
      setDone(true);
    } catch (err) {
      setSubmitting(false);
      setSubmitError(err && err.message ? err.message : 'Something went wrong. Please try again.');
    }
  };

  const reset = () => {
    setDone(false); setStep(0); setSubStep(0);
    setSubmitting(false); setSubmitError(null);
    setStep2Data({
      name: '', email: '', phone: '', location: '',
      languages: [], tenure: '', companyDesc: '',
      revenueNow: '', revenueTarget: '', revenueConsistency: '',
      marketingOwner: '', teamSize: '',
      paidAds: '', adSpend: '',
      salesFunnel: '', caseStudies: '', caseStudiesDetail: '',
      platforms: [], formats: [], perception: [],
    });
    setVoiceAnswers({});
  };

  // ── Screen body ──────────────────────────────────────
  const renderStep = () => {
    if (step === 0) return <Step1Welcome t={t} onNext={next} />;
    if (step === 1) return <Step2QuickInfo t={t} onNext={next} data={step2Data} setData={setStep2Data} />;
    if (isVoiceStep(step)) {
      const cfg = PAOS[VOICE_STEP_CONFIGS[step]];
      return (
        <VoiceStep
          stepConfig={cfg}
          subStep={subStep} setSubStep={setSubStep}
          t={t} onNext={next}
          answers={voiceAnswers} setAnswers={setVoiceAnswers}
          step2Data={step2Data}
        />
      );
    }
    if (step === 6) return (
      <Step7WrapUp
        t={t} onFinish={finish}
        step2Data={step2Data} voiceAnswers={voiceAnswers}
        submitting={submitting} error={submitError}
      />
    );
    return null;
  };

  const screenLabel = done
    ? '08 Booked'
    : `0${step + 1} ${STEP_NAMES[step]}` + (isVoiceStep(step) ? ` · Q${subStep + 1}` : '');

  const screen = (
    <div
      style={{
        width: '100%', height: '100%', background: t.bg,
        display: 'flex', flexDirection: 'column',
        fontFamily: 'Geist, system-ui, sans-serif', color: t.ink,
        position: 'relative', overflow: 'hidden',
      }}
      data-screen-label={screenLabel}
    >
      {!done && (
        <Header
          step={step} total={TOTAL} t={t}
          onBack={back} canBack={step > 0 || (isVoiceStep(step) && subStep > 0)}
          stepName={STEP_NAMES[step]}
        />
      )}
      <div style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden', display: 'flex', flexDirection: 'column' }}>
        {done ? (
          <Step8Booked t={t} name={(step2Data.name || '').split(' ')[0]} onReset={reset} />
        ) : (
          <div
            key={`${step}-${subStep}`}
            style={{ animation: 'fadeUp 340ms ease both', minHeight: '100%', display: 'flex', flexDirection: 'column' }}
          >
            {renderStep()}
          </div>
        )}
      </div>
    </div>
  );

  return (
    <div style={{
      minHeight: '100vh', width: '100%',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: '#E9E4DA',
      padding: 32, boxSizing: 'border-box',
      backgroundImage: 'radial-gradient(circle at 30% 20%, #F0EAE0 0%, #E5DFD3 60%, #DCD5C8 100%)',
    }}>
      {tw.showFrame ? (
        <IOSDevice width={390} height={844}>{screen}</IOSDevice>
      ) : (
        <div style={{
          width: 390, height: 844, borderRadius: 32, overflow: 'hidden',
          boxShadow: '0 30px 60px rgba(0,0,0,0.18)',
        }}>{screen}</div>
      )}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Brand">
          <TweakColor
            label="Primary"
            value={tw.primary}
            options={['#294669', '#1F3A5F', '#2F5D3B', '#7A3B2E', '#1A1A1A']}
            onChange={(v) => setTw('primary', v)}
          />
          <TweakRadio
            label="Background"
            value={tw.surface}
            options={[{ value: 'warm', label: 'Warm' }, { value: 'cool', label: 'Cool' }]}
            onChange={(v) => setTw('surface', v)}
          />
        </TweakSection>
        <TweakSection label="Display">
          <TweakToggle
            label="Show device frame"
            value={tw.showFrame}
            onChange={(v) => setTw('showFrame', v)}
          />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

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