/* GA-Coach · Kompetenz-Check — App / Zustandsmaschine + Persistenz
   Phasen: landing → quiz (intro + Fragen) → result → success */

const KC_STORE = 'gakc_state_v2';

function kcLoad() {
  try {
    const raw = localStorage.getItem(KC_STORE);
    if (!raw) return null;
    const s = JSON.parse(raw);
    if (s && typeof s === 'object') return s;
  } catch (e) {}
  return null;
}

function KCApp() {
  const saved = kcLoad();
  const [phase, setPhase] = useState((saved && saved.phase) || 'landing');
  const [quizStep, setQuizStep] = useState(saved && saved.quizStep != null ? saved.quizStep : 'intro');
  const [answers, setAnswers] = useState((saved && saved.answers) || {});
  const [email, setEmail] = useState((saved && saved.email) || '');

  // Reveal-on-scroll (Landing)
  useReveal();
  useEffect(() => { if (window.lucide) window.lucide.createIcons(); });

  // Persistenz
  useEffect(() => {
    try { localStorage.setItem(KC_STORE, JSON.stringify({ phase, quizStep, answers, email })); } catch (e) {}
  }, [phase, quizStep, answers, email]);

  // Beim Phasenwechsel nach oben
  const toTop = () => { try { window.scrollTo(0, 0); } catch (e) {} };

  const start = () => { setQuizStep('intro'); setPhase('quiz'); toTop(); };
  const exitToLanding = () => { setPhase('landing'); toTop(); };
  const complete = () => { setPhase('result'); toTop(); };
  const restart = () => { setAnswers({}); setEmail(''); setQuizStep('intro'); setPhase('landing'); toTop(); };
  const submitEmail = async (mail) => {
    setEmail(mail);
    try {
      const prof = window.buildProfile(answers);
      await fetch('/api/kc-report/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: mail, profile: prof }),
      });
    } catch (e) {
      console.warn('kc-report send failed:', e);
    }
    setPhase('success');
    toTop();
  };

  const onContinue = { submit: submitEmail, restart };

  /* ----- Landing ----- */
  if (phase === 'landing') {
    return (
      <React.Fragment>
        <KCNav onStart={start} />
        <main>
          <KCHero onStart={start} />
          <KCWhy />
          <KCProcess onStart={start} />
          <KCAudience />
          <KCFinalCTA onStart={start} />
        </main>
        <KCFooter />
      </React.Fragment>
    );
  }

  /* ----- Focus-Stage (quiz / result / success) ----- */
  const QUESTIONS = window.GA_ASSESSMENT.questions;
  const total = QUESTIONS.length;
  let barRight = null;
  if (phase === 'quiz') {
    barRight = (
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        {quizStep !== 'intro' && <span style={{ fontSize: 13, fontWeight: 800, color: 'var(--ga-muted)', letterSpacing: '.03em' }}>Frage {quizStep + 1} / {total}</span>}
        <button className="kc-exit" onClick={exitToLanding}><Icon name="x" size={16} /> Abbrechen</button>
      </div>
    );
  } else {
    barRight = <a href="/" className="kc-exit" style={{ textDecoration: 'none' }}><Icon name="home" size={16} /> Zur Startseite</a>;
  }

  const profile = (phase === 'result' || phase === 'success') ? window.buildProfile(answers) : null;

  return (
    <div className="kc-stage gaa-root">
      <div className="kc-stage-bar">
        <a href="/" style={{ display: 'inline-flex', alignItems: 'center', gap: 10, textDecoration: 'none' }}>
          <span style={{ display: 'inline-flex', background: '#fff', borderRadius: 9, padding: '4px 8px', boxShadow: 'var(--ga-shadow-1)', border: '1px solid var(--ga-line)' }}>
            <img src="assets/ga-coach-logo.jpg" alt="GA-Coach" style={{ height: 28, display: 'block' }} />
          </span>
          <span style={{ fontSize: 11, fontWeight: 800, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--ga-primary)' }} className="kc-bar-label">Kompetenz-Check</span>
        </a>
        {barRight}
      </div>
      <div className="kc-stage-main">
        <div className="kc-fade-enter" key={phase} style={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
          {phase === 'quiz' && (
            <KCAssessment
              step={quizStep} setStep={setQuizStep}
              answers={answers} setAnswers={setAnswers}
              onExit={exitToLanding} onComplete={complete}
            />
          )}
          {phase === 'result' && <KCResult profile={profile} onContinue={onContinue} />}
          {phase === 'success' && <KCSuccess profile={profile} email={email} onRestart={restart} />}
        </div>
      </div>
    </div>
  );
}

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