// Resultaatpagina: benchmark, strategie, data, kanalen, CTA's
// Alle teksten en cijfers komen uit `data` (door de server gegenereerd per scan).

// Vaste bucket-labels — identiek aan de opties van de spend-vraag
const BUCKET_LABELS = ['< €1.000', '€1.000 – €2.500', '€2.500 – €5.000', '€5.000 – €10.000', '€10.000 – €20.000', '€20.000+'];

// Echte specialisten van Brandmerck, gekoppeld aan kanaal-key
const EXPERTS = {
  sea: { name: 'Nico Zeinstra', role: 'Senior SEA-specialist', photo: 'images/expert-nico.jpg' },
  seo: { name: 'Thijs van Beijeren', role: 'SEO-specialist', photo: 'images/expert-thijs.jpg' },
  social: { name: 'Esther Wijbenga', role: 'Social & Google Ads-specialist', photo: 'images/expert-esther.jpg' },
};

// Fallback als reviews.json (echte reviews, zie server/fetch-reviews.js) ontbreekt
const REVIEWS_FALLBACK = [
  { text: 'Met veel SEO-bedrijven gewerkt, maar geen enkele kwam met daadwerkelijke verbetering. Brandmerck deed dit wel.', name: 'Eigenaar beveiligingsbedrijf', rating5: 5 },
  { text: 'Een duidelijke doelstelling en strategie na het eerste gesprek. Binnen één jaar uitstekende resultaten.', name: 'De Kreij Horeca', rating5: 5 },
  { text: 'Goede communicatie en korte lijnen! Leuke, enthousiaste mensen en veel kennis in huis.', name: 'MKB-ondernemer', rating5: 5 },
];

// useReviewsData / nlRating / ReviewBadge komen uit groeiscan-shared.jsx

function ResultHeader({ lead, data }) {
  return (
    <header style={{ background: '#fff' }}>
      {/* Topbar */}
      <div style={{ background: 'var(--bm-dark)', padding: '22px clamp(20px, 6vw, 72px)' }}>
        <div style={{ maxWidth: 1080, margin: '0 auto', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
          <BmLogo light />
          <CtaButton>Bespreek met een strateeg</CtaButton>
        </div>
      </div>

      {/* Hero met foto + diagonaal teal vlak */}
      <div style={{ position: 'relative', minHeight: 'clamp(320px, 42vw, 480px)', overflow: 'hidden', background: 'var(--bm-dark)' }}>
        <img src="images/overleg.jpg" alt="Overleg bij Brandmerck"
          style={{ position: 'absolute', top: 0, bottom: 0, left: '22%', width: '78%', height: '100%', objectFit: 'cover', objectPosition: 'center 25%' }} />
        <div style={{
          position: 'absolute', inset: 0, background: 'var(--bm-dark)',
          clipPath: 'polygon(0 0, 28% 0, 52% 100%, 0 100%)'
        }}></div>
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 'clamp(28px, 6vw, 64px)',
          padding: '0 clamp(20px, 6vw, 72px)'
        }}>
          <div style={{ maxWidth: 1080, margin: '0 auto' }}>
            <span style={{
              display: 'inline-block', border: '1.5px solid #fff', color: '#fff',
              fontSize: 13, fontWeight: 700, letterSpacing: '2px', textTransform: 'uppercase',
              padding: '8px 16px', marginBottom: 18
            }}>Jouw groeiplan</span>
            <h1 style={{
              color: '#fff', fontWeight: 900, fontSize: 'clamp(30px, 4.4vw, 52px)',
              margin: 0, lineHeight: 1.1, maxWidth: 720,
              textShadow: '0 2px 16px rgba(9,43,41,0.35)'
            }}>
              Groeiplan voor {lead.website}
            </h1>
          </div>
        </div>
      </div>

      {/* Intro-band: teal panel met notch, badges rechts op wit */}
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.5fr) minmax(240px, 1fr)', alignItems: 'stretch' }} className="gs-two-col">
        <div style={{
          background: 'var(--bm-dark)', color: '#C6DBD9',
          padding: '36px clamp(20px, 6vw, 72px) 40px',
          clipPath: 'polygon(0 0, 100% 0, 100% calc(100% - 26px), calc(100% - 26px) 100%, 0 100%)'
        }}>
          <p style={{ margin: 0, fontSize: 16, lineHeight: 1.7, maxWidth: 640 }}>
            {data.intro}{lead.email ? ` Ook verstuurd naar ${lead.email}.` : ''}
          </p>
        </div>
        <ResultHeaderBadges />
      </div>
    </header>
  );
}

// Reviewscores in de headerband: gecombineerd gemiddelde + beide bronnen
function ResultHeaderBadges() {
  const data = useReviewsData();
  const g = data?.google, f = data?.feedback_company;
  return (
    <div style={{ background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 22, padding: '24px 20px' }}>
      <div style={{ textAlign: 'center' }}>
        <div style={{ fontWeight: 900, fontSize: 24, color: '#12302E' }}>{nlRating(g?.rating) || '4,7'} <span style={{ color: '#F4B400', fontSize: 18 }}>★</span></div>
        <div style={{ fontSize: 12, color: '#5A7472' }}>{g?.count ? `${g.count} Google-reviews` : 'Google-reviews'}</div>
      </div>
      <div style={{ width: 1, height: 44, background: '#E4EDEC' }}></div>
      <div style={{ textAlign: 'center' }}>
        <div style={{ fontWeight: 900, fontSize: 24, color: '#12302E' }}>{nlRating(f?.rating) || '9,2'}<span style={{ color: '#5A7472', fontSize: 14, fontWeight: 700 }}>/10</span></div>
        <div style={{ fontSize: 12, color: '#5A7472' }}>{f?.count ? `${f.count} reviews · The Feedback Company` : 'The Feedback Company'}</div>
      </div>
    </div>
  );
}

function SectionShell({ num, tag, title, children, alt }) {
  return (
    <section style={{ background: alt ? 'var(--bm-mist)' : '#fff', padding: '58px clamp(20px, 6vw, 72px)' }}>
      <div style={{ maxWidth: 1080, margin: '0 auto' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14 }}>
          <span style={{ fontFamily: "'Lato', sans-serif", fontWeight: 900, fontSize: 15, color: 'var(--bm-teal)', letterSpacing: '1px' }}>{num}</span>
          <SectionTag>{tag}</SectionTag>
        </div>
        <h2 style={{ fontWeight: 900, fontSize: 'clamp(22px, 2.8vw, 30px)', color: '#12302E', margin: '0 0 24px', textWrap: 'balance' }}>{title}</h2>
        {children}
      </div>
    </section>
  );
}

function BenchmarkSection({ answers, benchView, data, num }) {
  const bench = data.benchmark;
  const buckets = BUCKET_LABELS.map((label, i) => ({ label, pct: bench.bucket_pcts[i] ?? 0 }));
  const spend = answers.spend;
  // In welke bucket valt de eigen uitgave?
  const ownBucket = spend === 'Minder dan €1.000' ? 0
    : spend === '€1.000 – €2.500' ? 1
    : spend === '€2.500 – €5.000' ? 2
    : spend === '€5.000 – €10.000' ? 3
    : spend === '€10.000 – €20.000' ? 4
    : spend === 'Meer dan €20.000' ? 5 : null;
  const sweetSpot = bench.sweet_spot || [];
  const max = Math.max(...buckets.map(b => b.pct), 1);

  return (
    <SectionShell num={num} tag="Benchmark" title="Wat investeren bedrijven zoals jij per maand?">
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(260px, 340px)', gap: 'clamp(24px, 4vw, 48px)', alignItems: 'start' }} className="gs-two-col">
        <div>
          {benchView === 'range' ? (
            <NotchCard style={{ padding: '34px 30px', textAlign: 'center' }} notch={16}>
              <p style={{ margin: '0 0 4px', fontSize: 13, fontWeight: 700, letterSpacing: '1px', textTransform: 'uppercase', color: '#5A7472' }}>Gemiddelde maandelijkse investering</p>
              <div style={{ fontSize: 'clamp(36px, 5vw, 52px)', fontWeight: 900, color: 'var(--bm-teal-ink)' }}>{bench.range_value}</div>
              <p style={{ margin: '8px 0 0', color: '#5A7472', fontSize: 14 }}>{bench.range_sub}</p>
            </NotchCard>
          ) : (
            <div>
              <div style={{ display: 'grid', gridTemplateColumns: `repeat(${buckets.length}, 1fr)`, gap: 10, alignItems: 'end', height: 220 }}>
                {buckets.map((b, i) => {
                  const isSweet = sweetSpot.includes(i);
                  const isOwn = i === ownBucket;
                  return (
                    <div key={b.label} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, height: '100%', justifyContent: 'flex-end' }}>
                      <span style={{ fontSize: 13, fontWeight: 900, color: isSweet ? 'var(--bm-teal-ink)' : '#8AA3A1' }}>{b.pct}%</span>
                      <div title={b.label} style={{
                        width: '100%', height: `${(b.pct / max) * 150}px`, borderRadius: '4px 4px 0 0',
                        background: isSweet ? 'var(--bm-teal)' : '#CBDDDB',
                        outline: isOwn ? '3px solid var(--bm-cta-1)' : 'none', outlineOffset: 2,
                        transition: 'height 0.6s ease'
                      }}></div>
                    </div>
                  );
                })}
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: `repeat(${buckets.length}, 1fr)`, gap: 10, marginTop: 8 }}>
                {buckets.map((b, i) => (
                  <span key={b.label} style={{ fontSize: 11.5, textAlign: 'center', color: i === ownBucket ? 'var(--bm-cta-1)' : '#5A7472', fontWeight: i === ownBucket ? 900 : 400, lineHeight: 1.3 }}>
                    {b.label}{i === ownBucket ? <><br />← jij nu</> : ''}
                  </span>
                ))}
              </div>
              <p style={{ marginTop: 18, fontSize: 13, color: '#8AA3A1' }}>{bench.caption}</p>
            </div>
          )}
        </div>
        <NotchCard style={{ padding: '26px 24px', background: 'var(--bm-dark)', color: '#fff' }} notch={16}>
          <h3 style={{ margin: '0 0 10px', fontSize: 16, fontWeight: 900, color: '#fff' }}>Wat betekent dit?</h3>
          <p style={{ margin: 0, fontSize: 14.5, lineHeight: 1.65, color: '#C6DBD9' }}>{bench.panel_p1}</p>
          <p style={{ margin: '12px 0 0', fontSize: 14.5, lineHeight: 1.65, color: '#C6DBD9' }}>{bench.panel_p2}</p>
          <p style={{ margin: '14px 0 0', fontSize: 13, color: '#8FB5B1' }}>{bench.panel_p3}</p>
        </NotchCard>
      </div>
    </SectionShell>
  );
}

function StrategySection({ data, num }) {
  const strat = data.strategy;
  return (
    <SectionShell num={num} tag="Strategie" title="Welke kanalen passen bij jouw bedrijf?" alt>
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.2fr) minmax(0, 0.8fr)', gap: 'clamp(24px, 4vw, 48px)' }} className="gs-two-col">
        <div style={{ fontSize: 15.5, lineHeight: 1.7, color: '#3A5250' }}>
          {strat.paragraphs.map((p, i) => (
            <p key={i} style={{ marginTop: i === 0 ? 0 : undefined, marginBottom: i === strat.paragraphs.length - 1 ? 0 : undefined }}>{p}</p>
          ))}
        </div>
        <NotchCard style={{ padding: '26px 24px' }} notch={16}>
          <h3 style={{ margin: '0 0 14px', fontSize: 15, fontWeight: 900 }}>Aanbevolen mix</h3>
          {strat.mix.map(({ name, pct }) => (
            <div key={name} style={{ marginBottom: 14 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5, fontWeight: 700, marginBottom: 5 }}>
                <span>{name}</span><span style={{ color: 'var(--bm-teal-ink)' }}>{pct}%</span>
              </div>
              <div style={{ height: 10, background: '#E4EDEC', borderRadius: 999 }}>
                <div style={{ width: `${pct}%`, height: '100%', background: 'var(--bm-teal)', borderRadius: 999 }}></div>
              </div>
            </div>
          ))}
          <p style={{ margin: '4px 0 0', fontSize: 12.5, color: '#8AA3A1' }}>{strat.mix_caption}</p>
        </NotchCard>
      </div>
    </SectionShell>
  );
}

// ── Sectie 03 vóór het onderzoek: formulier + mini-loader ──────────────────

const RESEARCH_STEPS = ['Zoektermen bepalen', 'Zoekvolumes ophalen', 'Posities meten', 'Concurrentie vergelijken', 'Onderbouwing schrijven'];

const REGION_OPTIONS = [
  { key: 'lokaal', label: 'Lokaal / regionaal' },
  { key: 'landelijk', label: 'Heel Nederland' },
  { key: 'internationaal', label: 'Ook internationaal' },
];
const AUDIENCE_OPTIONS = [
  { key: 'b2b', label: 'Zakelijke klanten (B2B)' },
  { key: 'b2c', label: 'Consumenten (B2C)' },
  { key: 'beide', label: 'Beide' },
];

function ChipRow({ options, value, onPick }) {
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
      {options.map((o) => {
        const active = value === o.key;
        return (
          <button key={o.key} type="button" onClick={() => onPick(o.key)} className="gs-chip" style={active ? {
            background: 'var(--bm-teal)', borderColor: 'var(--bm-teal)', color: '#fff',
          } : undefined}>{o.label}</button>
        );
      })}
    </div>
  );
}

function FieldLabel({ children, hint }) {
  return (
    <div style={{ margin: '0 0 10px' }}>
      <div style={{ fontSize: 14.5, fontWeight: 900, color: '#12302E' }}>{children}</div>
      {hint && <div style={{ fontSize: 12.5, color: '#8AA3A1', marginTop: 2 }}>{hint}</div>}
    </div>
  );
}

function ResearchSection({ data, scanId, onResearchDone, num }) {
  const { useState, useEffect, useRef } = React;
  const [mode, setMode] = useState('form'); // 'form' | 'running'
  const [services, setServices] = useState([]);           // geselecteerd (max 3)
  const [customServices, setCustomServices] = useState([]); // zelf toegevoegde chips
  const [customInput, setCustomInput] = useState('');
  const [comps, setComps] = useState([]);                  // geselecteerde concurrenten (max 3)
  const [customComps, setCustomComps] = useState([]);      // zelf toegevoegde concurrent-chips
  const [compInput, setCompInput] = useState('');
  const [scope, setScope] = useState('landelijk');
  const [place, setPlace] = useState('');
  const [audience, setAudience] = useState('beide');
  const [error, setError] = useState('');
  const [step, setStep] = useState(0);
  const doneRef = useRef(false);

  const allServices = [...(data.suggestedServices || []), ...customServices];

  function toggleService(s) {
    setError('');
    setServices((cur) => cur.includes(s) ? cur.filter((x) => x !== s) : cur.length >= 3 ? cur : [...cur, s]);
  }

  function addCustom() {
    const s = customInput.trim().slice(0, 60);
    if (!s) return;
    if (!allServices.some((x) => x.toLowerCase() === s.toLowerCase())) setCustomServices((cur) => [...cur, s]);
    if (services.length < 3 && !services.includes(s)) setServices((cur) => [...cur, s]);
    setCustomInput('');
  }

  const allComps = [...(data.suggestedCompetitors || []), ...customComps];

  function toggleComp(d) {
    setError('');
    setComps((cur) => cur.includes(d) ? cur.filter((x) => x !== d) : cur.length >= 3 ? cur : [...cur, d]);
  }

  function addCompCustom() {
    // lichte normalisatie voor de chip; de server valideert het domein definitief
    const d = compInput.trim().toLowerCase().replace(/^https?:\/\//, '').split(/[/?#]/)[0].slice(0, 60);
    if (!d) return;
    if (!allComps.some((x) => x === d)) setCustomComps((cur) => [...cur, d]);
    if (comps.length < 3 && !comps.includes(d)) setComps((cur) => [...cur, d]);
    setCompInput('');
  }

  async function start() {
    if (!services.length) { setError('Kies minimaal één dienst om op te onderzoeken.'); return; }
    setError('');
    setMode('running'); setStep(0);
    try {
      const res = await fetch(`/api/scan/${scanId}/research`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          services,
          competitors: comps,
          region: { scope, place: place.trim() },
          audience,
        }),
      });
      if (!res.ok && res.status !== 409) {
        const d = await res.json().catch(() => ({}));
        setError(d.error || 'Het onderzoek kon niet worden gestart. Probeer het opnieuw.');
        setMode('form');
      }
      // 409 "loopt al" → gewoon doorpollen
    } catch (e) {
      setError('Geen verbinding. Controleer je internet en probeer het opnieuw.');
      setMode('form');
    }
  }

  // Bij mount: loopt er al een onderzoek (bv. na een refresh)? Dan meteen doorpollen.
  useEffect(() => {
    let cancelled = false;
    fetch(`/api/scan/${scanId}/research`).then((r) => r.json()).then((d) => {
      if (cancelled) return;
      if (d.status === 'running') setMode('running');
      else if (d.status === 'done' && d.result && !doneRef.current) { doneRef.current = true; onResearchDone(d.result); }
    }).catch(() => {});
    return () => { cancelled = true; };
  }, [scanId]);

  // Poll zolang het onderzoek loopt
  useEffect(() => {
    if (mode !== 'running') return;
    let stopped = false;
    let idlePolls = 0;
    async function poll() {
      try {
        const res = await fetch(`/api/scan/${scanId}/research`);
        const d = await res.json();
        if (stopped) return;
        if (d.status === 'running') { setStep(d.step ?? 0); return; }
        if (d.status === 'done' && d.result) {
          if (!doneRef.current) { doneRef.current = true; onResearchDone(d.result); }
          return;
        }
        if (d.status === 'error') { setError(d.error || 'Er ging iets mis bij het onderzoek. Probeer het opnieuw.'); setMode('form'); return; }
        // 'idle' vlak na de start kan een race zijn — na een paar polls opgeven
        if (++idlePolls >= 5) { setError('Het onderzoek is niet gestart. Probeer het opnieuw.'); setMode('form'); }
      } catch (e) { /* netwerk-hikje: volgende poll */ }
    }
    const iv = setInterval(poll, 1500);
    poll();
    return () => { stopped = true; clearInterval(iv); };
  }, [mode, scanId]);

  return (
    <SectionShell num={num} tag="Onderzoek" title="Ontdek wat er voor jou te winnen valt in Google">
      <p style={{ margin: '0 0 26px', fontSize: 15.5, lineHeight: 1.7, color: '#3A5250', maxWidth: 720 }}>
        Vertel kort waar de focus moet liggen. We meten dan live je zoekvolumes, huidige posities en
        concurrenten, en onderbouwen we wat gerichte marketing jou kan opleveren. Gratis, duurt ongeveer een minuut.
      </p>

      {mode === 'running' ? (
        <NotchCard style={{ padding: '32px 30px', maxWidth: 560 }} notch={16}>
          <style>{`@keyframes gs-spin { to { transform: rotate(360deg); } }`}</style>
          <h3 style={{ margin: '0 0 18px', fontSize: 18, fontWeight: 900 }}>We onderzoeken je groeikansen…</h3>
          <div style={{ display: 'grid', gap: 0 }}>
            {RESEARCH_STEPS.map((s, i) => {
              const isDone = i < step;
              const isActive = i === step;
              return (
                <div key={s} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '7px 0', 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)' : '2px solid #CBDDDB',
                    borderTopColor: isActive ? 'transparent' : undefined,
                    color: '#fff',
                    animation: isActive ? 'gs-spin 0.9s linear infinite' : 'none',
                  }}>{isDone ? '✓' : ''}</span>
                  <span style={{ color: isDone ? '#5A7472' : isActive ? '#12302E' : '#8AA3A1', fontSize: 15, fontWeight: isActive ? 900 : 400 }}>{s}</span>
                </div>
              );
            })}
          </div>
          <p style={{ margin: '16px 0 0', fontSize: 12.5, color: '#8AA3A1' }}>
            We halen live data op uit Google. Dit duurt ongeveer een minuut.
          </p>
        </NotchCard>
      ) : (
        <NotchCard style={{ padding: '32px 30px 28px', maxWidth: 720 }} notch={16}>
          {/* 1. Diensten */}
          <FieldLabel hint="Kies er maximaal 3, daar richten we het onderzoek op.">
            Welke diensten zijn voor jou het belangrijkst? <span style={{ color: 'var(--bm-teal-ink)' }}>({services.length}/3)</span>
          </FieldLabel>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 12 }}>
            {allServices.map((s) => {
              const active = services.includes(s);
              return (
                <button key={s} type="button" onClick={() => toggleService(s)} className="gs-chip" style={active ? {
                  background: 'var(--bm-teal)', borderColor: 'var(--bm-teal)', color: '#fff',
                } : services.length >= 3 ? { opacity: 0.5, cursor: 'default' } : undefined}>{s}</button>
              );
            })}
          </div>
          <div style={{ display: 'flex', gap: 10, marginBottom: 26 }}>
            <input value={customInput} onChange={(e) => setCustomInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); addCustom(); } }}
              placeholder="Andere dienst…" className="gs-input" style={{ maxWidth: 280 }} />
            <button type="button" onClick={addCustom} className="gs-chip" style={{ flex: '0 0 auto' }}>+ Toevoegen</button>
          </div>

          {/* 2. Concurrenten */}
          <FieldLabel hint={allComps.length
            ? 'Deze bedrijven scoren op dezelfde zoektermen als jij. Kies wie je wilt vergelijken, of voeg zelf toe. Laat je het leeg, dan kiezen wij ze.'
            : 'Laat leeg, dan zoeken wij ze voor je op basis van gedeelde zoektermen.'}>
            Wie zijn je belangrijkste concurrenten? <span style={{ fontWeight: 400, color: '#8AA3A1' }}>(optioneel, max 3)</span>
          </FieldLabel>
          {allComps.length > 0 && (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 12 }}>
              {allComps.map((d) => {
                const active = comps.includes(d);
                return (
                  <button key={d} type="button" onClick={() => toggleComp(d)} className="gs-chip" style={active ? {
                    background: 'var(--bm-teal)', borderColor: 'var(--bm-teal)', color: '#fff',
                  } : comps.length >= 3 ? { opacity: 0.5, cursor: 'default' } : undefined}>{d}</button>
                );
              })}
            </div>
          )}
          <div style={{ display: 'flex', gap: 10, marginBottom: 26 }}>
            <input value={compInput} onChange={(e) => setCompInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); addCompCustom(); } }}
              placeholder="Andere concurrent, bv. concurrent.nl" className="gs-input" style={{ maxWidth: 280 }} />
            <button type="button" onClick={addCompCustom} className="gs-chip" style={{ flex: '0 0 auto' }}>+ Toevoegen</button>
          </div>

          {/* 3. Focusregio */}
          <FieldLabel>Waar zoek je klanten?</FieldLabel>
          <div style={{ marginBottom: scope === 'lokaal' ? 12 : 26 }}>
            <ChipRow options={REGION_OPTIONS} value={scope} onPick={(k) => { setScope(k); setError(''); }} />
          </div>
          {scope === 'lokaal' && (
            <input value={place} onChange={(e) => setPlace(e.target.value)} placeholder="Plaats of regio, bv. Leeuwarden"
              className="gs-input" style={{ maxWidth: 280, marginBottom: 26 }} />
          )}

          {/* 4. Doelgroep */}
          <FieldLabel>Voor wie werk je vooral?</FieldLabel>
          <div style={{ marginBottom: 26 }}>
            <ChipRow options={AUDIENCE_OPTIONS} value={audience} onPick={(k) => { setAudience(k); setError(''); }} />
          </div>

          {error && <div style={{ color: '#C4441C', fontSize: 13.5, fontWeight: 700, marginBottom: 14 }}>{error}</div>}
          <CtaButton big onClick={start}>Start het gratis onderzoek</CtaButton>
          <p style={{ margin: '12px 0 0', fontSize: 12.5, color: '#8AA3A1' }}>
            Live Google-data: zoekvolumes, posities en klikprijzen voor jouw markt.
          </p>
        </NotchCard>
      )}
    </SectionShell>
  );
}

function DataSection({ data, num }) {
  const keywords = data.keywords || [];
  return (
    <SectionShell num={num} tag="Data" title="Wat zegt de data over jouw positie?">
      {data.data_intro && (
        <p style={{ margin: '0 0 26px', fontSize: 15.5, lineHeight: 1.7, color: '#3A5250', maxWidth: 720 }}>{data.data_intro}</p>
      )}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 18, marginBottom: 34 }}>
        {data.stats.map(s => (
          <NotchCard key={s.label} style={{ padding: '22px 20px' }} notch={14}>
            <div style={{ fontSize: 32, fontWeight: 900, color: 'var(--bm-teal-ink)', lineHeight: 1 }}>{s.value}</div>
            <div style={{ fontSize: 12.5, color: '#8AA3A1', margin: '4px 0 10px' }}>{s.sub}</div>
            <div style={{ fontSize: 13.5, fontWeight: 700, color: '#2E4A48', lineHeight: 1.4 }}>{s.label}</div>
          </NotchCard>
        ))}
      </div>
      {keywords.length > 0 && (
        <React.Fragment>
          <NotchCard style={{ padding: '4px 0 0', overflow: 'hidden' }} notch={16}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
              <thead>
                <tr style={{ textAlign: 'left', color: '#5A7472', fontSize: 12, textTransform: 'uppercase', letterSpacing: '0.8px' }}>
                  <th style={{ padding: '14px 22px' }}>Kansrijke zoekterm</th>
                  <th style={{ padding: '14px 12px' }}>Zoekvolume p/m</th>
                  <th style={{ padding: '14px 12px' }}>Jouw positie</th>
                  <th style={{ padding: '14px 22px' }}>Gem. klikprijs</th>
                </tr>
              </thead>
              <tbody>
                {keywords.map((k, i) => (
                  <tr key={k.kw} style={{ borderTop: '1px solid #E4EDEC', background: i % 2 ? '#FAFCFB' : '#fff' }}>
                    <td style={{ padding: '13px 22px', fontWeight: 700, color: '#12302E' }}>{k.kw}</td>
                    <td style={{ padding: '13px 12px' }}>{k.vol}</td>
                    <td style={{ padding: '13px 12px', color: k.pos === '—' ? '#C4441C' : '#2E4A48', fontWeight: 700 }}>
                      {k.pos === '—' ? 'Niet gevonden' : `#${k.pos}`}
                    </td>
                    <td style={{ padding: '13px 22px' }}>{k.cpc}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </NotchCard>
          <p style={{ marginTop: 16, fontSize: 13, color: '#8AA3A1' }}>
            Bron: actuele zoekdata (DataForSEO), regio Nederland. "Niet gevonden" = geen positie in de top 100.
          </p>
        </React.Fragment>
      )}
    </SectionShell>
  );
}

const NL_MONTHS_SHORT = ['jan', 'feb', 'mrt', 'apr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'];
const fmtNum = (n) => new Intl.NumberFormat('nl-NL').format(n);

function CompetitorsSection({ data, num }) {
  const comp = data.competitorData;
  const rows = [
    { domain: comp.lead.domain.replace(/^www\./, ''), etv: comp.lead.etv || 0, count: comp.lead.count || 0, authority: comp.lead.authority, isLead: true },
    ...comp.list.map(c => ({ domain: c.domain.replace(/^www\./, ''), etv: c.etv, count: c.count, authority: c.authority, isLead: false })),
  ];
  const maxEtv = Math.max(...rows.map(r => r.etv), 1);
  const gap = comp.gap || [];
  const hero = data.serpHero;

  return (
    <SectionShell num={num} tag="Concurrentie" title="Wie pakt de klanten die jij misloopt?" alt>
      <p style={{ margin: '0 0 26px', fontSize: 15.5, lineHeight: 1.7, color: '#3A5250', maxWidth: 720 }}>{data.competitors.intro}</p>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(260px, 340px)', gap: 'clamp(24px, 4vw, 48px)', alignItems: 'start' }} className="gs-two-col">
        {/* Verkeersvergelijking */}
        <NotchCard style={{ padding: '26px 24px' }} notch={16}>
          <h3 style={{ margin: '0 0 4px', fontSize: 15, fontWeight: 900 }}>Geschat organisch bezoek per maand</h3>
          <p style={{ margin: '0 0 18px', fontSize: 12.5, color: '#8AA3A1' }}>Op basis van posities × zoekvolumes (DataForSEO)</p>
          {rows.map(r => (
            <div key={r.domain} style={{ marginBottom: 14 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', fontSize: 13.5, marginBottom: 5, gap: 8 }}>
                <span style={{ fontWeight: r.isLead ? 900 : 700, color: r.isLead ? 'var(--bm-cta-2)' : '#2E4A48', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {r.domain}{r.isLead ? ' ← jij' : ''}
                </span>
                <span style={{ color: '#5A7472', flex: '0 0 auto' }}>
                  ≈ {fmtNum(r.etv)} bez. p/m
                  {r.authority != null && <span style={{ marginLeft: 8, fontSize: 11, background: '#E9F2F1', borderRadius: 999, padding: '2px 8px', color: 'var(--bm-teal-ink)', fontWeight: 700 }}>autoriteit {r.authority}</span>}
                </span>
              </div>
              <div style={{ height: 12, background: '#EEF4F3', borderRadius: 999 }}>
                <div style={{
                  width: `${Math.max(2, (r.etv / maxEtv) * 100)}%`, height: '100%', borderRadius: 999,
                  background: r.isLead ? '#CBDDDB' : 'var(--bm-teal)',
                  outline: r.isLead ? '2px solid var(--bm-cta-1)' : 'none', outlineOffset: 1,
                }}></div>
              </div>
              <div style={{ fontSize: 11.5, color: '#8AA3A1', marginTop: 3 }}>{fmtNum(r.count)} zoektermen in top-100</div>
            </div>
          ))}
        </NotchCard>

        {/* Duiding */}
        <NotchCard style={{ padding: '26px 24px', background: 'var(--bm-dark)', color: '#fff' }} notch={16}>
          <h3 style={{ margin: '0 0 10px', fontSize: 16, fontWeight: 900, color: '#fff' }}>Wat betekent dit?</h3>
          <p style={{ margin: 0, fontSize: 14.5, lineHeight: 1.65, color: '#C6DBD9' }}>{data.competitors.insight}</p>
        </NotchCard>
      </div>

      {/* Keyword-gap tabel */}
      {gap.length > 0 && (
        <div style={{ marginTop: 34 }}>
          <h3 style={{ margin: '0 0 14px', fontSize: 17, fontWeight: 900, color: '#12302E' }}>Waar concurrenten wél gevonden worden</h3>
          <NotchCard style={{ padding: '4px 0 0', overflow: 'hidden' }} notch={16}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
              <thead>
                <tr style={{ textAlign: 'left', color: '#5A7472', fontSize: 12, textTransform: 'uppercase', letterSpacing: '0.8px' }}>
                  <th style={{ padding: '14px 22px' }}>Zoekterm</th>
                  <th style={{ padding: '14px 12px' }}>Zoekvolume p/m</th>
                  <th style={{ padding: '14px 12px' }}>Concurrent</th>
                  <th style={{ padding: '14px 22px' }}>Jouw positie</th>
                </tr>
              </thead>
              <tbody>
                {gap.map((g, i) => (
                  <tr key={g.kw} style={{ borderTop: '1px solid #E4EDEC', background: i % 2 ? '#FAFCFB' : '#fff' }}>
                    <td style={{ padding: '13px 22px', fontWeight: 700, color: '#12302E' }}>{g.kw}</td>
                    <td style={{ padding: '13px 12px' }}>{g.vol}</td>
                    <td style={{ padding: '13px 12px', color: '#2E4A48' }}>{g.compDomain.replace(/^www\./, '')} · <strong>#{g.compPos}</strong></td>
                    <td style={{ padding: '13px 22px', color: g.ownPos ? '#2E4A48' : '#C4441C', fontWeight: 700 }}>{g.ownPos ? `#${g.ownPos}` : 'Niet gevonden'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </NotchCard>
          <p style={{ marginTop: 14, fontSize: 13, color: '#8AA3A1' }}>Bron: DataForSEO Labs, regio Nederland. "Niet gevonden" = geen positie in de top 100 volgens de laatste databasegegevens.</p>
        </div>
      )}

      {/* SERP-hero */}
      {hero && (
        <div style={{ marginTop: 34 }}>
          <h3 style={{ margin: '0 0 14px', fontSize: 17, fontWeight: 900, color: '#12302E' }}>
            Zo ziet pagina 1 eruit voor "{hero.kw}" <span style={{ fontWeight: 400, fontSize: 14, color: '#5A7472' }}>({hero.vol} zoekopdrachten p/m)</span>
          </h3>
          <NotchCard style={{ padding: '18px 0 10px' }} notch={16}>
            {hero.items.map((it) => (
              <div key={it.pos} style={{ display: 'flex', alignItems: 'baseline', gap: 14, padding: '7px 24px', borderTop: it.pos > 1 ? '1px solid #F0F5F4' : 'none' }}>
                <span style={{ flex: '0 0 26px', fontWeight: 900, color: 'var(--bm-teal)', fontSize: 14 }}>#{it.pos}</span>
                <span style={{ flex: '0 0 auto', fontWeight: 700, fontSize: 13.5, color: '#2E4A48' }}>{it.domain}</span>
                <span style={{ fontSize: 13, color: '#8AA3A1', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.title}</span>
              </div>
            ))}
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '10px 24px', borderTop: '1.5px dashed #E4B8A6', background: '#FFF8F4' }}>
              <span style={{ flex: '0 0 26px', fontWeight: 900, color: 'var(--bm-cta-2)', fontSize: 14 }}>—</span>
              <span style={{ fontWeight: 900, fontSize: 13.5, color: 'var(--bm-cta-2)' }}>Jij staat er niet tussen</span>
            </div>
          </NotchCard>
        </div>
      )}
    </SectionShell>
  );
}

function PotentialSection({ data, num }) {
  const pot = data.potentialData;
  const trend = data.trend;
  const unused = data.unused;
  const maxTrend = trend ? Math.max(...trend.months.map(m => m.volume), 1) : 1;

  const statCards = [
    { value: pot.fmt.extraClicks, sub: 'extra bezoekers per maand', label: `Bij een top-3 positie op de geanalyseerde zoektermen` },
    pot.fmt.adValueMonth && { value: pot.fmt.adValueMonth, sub: 'advertentiewaarde per maand', label: 'Wat dit verkeer zou kosten via Google Ads' },
    pot.fmt.adValueYear && { value: pot.fmt.adValueYear, sub: 'advertentiewaarde per jaar', label: 'De jaarlijkse waarde van deze organische posities' },
    unused && { value: fmtNum(unused.count), sub: `samen ${fmtNum(unused.totalVolume)} zoekopdrachten p/m`, label: 'Extra relevante zoektermen, nog onbenut' },
  ].filter(Boolean);

  return (
    <SectionShell num={num} tag="Potentieel" title="Wat levert een top-3 positie op?">
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 18, marginBottom: 34 }}>
        {statCards.map(s => (
          <NotchCard key={s.label} style={{ padding: '22px 20px' }} notch={14}>
            <div style={{ fontSize: 30, fontWeight: 900, color: 'var(--bm-teal-ink)', lineHeight: 1 }}>{s.value}</div>
            <div style={{ fontSize: 12.5, color: '#8AA3A1', margin: '4px 0 10px' }}>{s.sub}</div>
            <div style={{ fontSize: 13.5, fontWeight: 700, color: '#2E4A48', lineHeight: 1.4 }}>{s.label}</div>
          </NotchCard>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.2fr) minmax(0, 0.8fr)', gap: 'clamp(24px, 4vw, 48px)', alignItems: 'start' }} className="gs-two-col">
        <div style={{ fontSize: 15.5, lineHeight: 1.7, color: '#3A5250' }}>
          {data.investment.paragraphs.map((p, i) => (
            <p key={i} style={{ marginTop: i === 0 ? 0 : undefined }}>{p}</p>
          ))}
        </div>

        {trend && (
          <NotchCard style={{ padding: '26px 24px' }} notch={16}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 10, marginBottom: 16 }}>
              <h3 style={{ margin: 0, fontSize: 15, fontWeight: 900 }}>Zoekvraag per maand</h3>
              {trend.peakMonths && (
                <span style={{ fontSize: 11.5, fontWeight: 700, background: '#E9F2F1', color: 'var(--bm-teal-ink)', borderRadius: 999, padding: '3px 10px', whiteSpace: 'nowrap' }}>
                  piek in {trend.peakMonths.join(' & ')}
                </span>
              )}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: `repeat(${trend.months.length}, 1fr)`, gap: 4, alignItems: 'end', height: 110 }}>
              {trend.months.map(m => (
                <div key={`${m.year}-${m.month}`} title={`${NL_MONTHS_SHORT[m.month - 1]}: ${fmtNum(m.volume)}`} style={{
                  height: `${Math.max(4, (m.volume / maxTrend) * 100)}%`,
                  background: 'var(--bm-teal)', opacity: 0.4 + 0.6 * (m.volume / maxTrend), borderRadius: '3px 3px 0 0',
                }}></div>
              ))}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: `repeat(${trend.months.length}, 1fr)`, gap: 4, marginTop: 6 }}>
              {trend.months.map(m => (
                <span key={`${m.year}-${m.month}`} style={{ fontSize: 9.5, textAlign: 'center', color: '#8AA3A1' }}>{NL_MONTHS_SHORT[m.month - 1]}</span>
              ))}
            </div>
            <p style={{ margin: '12px 0 0', fontSize: 12, color: '#8AA3A1' }}>Totaal zoekvolume over jouw zoektermen, afgelopen 12 maanden.</p>
          </NotchCard>
        )}
      </div>

      <p style={{ marginTop: 26, fontSize: 12.5, color: '#8AA3A1' }}>
        Berekend met de gemiddelde klikverdeling per Google-positie en de gemeten zoekvolumes en klikprijzen: een indicatie van de orde van grootte, geen garantie.
      </p>
    </SectionShell>
  );
}

// Social bereik: rekenmodel-doelgroepen per platform + echte concurrent-ads (Ad Library)
function SocialSection({ data, num }) {
  const s = data.socialData;
  const maxAudience = Math.max(...s.platforms.map((p) => p.audience), 1);
  const ads = s.competitorAds || [];

  return (
    <SectionShell num={num} tag="Social bereik" title="Hoeveel mensen kun je bereiken via social?" alt>
      <p style={{ margin: '0 0 26px', fontSize: 15.5, lineHeight: 1.7, color: '#3A5250', maxWidth: 720 }}>{data.social.intro}</p>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(260px, 340px)', gap: 'clamp(24px, 4vw, 48px)', alignItems: 'start' }} className="gs-two-col">
        <div>
          {/* Doelgroepprofiel + bereikbaar per platform */}
          <NotchCard style={{ padding: '26px 24px' }} notch={16}>
            <h3 style={{ margin: '0 0 4px', fontSize: 15, fontWeight: 900 }}>Jouw doelgroep in {s.regionLabel}</h3>
            {s.doelgroep && (
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, flexWrap: 'wrap', margin: '10px 0 6px' }}>
                <span style={{ fontSize: 26, fontWeight: 900, color: 'var(--bm-teal-ink)', fontFamily: "'Lato', sans-serif" }}>≈ {fmtNum(s.doelgroep.omvang)}</span>
                <span style={{ fontSize: 13.5, color: '#3A5250' }}>{s.doelgroep.omschrijving}</span>
              </div>
            )}
            <p style={{ margin: '0 0 18px', fontSize: 12.5, color: '#8AA3A1' }}>Daarvan bereikbaar per platform:</p>
            {s.platforms.map((p) => (
              <div key={p.key} style={{ marginBottom: 14 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', fontSize: 13.5, marginBottom: 5 }}>
                  <span style={{ fontWeight: 700, color: '#2E4A48' }}>{p.label}</span>
                  <span style={{ color: '#5A7472' }}>≈ {fmtNum(p.audience)} mensen</span>
                </div>
                <div style={{ height: 12, background: '#EEF4F3', borderRadius: 999 }}>
                  <div style={{ width: `${Math.max(3, (p.audience / maxAudience) * 100)}%`, height: '100%', borderRadius: 999, background: 'var(--bm-teal)' }}></div>
                </div>
              </div>
            ))}
            <div style={{ marginTop: 18, paddingTop: 16, borderTop: '1px solid #E4EDEC', display: 'flex', alignItems: 'baseline', gap: 12, flexWrap: 'wrap' }}>
              {s.fullReach ? (
                <React.Fragment>
                  <span style={{ fontSize: 26, fontWeight: 900, color: 'var(--bm-teal-ink)', fontFamily: "'Lato', sans-serif" }}>~ €{fmtNum(s.fullReach.monthlyCost)} p/m</span>
                  <span style={{ fontSize: 13.5, color: '#3A5250' }}>kost het indicatief om je volledige doelgroep (≈ {fmtNum(s.fullReach.audience)} mensen) elke maand te bereiken op Facebook/Instagram</span>
                </React.Fragment>
              ) : (
                <React.Fragment>
                  <span style={{ fontSize: 26, fontWeight: 900, color: 'var(--bm-teal-ink)', fontFamily: "'Lato', sans-serif" }}>≈ {fmtNum(s.reach.people)}</span>
                  <span style={{ fontSize: 13.5, color: '#3A5250' }}>mensen per maand te bereiken op Facebook/Instagram met ~€{s.reach.budget} advertentiebudget</span>
                </React.Fragment>
              )}
            </div>
          </NotchCard>

          {/* Concurrenten die nu adverteren */}
          {ads.length > 0 && (
            <NotchCard style={{ padding: '22px 24px', marginTop: 22 }} notch={16}>
              <h3 style={{ margin: '0 0 12px', fontSize: 15, fontWeight: 900 }}>Wie adverteert er nú op Meta?</h3>
              {ads.map((a) => (
                <div key={a.domain} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 0', borderTop: '1px solid #F0F5F4', fontSize: 13.5 }}>
                  <span style={{ fontWeight: 700, color: '#2E4A48' }}>{a.domain.replace(/^www\./, '')}</span>
                  {a.activeAds > 0 ? (
                    <span style={{ fontSize: 12, fontWeight: 700, background: '#FDEFD9', color: '#B96A12', borderRadius: 999, padding: '4px 12px' }}>
                      ✓ actief · {a.activeAds}{a.cappedAt ? '+' : ''} advertenties
                    </span>
                  ) : (
                    <span style={{ fontSize: 12, fontWeight: 700, background: '#EEF4F3', color: '#5A7472', borderRadius: 999, padding: '4px 12px' }}>geen actieve advertenties</span>
                  )}
                </div>
              ))}

              {/* Voorbeeldadvertenties (echte creatives uit de Ad Library) */}
              {ads.some((a) => a.preview) && (
                <div style={{ marginTop: 18 }}>
                  <p style={{ margin: '0 0 10px', fontSize: 12.5, color: '#8AA3A1' }}>Zo zien hun advertenties eruit:</p>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 12 }}>
                    {ads.filter((a) => a.preview).map((a) => {
                      const pv = a.preview;
                      return (
                        <a key={a.domain} href={pv.adLibraryUrl || undefined} target="_blank" rel="noopener noreferrer"
                          style={{ display: 'block', border: '1px solid #E4EDEC', borderRadius: 10, overflow: 'hidden', background: '#fff', textDecoration: 'none', color: 'inherit' }}>
                          {pv.image && (
                            <div style={{ position: 'relative' }}>
                              <img src={pv.image} alt={`Advertentie van ${a.domain.replace(/^www\./, '')}`}
                                style={{ display: 'block', width: '100%', aspectRatio: '4 / 3', objectFit: 'cover' }} />
                              {pv.isVideo && (
                                <span style={{ position: 'absolute', top: 8, right: 8, fontSize: 10.5, fontWeight: 700, background: 'rgba(15,32,31,0.72)', color: '#fff', borderRadius: 999, padding: '3px 9px' }}>▶ video</span>
                              )}
                            </div>
                          )}
                          <div style={{ padding: '10px 12px' }}>
                            <div style={{ fontSize: 12, fontWeight: 800, color: '#2E4A48', marginBottom: 3 }}>{pv.pageName || a.domain.replace(/^www\./, '')}</div>
                            {pv.title && <div style={{ fontSize: 12.5, fontWeight: 700, color: '#3A5250', marginBottom: 3 }}>{pv.title}</div>}
                            {pv.text && (
                              <div style={{ fontSize: 12, lineHeight: 1.5, color: '#5A7472', display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{pv.text}</div>
                            )}
                            {pv.adLibraryUrl && <div style={{ marginTop: 6, fontSize: 11.5, fontWeight: 700, color: 'var(--bm-teal)' }}>Bekijk in Ad Library ↗</div>}
                          </div>
                        </a>
                      );
                    })}
                  </div>
                </div>
              )}
              <p style={{ margin: '12px 0 0', fontSize: 12, color: '#8AA3A1' }}>Bron: openbare Meta Ad Library, advertenties gericht op Nederland.</p>
            </NotchCard>
          )}
        </div>

        {/* Duiding */}
        <NotchCard style={{ padding: '26px 24px', background: 'var(--bm-dark)', color: '#fff' }} notch={16}>
          <h3 style={{ margin: '0 0 10px', fontSize: 16, fontWeight: 900, color: '#fff' }}>Wat betekent dit?</h3>
          <p style={{ margin: 0, fontSize: 14.5, lineHeight: 1.65, color: '#C6DBD9' }}>{data.social.insight}</p>
        </NotchCard>
      </div>

      <p style={{ marginTop: 26, fontSize: 12.5, color: '#8AA3A1' }}>
        Doelgroepen: Brandmerck-rekenmodel {s.edition} o.b.v. Newcom Nationale Social Media Onderzoek en CBS-bevolkingscijfers{s.regionAssumed ? ' (verzorgingsgebied als aanname)' : ''}; kostenindicatie o.b.v. gemiddelde Nederlandse advertentieprijzen (CPM).
      </p>
    </SectionShell>
  );
}

function MidCta({ onCta }) {
  return (
    <section style={{ background: 'var(--bm-dark)', padding: '52px clamp(20px, 6vw, 72px)' }}>
      <div style={{ maxWidth: 1080, margin: '0 auto', display: 'flex', flexWrap: 'wrap', alignItems: 'center', justifyContent: 'space-between', gap: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 22, maxWidth: 680 }}>
          <img src="images/expert-erwin.jpg" alt="Erwin Hoekstra"
            style={{ width: 96, height: 96, flex: '0 0 auto', borderRadius: '50%', objectFit: 'cover', objectPosition: 'center 20%' }} />
          <div>
            <h2 style={{ color: '#fff', fontWeight: 900, fontSize: 'clamp(20px, 2.6vw, 27px)', margin: '0 0 8px' }}>
              Benieuwd wat dit concreet voor jou betekent?
            </h2>
            <p style={{ color: '#B7D2CF', fontSize: 15, margin: 0, lineHeight: 1.6 }}>
              Plan een vrijblijvend gesprek met een van onze 40+ marketingdeskundigen en ontvang een
              échte strategie op maat. Samenwerken kan al vanaf €1.000 per maand.
            </p>
          </div>
        </div>
        <CtaButton big onClick={onCta}>Bespreek dit plan</CtaButton>
      </div>
    </section>
  );
}

function ReviewsSection() {
  const { useEffect, useRef } = React;
  const data = useReviewsData();
  const trackRef = useRef(null);
  const pausedRef = useRef(false);

  const reviews = data?.reviews || REVIEWS_FALLBACK;

  function slide(dir) {
    const el = trackRef.current;
    if (!el) return;
    const step = (el.children[0]?.offsetWidth || 320) + 22;
    const atEnd = el.scrollLeft + el.clientWidth >= el.scrollWidth - 10;
    if (dir > 0 && atEnd) el.scrollTo({ left: 0, behavior: 'smooth' });
    else el.scrollBy({ left: dir * step, behavior: 'smooth' });
  }

  // Rustig automatisch doorschuiven; pauzeert zolang de muis erop staat
  useEffect(() => {
    const iv = setInterval(() => { if (!pausedRef.current) slide(1); }, 6000);
    return () => clearInterval(iv);
  }, [reviews.length]);

  const arrowStyle = {
    width: 42, height: 42, borderRadius: '50%', border: '1.5px solid #C9DAD8', background: '#fff',
    color: 'var(--bm-teal-ink)', fontSize: 18, fontWeight: 900, cursor: 'pointer',
    display: 'grid', placeItems: 'center', boxShadow: '0 4px 12px rgba(6,40,38,0.10)', flex: '0 0 auto',
  };

  return (
    <section style={{ background: 'var(--bm-mist)', padding: '58px clamp(20px, 6vw, 72px)' }}>
      <div style={{ maxWidth: 1080, margin: '0 auto' }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', justifyContent: 'space-between', gap: 16, marginBottom: 28 }}>
          <div>
            <SectionTag>Klantervaringen</SectionTag>
            <h2 style={{ fontWeight: 900, fontSize: 'clamp(22px, 2.8vw, 30px)', color: '#12302E', margin: '14px 0 0' }}>
              Dit zeggen ondernemers over Brandmerck
            </h2>
          </div>
          <ReviewBadge />
        </div>

        {/* Slider: swipe/scroll-snap + pijlen, alleen positieve reviews */}
        <style>{`.gs-reviews-track { scrollbar-width: none; } .gs-reviews-track::-webkit-scrollbar { display: none; }`}</style>
        <div ref={trackRef} className="gs-reviews-track"
          onMouseEnter={() => { pausedRef.current = true; }}
          onMouseLeave={() => { pausedRef.current = false; }}
          style={{ display: 'flex', gap: 22, overflowX: 'auto', scrollSnapType: 'x mandatory', padding: '4px 2px 10px' }}>
          {reviews.map((r, i) => (
            <NotchCard key={i} style={{
              padding: '26px 24px', display: 'flex', flexDirection: 'column', gap: 14,
              flex: '0 0 auto', width: 'min(320px, 82vw)', scrollSnapAlign: 'start',
            }} notch={14}>
              <div style={{ color: '#F4B400', fontSize: 15, letterSpacing: 2 }}>{'★'.repeat(Math.max(1, Math.round(r.rating5 || 5)))}</div>
              <p style={{
                margin: 0, fontSize: 14.5, lineHeight: 1.65, color: '#3A5250', flex: 1,
                display: '-webkit-box', WebkitLineClamp: 7, WebkitBoxOrient: 'vertical', overflow: 'hidden',
              }}>“{r.text}”</p>
              <div>
                <div style={{ fontWeight: 900, fontSize: 14, color: '#12302E' }}>{r.name}</div>
                <div style={{ fontSize: 12.5, color: '#8AA3A1' }}>{r.source === 'feedbackcompany' ? 'Review via The Feedback Company' : 'Review via Google'}</div>
              </div>
            </NotchCard>
          ))}
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 14 }}>
          <p style={{ margin: 0, fontSize: 13, color: '#8AA3A1' }}>
            Alle beoordelingen zijn afkomstig van klanten via Google en The Feedback Company.
          </p>
          <div style={{ display: 'flex', gap: 10 }}>
            <button type="button" aria-label="Vorige reviews" onClick={() => slide(-1)} style={arrowStyle}>‹</button>
            <button type="button" aria-label="Volgende reviews" onClick={() => slide(1)} style={arrowStyle}>›</button>
          </div>
        </div>
      </div>
    </section>
  );
}

function TeamBand() {
  return (
    <section style={{ position: 'relative', minHeight: 340, display: 'flex', alignItems: 'flex-end', overflow: 'hidden' }}>
      <img src="images/teamfoto.jpg" alt="Het team van Brandmerck"
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center 55%' }} />
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(9,43,41,0.15) 30%, rgba(9,43,41,0.85) 100%)' }}></div>
      <div style={{ position: 'relative', width: '100%', maxWidth: 1080, margin: '0 auto', padding: '120px clamp(20px, 6vw, 72px) 34px', display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', alignItems: 'flex-end', gap: 16 }}>
        <div>
          <SectionTag>Het team</SectionTag>
          <h2 style={{ color: '#fff', fontWeight: 900, fontSize: 'clamp(20px, 2.6vw, 27px)', margin: '12px 0 0', textShadow: '0 2px 12px rgba(0,0,0,0.4)' }}>
            40+ deskundigen, één doel: jouw groei
          </h2>
        </div>
      </div>
    </section>
  );
}

function ChannelsSection({ data, num }) {
  return (
    <SectionShell num={num} tag="Kanaalstrategie" title="Per kanaal: zo pakken we het aan">
      <div style={{ display: 'grid', gap: 22 }}>
        {data.channels.map((c, i) => {
          const expert = EXPERTS[c.key] || EXPERTS.sea;
          return (
            <NotchCard key={c.key} style={{ padding: '30px 30px 26px' }} notch={16}>
              <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 12, marginBottom: 12 }}>
                <span style={{ fontWeight: 900, fontSize: 22, color: 'var(--bm-teal)', fontFamily: "'Lato', sans-serif" }}>{String(i + 1).padStart(2, '0')}</span>
                <h3 style={{ margin: 0, fontSize: 19, fontWeight: 900 }}>{c.name}</h3>
                <span style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: '0.8px', textTransform: 'uppercase', color: 'var(--bm-cta-1)', border: '1.5px solid var(--bm-cta-1)', borderRadius: 999, padding: '4px 12px' }}>{c.tag}</span>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)', gap: 'clamp(18px, 3vw, 40px)' }} className="gs-two-col">
                <p style={{ margin: 0, fontSize: 15, lineHeight: 1.65, color: '#3A5250' }}>{c.why}</p>
                <div>
                  <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 8, fontSize: 14.5, color: '#2E4A48' }}>
                    {c.plan.map(p => <li key={p} style={{ display: 'flex', gap: 0 }}><Check /><span>{p}</span></li>)}
                  </ul>
                  <div style={{ marginTop: 14, fontSize: 13, fontWeight: 700, color: '#5A7472' }}>› {c.budget}</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 16, paddingTop: 14, borderTop: '1px solid #E4EDEC' }}>
                    <img src={expert.photo} alt={expert.name}
                      style={{ width: 48, height: 48, flex: '0 0 auto', borderRadius: '50%', objectFit: 'cover', objectPosition: 'center 20%' }} />
                    <div>
                      <div style={{ fontWeight: 900, fontSize: 13.5, color: '#12302E' }}>{expert.name}</div>
                      <div style={{ fontSize: 12.5, color: '#8AA3A1' }}>{expert.role}</div>
                    </div>
                  </div>
                </div>
              </div>
            </NotchCard>
          );
        })}
      </div>
    </SectionShell>
  );
}

function ContactSection({ lead, scanId, formRef }) {
  const { useState } = React;
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [email, setEmail] = useState(lead.email || '');
  const [sent, setSent] = useState(false);
  const [error, setError] = useState('');

  async function submit(e) {
    e.preventDefault();
    if (!name.trim()) { setError('Vul je naam in'); return; }
    if (!/^\S+@\S+\.\S+$/.test(email.trim())) { setError('Vul een geldig e-mailadres in'); return; }
    setError('');
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ scanId, name: name.trim(), phone: phone.trim(), email: email.trim() }),
      });
      if (!res.ok) {
        const d = await res.json().catch(() => ({}));
        setError(d.error || 'Versturen mislukt. Probeer het opnieuw.');
        return;
      }
      setSent(true);
    } catch (err) {
      setError('Versturen mislukt. Controleer je verbinding.');
    }
  }

  return (
    <section ref={formRef} style={{ background: 'var(--bm-dark)', padding: '64px clamp(20px, 6vw, 72px) 80px' }}>
      <div style={{ maxWidth: 1080, margin: '0 auto', display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(320px, 420px)', gap: 'clamp(28px, 5vw, 64px)', alignItems: 'center' }} className="gs-two-col">
        <div>
          <SectionTag>Volgende stap</SectionTag>
          <h2 style={{ color: '#fff', fontWeight: 900, fontSize: 'clamp(24px, 3vw, 32px)', margin: '16px 0 14px' }}>
            Van indicatie naar échte strategie
          </h2>
          <p style={{ color: '#C6DBD9', fontSize: 15.5, lineHeight: 1.7, margin: '0 0 18px' }}>
            Deze scan geeft een eerste richting. Een strateeg van Brandmerck vertaalt het naar een
            concreet plan: doelen, budgetverdeling en een aanpak die elke maand beter wordt.
          </p>
          <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: 10, color: '#E4F0EF', fontSize: 15 }}>
            <li><Check />Vrijblijvend gesprek van 30 minuten</li>
            <li><Check />Strategie op maat, geen losse acties</li>
            <li><Check />Volledige marketingafdeling vanaf €1.000 per maand</li>
          </ul>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginTop: 26 }}>
            <img src="images/expert-erwin.jpg" alt="Erwin Hoekstra"
              style={{ width: 64, height: 64, flex: '0 0 auto', borderRadius: '50%', objectFit: 'cover', objectPosition: 'center 20%' }} />
            <div>
              <div style={{ color: '#fff', fontWeight: 900, fontSize: 15 }}>Erwin Hoekstra</div>
              <div style={{ color: '#8FB5B1', fontSize: 13.5 }}>Marketingstrateeg &amp; co-founder</div>
            </div>
          </div>
        </div>
        <NotchCard style={{ padding: '32px 30px 28px' }}>
          {sent ? (
            <div style={{ textAlign: 'center', padding: '24px 0' }}>
              <div style={{ width: 54, height: 54, borderRadius: '50%', background: 'var(--bm-teal)', color: '#fff', display: 'grid', placeItems: 'center', fontSize: 26, margin: '0 auto 14px' }}>✓</div>
              <h3 style={{ margin: '0 0 8px', fontSize: 20, fontWeight: 900 }}>Aanvraag ontvangen</h3>
              <p style={{ margin: 0, color: '#5A7472', fontSize: 14.5, lineHeight: 1.6 }}>
                Een strateeg neemt binnen één werkdag contact met je op om het gesprek in te plannen.
              </p>
            </div>
          ) : (
            <div>
              <h3 style={{ margin: '0 0 4px', fontSize: 20, fontWeight: 900 }}>Plan je gesprek</h3>
              <p style={{ margin: '0 0 18px', color: '#5A7472', fontSize: 13.5 }}>Gratis en vrijblijvend</p>
              <form onSubmit={submit} style={{ display: 'grid', gap: 13 }}>
                <input value={name} onChange={e => setName(e.target.value)} placeholder="Je naam" className="gs-input" />
                <input value={phone} onChange={e => setPhone(e.target.value)} placeholder="Telefoonnummer (optioneel)" className="gs-input" />
                <input value={email} onChange={e => setEmail(e.target.value)} placeholder="E-mailadres" type="email" className="gs-input" />
                {error && <div style={{ color: '#C4441C', fontSize: 13, fontWeight: 700 }}>{error}</div>}
                <CtaButton type="submit" big style={{ width: '100%' }}>Bespreek met een strateeg</CtaButton>
              </form>
            </div>
          )}
        </NotchCard>
      </div>
    </section>
  );
}

function ResultPage({ lead, answers, data, scanId, benchView, onRestart, onResearchDone }) {
  const formRef = React.useRef(null);
  function toForm() {
    const el = formRef.current;
    if (el) window.scrollTo({ top: el.offsetTop - 10, behavior: 'smooth' });
  }
  // Sectie 03 is het onderzoeksformulier totdat de research-data binnen is.
  const hasResearch = !!data.research;
  // Dynamische sectienummering: secties zonder data verdwijnen zonder gat
  const hasComp = hasResearch && !!(data.competitorData && data.competitorData.list && data.competitorData.list.length && data.competitors);
  const hasPot = hasResearch && !!(data.potentialData && data.investment);
  const hasSocial = hasResearch && !!(data.socialData && data.social);
  let n = 3;
  const compNum = hasComp ? ++n : null;
  const potNum = hasPot ? ++n : null;
  const socNum = hasSocial ? ++n : null;
  const chanNum = ++n;
  const pad = (x) => String(x).padStart(2, '0');

  return (
    <div data-screen-label="Resultaat / Groeiplan" style={{ background: '#fff' }}>
      <ResultHeader lead={lead} data={data} />
      <BenchmarkSection answers={answers} benchView={benchView} data={data} num="01" />
      <StrategySection data={data} num="02" />
      <MidCta onCta={toForm} />
      {hasResearch
        ? <DataSection data={data} num="03" />
        : <ResearchSection data={data} scanId={scanId} onResearchDone={onResearchDone} num="03" />}
      {hasComp && <CompetitorsSection data={data} num={pad(compNum)} />}
      {hasPot && <PotentialSection data={data} num={pad(potNum)} />}
      {hasSocial && <SocialSection data={data} num={pad(socNum)} />}
      <ReviewsSection />
      <ChannelsSection data={data} num={pad(chanNum)} />
      <TeamBand />
      <ContactSection lead={lead} scanId={scanId} formRef={formRef} />
      <footer style={{ background: 'var(--bm-darker)', padding: '20px clamp(20px, 6vw, 72px)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
        <span style={{ color: '#6E8F8C', fontSize: 12.5 }}>© Brandmerck · Online marketingbureau in Friesland</span>
        <button onClick={onRestart} style={{ background: 'none', border: 'none', color: '#6E8F8C', fontSize: 12.5, cursor: 'pointer', textDecoration: 'underline', fontFamily: "'Lato', sans-serif" }}>
          Scan opnieuw doen
        </button>
      </footer>
    </div>
  );
}

Object.assign(window, { ResultPage });
