// 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 second opinion en
// datakwaliteit. Niet-afgenomen kanalen komen nergens voor.
function AuditReport({ report, onRestart }) {
  const { audit, scores, narrative, findings, meta } = report;
  useReportTracking(report?.shareToken, 'basis');
  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 tgMode = tg?.method === 'browser' ? 'browser' : (tg?.method === 'container' || tg?.container?.inspected) ? 'container' : 'static';
  const staticUnknown = tgMode === 'static' && !!tg?.gtm?.present;
  const tagRow = (label, t, { fire = true, homepage = true } = {}) => {
    if (!t) return null;
    const ids = t.ids?.length ? ` · ${t.ids.slice(0, 2).join(', ')}` : '';
    if (!t.present) return staticUnknown ? [label, 'niet vast te stellen (laadt mogelijk via Tag Manager)', '#8A5A0B'] : [label, tgMode === 'container' ? 'niet in de container gevonden' : '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 (!homepage && t.present) return [label, `${t.configuredIn === 'container' ? 'geconfigureerd in Tag Manager' : 'aanwezig'}${ids} (vuurt pas bij een conversie)`, 'var(--au-green)'];
    if (t.firedAfterConsent === false && tg?.cmp?.acceptClicked) return [label, `aanwezig, vuurt niet na toestemming${ids}`, 'var(--au-orange)'];
    if (t.configuredIn === 'container') return [label, `geconfigureerd in Tag Manager${ids}`, 'var(--au-green)'];
    return [label, `aanwezig, vuren niet gemeten${ids}`, '#8A5A0B'];
  };
  const otherTags = Object.entries(tg?.container?.other || {}).filter(([, v]) => v).map(([k]) => ({ microsoft: 'Microsoft Ads', pinterest: 'Pinterest', tiktok: 'TikTok', linkedin: 'LinkedIn', clarity: 'Microsoft Clarity', hotjar: 'Hotjar', snapchat: 'Snapchat' }[k] || k));
  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>

      {/* Disclaimer: buitenkant-meting, alleen een second opinion geeft sluitende antwoorden */}
      <div style={{ background: '#FFF6EA', borderBottom: '1px solid #F5D9B5' }}>
        <div style={{ maxWidth: 1040, margin: '0 auto', padding: '16px clamp(20px, 6vw, 72px)', display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <span aria-hidden="true" style={{ flex: '0 0 auto', width: 26, height: 26, borderRadius: '50%', background: 'var(--bm-cta-1)', color: '#fff', display: 'grid', placeItems: 'center', fontWeight: 900, fontSize: 15, marginTop: 1 }}>!</span>
          <p style={{ margin: 0, fontSize: 13.5, lineHeight: 1.6, color: '#3A5250' }}>
            <b style={{ color: '#12302E' }}>Goed om te weten:</b> deze audit is van buitenaf gemeten, op publieke data en zonder toegang tot je accounts. Een lagere score kan een goede verklaring hebben: een kanaal dat bewust op pauze staat, seizoensinvloed, of meting die anders is ingericht dan wij van buiten kunnen zien. Sluitende antwoorden geeft alleen een second opinion met toegang tot je accounts.
          </p>
        </div>
      </div>

      {/* 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, alignItems: 'start' }}>
          {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'}>{s.facts?.gated ? 'niet van toepassing' : null}</Stoplicht>
                  </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>
                {/* Hoofdpunten eerst (Kevin, 22 sep 2026); het verhaal erachter
                    (bevinding, cijfers, betekenis) uitklapbaar, zodat de kaart
                    niet alles in één keer op je afvuurt. */}
                {(t.strengths?.length || t.issues?.length) ? (
                  <React.Fragment>
                    <Punten items={t.strengths} tone="good" />
                    <Punten items={t.issues} tone="bad" style={{ marginTop: t.strengths?.length ? 6 : 0 }} />
                  </React.Fragment>
                ) : (t.finding && <p style={{ margin: 0, fontSize: 14, lineHeight: 1.6, color: '#12302E', fontWeight: 700 }}>{t.finding}</p>)}
                {(t.finding || t.evidence || t.meaning) && (
                  <details className="au-details">
                    <summary>Details</summary>
                    <div style={{ paddingTop: 10 }}>
                      {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, fontSize: 13.5, lineHeight: 1.6, color: 'var(--bm-teal-ink)', fontWeight: 700 }}>{t.meaning}</p>}
                    </div>
                  </details>
                )}
              </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 4px', fontSize: 15, fontWeight: 900 }}>Google Ads</h3>
                <p style={{ margin: '0 0 8px', fontSize: 12.5, color: '#8AA3A1' }}>Bron: Google Ads Transparency Center (de advertenties die Google zelf toont).</p>
                <Rijen rows={[
                  ['Advertenties in het Transparency Center', tc.cappedAt ? `${tc.cappedAt}+` : String(tc.adCount), tc.adCount > 0 ? 'var(--au-green)' : '#C4441C'],
                  ['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'],
                ]} />
                {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>
            )}

            {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={false} />
            </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'],
                ['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 (geef bij een volgende audit zelf je kernzoektermen op voor een scherper beeld)'}; live Google-zoekresultaat (NL), aangevuld met de Semrush-database. Organisch in de top 10: {n['serp-keywords'].perKeyword.filter((k) => k.ownOrganicPos != null && k.ownOrganicPos <= 10).length} van {n['serp-keywords'].perKeyword.length}.</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 specialist van Brandmerck met alleen-lezen toegang mee in je Google Ads- en SEO-data." />
        </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, { homepage: false }) : null,
                  show.meta ? tagRow('Meta-pixel', tg.metaPixel) : null,
                  ['Consent mode', tg.consentMode?.present ? `ja${consentWord ? `, ${consentWord}` : ''}${tg.consentMode?.source === 'container' ? ' (via Tag Manager)' : ''}` : staticUnknown ? 'niet vast te stellen' : tgMode === 'container' ? 'niet in de container gevonden' : 'niet gevonden', tg.consentMode?.present ? 'var(--au-green)' : staticUnknown ? '#8A5A0B' : '#C4441C'],
                  otherTags.length ? ['Ook geconfigureerd', otherTags.join(', '), '#12302E'] : null,
                  ['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${tg.serverSide.host ? `, via ${tg.serverSide.host}` : ''}`, 'var(--au-green)'] : staticUnknown ? ['Server-side tagging', 'niet vast te stellen', '#8A5A0B'] : ['Server-side tagging', 'niet gevonden', '#8A5A0B'],
                ]} />
                <p style={{ margin: '10px 0 0', fontSize: 11.5, color: '#8AA3A1' }}>{tgMode === '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.${tg.container?.inspected ? ' De Tag Manager-container is daarnaast gelezen.' : ''}`
                  : tgMode === 'container'
                    ? `De Tag Manager-container is gelezen (${tg.container?.tagCount ?? '?'} tags): dit zijn de tags die erin geconfigureerd staan. Of ze daadwerkelijk vuren is niet in een browser gemeten.${tg.container?.shared ? ' Gedeelde container van een platform: alleen de tags voor dit domein zijn geteld.' : ''}`
                    : 'Statisch uit de broncode; de Tag Manager-container kon niet gelezen worden, dus wat via Tag Manager laadt is niet vast te stellen.'}</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,
                  ]} />
                  {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 checked = rows.filter((u) => !u.fetchFailed);
        const reachable = checked.filter((u) => u.statusCode === 200).length;
        const withConv = checked.filter((u) => u.hasConversionPoint).length;
        const paidRows = rows.filter((u) => u.source !== 'homepage');
        const withHead = paidRows.filter((u) => u.headlineMatch);
        const headOk = withHead.filter((u) => u.headlineMatch === 'h1').length;
        const tracked = rows.filter((u) => u.hasTracking === true).length;
        const trackKnown = rows.filter((u) => u.hasTracking != null).length;
        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", checked.length ? String(checked.length) : '–')}
              {tile('Bereikbaar', checked.length ? `${reachable} van ${checked.length}` : 'niet te laden', !checked.length ? '#8AA3A1' : reachable === checked.length ? 'var(--au-green)' : '#C4441C')}
              {tile('Met conversiepunt', checked.length ? `${withConv} van ${checked.length}` : '–', !checked.length ? '#8AA3A1' : withConv === checked.length ? 'var(--au-green)' : withConv ? '#8A5A0B' : '#C4441C')}
              {tile('Kop sluit aan op de advertentie', withHead.length ? `${headOk} van ${withHead.length}` : '–', !withHead.length ? '#8AA3A1' : headOk === withHead.length ? 'var(--au-green)' : headOk ? '#8A5A0B' : '#C4441C')}
              {tile('Meting op de pagina', trackKnown ? `${tracked} van ${trackKnown}` : '–', !trackKnown ? '#8AA3A1' : tracked === trackKnown ? 'var(--au-green)' : '#C4441C')}
              {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${u.keyword ? ` · "${u.keyword}"${u.brand ? ' (merkterm)' : ''}` : ''}` : u.source === 'meta' ? 'Meta-advertentie' : 'Homepage'}{u.pageType ? ` · ${u.pageType === 'webshop' ? 'webshop' : 'leadpagina'}` : ''}</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 (alleen als de checklist is ingevuld of er tekst over is) */}
      {(Array.isArray(audit.agencyDeliverables) || narrative?.samenwerking) && (
      <AuditSection tag="Samenwerking" title="Wat krijg je van je bureau?" alt>
        <div style={{ maxWidth: 640 }}>
          <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.</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.</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 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: een lagere score kan een verklaring hebben die van buiten niet zichtbaar is. Alleen een second opinion met toegang tot je accounts geeft sluitende resultaten.</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 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); reportEvent('second_opinion_verstuurd:formulier'); }
      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 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).</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 }}>Eerlijk: we zijn zelf een marketingbureau en zeggen dat ook. Je krijgt een oordeel op basis van je echte data, 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 specialist van Brandmerck 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 });
