// Scan-loader: echte pipeline-voortgang via polling + optionele vragen tijdens het wachten
const SCAN_STEPS = [
  'Website analyseren',
  'Bedrijfsprofiel opstellen',
  'Benchmark berekenen',
  'Groeiplan samenstellen',
];

const SCAN_QUESTIONS = [
  {
    id: 'spend', q: 'Hoeveel geef je nu maandelijks uit aan marketing?',
    options: ['Minder dan €1.000', '€1.000 – €2.500', '€2.500 – €5.000', '€5.000 – €10.000', '€10.000 – €20.000', 'Meer dan €20.000'],
  },
  {
    id: 'team', q: 'Met hoeveel mensen zijn jullie?',
    options: ['1 – 5', '6 – 15', '16 – 50', '50+'],
  },
  {
    id: 'revenue', q: 'In welke jaarlijkse omzet-range zitten jullie?',
    options: ['Tot €250K', '€250K – €1M', '€1M – €5M', 'Meer dan €5M'],
  },
  {
    id: 'belief', q: 'Denk je dat online marketing voor jouw bedrijf kan werken?',
    options: ['Ja, zeker', 'Waarschijnlijk wel', 'Ik twijfel', 'Nee, eigenlijk niet'],
  },
];

function ScanLoader({ lead, scanId, minDuration, onDone, onRestart, answers, setAnswers }) {
  const { useState, useEffect, useRef } = React;
  const [progress, setProgress] = useState(0);      // weergegeven balk (geëased)
  const [serverStep, setServerStep] = useState(0);
  const [serverStatus, setServerStatus] = useState('running');
  const [errorMsg, setErrorMsg] = useState('');
  const [qIndex, setQIndex] = useState(0);
  const resultRef = useRef(null);
  const startRef = useRef(Date.now());
  const [minElapsed, setMinElapsed] = useState(false);

  // Poll de server elke 1,5s
  useEffect(() => {
    if (!scanId) { setServerStatus('error'); setErrorMsg('Geen scan gevonden.'); return; }
    let stopped = false;
    async function poll() {
      try {
        const res = await fetch(`/api/scan/${scanId}`);
        if (res.status === 404) {
          if (!stopped) { setServerStatus('error'); setErrorMsg('De scan is verlopen. Start opnieuw.'); }
          return;
        }
        const d = await res.json();
        if (stopped) return;
        setServerStep(d.step ?? 0);
        setServerStatus(d.status);
        if (d.status === 'done' && d.result) resultRef.current = d.result;
        if (d.status === 'error') setErrorMsg(d.error || 'Er ging iets mis.');
      } catch (e) { /* netwerk-hikje: volgende poll */ }
    }
    poll();
    const iv = setInterval(poll, 1500);
    return () => { stopped = true; clearInterval(iv); };
  }, [scanId]);

  // Minimale weergavetijd zodat de loader niet voorbij flitst
  useEffect(() => {
    const ms = Math.max(3, minDuration || 10) * 1000;
    const to = setTimeout(() => setMinElapsed(true), ms);
    return () => clearTimeout(to);
  }, [minDuration]);

  // Eas de balk soepel richting de serverstand
  useEffect(() => {
    let raf;
    function tick() {
      setProgress((p) => {
        const target = serverStatus === 'done' ? 1 : Math.min(0.97, (serverStep + 0.8) / SCAN_STEPS.length);
        const next = p + (target - p) * 0.03;
        return next > p ? next : p;
      });
      raf = requestAnimationFrame(tick);
    }
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [serverStep, serverStatus]);

  const done = serverStatus === 'done' && minElapsed && progress >= 0.99;
  const stepIdx = serverStatus === 'done' ? SCAN_STEPS.length - 1 : Math.min(SCAN_STEPS.length - 1, serverStep);
  const allAnswered = qIndex >= SCAN_QUESTIONS.length;
  const q = SCAN_QUESTIONS[qIndex];

  function postAnswers(nextAnswers, doneFlag) {
    if (!scanId) return;
    fetch(`/api/scan/${scanId}/answers`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ answers: nextAnswers, done: doneFlag }),
    }).catch(() => {});
  }

  function answer(opt) {
    const next = { ...answers, [q.id]: opt };
    setAnswers(next);
    const isLast = qIndex + 1 >= SCAN_QUESTIONS.length;
    postAnswers(next, isLast);
    setQIndex(qIndex + 1);
  }

  function skip() {
    const isLast = qIndex + 1 >= SCAN_QUESTIONS.length;
    if (isLast) postAnswers(answers, true);
    setQIndex(qIndex + 1);
  }

  // Foutscherm
  if (serverStatus === 'error') {
    return (
      <div data-screen-label="Scan loader" 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, display: 'grid', placeItems: 'center', padding: '0 clamp(20px, 6vw, 72px) 80px' }}>
          <NotchCard style={{ padding: '38px 36px', maxWidth: 480, textAlign: 'center' }}>
            <div style={{ width: 54, height: 54, borderRadius: '50%', background: '#FBE9E1', color: '#C4441C', display: 'grid', placeItems: 'center', fontSize: 24, margin: '0 auto 14px', fontWeight: 900 }}>!</div>
            <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, lineHeight: 1.6 }}>{errorMsg}</p>
            <CtaButton big onClick={onRestart}>Opnieuw proberen</CtaButton>
          </NotchCard>
        </div>
      </div>
    );
  }

  return (
    <div data-screen-label="Scan loader" style={{ minHeight: '100vh', background: 'var(--bm-dark)', display: 'flex', flexDirection: 'column' }}>
      <style>{`
        @keyframes gs-pulse { 0%,100% { box-shadow: 0 0 0 0 rgba(31,166,158,0.5); } 50% { box-shadow: 0 0 0 8px rgba(31,166,158,0); } }
        @keyframes gs-spin { to { transform: rotate(360deg); } }
      `}</style>
      <header style={{ padding: '22px clamp(20px, 6vw, 72px)' }}>
        <div style={{ maxWidth: 1040, margin: '0 auto' }}><BmLogo light /></div>
      </header>

      <div style={{
        flex: 1, width: '100%', maxWidth: 1040, margin: '0 auto',
        padding: '2vh clamp(20px, 6vw, 72px) 60px',
        display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(320px, 1.1fr)',
        gap: 'clamp(32px, 6vw, 80px)', alignItems: 'center'
      }} className="gs-two-col">

        {/* Links: voortgang */}
        <div>
          <SectionTag>Scan actief</SectionTag>
          <h1 style={{ color: '#fff', fontWeight: 900, fontSize: 'clamp(26px, 3.2vw, 36px)', margin: '18px 0 8px', lineHeight: 1.15 }}>
            We scannen<br />{lead.website}
          </h1>
          <p style={{ color: '#8FB5B1', fontSize: 14.5, margin: '0 0 28px' }}>
            {done ? 'Klaar! Je groeiplan staat voor je klaar.' : 'Dit duurt ongeveer een minuut.'}
          </p>

          {/* Stappen verticaal */}
          <div style={{ display: 'grid', gap: 0 }}>
            {SCAN_STEPS.map((s, i) => {
              const isDone = i < stepIdx || done;
              const isActive = i === stepIdx && !done;
              return (
                <div key={s} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '7px 0', transition: 'opacity 0.3s', opacity: isDone || isActive ? 1 : 0.45 }}>
                  <span style={{
                    width: 26, height: 26, borderRadius: '50%', flex: '0 0 auto',
                    display: 'grid', placeItems: 'center', fontSize: 13, fontWeight: 900,
                    background: isDone ? 'var(--bm-teal)' : 'transparent',
                    border: isDone ? 'none' : isActive ? '2.5px solid var(--bm-teal-bright)' : '2px solid rgba(255,255,255,0.25)',
                    borderTopColor: isActive ? 'transparent' : undefined,
                    color: '#fff',
                    animation: isActive ? 'gs-spin 0.9s linear infinite' : 'none',
                    transition: 'background 0.3s'
                  }}>{isDone ? '✓' : ''}</span>
                  <span style={{
                    color: isDone ? '#C6DBD9' : isActive ? '#fff' : '#7FA09D',
                    fontSize: 15, fontWeight: isActive ? 900 : 400, transition: 'color 0.3s'
                  }}>{s}</span>
                </div>
              );
            })}
          </div>

          {done && (
            <div style={{ marginTop: 30 }}>
              <CtaButton big onClick={() => onDone(resultRef.current)}>Bekijk je groeiplan</CtaButton>
            </div>
          )}
        </div>

        {/* Rechts: vragen */}
        <div>
          {(!done || !allAnswered) ? (
            <NotchCard style={{ padding: '32px 30px 26px', textAlign: 'left' }} notch={18}>
              {!allAnswered ? (
                <div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
                    <div style={{ display: 'flex', gap: 6 }}>
                      {SCAN_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>
                  <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '1px', textTransform: 'uppercase', color: 'var(--bm-teal-ink)', marginBottom: 6 }}>
                    Terwijl je wacht · vraag {qIndex + 1} van {SCAN_QUESTIONS.length}
                  </div>
                  <h3 style={{ margin: '0 0 18px', fontSize: 20, fontWeight: 900, lineHeight: 1.3 }}>{q.q}</h3>
                  <div style={{ display: 'grid', gap: 10 }}>
                    {q.options.map(opt => (
                      <button key={opt} onClick={() => answer(opt)} className="gs-chip" style={{ textAlign: 'left', borderRadius: 10, padding: '13px 16px' }}>{opt}</button>
                    ))}
                  </div>
                  <p style={{ margin: '16px 0 0', fontSize: 12, color: '#8AA3A1' }}>
                    Niet verplicht, maar hoe meer we weten, hoe scherper je plan.
                  </p>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 12 }}>
                    {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 vraag</button>
                    ) : <span></span>}
                    <button onClick={skip} 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: '18px 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 }}>
                    We verwerken je antwoorden in het groeiplan. Nog even geduld…
                  </p>
                  <button onClick={() => setQIndex(SCAN_QUESTIONS.length - 1)} 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>
          ) : (
            <NotchCard style={{ padding: 0, overflow: 'hidden' }} notch={18}>
              <img src="images/overleg.jpg" alt="Overleg bij Brandmerck" style={{ display: 'block', width: '100%', height: 260, objectFit: 'cover', objectPosition: 'center 30%' }} />
              <div style={{ padding: '22px 26px 24px' }}>
                <h3 style={{ margin: '0 0 6px', fontSize: 18, fontWeight: 900 }}>Je groeiplan is klaar</h3>
                <p style={{ margin: 0, color: '#5A7472', fontSize: 14, lineHeight: 1.6 }}>
                  Benchmark, strategie en kanaaladvies staan voor je klaar, opgesteld volgens de aanpak van Brandmerck.
                </p>
              </div>
            </NotchCard>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ScanLoader, SCAN_QUESTIONS });
