// Agency Audit — het rapport: oordeel, vijf scores met duiding, activiteit
// (wat er draait), zichtbaarheid (interactieve grafiek, zoektermen,
// vergelijkbare partijen), meting en merknaam, landingspagina's met kwaliteit,
// samenwerking en vragen, conclusie, de onafhankelijke second opinion en
// datakwaliteit. Niet-afgenomen kanalen komen nergens voor.
function AuditReport({ report, onRestart }) {
  const { audit, scores, narrative, findings, meta } = report;
  const n = Object.fromEntries((findings || []).filter((f) => f.status === 'ok' || f.status === 'partial').map((f) => [f.source, f.normalized]));
  const verdict = AUDIT_VERDICTS[scores?.verdict] || AUDIT_VERDICTS.insufficient_data;
  const fmt = (v) => new Intl.NumberFormat('nl-NL').format(Math.round(v || 0));
  const short = (u) => String(u || '').replace(/^https?:\/\/(www\.)?/, '').replace(/\/$/, '') || '/';
  const daysAgo = (d) => (d == null ? 'onbekend' : d === 0 ? 'vandaag' : d === 1 ? 'gisteren' : `${d} dagen geleden`);
  const cap = (s) => (s ? s.charAt(0).toUpperCase() + s.slice(1) : s);
  const toCta = () => document.getElementById('au-contact')?.scrollIntoView({ behavior: 'smooth' });

  const services = audit.services || [];
  const known = services.length > 0;
  const show = { sea: !known || services.includes('sea'), meta: !known || services.includes('meta'), seo: !known || services.includes('seo') };
  const budgetLabel = (meta?.budgets || []).find((b) => b.key === audit.monthlyBudget)?.label;
  const serviceLabels = services.map((s) => (meta?.services || []).find((x) => x.key === s)?.label || s);

  const seo = n['seo-data'];
  const tc = show.sea ? n['transparency-center'] : null;
  const metaN = show.meta ? n['meta-ad-library'] : null;
  const cr = n['site-crawl']; const sm = n.sitemap; const tg = n['tag-detect']; const sb = n['serp-brand']; const lp = n['landing-pages']; const comp = n['seo-competitors'];
  const brand = scores?.brand_bidding?.facts || {};
  const landingRows = scores?.landing?.facts?.rows || [];
  const conclusie = narrative?.conclusie;
  const expectedSources = (meta?.expected || []).filter((s) => (s !== 'meta-ad-library' || show.meta) && (s !== 'transparency-center' || show.sea));
  const th = { textAlign: 'left', color: '#5A7472', fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.8px', padding: '6px 8px 6px 0', fontWeight: 800 };
  const td = { padding: '7px 8px 7px 0', borderTop: '1px solid #F0F5F4', fontSize: 13 };

  // Tag-rij: aanwezig, vuurt (vóór/na toestemming), met ID's
  const tagRow = (label, t, { fire = true } = {}) => {
    if (!t) return null;
    const ids = t.ids?.length ? ` · ${t.ids.slice(0, 2).join(', ')}` : '';
    if (!t.present) return [label, 'niet gevonden', '#C4441C'];
    if (!fire) return [label, `aanwezig${ids}`, 'var(--au-green)'];
    if (t.firedAfterConsent === true) return [label, `vuurt${t.firedBeforeConsent ? ', ook vóór toestemming' : ' na toestemming'}${ids}`, 'var(--au-green)'];
    if (t.firedAfterConsent === false) return [label, `aanwezig, vuurt niet${ids}`, 'var(--au-orange)'];
    return [label, `aanwezig, vuren niet gemeten${ids}`, '#8A5A0B'];
  };
  const consentWord = { denied: 'standaard alles geweigerd', partial: 'standaard deels toegestaan', granted: 'standaard alles toegestaan', declared: 'in de code gezet' }[tg?.consentMode?.defaultState];

  return (
    <div data-screen-label="Audit rapport" style={{ background: '#fff' }}>
      {/* Kop + oordeel */}
      <header style={{ background: 'var(--bm-dark)', padding: '22px clamp(20px, 6vw, 72px) 56px' }}>
        <div style={{ maxWidth: 1040, margin: '0 auto' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12, marginBottom: 34 }}>
            <BmLogo light />
            <CtaButton onClick={toCta}>Second opinion aanvragen</CtaButton>
          </div>
          <SectionTag>Agency audit · {audit.domain}</SectionTag>
          <div className="gs-two-col" style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 240px', gap: 'clamp(24px, 4vw, 56px)', alignItems: 'center', marginTop: 18 }}>
            <div>
              <h1 style={{ color: '#fff', fontWeight: 900, fontSize: 'clamp(28px, 3.6vw, 42px)', margin: '0 0 12px', lineHeight: 1.12, textWrap: 'balance' }}>{verdict.label}</h1>
              <p style={{ color: '#C6DBD9', fontSize: 16.5, lineHeight: 1.65, margin: '0 0 18px', maxWidth: 640 }}>{narrative?.summary || verdict.text}</p>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {AUDIT_DIMENSIONS.map((d) => <Stoplicht key={d.key} light={scores?.[d.key]?.light || 'grey'}>{d.label}{scores?.[d.key]?.score != null ? ` ${scores[d.key].score}` : ''}</Stoplicht>)}
              </div>
              {(serviceLabels.length || budgetLabel) && (
                <p style={{ color: '#8FB5B1', fontSize: 13, margin: '16px 0 0' }}>
                  Beoordeeld op {serviceLabels.length ? serviceLabels.join(', ') : 'alle kanalen met data'}{budgetLabel ? ` · budget ${budgetLabel} per maand` : ''}.
                </p>
              )}
            </div>
            <NotchCard style={{ padding: '18px 16px 10px', display: 'grid', placeItems: 'center' }} notch={16}>
              <ScoreGauge score={scores?.total ?? null} tone={verdict.tone} />
              <div style={{ fontSize: 12, color: '#8AA3A1', marginTop: -4 }}>totaalscore</div>
            </NotchCard>
          </div>
        </div>
      </header>

      {/* Vijf deelscores */}
      <AuditSection tag="De vijf metingen" title="Wat we zagen, per onderdeel">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 18 }}>
          {AUDIT_DIMENSIONS.map((d) => {
            const s = scores?.[d.key] || {}; const t = narrative?.[d.key] || {};
            const st = LIGHT_STYLE[s.light] || LIGHT_STYLE.grey;
            return (
              <NotchCard key={d.key} style={{ padding: '22px 22px', borderTop: `3px solid ${st.bar}` }} notch={14}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 10 }}>
                  <div>
                    <div style={{ fontSize: 11.5, fontWeight: 800, color: '#8AA3A1', textTransform: 'uppercase', letterSpacing: '0.8px' }}>{d.sub}</div>
                    <h3 style={{ margin: '2px 0 0', fontSize: 18, fontWeight: 900 }}>{d.label}</h3>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: 30, fontWeight: 900, color: '#12302E', lineHeight: 1, fontFamily: "'Lato', sans-serif" }}>{s.score ?? '–'}</div>
                    <Stoplicht light={s.light || 'grey'} />
                  </div>
                </div>
                <div style={{ height: 6, background: '#EEF4F3', borderRadius: 999, margin: '12px 0 14px' }}>
                  <div style={{ width: `${Math.max(2, s.score || 0)}%`, height: '100%', borderRadius: 999, background: st.bar }}></div>
                </div>
                {t.finding && <p style={{ margin: '0 0 8px', fontSize: 14, lineHeight: 1.6, color: '#12302E', fontWeight: 700 }}>{t.finding}</p>}
                {t.evidence && <p style={{ margin: '0 0 8px', fontSize: 13.5, lineHeight: 1.6, color: '#3A5250' }}>{t.evidence}</p>}
                {t.meaning && <p style={{ margin: '0 0 12px', fontSize: 13.5, lineHeight: 1.6, color: 'var(--bm-teal-ink)', fontWeight: 700 }}>{t.meaning}</p>}
                <Punten items={t.strengths} tone="good" />
                <Punten items={t.issues} tone="bad" style={{ marginTop: t.strengths?.length ? 6 : 0 }} />
              </NotchCard>
            );
          })}
        </div>
      </AuditSection>

      {/* Activiteit: tijdlijn + wat er draait */}
      {(scores?.activity?.facts?.channels?.length > 0 || tc || metaN || (show.seo && cr?.ok)) && (
        <AuditSection tag="Activiteit" title="Wanneer is er voor het laatst iets gebeurd, en wat draait er nu?" alt>
          {scores?.activity?.facts?.channels?.length > 0 && (
            <NotchCard style={{ padding: '22px 24px' }} notch={16}>
              <ActivityTimeline channels={scores.activity.facts.channels} />
              <p style={{ margin: '10px 0 0', fontSize: 12, color: '#8AA3A1' }}>Laatste nieuwe advertentie (Google Ads Transparency Center{show.meta ? ', Meta Ad Library' : ''}), laatste inhoudelijke wijziging van de website (sitemap, Wayback Machine, HTTP-headers) en laatste blogbericht. Alleen afgenomen kanalen tellen mee.</p>
            </NotchCard>
          )}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 18, marginTop: 18 }}>
            {tc && (
              <NotchCard style={{ padding: '22px 24px' }} notch={14}>
                <h3 style={{ margin: '0 0 10px', fontSize: 15, fontWeight: 900 }}>Google Ads</h3>
                <Rijen rows={[
                  ['Advertenties in het Transparency Center', tc.cappedAt ? `${tc.cappedAt}+` : String(tc.adCount)],
                  ['Afgelopen week nog getoond', String(tc.activeAdCount), tc.activeAdCount > 0 ? 'var(--au-green)' : '#C4441C'],
                  ['Nieuwste advertentie gestart', daysAgo(tc.daysSinceLastNewAd)],
                  ['Formats', Object.entries(tc.adsPerFormat || {}).map(([k, v]) => `${v}× ${k}`).join(', ') || 'geen'],
                  seo ? ['Betaalde zoektermen (Semrush)', fmt(seo.paidKeywords)] : null,
                  seo ? ['Geschat betaald verkeer', `${fmt(seo.paidTraffic)} p/m`] : null,
                  seo ? ['Actief in de laatste 12 maanden', `${seo.paidActiveMonths12m} van 12 maanden`] : null,
                ]} />
                {tc.transparencyUrl && <a href={tc.transparencyUrl} target="_blank" rel="noopener noreferrer" style={{ display: 'inline-block', marginTop: 12, fontSize: 12.5, fontWeight: 700 }}>Bekijk de advertenties in het Transparency Center ↗</a>}
              </NotchCard>
            )}
            {tc && seo?.adCopies?.length > 0 && (
              <NotchCard style={{ padding: '22px 24px' }} notch={14}>
                <h3 style={{ margin: '0 0 4px', fontSize: 15, fontWeight: 900 }}>Zo adverteer je nu</h3>
                <p style={{ margin: '0 0 12px', fontSize: 12.5, color: '#8AA3A1' }}>Unieke advertentieteksten uit Google (Semrush), met de pagina waar ze op landen.</p>
                {seo.adCopies.slice(0, 3).map((a, i) => (
                  <div key={i} style={{ padding: '10px 0', borderTop: '1px solid #F0F5F4' }}>
                    <div style={{ fontSize: 13.5, fontWeight: 800, color: '#1A0DAB', lineHeight: 1.35 }}>{a.title}</div>
                    <div style={{ fontSize: 12.5, color: '#3A5250', lineHeight: 1.5, marginTop: 3, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{a.description}</div>
                    <div style={{ fontSize: 11.5, color: '#1F6B43', marginTop: 3, fontFamily: 'monospace' }}>{short(a.url)}</div>
                  </div>
                ))}
                {seo.adCopies.length > 3 && <p style={{ margin: '8px 0 0', fontSize: 12, color: '#8AA3A1' }}>En nog {seo.adCopies.length - 3} andere teksten.</p>}
              </NotchCard>
            )}
            {tc && seo?.topPaidKeywords?.length > 0 && (
              <NotchCard style={{ padding: '22px 24px' }} notch={14}>
                <h3 style={{ margin: '0 0 4px', fontSize: 15, fontWeight: 900 }}>Betaalde zoektermen met het meeste verkeer</h3>
                <p style={{ margin: '0 0 8px', fontSize: 12.5, color: '#8AA3A1' }}>Positie van je advertentie en zoekvolume per maand (Semrush, NL).</p>
                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                  <thead><tr><th style={th}>Zoekterm</th><th style={{ ...th, textAlign: 'right' }}>Positie</th><th style={{ ...th, textAlign: 'right' }}>Volume</th></tr></thead>
                  <tbody>{seo.topPaidKeywords.slice(0, 7).map((k) => <tr key={k.keyword}><td style={td}>{k.keyword}</td><td style={{ ...td, textAlign: 'right', fontWeight: 800 }}>{k.position ?? '–'}</td><td style={{ ...td, textAlign: 'right', color: '#5A7472' }}>{fmt(k.volume)}</td></tr>)}</tbody>
                </table>
              </NotchCard>
            )}
            {metaN && (
              <NotchCard style={{ padding: '22px 24px' }} notch={14}>
                <h3 style={{ margin: '0 0 10px', fontSize: 15, fontWeight: 900 }}>Meta-advertenties</h3>
                {['low', 'none'].includes(metaN.matchConfidence) ? (
                  <p style={{ margin: 0, fontSize: 13.5, color: '#3A5250', lineHeight: 1.6 }}>De advertenties die de Meta Ad Library op "{metaN.query}" teruggeeft, passen niet bij de bedrijfsnaam. Dit kanaal is daarom niet beoordeeld.</p>
                ) : (
                  <Rijen rows={[
                    ['Actieve advertenties', String(metaN.activeCount), metaN.activeCount > 0 ? 'var(--au-green)' : '#C4441C'],
                    ['Nieuwste advertentie gestart', daysAgo(metaN.daysSinceLastNewAd)],
                    ['Platforms', (metaN.platforms || []).join(', ') || 'geen'],
                  ]} />
                )}
                {metaN.sampleAds?.[0] && !['low', 'none'].includes(metaN.matchConfidence) && <p style={{ margin: '10px 0 0', fontSize: 12.5, color: '#3A5250', fontStyle: 'italic' }}>“{(metaN.sampleAds[0].title || metaN.sampleAds[0].text || '').slice(0, 140)}”</p>}
                <a href={metaN.adLibraryUrl} target="_blank" rel="noopener noreferrer" style={{ display: 'inline-block', marginTop: 12, fontSize: 12.5, fontWeight: 700 }}>Bekijk in de Meta Ad Library ↗</a>
              </NotchCard>
            )}
            {show.seo && cr?.ok && (
              <NotchCard style={{ padding: '22px 24px' }} notch={14}>
                <h3 style={{ margin: '0 0 10px', fontSize: 15, fontWeight: 900 }}>Website en content</h3>
                <Rijen rows={[
                  ["Pagina's gecrawld", String(cr.pageCount)],
                  ['Kapotte links', String(cr.brokenLinks?.length || 0), (cr.brokenLinks?.length || 0) > 0 ? '#C4441C' : 'var(--au-green)'],
                  ['Laatste wijzigingssignaal', daysAgo(cr.daysSinceLastChange)],
                  sm?.found ? ["URL's in de sitemap", fmt(sm.urlCount)] : null,
                  sm?.found ? ['Gewijzigd in de laatste 30 / 90 dagen', `${sm.lastmodDistribution?.d30 ?? 0} / ${sm.lastmodDistribution?.d90 ?? 0}`] : null,
                  ['Blog of nieuws', cr.lastModifiedSignals?.blogLastPost ? `laatste bericht ${cr.lastModifiedSignals.blogLastPost}` : 'niet gevonden', cr.lastModifiedSignals?.blogLastPost ? undefined : '#8A5A0B'],
                  ['Conversiepunten op de homepage', [cr.homepage?.hasForm && 'formulier', cr.homepage?.hasPhone && 'telefoonnummer'].filter(Boolean).join(', ') || 'geen', (cr.homepage?.hasForm || cr.homepage?.hasPhone) ? 'var(--au-green)' : '#C4441C'],
                ]} />
              </NotchCard>
            )}
          </div>
        </AuditSection>
      )}

      {/* Zichtbaarheid: interactieve grafiek, cijfers, zoektermen, vergelijkbare partijen */}
      {seo?.trend12m?.length > 0 && (
        <AuditSection tag="Zichtbaarheid" title="Groei je mee met vergelijkbare partijen?">
          <div className="gs-two-col" style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.4fr) minmax(260px, 0.6fr)', gap: 22, alignItems: 'start' }}>
            <NotchCard style={{ padding: '22px 24px' }} notch={16}>
              <h3 style={{ margin: '0 0 12px', fontSize: 15, fontWeight: 900 }}>Twaalf maanden, jij naast de markt</h3>
              <InteractiveTrendChart ownLabel={audit.domain} own={seo.trend12m} competitors={comp?.competitors || []} showPaid={show.sea} />
            </NotchCard>
            <NotchCard style={{ padding: '22px 24px', background: 'var(--bm-dark)', color: '#fff' }} notch={16}>
              <h3 style={{ margin: '0 0 12px', fontSize: 15, fontWeight: 900, color: '#fff' }}>In cijfers</h3>
              {[
                ['Organisch verkeer', `${fmt(seo.organicTraffic)} p/m`],
                ['Organische zoektermen', fmt(seo.organicKeywords)],
                ['12-maandstrend organisch', seo.organicTrendPct != null ? `${seo.organicTrendPct >= 0 ? '+' : ''}${seo.organicTrendPct}%` : 'onbekend'],
                ['Markt (mediaan)', comp?.benchmark?.organicTrendMedian != null ? `${comp.benchmark.organicTrendMedian >= 0 ? '+' : ''}${Math.round(comp.benchmark.organicTrendMedian)}%` : 'geen benchmark'],
                show.sea ? ['Betaald verkeer', `${fmt(seo.paidTraffic)} p/m`] : null,
                show.sea ? ['12-maandstrend betaald', seo.paidTrendPct != null ? `${seo.paidTrendPct >= 0 ? '+' : ''}${seo.paidTrendPct}%` : 'onbekend'] : null,
                ['Autoriteit', seo.backlinks?.authority != null ? `${seo.backlinks.authority}/100` : '–'],
                ['Verwijzende websites', seo.backlinks?.refDomains != null ? fmt(seo.backlinks.refDomains) : '–'],
              ].filter(Boolean).map(([k, v]) => (
                <div key={k} style={{ display: 'flex', justifyContent: 'space-between', gap: 10, padding: '7px 0', borderTop: '1px solid rgba(255,255,255,0.12)', fontSize: 13.5 }}>
                  <span style={{ color: '#8FB5B1' }}>{k}</span><span style={{ fontWeight: 800 }}>{v}</span>
                </div>
              ))}
              <p style={{ margin: '12px 0 0', fontSize: 11, color: '#6E8F8C' }}>Bron: Semrush (NL), schattingen.</p>
            </NotchCard>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: 18, marginTop: 18 }}>
            {seo.topOrganicKeywords?.length > 0 && (
              <NotchCard style={{ padding: '22px 24px' }} notch={14}>
                <h3 style={{ margin: '0 0 4px', fontSize: 15, fontWeight: 900 }}>Waar je organisch op gevonden wordt</h3>
                <p style={{ margin: '0 0 8px', fontSize: 12.5, color: '#8AA3A1' }}>Zoektermen die het meeste organische verkeer opleveren, met je positie in Google.</p>
                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                  <thead><tr><th style={th}>Zoekterm</th><th style={{ ...th, textAlign: 'right' }}>Positie</th><th style={{ ...th, textAlign: 'right' }}>Volume</th><th style={{ ...th, textAlign: 'right' }}>Aandeel</th></tr></thead>
                  <tbody>{seo.topOrganicKeywords.slice(0, 8).map((k) => <tr key={k.keyword}><td style={td}>{k.keyword}</td><td style={{ ...td, textAlign: 'right', fontWeight: 800, color: k.position != null && k.position <= 3 ? 'var(--au-green)' : k.position != null && k.position <= 10 ? '#12302E' : '#8A5A0B' }}>{k.position ?? '–'}</td><td style={{ ...td, textAlign: 'right', color: '#5A7472' }}>{fmt(k.volume)}</td><td style={{ ...td, textAlign: 'right', color: '#5A7472' }}>{k.trafficPct}%</td></tr>)}</tbody>
                </table>
              </NotchCard>
            )}
            {comp?.competitors?.length > 0 && (
              <NotchCard style={{ padding: '22px 24px' }} notch={14}>
                <h3 style={{ margin: '0 0 4px', fontSize: 15, fontWeight: 900 }}>Vergelijkbare partijen</h3>
                <p style={{ margin: '0 0 8px', fontSize: 12.5, color: '#8AA3A1' }}>Domeinen die op dezelfde zoektermen scoren als jij, met hun organische groei over twaalf maanden.</p>
                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                  <thead><tr><th style={th}>Domein</th><th style={{ ...th, textAlign: 'right' }}>Organisch p/m</th><th style={{ ...th, textAlign: 'right' }}>12 mnd</th><th style={{ ...th, textAlign: 'right' }}>Gedeeld</th></tr></thead>
                  <tbody>
                    <tr><td style={{ ...td, fontWeight: 900, color: 'var(--bm-cta-2)' }}>{audit.domain} ← jij</td><td style={{ ...td, textAlign: 'right', fontWeight: 800 }}>{fmt(seo.organicTraffic)}</td><td style={{ ...td, textAlign: 'right', fontWeight: 800, color: (seo.organicTrendPct || 0) >= 0 ? 'var(--au-green)' : '#C4441C' }}>{seo.organicTrendPct != null ? `${seo.organicTrendPct >= 0 ? '+' : ''}${seo.organicTrendPct}%` : '–'}</td><td style={{ ...td, textAlign: 'right', color: '#5A7472' }}>–</td></tr>
                    {comp.competitors.slice(0, 3).map((c) => <tr key={c.domain}><td style={td}>{c.domain}</td><td style={{ ...td, textAlign: 'right' }}>{fmt(c.organicTraffic)}</td><td style={{ ...td, textAlign: 'right', fontWeight: 800, color: (c.organicTrendPct || 0) >= 0 ? 'var(--au-green)' : '#C4441C' }}>{c.organicTrendPct != null ? `${c.organicTrendPct >= 0 ? '+' : ''}${c.organicTrendPct}%` : '–'}</td><td style={{ ...td, textAlign: 'right', color: '#5A7472' }}>{c.commonKeywords ? fmt(c.commonKeywords) : '–'}</td></tr>)}
                  </tbody>
                </table>
                <p style={{ margin: '8px 0 0', fontSize: 11.5, color: '#8AA3A1' }}>Gedeeld = aantal zoektermen waarop jullie allebei in de top-100 staan.</p>
              </NotchCard>
            )}
          </div>
          {n['serp-keywords']?.perKeyword?.length > 0 && (
            <NotchCard style={{ padding: '22px 24px', marginTop: 18 }} notch={14}>
              <h3 style={{ margin: '0 0 4px', fontSize: 15, fontWeight: 900 }}>Kernzoektermen: sta jij er, en wie adverteert er?</h3>
              <p style={{ margin: '0 0 8px', fontSize: 12.5, color: '#8AA3A1' }}>Zoektermen {n['serp-keywords'].keywordsSource === 'intake' ? 'die je hebt opgegeven' : 'afgeleid uit je website'}; live Google-zoekresultaat (NL), aangevuld met de Semrush-database.</p>
              <div style={{ overflowX: 'auto' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 560 }}>
                  <thead><tr><th style={th}>Zoekterm</th>{show.sea && <th style={th}>Eigen advertentie</th>}<th style={{ ...th, textAlign: 'right' }}>Organisch</th>{show.sea && <th style={th}>Andere adverteerders</th>}</tr></thead>
                  <tbody>
                    {n['serp-keywords'].perKeyword.map((k) => (
                      <tr key={k.keyword}>
                        <td style={{ ...td, fontWeight: 700 }}>{k.keyword}</td>
                        {show.sea && <td style={{ ...td, color: k.ownAdPresent ? 'var(--au-green)' : '#8A5A0B', fontWeight: 800 }}>{k.ownAdPresent ? `ja${k.ownAdPosition != null ? `, positie ${k.ownAdPosition}` : ''}` : 'nee'}</td>}
                        <td style={{ ...td, textAlign: 'right', fontWeight: 800, color: k.ownOrganicPos != null && k.ownOrganicPos <= 3 ? 'var(--au-green)' : k.ownOrganicPos != null && k.ownOrganicPos <= 10 ? '#12302E' : '#8A5A0B' }}>{k.ownOrganicPos != null ? `#${k.ownOrganicPos}` : 'niet in top-10'}</td>
                        {show.sea && <td style={{ ...td, color: '#5A7472', fontSize: 12.5 }}>{k.advertisers?.length ? k.advertisers.slice(0, 3).map((a) => a.domain).join(', ') : 'geen gezien'}</td>}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </NotchCard>
          )}
          <AuditCta text="Wil je weten of dit beeld klopt en wat erachter zit? In een second opinion kijkt een onafhankelijke specialist met alleen-lezen toegang mee in je Google Ads- en SEO-data. Je bureau hoeft er niets van te merken." />
        </AuditSection>
      )}

      {/* Meting + merknaam */}
      {(tg || sb) && (
        <AuditSection tag="Meting en merknaam" title="Wordt er gemeten, en wie pakt jouw naam?" alt>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 18 }}>
            {tg && (
              <NotchCard style={{ padding: '22px 24px' }} notch={14}>
                <h3 style={{ margin: '0 0 10px', fontSize: 15, fontWeight: 900 }}>Tags op de website</h3>
                <Rijen rows={[
                  tagRow('Google Tag Manager', tg.gtm, { fire: false }),
                  tagRow('Google Analytics 4', tg.ga4),
                  show.sea ? tagRow('Google Ads-conversietag', tg.adsConversion) : null,
                  show.meta ? tagRow('Meta-pixel', tg.metaPixel) : null,
                  ['Consent mode', tg.consentMode?.present ? `ja${consentWord ? `, ${consentWord}` : ''}` : 'niet gevonden', tg.consentMode?.present ? 'var(--au-green)' : '#C4441C'],
                  ['Cookiebanner', tg.cmp?.vendor ? `${cap(tg.cmp.vendor)}${tg.cmp.acceptClicked ? ' (geaccepteerd in de meting)' : ''}` : 'niet herkend', tg.cmp?.vendor ? '#12302E' : '#8A5A0B'],
                  tg.serverSide?.present ? ['Server-side tagging', `ja, via ${tg.serverSide.host}`, 'var(--au-green)'] : null,
                ]} />
                <p style={{ margin: '10px 0 0', fontSize: 11.5, color: '#8AA3A1' }}>{tg.method === 'browser' ? 'Gemeten in een echte browser, vóór en na het accepteren van cookies. "Ook vóór toestemming" is met consent mode toegestaan: dat zijn cookieloze metingen.' : 'Statisch uit de broncode; of tags daadwerkelijk vuren is niet gemeten.'}</p>
              </NotchCard>
            )}
            {sb?.queries?.[0] && (() => {
              const q = sb.queries[0];
              const ownAd = brand.ownAdPresent ?? q.ownAdPresent;
              const ownTxt = ownAd
                ? `ja${brand.ownAdPosition != null ? `, positie ${brand.ownAdPosition}` : ''}${brand.ownAdSource === 'semrush' ? ' (Semrush)' : brand.ownAdSource === 'serp' ? ' (live zoekresultaat)' : ''}`
                : 'nee';
              const orgTxt = brand.organicPosition != null
                ? `#${brand.organicPosition}${brand.organicPositionSemrush != null && brand.organicPositionSerp != null && brand.organicPositionSemrush !== brand.organicPositionSerp ? ` (Semrush NL #${brand.organicPositionSemrush}, live zoekresultaat #${brand.organicPositionSerp})` : ''}`
                : q.organicPosition != null ? `#${q.organicPosition}` : 'niet in de top-10';
              return (
                <NotchCard style={{ padding: '22px 24px' }} notch={14}>
                  <h3 style={{ margin: '0 0 4px', fontSize: 15, fontWeight: 900 }}>Google-zoekopdracht "{q.query}"</h3>
                  <p style={{ margin: '0 0 12px', fontSize: 12.5, color: '#8AA3A1' }}>Wat iemand ziet die jouw naam intikt: live zoekresultaat, aangevuld met de Semrush NL-database.</p>
                  <Rijen rows={[
                    ['Eigen advertentie op je naam', ownTxt, ownAd ? 'var(--au-green)' : '#8A5A0B'],
                    ['Concurrent-advertenties erboven', q.competitorAdsAbove?.length ? q.competitorAdsAbove.map((c) => c.domain).join(', ') : 'geen', q.competitorAdsAbove?.length ? '#C4441C' : 'var(--au-green)'],
                    ['Jouw organische positie', orgTxt, brand.organicPosition != null && brand.organicPosition <= 3 ? 'var(--au-green)' : '#8A5A0B'],
                    brand.brandPaidKeywords?.length ? ['Betaalde merktermen', brand.brandPaidKeywords.slice(0, 3).map((k) => `"${k.keyword}" (${k.position})`).join(', ')] : null,
                    brand.paidBrandShare != null && show.sea ? ['Aandeel merktermen in betaald verkeer', `${Math.round(brand.paidBrandShare * 100)}%`] : null,
                  ]} />
                  {q.organicTop?.length > 0 && <p style={{ margin: '10px 0 0', fontSize: 11.5, color: '#8AA3A1' }}>Organische top in het live zoekresultaat: {q.organicTop.join(' · ')}</p>}
                </NotchCard>
              );
            })()}
          </div>
          <AuditCta compact text="Conversiemeting, consent en attributie zie je van buiten niet volledig. In de second opinion controleren we ze in je Google Ads- en GA4-account en leggen we in gewone taal uit wat het betekent." />
        </AuditSection>
      )}

      {/* Landingspagina's met kwaliteit */}
      {lp?.perUrl?.length > 0 && (() => {
        const rows = lp.perUrl;
        const reachable = rows.filter((u) => u.statusCode === 200).length;
        const withConv = rows.filter((u) => u.hasConversionPoint).length;
        const matches = rows.map((u) => u.adMessageMatch).filter((v) => v != null);
        const matchAvg = matches.length ? Math.round((matches.reduce((a, b) => a + b, 0) / matches.length) * 100) : null;
        const speeds = rows.map((u) => u.speedScore).filter((v) => v != null);
        const speedAvg = speeds.length ? Math.round(speeds.reduce((a, b) => a + b, 0) / speeds.length) : null;
        const tile = (k, v, color) => (
          <div key={k} style={{ background: '#fff', borderRadius: 12, padding: '14px 16px', boxShadow: '0 4px 14px rgba(6,40,38,0.06)' }}>
            <div style={{ fontSize: 24, fontWeight: 900, color: color || '#12302E', lineHeight: 1, fontFamily: "'Lato', sans-serif" }}>{v}</div>
            <div style={{ fontSize: 12, color: '#5A7472', marginTop: 4 }}>{k}</div>
          </div>
        );
        return (
          <AuditSection tag="Landingspagina's" title="Waar landen betaalde bezoekers, en maakt de pagina het af?">
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: 12, marginBottom: 18 }}>
              {tile("Pagina's gemeten", String(rows.length))}
              {tile('Bereikbaar', `${reachable} van ${rows.length}`, reachable === rows.length ? 'var(--au-green)' : '#C4441C')}
              {tile('Met conversiepunt', `${withConv} van ${rows.length}`, withConv === rows.length ? 'var(--au-green)' : withConv ? '#8A5A0B' : '#C4441C')}
              {tile('Overeenkomst met advertentie', matchAvg != null ? `${matchAvg}%` : '–', matchAvg == null ? '#8AA3A1' : matchAvg >= 25 ? 'var(--au-green)' : '#8A5A0B')}
              {tile('Laadsnelheid mobiel', speedAvg != null ? `${speedAvg}/100` : 'niet gemeten', speedAvg == null ? '#8AA3A1' : speedAvg >= 70 ? 'var(--au-green)' : speedAvg >= 50 ? '#8A5A0B' : '#C4441C')}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 18 }}>
              {rows.map((u) => {
                const r = landingRows.find((x) => x.url === u.url) || {};
                const st = LIGHT_STYLE[r.light] || LIGHT_STYLE.grey;
                return (
                  <NotchCard key={u.url} style={{ padding: '20px 22px', borderTop: `3px solid ${st.bar}` }} notch={14}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'flex-start' }}>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: 11.5, fontWeight: 800, color: '#8AA3A1', textTransform: 'uppercase', letterSpacing: '0.8px' }}>{u.source === 'google_ads' ? 'Google Ads-landingspagina' : u.source === 'meta' ? 'Meta-landingspagina' : 'Homepage'}</div>
                        <h3 style={{ margin: '2px 0 4px', fontSize: 15.5, fontWeight: 900, lineHeight: 1.3 }}>{u.title || u.h1 || short(u.url)}</h3>
                        <div style={{ fontSize: 11.5, color: '#5A7472', fontFamily: 'monospace', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{short(u.url)}</div>
                      </div>
                      <div style={{ textAlign: 'right', flex: '0 0 auto' }}>
                        <div style={{ fontSize: 24, fontWeight: 900, color: '#12302E', lineHeight: 1, fontFamily: "'Lato', sans-serif" }}>{r.score ?? '–'}</div>
                        <Stoplicht light={r.light || 'grey'} />
                      </div>
                    </div>
                    {u.adText && <p style={{ margin: '12px 0 0', padding: '8px 12px', background: 'var(--bm-mist)', borderRadius: 8, fontSize: 12.5, color: '#3A5250', lineHeight: 1.5, fontStyle: 'italic' }}>Advertentie: “{u.adText.slice(0, 140)}{u.adText.length > 140 ? '…' : ''}”</p>}
                    <div style={{ marginTop: 12, display: 'grid', gap: 6 }}>
                      <Punten items={r.good} tone="good" />
                      <Punten items={r.bad} tone="bad" />
                      {r.notes?.length > 0 && <p style={{ margin: 0, fontSize: 12, color: '#8AA3A1' }}>{r.notes.join(' · ')}</p>}
                    </div>
                  </NotchCard>
                );
              })}
            </div>
            <AuditCta text="Of een landingspagina echt klanten oplevert, blijkt pas uit de kosten per aanvraag en de uitval per pagina. Die cijfers nemen we mee in de second opinion." />
          </AuditSection>
        );
      })()}

      {/* Samenwerking + vragen */}
      <AuditSection tag="Samenwerking" title="Wat krijg je van je bureau, en wat vraag je?" alt>
        <div className="gs-two-col" style={{ display: 'grid', gridTemplateColumns: 'minmax(260px, 0.8fr) minmax(0, 1.2fr)', gap: 22, alignItems: 'start' }}>
          <NotchCard style={{ padding: '22px 24px' }} notch={14}>
            <h3 style={{ margin: '0 0 10px', fontSize: 15, fontWeight: 900 }}>Samenwerking met je bureau</h3>
            {(meta?.deliverables || []).map((d) => {
              const has = (audit.agencyDeliverables || []).includes(d.key);
              return (
                <div key={d.key} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 0', borderTop: '1px solid #F0F5F4', fontSize: 13.5, color: has ? '#12302E' : '#8AA3A1' }}>
                  <span style={{ width: 20, height: 20, borderRadius: '50%', background: has ? 'var(--au-green)' : '#DCE8E6', color: '#fff', display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 900, flex: '0 0 auto' }}>{has ? '✓' : '–'}</span>{d.label}
                </div>
              );
            })}
            {narrative?.samenwerking && <p style={{ margin: '12px 0 0', fontSize: 13.5, lineHeight: 1.6, color: '#3A5250' }}>{narrative.samenwerking}</p>}
            {!Array.isArray(audit.agencyDeliverables) && !narrative?.samenwerking && <p style={{ margin: '12px 0 0', fontSize: 12.5, color: '#8AA3A1' }}>Je hebt de checklist niet ingevuld; de vragen hiernaast helpen je dit zelf te toetsen.</p>}
            {Array.isArray(audit.agencyDeliverables) && audit.agencyDeliverables.length === 0 && !narrative?.samenwerking && <p style={{ margin: '12px 0 0', fontSize: 12.5, color: '#8AA3A1' }}>Je gaf aan geen van deze vier van je bureau te krijgen. Elk punt is een vraag waard.</p>}
          </NotchCard>
          <NotchCard style={{ padding: '24px 26px', background: 'var(--bm-dark)', color: '#fff' }} notch={16}>
            <h3 style={{ margin: '0 0 6px', fontSize: 17, fontWeight: 900, color: '#fff' }}>Vijf vragen voor je bureau</h3>
            <p style={{ margin: '0 0 14px', fontSize: 13, color: '#8FB5B1' }}>Elke vraag komt uit een concrete bevinding. Een ontwijkend antwoord zegt genoeg.</p>
            <ol style={{ margin: 0, paddingLeft: 22, display: 'grid', gap: 10 }}>
              {(narrative?.questionsForAgency || []).map((q, i) => <li key={i} style={{ fontSize: 14.5, lineHeight: 1.55, color: '#E4F0EF' }}>{q.question}</li>)}
            </ol>
            <p style={{ margin: '16px 0 0', fontSize: 12.5, color: '#8FB5B1', lineHeight: 1.5 }}>Wil je de antwoorden onafhankelijk laten toetsen? <button type="button" onClick={toCta} style={{ background: 'none', border: 'none', padding: 0, color: '#FFD9C2', fontWeight: 800, cursor: 'pointer', fontFamily: "'Lato', sans-serif", fontSize: 12.5, textDecoration: 'underline' }}>Daar is de second opinion voor.</button></p>
          </NotchCard>
        </div>
      </AuditSection>

      {/* Conclusie */}
      {conclusie && (
        <AuditSection tag="Conclusie" title="Wat dit rapport zegt, in het kort">
          <NotchCard style={{ padding: '26px 28px' }} notch={16}>
            <p style={{ margin: 0, fontSize: 15.5, lineHeight: 1.7, color: '#12302E' }}>{conclusie.samenvatting}</p>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 22, marginTop: 20 }}>
              <div>
                <h3 style={{ margin: '0 0 10px', fontSize: 14, fontWeight: 900, color: '#1F6B43', textTransform: 'uppercase', letterSpacing: '0.6px' }}>Wat aantoonbaar goed staat</h3>
                <Punten items={conclusie.sterk} tone="good" />
              </div>
              <div>
                <h3 style={{ margin: '0 0 10px', fontSize: 14, fontWeight: 900, color: '#9B3413', textTransform: 'uppercase', letterSpacing: '0.6px' }}>Wat als eerste aandacht vraagt</h3>
                <Punten items={conclusie.aandacht} tone="bad" />
              </div>
            </div>
            {conclusie.volgende_stap && <div style={{ marginTop: 20, padding: '14px 18px', background: 'var(--bm-mist)', borderRadius: 12, fontSize: 14, lineHeight: 1.6, color: '#12302E' }}><b>Volgende stap:</b> {conclusie.volgende_stap}</div>}
          </NotchCard>
          <AuditCta text="Twijfel je of dit beeld klopt, of wil je de antwoorden van je bureau laten toetsen? Een second opinion is onafhankelijk, kijkt mét toegang tot je accounts en verplicht je nergens toe." />
        </AuditSection>
      )}

      {/* Second opinion */}
      <AuditContact audit={audit} />

      {/* Datakwaliteit */}
      <AuditSection tag="Datakwaliteit" title="Waar dit beeld op rust" alt>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 8 }}>
          {expectedSources.map((src) => {
            const f = (findings || []).find((x) => x.source === src);
            const st = f?.status || 'missing';
            const color = st === 'ok' ? 'var(--au-green)' : st === 'partial' ? 'var(--au-orange)' : st === 'failed' ? '#C4441C' : '#8AA3A1';
            const label = st === 'ok' ? 'gemeten' : st === 'partial' ? 'deels gemeten' : st === 'failed' ? 'mislukt' : st === 'not_applicable' ? 'niet van toepassing' : 'niet uitgevoerd';
            return <div key={src} style={{ fontSize: 13, color: '#3A5250', display: 'flex', gap: 8, alignItems: 'center' }}><span style={{ width: 8, height: 8, borderRadius: '50%', background: color, flex: '0 0 auto' }}></span>{AUDIT_CHECK_LABELS[src] || src} <span style={{ color: '#8AA3A1' }}>· {label}</span></div>;
          })}
        </div>
        <p style={{ margin: '16px 0 0', fontSize: 12.5, color: '#8AA3A1', maxWidth: 720 }}>{narrative?.dataNotes || ''} Alle metingen zijn gedaan op publiek zichtbare data, zonder toegang tot accounts. Scores en het oordeel volgen vaste regels; de tekst licht ze toe. Dit is een indicatie, geen accountantsverklaring.</p>
      </AuditSection>

      <SecondOpinionBar />

      <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" }}>Audit opnieuw doen</button>
      </footer>
    </div>
  );
}

// Uitleg en aanvraag van de onafhankelijke second opinion (Google Ads en SEO)
function AuditContact({ audit }) {
  const { useState } = React;
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [email, setEmail] = useState('');
  const [focus, setFocus] = useState('');
  const [state, setState] = useState('idle');
  async function submit(e) {
    e.preventDefault();
    if (!name.trim() || !/^\S+@\S+\.\S+$/.test(email.trim())) { setState('invalid'); return; }
    setState('busy');
    try {
      const res = await fetch('/api/contact', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ scanId: `audit:${audit.id}`, name: name.trim(), phone: phone.trim(), email: email.trim(), kind: 'second_opinion', focus }) });
      if (res.ok) gsTrack('second_opinion_requested', { product: 'audit', audit_id: audit.id, focus: focus || '' }, audit.id);
      setState(res.ok ? 'done' : 'error');
    } catch { setState('error'); }
  }
  const chip = (active) => ({ borderRadius: 999, padding: '7px 14px', fontSize: 12.5, fontWeight: 800, cursor: 'pointer', border: '1.5px solid ' + (active ? 'var(--bm-teal)' : '#D8E5E3'), background: active ? 'var(--bm-teal)' : '#fff', color: active ? '#fff' : '#3A5250', fontFamily: "'Lato', sans-serif" });
  return (
    <section id="au-contact" style={{ background: 'var(--bm-dark)', padding: '64px clamp(20px, 6vw, 72px) 80px' }}>
      <div className="gs-two-col" style={{ maxWidth: 1040, margin: '0 auto', display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(300px, 420px)', gap: 'clamp(24px, 5vw, 64px)', alignItems: 'start' }}>
        <div>
          <SectionTag>Second opinion</SectionTag>
          <h2 style={{ color: '#fff', fontWeight: 900, fontSize: 'clamp(24px, 3vw, 34px)', margin: '14px 0 12px', textWrap: 'balance' }}>Een onafhankelijke second opinion op je Google Ads en SEO</h2>
          <p style={{ color: '#C6DBD9', fontSize: 15.5, lineHeight: 1.65, margin: '0 0 18px', maxWidth: 560 }}>Deze audit kijkt van buiten. Een second opinion kijkt van binnen: een senior specialist beoordeelt met alleen-lezen toegang je Google Ads-, GA4- en Search Console-data en vertelt je in gewone taal wat er goed gaat, wat beter kan en of je krijgt wat je betaalt.</p>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: 18, marginBottom: 18 }}>
            <div>
              <div style={{ fontSize: 11.5, fontWeight: 800, color: '#8FB5B1', textTransform: 'uppercase', letterSpacing: '0.8px', marginBottom: 8 }}>Wat je krijgt</div>
              <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'grid', gap: 7 }}>
                {['Beoordeling van campagnes, zoektermen, biedingen en kosten per aanvraag (Google Ads)', 'Beoordeling van techniek, content, autoriteit en posities (SEO)', 'Controle of de conversiemeting klopt en of de rapportage van je bureau overeenkomt met de data', 'Een kort verslag met prioriteiten en een gesprek van dertig minuten om het door te nemen'].map((t) => (
                  <li key={t} style={{ display: 'flex', gap: 9, color: '#E4F0EF', fontSize: 13.5, lineHeight: 1.5 }}><span style={{ color: 'var(--bm-cta-1)', fontWeight: 900 }}>✓</span><span>{t}</span></li>
                ))}
              </ul>
            </div>
            <div>
              <div style={{ fontSize: 11.5, fontWeight: 800, color: '#8FB5B1', textTransform: 'uppercase', letterSpacing: '0.8px', marginBottom: 8 }}>Zo werkt het</div>
              <ol style={{ margin: 0, paddingLeft: 18, display: 'grid', gap: 7, color: '#E4F0EF', fontSize: 13.5, lineHeight: 1.5 }}>
                <li>Je vraagt de second opinion aan; we bellen kort om af te stemmen wat je wilt weten.</li>
                <li>Je geeft alleen-lezen toegang tot de accounts (vijf minuten werk, we leggen uit hoe). Je bureau hoeft hier niets van te merken.</li>
                <li>Binnen vijf werkdagen ontvang je de bevindingen en nemen we ze samen door.</li>
              </ol>
            </div>
          </div>
          <p style={{ color: '#8FB5B1', fontSize: 13, lineHeight: 1.6, margin: '0 0 14px', maxWidth: 560 }}>Onafhankelijk: we beoordelen, we verkopen niet. Je zit nergens aan vast en je beslist zelf wat je met de uitkomst doet.</p>
          <ReviewBadge />
        </div>
        <NotchCard style={{ padding: '28px 26px' }} notch={16}>
          {state === 'done' ? (
            <div style={{ textAlign: 'center', padding: '10px 0' }}><div style={{ fontSize: 18, fontWeight: 900 }}>Dank je wel</div><p style={{ color: '#5A7472', fontSize: 14, margin: '6px 0 0' }}>We bellen je binnen één werkdag om af te stemmen wat je wilt weten.</p></div>
          ) : (
            <form onSubmit={submit} style={{ display: 'grid', gap: 12 }}>
              <div style={{ fontSize: 16, fontWeight: 900, color: '#12302E' }}>Vraag de second opinion aan</div>
              <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Je naam" className="gs-input" autoComplete="name" />
              <input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="E-mailadres" type="email" className="gs-input" autoComplete="email" />
              <input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="Telefoonnummer (optioneel)" className="gs-input" autoComplete="tel" />
              <div>
                <div style={{ fontSize: 12.5, color: '#5A7472', marginBottom: 6 }}>Waar wil je vooral zekerheid over? <span style={{ color: '#8AA3A1' }}>(optioneel)</span></div>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {[['ads', 'Google Ads'], ['seo', 'SEO'], ['beide', 'Allebei']].map(([k, l]) => <button key={k} type="button" onClick={() => setFocus(focus === k ? '' : k)} style={chip(focus === k)}>{l}</button>)}
                </div>
              </div>
              {state === 'invalid' && <div style={{ color: '#C4441C', fontSize: 13, fontWeight: 700 }}>Vul je naam en een geldig e-mailadres in.</div>}
              {state === 'error' && <div style={{ color: '#C4441C', fontSize: 13, fontWeight: 700 }}>Versturen mislukte. Probeer het opnieuw.</div>}
              <CtaButton type="submit" style={{ width: '100%', opacity: state === 'busy' ? 0.6 : 1 }}>{state === 'busy' ? 'Even geduld…' : 'Vraag de second opinion aan'}</CtaButton>
              <p style={{ margin: 0, fontSize: 11.5, color: '#8AA3A1', textAlign: 'center', lineHeight: 1.5 }}>Vrijblijvend. We reageren binnen één werkdag en bellen eerst om te kijken of het zinvol is.</p>
            </form>
          )}
        </NotchCard>
      </div>
    </section>
  );
}

// Slanke balk onderin zodra de lezer voorbij de vijf metingen is; verdwijnt bij
// het aanvraagblok en na wegklikken (per sessie).
function SecondOpinionBar() {
  const { useState, useEffect } = React;
  const [visible, setVisible] = useState(false);
  const [dismissed, setDismissed] = useState(() => { try { return sessionStorage.getItem('au_bar') === '1'; } catch { return false; } });
  useEffect(() => {
    if (dismissed) return undefined;
    const target = document.getElementById('au-contact');
    let nearForm = false;
    const update = () => setVisible(window.scrollY > 900 && !nearForm);
    const io = target && 'IntersectionObserver' in window ? new IntersectionObserver((es) => { nearForm = es.some((e) => e.isIntersecting); update(); }, { rootMargin: '0px 0px -10% 0px' }) : null;
    if (io) io.observe(target);
    window.addEventListener('scroll', update, { passive: true });
    update();
    return () => { if (io) io.disconnect(); window.removeEventListener('scroll', update); };
  }, [dismissed]);
  if (dismissed || !visible) return null;
  return (
    <div style={{ position: 'fixed', left: 0, right: 0, bottom: 0, zIndex: 50, background: 'rgba(18,48,46,0.96)', color: '#fff', padding: '10px clamp(16px, 4vw, 40px)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 14, flexWrap: 'wrap', boxShadow: '0 -6px 20px rgba(0,0,0,0.18)' }}>
      <span style={{ fontSize: 13.5, color: '#C6DBD9' }}>Wil je zekerheid over dit beeld? Een onafhankelijke specialist kijkt met je mee.</span>
      <CtaButton onClick={() => document.getElementById('au-contact')?.scrollIntoView({ behavior: 'smooth' })} style={{ padding: '9px 16px', fontSize: 12.5 }}>Second opinion aanvragen</CtaButton>
      <button type="button" aria-label="Sluiten" onClick={() => { setDismissed(true); try { sessionStorage.setItem('au_bar', '1'); } catch { /* privémodus */ } }} style={{ background: 'none', border: 'none', color: '#8FB5B1', fontSize: 20, cursor: 'pointer', lineHeight: 1, padding: '2px 6px' }}>×</button>
    </div>
  );
}

Object.assign(window, { AuditReport });
