// Agency Audit — voortgang met live checks + de drie vragen tijdens het wachten.
// Het rapport opent pas als de vragen zijn afgerond (of overgeslagen): de
// antwoorden bepalen welke kanalen worden beoordeeld.
const AUDIT_QUESTIONS = [
  { id: 'services', q: 'Welke diensten neem je af van je bureau?', multi: true, hint: 'Alleen deze kanalen beoordelen we; over de rest zeggen we niets.',
    options: [['seo', 'SEO'], ['sea', 'SEA (Google Ads)'], ['meta', 'Adverteren op Meta (Facebook & Instagram)']] },
  { id: 'monthlyBudget', q: 'Hoeveel betaal je je bureau per maand?', multi: false, hint: 'Niet verplicht. Het zet de lat voor wat je mag verwachten.',
    options: [['0-500', '€ 0 – 500'], ['500-1000', '€ 500 – 1.000'], ['1000-2000', '€ 1.000 – 2.000'], ['2000-5000', '€ 2.000 – 5.000'], ['5000+', '€ 5.000+']] },
  { id: 'agencyDeliverables', q: 'Krijg je dit van je bureau?', multi: true, hint: 'Vink aan wat van toepassing is.',
    options: [['rapportage', 'Duidelijke rapportage'], ['live_inzicht', 'Live inzicht in de data en lopende campagnes'], ['updates', 'Inzicht in wat er gebeurt en regelmatige updates'], ['onderbouwing', 'Duidelijke onderbouwing van de resultaten']] },
];

function AuditProgress({ auditId, onDone, onRestart, concernOptions = null }) {
  const { useState, useEffect, useRef } = React;
  // Landing-variant zonder vinkjes boven de vouw: de vier twijfels komen hier als eerste vraag
  const QUESTIONS = Array.isArray(concernOptions) && concernOptions.length
    ? [{ id: 'concerns', q: 'Waar twijfel je over?', multi: true, hint: 'Vink aan wat je niet zeker weet. Dit nemen we mee in het rapport.', options: concernOptions }, ...AUDIT_QUESTIONS]
    : AUDIT_QUESTIONS;
  const [state, setState] = useState(null);
  const [errorMsg, setErrorMsg] = useState('');
  const [qIndex, setQIndex] = useState(0);
  const [answers, setAnswers] = useState({ concerns: [], services: [], monthlyBudget: null, agencyDeliverables: [] });
  const [mail, setMail] = useState({ value: '', busy: false, done: false, error: '' });
  async function leaveEmail(e) {
    e?.preventDefault?.();
    const v = mail.value.trim();
    if (!/^\S+@\S+\.\S+$/.test(v)) { setMail((m) => ({ ...m, error: 'Vul een geldig e-mailadres in' })); return; }
    setMail((m) => ({ ...m, busy: true, error: '' }));
    try {
      const r = await fetch(`/api/audit/${auditId}/email`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: v }) });
      const d = await r.json().catch(() => ({}));
      if (!r.ok) throw new Error(d.error || 'Dat lukte niet');
      if (typeof gsTrack === 'function') gsTrack('audit_email_left', { product: 'audit', audit_id: auditId }, `${auditId}:email`);
      setMail({ value: v, busy: false, done: true, error: '' });
    } catch (err) { setMail((m) => ({ ...m, busy: false, error: err.message })); }
  }
  const [refining, setRefining] = useState(false);
  const doneRef = useRef(false);
  // 'done' mag het rapport pas openen na de afsluitende POST, en alleen via
  // polls die daarna zijn gestart (anders opent een verouderd rapport)
  const finalRef = useRef({ acked: false, since: 0 });

  useEffect(() => {
    let stopped = false;
    async function poll() {
      const startedAt = Date.now();
      try {
        const res = await fetch(`/api/audit/${auditId}`);
        if (res.status === 404) { if (!stopped) setErrorMsg('De audit is verlopen. Start opnieuw.'); return; }
        const d = await res.json();
        if (stopped) return;
        setState(d);
        if (d.audit?.status === 'error') setErrorMsg(d.audit.error || 'Er ging iets mis.');
        const fin = finalRef.current;
        if (d.audit?.status === 'done' && d.report && fin.acked && startedAt >= fin.since && !doneRef.current) { doneRef.current = true; setTimeout(() => onDone(d.report), 600); }
      } catch { /* netwerk-hikje */ }
    }
    poll();
    const iv = setInterval(poll, 2000);
    return () => { stopped = true; clearInterval(iv); };
  }, [auditId]);

  function post(next, final = false) {
    return fetch(`/api/audit/${auditId}/answers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...next, final }) })
      .then((r) => r.json()).catch(() => ({}));
  }
  const q = QUESTIONS[qIndex];
  const allAnswered = qIndex >= QUESTIONS.length;
  function advance(next) {
    if (qIndex + 1 < QUESTIONS.length) { post(next); setQIndex(qIndex + 1); return; }
    // laatste vraag: afsluitende POST; is de audit al klaar, dan schrijft de server het rapport opnieuw
    setQIndex(QUESTIONS.length);
    finalRef.current = { acked: false, since: 0 };
    post(next, true).then((r) => { finalRef.current = { acked: true, since: Date.now() }; setRefining(!!r?.refining); });
  }
  function toggle(val) {
    const next = { ...answers };
    if (q.multi) next[q.id] = next[q.id].includes(val) ? next[q.id].filter((x) => x !== val) : [...next[q.id], val];
    else next[q.id] = val;
    setAnswers(next);
    if (q.multi) post(next); else advance(next);
  }

  const checks = state?.expected || [];
  const progress = state?.audit?.progress?.checks || {};
  const doneCount = Object.values(progress).filter((c) => c.status && c.status !== 'running').length;
  const stage = state?.audit?.progress?.stage || 'start';
  const stageLabel = stage.startsWith('checks') ? 'Bronnen meten' : stage === 'answers' ? 'Wachten op je antwoorden' : stage === 'scoring' ? 'Scores berekenen' : stage === 'narrative' ? 'Rapport schrijven' : stage === 'done' ? 'Klaar' : 'Opstarten';
  const measured = stage === 'answers' || stage === 'scoring' || stage === 'narrative' || stage === 'done';

  if (errorMsg) {
    return (
      <div style={{ minHeight: '100vh', background: 'var(--bm-dark)', display: 'grid', placeItems: 'center', padding: 24 }}>
        <NotchCard style={{ padding: '38px 36px', maxWidth: 480, textAlign: 'center' }}>
          <h2 style={{ margin: '0 0 8px', fontSize: 20, fontWeight: 900 }}>Dat ging niet helemaal goed</h2>
          <p style={{ margin: '0 0 22px', color: '#5A7472', fontSize: 14.5 }}>{errorMsg}</p>
          <CtaButton onClick={onRestart}>Opnieuw proberen</CtaButton>
        </NotchCard>
      </div>
    );
  }

  // Layout (Kevin, 22 sep 2026): één kolom, de vragen bovenaan en prominent,
  // daaronder de voortgang. Wie zijn e-mail achterlaat houdt de bevestiging
  // in beeld — die verdween eerder zodra de server hasEmail terugmeldde.
  const totalChecks = Math.max(1, checks.length);
  const pct = Math.max(4, (doneCount / totalChecks) * 100);
  const link = { background: 'none', border: 'none', color: 'var(--bm-teal-ink)', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: "'Lato', sans-serif", padding: 0 };
  const kop = (t) => <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '1px', textTransform: 'uppercase', color: 'var(--bm-teal-ink)', marginBottom: 6 }}>{t}</div>;

  const vragenKaart = !allAnswered ? (
    <NotchCard style={{ padding: 'clamp(24px, 4vw, 34px) clamp(22px, 4vw, 36px) 26px' }} notch={20}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginBottom: 14, flexWrap: 'wrap' }}>
        {kop(`Terwijl je wacht · vraag ${qIndex + 1} van ${QUESTIONS.length}`)}
        <div style={{ display: 'flex', gap: 6 }}>
          {QUESTIONS.map((_, i) => <span key={i} style={{ width: i === qIndex ? 22 : 8, height: 8, borderRadius: 999, background: i < qIndex ? 'var(--bm-teal)' : i === qIndex ? 'var(--bm-teal-bright)' : '#DCE8E6', transition: 'all 0.25s' }}></span>)}
        </div>
      </div>
      <h2 style={{ margin: '0 0 6px', fontSize: 'clamp(20px, 2.4vw, 24px)', fontWeight: 900, lineHeight: 1.25 }}>{q.q}</h2>
      <p style={{ margin: '0 0 16px', fontSize: 13.5, color: '#6E8886' }}>{q.hint}</p>
      <div style={{ display: 'grid', gap: 8 }}>
        {q.options.map(([val, label]) => {
          const active = q.multi ? answers[q.id].includes(val) : answers[q.id] === val;
          return <button key={val} type="button" className="gs-chip" onClick={() => toggle(val)} style={{ textAlign: 'left', borderRadius: 10, padding: '13px 16px', fontSize: 15, ...(active ? { background: 'var(--bm-teal)', borderColor: 'var(--bm-teal)', color: '#fff' } : {}) }}>{q.multi ? (active ? '☑ ' : '☐ ') : ''}{label}</button>;
        })}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 18 }}>
        {qIndex > 0 ? <button onClick={() => setQIndex(qIndex - 1)} style={link}>← Vorige</button> : <span></span>}
        {q.multi ? <CtaButton onClick={() => advance(answers)} style={{ padding: '11px 20px', fontSize: 14 }}>{qIndex + 1 === QUESTIONS.length ? (measured ? 'Naar mijn rapport →' : 'Afronden →') : 'Verder →'}</CtaButton> : <button onClick={() => advance(answers)} style={link}>Overslaan →</button>}
      </div>
    </NotchCard>
  ) : (
    <NotchCard style={{ padding: '22px 26px', display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }} notch={16}>
      <div style={{ width: 44, height: 44, borderRadius: '50%', background: 'var(--bm-teal)', color: '#fff', display: 'grid', placeItems: 'center', fontSize: 20, flex: '0 0 auto' }}>✓</div>
      <div style={{ flex: '1 1 240px', minWidth: 0 }}>
        <h3 style={{ margin: '0 0 3px', fontSize: 17, fontWeight: 900 }}>Dank je wel</h3>
        <p style={{ margin: 0, color: '#5A7472', fontSize: 14 }}>
          {refining ? 'We verwerken je antwoorden in het rapport. Dit duurt ongeveer een halve minuut…' : stage === 'done' ? 'Het rapport wordt geopend…' : 'We wegen je antwoorden mee in het oordeel. Het rapport opent hier vanzelf.'}
        </p>
      </div>
      {!refining && stage !== 'done' && <button onClick={() => setQIndex(0)} style={link}>← Antwoorden aanpassen</button>}
    </NotchCard>
  );

  // e-mail: bevestiging blijft staan (mail.done), ook als de poll hasEmail=true meldt
  const mailKaart = mail.done ? (
    <div style={{ background: '#E6F4F2', border: '1.5px solid #9FD3CD', borderRadius: 12, padding: '16px 20px', display: 'flex', gap: 14, alignItems: 'flex-start' }}>
      <span style={{ width: 26, height: 26, borderRadius: '50%', background: 'var(--bm-teal)', color: '#fff', display: 'grid', placeItems: 'center', fontSize: 13, fontWeight: 900, flex: '0 0 auto' }}>✓</span>
      <div style={{ fontSize: 14, color: '#12302E', lineHeight: 1.6 }}>
        <b>Je kunt deze pagina nu sluiten als je niet wilt wachten.</b> Zodra het rapport klaar is, staat de link in je inbox op <b>{mail.value}</b>. Blijf je hier, dan opent het rapport vanzelf.
      </div>
    </div>
  ) : (state?.audit && !state.audit.hasEmail && stage !== 'done') ? (
    <NotchCard style={{ padding: '20px 24px 18px' }} notch={14}>
      <form onSubmit={leaveEmail} style={{ display: 'grid', gap: 8 }}>
        {kop('Liever niet wachten?')}
        <p style={{ margin: 0, fontSize: 13.5, color: '#3A5250', lineHeight: 1.55 }}>Laat je e-mail achter, dan sturen we de link zodra het rapport klaar is. Je kunt de pagina daarna sluiten.</p>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <input value={mail.value} onChange={(e) => setMail((m) => ({ ...m, value: e.target.value, error: '' }))} placeholder="naam@jouwbedrijf.nl" type="email" className="gs-input" style={{ flex: '1 1 200px', minWidth: 0 }} />
          <CtaButton type="submit" style={{ padding: '10px 16px', fontSize: 13, opacity: mail.busy ? 0.6 : 1 }}>{mail.busy ? 'Even…' : 'Mail me de link'}</CtaButton>
        </div>
        {mail.error && <p style={{ margin: 0, fontSize: 12.5, color: '#C4441C' }}>{mail.error}</p>}
      </form>
    </NotchCard>
  ) : null;

  const voortgang = (
    <div style={{ background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.10)', borderRadius: 14, padding: 'clamp(18px, 3vw, 24px)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12, flexWrap: 'wrap', marginBottom: 10 }}>
        <div style={{ color: '#fff', fontWeight: 900, fontSize: 15 }}>{stageLabel}</div>
        <div style={{ color: '#B7D2CF', fontSize: 13 }}>{doneCount} van {checks.length || '…'} bronnen gemeten</div>
      </div>
      <div style={{ height: 8, background: 'rgba(255,255,255,0.12)', borderRadius: 999, marginBottom: 18 }}>
        <div style={{ width: `${pct}%`, height: '100%', borderRadius: 999, background: 'var(--bm-cta-1)', transition: 'width 0.6s' }}></div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(210px, 1fr))', gap: '7px 16px' }}>
        {checks.map((src) => {
          const c = progress[src];
          const st = c?.status;
          const icon = st === 'ok' ? '✓' : st === 'partial' ? '◐' : st === 'failed' ? '!' : st === 'not_applicable' ? '–' : '…';
          const color = st === 'ok' ? '#7FD1A8' : st === 'partial' ? '#F0C05A' : st === 'failed' ? '#F08A5A' : st === 'not_applicable' ? '#8FB5B1' : '#5F7C78';
          return (
            <div key={src} style={{ display: 'flex', alignItems: 'center', gap: 9, color: st ? '#E4F0EF' : '#8FB5B1', fontSize: 13.5 }}>
              <span style={{ width: 20, height: 20, borderRadius: '50%', border: `2px solid ${color}`, color, display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 900, flex: '0 0 auto' }}>{icon}</span>
              {AUDIT_CHECK_LABELS[src] || src}
            </div>
          );
        })}
      </div>
      {state?.audit?.hasEmail && !mail.done && stage !== 'done' && (
        <p style={{ margin: '16px 0 0', color: '#B7D2CF', fontSize: 13, lineHeight: 1.55 }}>Je kunt deze pagina sluiten: zodra het rapport klaar is, mailen we je de link.</p>
      )}
    </div>
  );

  return (
    <div data-screen-label="Audit voortgang" style={{ minHeight: '100vh', background: 'var(--bm-dark)', display: 'flex', flexDirection: 'column' }}>
      <header style={{ padding: '22px clamp(20px, 6vw, 72px)' }}>
        <div style={{ maxWidth: 760, margin: '0 auto', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
          <BmLogo light />
          <SectionTag>Audit actief · {stageLabel}</SectionTag>
        </div>
      </header>
      <div style={{ flex: 1, maxWidth: 760, width: '100%', margin: '0 auto', padding: '6px clamp(20px, 6vw, 72px) 80px', display: 'grid', gap: 18, alignContent: 'start' }}>
        <div>
          <h1 style={{ color: '#fff', fontWeight: 900, fontSize: 'clamp(24px, 3vw, 32px)', margin: '0 0 6px', lineHeight: 1.15, overflowWrap: 'anywhere' }}>We meten {state?.audit?.domain || 'je marketing'} van buitenaf</h1>
          <p style={{ color: '#B7D2CF', fontSize: 15, margin: 0 }}>
            {measured && !allAnswered ? 'De metingen zijn klaar. Rond de vragen hieronder af (of sla ze over), dan openen we je rapport.' : 'Dit duurt 2 tot 4 minuten. Beantwoord intussen drie korte vragen; die bepalen wat we beoordelen.'}
          </p>
        </div>
        {vragenKaart}
        {allAnswered && mailKaart}
        {voortgang}
        {!allAnswered && mailKaart}
      </div>
    </div>
  );
}

Object.assign(window, { AuditProgress, AUDIT_QUESTIONS });
