/* Diagnostic IA dirigeant — App production
 * - Lit le token depuis l'URL (?t=...)
 * - Fetch /api/me au boot pour valider + récupérer firstName/email/alreadyDone
 * - Au submit : POST /api/submit, gère loading/error/success
 * - Pas de Tweaks panel, pas de prefill
 * - Si pas de token : variant "invalid-token"
 * - Si déjà rempli : variant "already-done" → redirige vers /results/:clientId
 * - /results/:clientId : viewer mode (hydraté depuis /api/results)
 */

const { useState, useEffect, useCallback } = React;

function getTokenFromUrl() {
  const params = new URLSearchParams(window.location.search);
  return params.get('t') || params.get('token') || null;
}

function App() {
  const [boot, setBoot] = useState({ status: 'loading', me: null });
  const [answers, setAnswers] = useState({});
  const [feeling, setFeeling] = useState([]);
  const [freeform, setFreeform] = useState('');
  const [step, setStep] = useState('welcome');
  const [submission, setSubmission] = useState({ resultsUrl: null });

  // Boot
  useEffect(() => {
    const path = window.location.pathname;
    const resultsMatch = path.match(/^\/results\/([a-zA-Z0-9_-]+)\/?$/);
    if (resultsMatch) {
      setBoot({ status: 'view-results', clientId: resultsMatch[1] });
      setStep('view-results');
      return;
    }

    const token = getTokenFromUrl();
    if (!token) {
      setBoot({ status: 'invalid', me: null });
      setStep('welcome-invalid');
      return;
    }

    fetch('/api/me?token=' + encodeURIComponent(token))
      .then(r => r.ok ? r.json() : Promise.reject(r.status))
      .then(me => {
        setBoot({ status: 'ok', me, token });
        setStep(me.alreadyDone ? 'welcome-done' : 'welcome');
      })
      .catch(() => {
        setBoot({ status: 'invalid', me: null });
        setStep('welcome-invalid');
      });
  }, []);

  // localStorage : reprise silencieuse sur même navigateur
  useEffect(() => {
    if (boot.status !== 'ok') return;
    const key = 'diag-dirigeant-' + boot.me.clientId;
    try {
      const saved = JSON.parse(localStorage.getItem(key) || '{}');
      if (saved.answers) setAnswers(saved.answers);
      if (saved.feeling) setFeeling(saved.feeling);
      if (saved.freeform) setFreeform(saved.freeform);
    } catch {}
  }, [boot.status]);

  useEffect(() => {
    if (boot.status !== 'ok') return;
    const key = 'diag-dirigeant-' + boot.me.clientId;
    try {
      localStorage.setItem(key, JSON.stringify({ answers, feeling, freeform }));
    } catch {}
  }, [answers, feeling, freeform, boot.status]);

  const handleAnswer = useCallback((qid, val) => {
    setAnswers(prev => ({ ...prev, [qid]: val }));
  }, []);

  const doneChapters = CHAPTERS
    .filter(ch => QUESTIONS.filter(q => q.chapter === ch.id)
      .every(q => answers[q.id] != null && (q.type !== 'multi' || (answers[q.id] || []).length > 0)))
    .map(ch => ch.id);

  // Ordre canonique pour navigation prev/next
  const order = ['welcome'];
  CHAPTERS.forEach(ch => {
    order.push({ kind: 'chapter-intro', chapterId: ch.id });
    QUESTIONS.filter(q => q.chapter === ch.id).forEach(q => order.push({ kind: 'question', qid: q.id }));
  });
  order.push('feeling', 'freeform', 'results');

  const stepKey = (s) => typeof s === 'string' ? s : `${s.kind}:${s.chapterId || s.qid}`;
  const goNext = () => {
    const idx = order.findIndex(s => stepKey(s) === stepKey(step));
    if (idx >= 0 && idx + 1 < order.length) setStep(order[idx + 1]);
  };
  const goPrev = () => {
    const idx = order.findIndex(s => stepKey(s) === stepKey(step));
    if (idx > 0) setStep(order[idx - 1]);
  };

  const submitDiagnostic = useCallback(async () => {
    setStep('loading');
    try {
      const r = await fetch('/api/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          token: boot.token,
          answers, feeling, freeform,
        }),
      });
      if (!r.ok) throw new Error('submit_failed');
      const data = await r.json();
      setSubmission({ resultsUrl: data.resultsUrl });
      try { localStorage.removeItem('diag-dirigeant-' + boot.me.clientId); } catch {}
      setStep('results');
    } catch (err) {
      console.error('Submit error', err);
      setStep('error');
    }
  }, [boot, answers, feeling, freeform]);

  const renderStep = () => {
    if (boot.status === 'loading') {
      return (
        <LoadingScreen
          variant="phrases"
          phrases={["Je vérifie votre lien…", "Un instant…"]}
        />
      );
    }

    if (step === 'welcome-invalid') {
      return <WelcomeScreen variant="invalid-token" />;
    }
    if (step === 'welcome-done') {
      return (
        <WelcomeScreen
          variant="already-done"
          firstName={boot.me?.firstName || 'vous'}
          onStart={() => {
            window.location.href = '/results/' + boot.me.clientId;
          }}
        />
      );
    }
    if (step === 'view-results') {
      return <ResultsViewer clientId={boot.clientId} />;
    }
    if (step === 'welcome') {
      return (
        <WelcomeScreen
          variant="standard"
          firstName={boot.me?.firstName || 'vous'}
          onStart={() => setStep({ kind: 'chapter-intro', chapterId: 'impacts' })}
        />
      );
    }
    if (step === 'loading') {
      return <LoadingScreen variant="phrases" />;
    }
    if (step === 'error') {
      return (
        <ErrorScreen
          onRetry={submitDiagnostic}
          onContinueAnyway={() => setStep('results')}
        />
      );
    }
    if (step === 'feeling') {
      return (
        <FeelingScreen
          answers={answers}
          doneChapters={doneChapters}
          value={feeling}
          onChange={setFeeling}
          onNext={() => setStep('freeform')}
          onBack={goPrev}
          progressStyle="axes"
          layout="editorial"
        />
      );
    }
    if (step === 'freeform') {
      return (
        <FreeformScreen
          answers={answers}
          doneChapters={doneChapters}
          value={freeform}
          onChange={setFreeform}
          onSubmit={submitDiagnostic}
          onBack={goPrev}
          progressStyle="axes"
        />
      );
    }
    if (step === 'results') {
      return (
        <ResultsScreen
          answers={answers}
          feeling={feeling}
          freeform={freeform}
          email={boot.me?.email}
          firstName={boot.me?.firstName}
          clientId={boot.me?.clientId}
        />
      );
    }
    if (step.kind === 'chapter-intro') {
      const chapter = CHAPTERS.find(c => c.id === step.chapterId);
      const firstQ = QUESTIONS.find(q => q.chapter === chapter.id);
      return (
        <ChapterIntroScreen
          chapter={chapter}
          answers={answers}
          doneChapters={doneChapters}
          onStart={() => setStep({ kind: 'question', qid: firstQ.id })}
          onBack={goPrev}
          showQuote={true}
        />
      );
    }
    if (step.kind === 'question') {
      const question = QUESTIONS.find(q => q.id === step.qid);
      const chapter = CHAPTERS.find(c => c.id === question.chapter);
      return (
        <QuestionScreen
          question={question}
          chapter={chapter}
          answers={answers}
          doneChapters={doneChapters}
          onAnswer={handleAnswer}
          onNext={goNext}
          onBack={goPrev}
          progressStyle="axes"
          optionsDensity="comfortable"
          numbering="continuous"
        />
      );
    }
    return null;
  };

  return (
    <div className="db-stage mode-desktop">
      <div className="db-frame" key={stepKey(step)}>
        {renderStep()}
      </div>
    </div>
  );
}

// ─── ResultsViewer : hydrate depuis /api/results/:id ──────────────
function ResultsViewer({ clientId }) {
  const [data, setData] = useState(null);
  const [err, setErr] = useState(null);

  useEffect(() => {
    fetch('/api/results/' + encodeURIComponent(clientId))
      .then(r => r.ok ? r.json() : Promise.reject(r.status))
      .then(setData)
      .catch(setErr);
  }, [clientId]);

  if (err) {
    return <WelcomeScreen variant="invalid-token" />;
  }
  if (!data) {
    return <LoadingScreen variant="phrases" />;
  }
  return (
    <ResultsScreen
      answers={data.answers}
      feeling={data.feeling}
      freeform={data.freeform}
      email={data.email}
      firstName={data.firstName}
      clientId={clientId}
    />
  );
}

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