// 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 }) {
  const { useState, useEffect, useRef } = React;
  const [state, setState] = useState(null);
  const [errorMsg, setErrorMsg] = useState('');
  const [qIndex, setQIndex] = useState(0);
  const [answers, setAnswers] = useState({ services: [], monthlyBudget: null, agencyDeliverables: [] });
  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 = AUDIT_QUESTIONS[qIndex];
  const allAnswered = qIndex >= AUDIT_QUESTIONS.length;
  function advance(next) {
    if (qIndex + 1 < AUDIT_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(AUDIT_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>
    );
  }

  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: 1040, margin: '0 auto' }}><BmLogo light /></div></header>
      <div style={{ flex: 1, maxWidth: 1040, width: '100%', margin: '0 auto', padding: '10px clamp(20px, 6vw, 72px) 80px', display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(320px, 440px)', gap: 'clamp(28px, 5vw, 64px)', alignItems: 'start' }} className="gs-two-col">
        <div>
          <SectionTag>Audit actief · {stageLabel}</SectionTag>
          <h1 style={{ color: '#fff', fontWeight: 900, fontSize: 'clamp(26px, 3.2vw, 36px)', margin: '18px 0 8px', lineHeight: 1.15 }}>We meten {state?.audit?.domain || 'je marketing'} van buitenaf</h1>
          <p style={{ color: '#B7D2CF', fontSize: 15, margin: '0 0 22px' }}>
            {measured && !allAnswered ? 'De metingen zijn klaar. Rond de vragen hiernaast af (of sla ze over), dan openen we je rapport.' : 'Dit duurt 2 tot 4 minuten. Sommige bronnen zijn traag; de audit wacht netjes op ze.'}
          </p>
          <div style={{ height: 8, background: 'rgba(255,255,255,0.12)', borderRadius: 999, marginBottom: 22 }}>
            <div style={{ width: `${Math.max(4, (doneCount / Math.max(1, checks.length)) * 100)}%`, height: '100%', borderRadius: 999, background: 'var(--bm-cta-1)', transition: 'width 0.6s' }}></div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 8 }}>
            {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: 10, color: st ? '#E4F0EF' : '#8FB5B1', fontSize: 13.5 }}>
                  <span style={{ width: 22, height: 22, borderRadius: '50%', border: `2px solid ${color}`, color, display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 900, flex: '0 0 auto' }}>{icon}</span>
                  {AUDIT_CHECK_LABELS[src] || src}
                </div>
              );
            })}
          </div>
        </div>

        <NotchCard style={{ padding: '30px 28px 24px' }} notch={18}>
          {!allAnswered ? (
            <div>
              <div style={{ display: 'flex', gap: 6, marginBottom: 14 }}>
                {AUDIT_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 style={{ fontSize: 12, fontWeight: 700, letterSpacing: '1px', textTransform: 'uppercase', color: 'var(--bm-teal-ink)', marginBottom: 6 }}>Terwijl je wacht · vraag {qIndex + 1} van {AUDIT_QUESTIONS.length}</div>
              <h3 style={{ margin: '0 0 6px', fontSize: 19, fontWeight: 900, lineHeight: 1.3 }}>{q.q}</h3>
              <p style={{ margin: '0 0 14px', fontSize: 12.5, color: '#8AA3A1' }}>{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: '12px 16px', ...(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: 16 }}>
                {qIndex > 0 ? <button onClick={() => setQIndex(qIndex - 1)} style={{ background: 'none', border: 'none', color: 'var(--bm-teal-ink)', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: "'Lato', sans-serif", padding: 0 }}>← Vorige</button> : <span></span>}
                {q.multi ? <CtaButton onClick={() => advance(answers)} style={{ padding: '10px 18px', fontSize: 13 }}>{qIndex + 1 === AUDIT_QUESTIONS.length ? (measured ? 'Naar mijn rapport →' : 'Afronden →') : 'Verder →'}</CtaButton> : <button onClick={() => advance(answers)} style={{ background: 'none', border: 'none', color: 'var(--bm-teal-ink)', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: "'Lato', sans-serif", padding: 0 }}>Overslaan →</button>}
              </div>
            </div>
          ) : (
            <div style={{ textAlign: 'center', padding: '14px 0' }}>
              <div style={{ width: 48, height: 48, borderRadius: '50%', background: 'var(--bm-teal)', color: '#fff', display: 'grid', placeItems: 'center', fontSize: 22, margin: '0 auto 12px' }}>✓</div>
              <h3 style={{ margin: '0 0 6px', fontSize: 18, 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. Nog even geduld…'}
              </p>
              {!refining && stage !== 'done' && <button onClick={() => setQIndex(0)} style={{ background: 'none', border: 'none', color: 'var(--bm-teal-ink)', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: "'Lato', sans-serif", padding: 0, marginTop: 14 }}>← Antwoorden aanpassen</button>}
            </div>
          )}
        </NotchCard>
      </div>
    </div>
  );
}

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