// ====================================================================
// RESULTS, HQ / CORPORATE channel-tab variants
// Portfolio-aggregated views for Paid Search, LSA, Local SEO, Social,
// plus the Demand Gen activation pitch (no perf data, it's not enrolled).
//
// Mounted by pages.jsx ResultsPage when persona === 'hq'. The single-
// location franchisee components (ResultsPpc / ResultsLsa / ResultsSeo /
// ResultsSocial / ResultsDemandGen) are unchanged.
// ====================================================================
const { useState: useStateHQ, useMemo: useMemoHQ } = React;

// Toast shortcut, same pattern as the rest of the app.
const Thq = (t, b, k) => window.toast && window.toast(t, b, k);

// --------------------------------------------------------------------
// SHARED: derive per-channel portfolio rollups from data.hqRollup +
// data.playbookPortfolio.channelAdoption. The rollup gives us per-
// location spend / leads totals; we model each channel's share of
// those totals using a stable per-location modifier so 700 locations
// can show channel-specific spread without inventing a giant table.
// --------------------------------------------------------------------

// Stable hash → 0..1 so each (location, channel) pair gets a deterministic
// modifier. Avoids inventing per-location-per-channel tables in data.js.
const hashFloat = (s) => {
  let h = 2166136261;
  for (let i = 0; i < s.length; i++) {h ^= s.charCodeAt(i);h = Math.imul(h, 16777619);}
  return (h >>> 0) % 10000 / 10000;
};

// Channel-share defaults (% of a location's blended spend), used when a
// location IS enrolled in that channel. Modulated per-location by a
// hash so the spread feels real.
const CHANNEL_BASE = {
  ppc: { spendShare: 0.50, cplBase: 34, leadShare: 0.36 },
  lsa: { spendShare: 0.18, cplBase: 18, leadShare: 0.30 },
  seo: { spendShare: 0.15, cplBase: 12, leadShare: 0.20 }, // organic, low effective CPL
  social: { spendShare: 0.17, cplBase: 28, leadShare: 0.14 }
};

// Determine if a location is "enrolled" in a given channel based on
// the existing services array on each rollup row.
const enrolledIn = (loc, ch) => {
  const map = { ppc: 'ppc', lsa: 'lsa', seo: 'seo', social: 'meta' };
  // Most rollup rows don't have an 'lsa' service entry, model LSA
  // enrollment as ppc-enrolled AND score >= 75 (mirrors brand norm).
  if (ch === 'lsa') return loc.services.includes('ppc') && loc.score >= 72;
  return loc.services.includes(map[ch]);
};

// Per-channel rollup for the entire portfolio.
function useChannelRollup(rollup, ch) {
  return useMemoHQ(() => {
    const base = CHANNEL_BASE[ch];
    const rows = rollup.
    filter((r) => enrolledIn(r, ch)).
    map((r) => {
      const mod = 0.65 + hashFloat(r.unit + ch) * 0.7; // 0.65× .. 1.35×
      const spend = Math.round(r.spend * base.spendShare * mod);
      // Higher score → more efficient; CPL bends ±35% around base.
      const eff = 1 + (80 - r.score) * 0.012;
      const cpl = Math.max(8, Math.round(base.cplBase * eff));
      const leads = Math.round(spend / cpl);
      // Per-location ROAS ranges 3.0..7.5
      const roasMod = 3.0 + (r.score - 60) * 0.10 + (hashFloat(r.unit + ch + 'r') - 0.5) * 1.2;
      const roas = +Math.max(2.5, Math.min(8.2, roasMod)).toFixed(1);
      const rev = Math.round(spend * roas);
      // Impression-share-loss-to-budget proxy: more underfunded → higher loss.
      const playbookTarget = Math.round(base.cplBase * 22 * mod);
      const underfundPct = playbookTarget > spend ? Math.round((playbookTarget - spend) / playbookTarget * 100) : 0;
      return { ...r, spend, cpl, leads, roas, rev, playbookTarget, underfundPct };
    });
    const totalSpend = rows.reduce((s, r) => s + r.spend, 0);
    const totalLeads = rows.reduce((s, r) => s + r.leads, 0);
    const totalRev = rows.reduce((s, r) => s + r.rev, 0);
    const cpl = totalLeads ? Math.round(totalSpend / totalLeads) : 0;
    const roas = totalSpend ? +(totalRev / totalSpend).toFixed(1) : 0;
    return {
      rows,
      totals: { spend: totalSpend, leads: totalLeads, rev: totalRev, cpl, roas, n: rows.length }
    };
  }, [rollup, ch]);
}

// --------------------------------------------------------------------
// SHARED LAYOUT, KPI strip + Top + Underfunded + Health signal card
// Each channel passes its own kpiAccent and HealthSignal node.
// --------------------------------------------------------------------
function HqChannelShell({ data, channelKey, channelLabel, accent, deltas, healthSignal, locale, underfundedFooter }) {
  const rollup = data.hqRollup || [];
  const { rows, totals } = useChannelRollup(rollup, channelKey);

  const top = useMemoHQ(() => [...rows].sort((a, b) => b.leads - a.leads).slice(0, 5), [rows]);
  const underfunded = useMemoHQ(
    () => [...rows].sort((a, b) => b.underfundPct - a.underfundPct).slice(0, 5),
    [rows]
  );

  // Modeled lift if you raised every underfunded location to its playbook target.
  const upliftLeads = underfunded.reduce((s, r) => {
    if (r.playbookTarget <= r.spend) return s;
    const gainSpend = r.playbookTarget - r.spend;
    return s + Math.round(gainSpend / r.cpl);
  }, 0);
  const upliftSpend = underfunded.reduce((s, r) => s + Math.max(0, r.playbookTarget - r.spend), 0);

  // The Paid-Search adoption row in playbookPortfolio gives us the brand-wide enrolled count.
  const adoption = (data.playbookPortfolio?.channelAdoption || []).find((c) => {
    const map = { ppc: 'Paid Search', lsa: 'LSA', seo: 'Local SEO', social: 'Meta' };
    return c.channel === map[channelKey];
  });

  return (
    <>
      {/* ---- HEADER STRIP, quick context above the KPIs ---- */}
      <div style={{
        marginBottom: 12, padding: '10px 14px', background: 'var(--cream)',
        border: '1px dashed var(--cream-3)', borderRadius: 10, fontSize: 12.5,
        color: 'var(--ink-3)', display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap'
      }}>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: accent }} />
        <strong style={{ color: 'var(--ink-2)' }}>{totals.n} locations</strong> running {channelLabel}
        {adoption && <>
          <span style={{ color: 'var(--ink-4)' }}>·</span>
          <span><strong style={{ color: 'var(--terra)' }}>{adoption.belowTarget}</strong> below target</span>
          <span style={{ color: 'var(--ink-4)' }}>·</span>
          <span><strong style={{ color: 'var(--ink-2)' }}>{adoption.notEnrolled}</strong> not enrolled (opp.)</span>
        </>}
        <span style={{ flex: 1 }} />
        <button className="btn btn-quiet btn-xs" onClick={() => Thq('All-locations view',
        `Opening location-by-location ${channelLabel} table.`, 'info')}>All locations →</button>
      </div>

      {/* ---- KPI STRIP ---- */}
      <div className="grid grid-4" style={{ marginBottom: 16 }}>
        <KpiCard label={`Total ${channelLabel} spend`} value={`$${(totals.spend / 1000).toFixed(1)}K`} delta={deltas.spend}
        color={accent} dotColor={accent} />
        <KpiCard label="Total leads" value={totals.leads.toLocaleString()} delta={deltas.leads}
        color="var(--terra)" dotColor="var(--terra)" />
        <KpiCard label="Blended CPL" value={`$${totals.cpl}`} delta={deltas.cpl} invert
        color="var(--sage)" dotColor="var(--sage)" />
        <KpiCard label="Blended ROAS" value={`${totals.roas}x`} delta={deltas.roas}
        color="var(--marigold)" dotColor="var(--marigold)" />
      </div>

      {/* ---- TOP PERFORMERS + UNDERFUNDED side-by-side ---- */}
      <SourceNote>{(channelKey === 'seo' ? 'Source: Google Search Console + GA4' : channelKey === 'lsa' ? 'Source: Google Ads · Local Services Ads' : channelKey === 'social' ? 'Source: Meta' : 'Source: Google Ads') + ' · CPL & ROAS calculated by LOCALACT'}</SourceNote>
      <div className="grid grid-2" style={{ marginBottom: 16 }}>
        <HqChannelLeaderboard
          title="Top performers"
          sub={`Top 5 locations driving ${channelLabel} leads this month`}
          tone="sage"
          channelKey={channelKey}
          rows={top}
          accent={accent} />
        
        <HqUnderfundedCard
          title={locale.underfundedTitle}
          sub={locale.underfundedSub}
          rows={underfunded}
          accent={accent}
          upliftLeads={upliftLeads}
          upliftSpend={upliftSpend}
          channelLabel={channelLabel}
          channelKey={channelKey}
          customFooter={underfundedFooter} />
        
      </div>

      {/* ---- BRAND-WIDE HEALTH SIGNAL ---- */}
      <SourceNote>{channelKey === 'seo' ? 'Calculated by LOCALACT · from Google Search Console' : channelKey === 'lsa' ? 'Source: Google Ads · Local Services Ads' : channelKey === 'social' ? 'Source: Meta' : 'Source: Google Ads'}</SourceNote>
      {healthSignal}
      <SourceNote>{channelKey === 'seo' ? 'Calculated by LOCALACT · AI-visibility index' : channelKey === 'lsa' ? 'Source: Google Ads · Local Services Ads · dispute rate calculated by LOCALACT' : channelKey === 'social' ? 'Source: Meta' : 'Source: Google Ads'}</SourceNote>
    </>);

}

// --------------------------------------------------------------------
// Reusable: leaderboard table tuned for channel rollups (shows spend,
// leads, ROAS columns rather than CPL).
// --------------------------------------------------------------------

// Tiny inline bar + percent for the SEO leaderboard cells. Color ramps
// red → amber → green so weak locations pop without a legend.
function SeoBarCell({ pct }) {
  const color = pct >= 85 ? 'var(--sage)' : pct >= 70 ? 'var(--marigold)' : 'var(--terra)';
  return (
    <div style={{ textAlign: 'right' }}>
      <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 12, fontWeight: 700, color, lineHeight: 1.1 }}>{pct}%</div>
      <div style={{ position: 'relative', height: 3, marginTop: 4, background: 'var(--cream-2)', borderRadius: 2, overflow: 'hidden' }}>
        <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: `${pct}%`, background: color, borderRadius: 2 }}/>
      </div>
    </div>
  );
}

function HqChannelLeaderboard({ title, sub, tone, rows, accent, channelKey }) {
  const dotBg = tone === 'sage' ? 'var(--sage-soft)' : 'var(--terra-soft)';
  const dotFg = tone === 'sage' ? 'var(--sage)' : 'var(--terra)';

  // Local SEO gets domain-specific columns instead of spend/leads/ROAS.
  // Numbers are derived deterministically from the rollup row so the same
  // location always shows the same scores, no flicker on re-render.
  const isSeo = channelKey === 'seo';
  const seoCols = (r) => {
    const seed = (r.unit || '').split('').reduce((a, c) => a + c.charCodeAt(0), 0);
    const rng  = (n) => ((seed * 9301 + n * 49297) % 233280) / 233280;
    const rank      = +(2.4 + rng(1) * 4.2).toFixed(1);     // avg local-pack rank 2.4–6.6
    const content   = Math.round(72 + rng(2) * 24);          // 72–96 content health %
    const schema    = Math.round(78 + rng(3) * 22);          // 78–100 schema coverage %
    const aiMention = Math.round(38 + rng(4) * 32);          // 38–70 AI mention rate %
    const queries   = Math.round(220 + rng(5) * 480);        // tracked queries ranking
    return { rank, content, schema, aiMention, queries };
  };

  if (isSeo) {
    return (
      <div className="card card-pad">
        <div className="card-header" style={{ marginBottom: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ width: 22, height: 22, borderRadius: '50%', background: dotBg, color: dotFg, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700 }}>↑</span>
            <div>
              <div className="card-title">{title}</div>
              <div className="card-sub">{sub}</div>
            </div>
          </div>
        </div>
        <div style={{
          display: 'grid',
          gridTemplateColumns: '28px 1.5fr 0.65fr 0.85fr 0.85fr 0.85fr',
          gap: 8, padding: '6px 10px 8px',
          borderBottom: '1px solid var(--cream-3)',
          fontSize: 10, color: 'var(--ink-4)',
          textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600,
        }}>
          <span>#</span>
          <span>Location</span>
          <span style={{ textAlign: 'right' }}>Rank</span>
          <span style={{ textAlign: 'right' }}>Content</span>
          <span style={{ textAlign: 'right' }}>Schema</span>
          <span style={{ textAlign: 'right' }}>AI cite</span>
        </div>
        {rows.map((r, i) => {
          const s = seoCols(r);
          return (
            <div key={r.unit}
                 style={{
                   display: 'grid',
                   gridTemplateColumns: '28px 1.5fr 0.65fr 0.85fr 0.85fr 0.85fr',
                   gap: 8, padding: '10px',
                   borderBottom: i === rows.length - 1 ? 'none' : '1px solid var(--cream-2)',
                   alignItems: 'center', fontSize: 12.5, cursor: 'pointer',
                 }}
                 onMouseEnter={(e) => e.currentTarget.style.background = 'var(--cream)'}
                 onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
                 onClick={() => Thq(r.unit, `Avg rank ${s.rank} · ${s.queries} ranking queries · ${s.aiMention}% AI cite rate`, 'info')}>
              <div style={{
                fontFamily: 'var(--ff-mono)',
                fontSize: 12, fontWeight: 700,
                color: i === 0 ? 'var(--sage)' : 'var(--ink-3)',
                textAlign: 'center',
              }}>{i + 1}</div>
              <div>
                <div style={{ color: 'var(--ink)', fontWeight: 600 }}>{r.unit}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 1 }}>
                  {r.city} · <span style={{ fontFamily: 'var(--ff-mono)' }}>{s.queries}</span> queries ranking
                </div>
              </div>
              <div style={{
                textAlign: 'right', fontFamily: 'var(--ff-mono)',
                color: s.rank <= 3.5 ? 'var(--sage)' : s.rank <= 5 ? 'var(--ink-2)' : 'var(--terra)',
                fontWeight: 600,
              }}>{s.rank}</div>
              <SeoBarCell pct={s.content}/>
              <SeoBarCell pct={s.schema}/>
              <SeoBarCell pct={s.aiMention}/>
            </div>
          );
        })}
      </div>
    );
  }

  return (
    <div className="card card-pad">
      <div className="card-header" style={{ marginBottom: 12 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ width: 22, height: 22, borderRadius: '50%', background: dotBg, color: dotFg, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700 }}>↑</span>
          <div>
            <div className="card-title">{title}</div>
            <div className="card-sub">{sub}</div>
          </div>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 0.7fr 0.7fr 0.7fr', gap: 8, padding: '6px 10px 8px', borderBottom: '1px solid var(--cream-3)', fontSize: 10, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>
        <span>Location</span>
        <span style={{ textAlign: 'right' }}>Spend</span>
        <span style={{ textAlign: 'right' }}>Leads</span>
        <span style={{ textAlign: 'right' }}>ROAS</span>
      </div>
      {rows.map((r, i) =>
      <div key={r.unit} style={{ display: 'grid', gridTemplateColumns: '1.6fr 0.7fr 0.7fr 0.7fr', gap: 8, padding: '10px', borderBottom: i === rows.length - 1 ? 'none' : '1px solid var(--cream-2)', alignItems: 'center', fontSize: 12.5, cursor: 'pointer' }}
      onMouseEnter={(e) => e.currentTarget.style.background = 'var(--cream)'}
      onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
      onClick={() => Thq(r.unit, `${r.leads} leads · $${r.spend} spend · ${r.roas}x ROAS`, 'info')}>
          <div>
            <div style={{ color: 'var(--ink)', fontWeight: 600 }}>{r.unit}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 1 }}>{r.city}</div>
          </div>
          <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>${r.spend}</div>
          <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>{r.leads}</div>
          <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: r.roas >= 5 ? 'var(--sage)' : r.roas >= 4 ? 'var(--ink-2)' : 'var(--terra)', fontWeight: 600 }}>{r.roas}x</div>
        </div>
      )}
    </div>);

}

// --------------------------------------------------------------------
// Underfunded locations card. Shows current vs playbook target and
// modeled lead lift if budget were raised. CTA = push budget proposal.
// --------------------------------------------------------------------
function HqUnderfundedCard({ title, sub, rows, accent, upliftLeads, upliftSpend, channelLabel, channelKey, customFooter }) {
  return (
    <div className="card card-pad" style={{ position: 'relative' }}>
      <div className="card-header" style={{ marginBottom: 12 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--marigold-soft)', color: 'var(--marigold)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700 }}>＋</span>
          <div>
            <div className="card-title">{title}</div>
            <div className="card-sub">{sub}</div>
          </div>
        </div>
      </div>
      {rows.map((r, i) => {
        const gain = Math.max(0, r.playbookTarget - r.spend);
        const liftLeads = Math.round(gain / r.cpl);
        return (
          <div key={r.unit} style={{ padding: '10px 6px', borderBottom: i === rows.length - 1 ? 'none' : '1px solid var(--cream-2)' }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 6 }}>
              <div style={{ flex: 1 }}>
                <div style={{ color: 'var(--ink)', fontWeight: 600, fontSize: 12.5 }}>{r.unit}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 1 }}>{r.city} · {r.underfundPct}% IS lost to budget</div>
              </div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--ff-mono)' }}>
                ${r.spend} / <span style={{ color: 'var(--ink-2)' }}>${r.playbookTarget}</span>
              </div>
            </div>
            <div style={{ position: 'relative', height: 5, background: 'var(--cream-2)', borderRadius: 3, overflow: 'hidden', marginBottom: 5 }}>
              <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: `${Math.min(100, r.spend / r.playbookTarget * 100).toFixed(0)}%`, background: accent, borderRadius: 3 }} />
              <div style={{ position: 'absolute', left: '100%', top: -1, bottom: -1, transform: 'translateX(-50%)', width: 1, background: 'var(--ink-3)' }} />
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11 }}>
              <span style={{ color: 'var(--sage)', fontWeight: 600 }}>+{liftLeads} leads/mo if raised</span>
              <button className="btn btn-quiet btn-xs"
              onClick={() => Thq(`${r.unit}: ${channelLabel} bump drafted`,
              `Proposed +$${gain}/mo to hit playbook target. Modeled lift: +${liftLeads} leads.`, 'ok')}>
                Push budget →
              </button>
            </div>
          </div>);

      })}
      {/* Footer: aggregate uplift + push-all CTA (or a channel-specific replacement) */}
      {customFooter ? customFooter :
      <div style={{ marginTop: 12, padding: '10px 12px', background: 'linear-gradient(135deg, var(--terra-soft), var(--marigold-soft))', borderRadius: 10, display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ flex: 1, fontSize: 12.5 }}>
            <strong style={{ color: 'var(--ink)' }}>+{upliftLeads} leads/mo</strong> 
            <span style={{ color: 'var(--ink-3)' }}>if all 5 hit playbook (+${upliftSpend.toLocaleString()})</span>
          </div>
          <button className="btn btn-primary btn-sm"
        onClick={() => Thq('Bulk budget push drafted',
        `Proposing $${upliftSpend.toLocaleString()}/mo across ${rows.length} locations. Modeled lift: +${upliftLeads} leads.`, 'ok')}>
            Push to all 5
          </button>
        </div>
      }
    </div>);

}

// --------------------------------------------------------------------
// Health-signal card, channel-specific brand-wide diagnostic.
// Reused by all four channel-tab HQ variants with different content.
// --------------------------------------------------------------------
function HqHealthSignal({ title, sub, accent, mainStat, mainLabel, mainBar, breakdown, footer, ctas }) {
  return (
    <div className="card card-pad" style={{ marginBottom: 16 }}>
      <div className="card-header" style={{ marginBottom: 14 }}>
        <div>
          <div className="card-title">{title}</div>
          <div className="card-sub">{sub}</div>
        </div>
        {ctas}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr', gap: 24, alignItems: 'center' }}>
        <div style={{ padding: 16, background: 'var(--cream)', borderRadius: 12, textAlign: 'center' }}>
          <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '.08em', fontWeight: 600, marginBottom: 4 }}>{mainLabel}</div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 44, fontWeight: 500, lineHeight: 1, color: 'var(--ink)' }}>{mainStat}</div>
          {mainBar &&
          <div style={{ marginTop: 12, height: 6, background: 'var(--cream-2)', borderRadius: 3, overflow: 'hidden' }}>
              <div style={{ width: `${mainBar.pct}%`, height: '100%', background: accent }} />
            </div>
          }
          {mainBar && <div style={{ fontSize: 10.5, color: 'var(--ink-4)', marginTop: 4, fontFamily: 'var(--ff-mono)' }}>{mainBar.label}</div>}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {breakdown.map((b, i) =>
          <div key={i}>
              <div style={{ display: 'flex', alignItems: 'baseline', marginBottom: 4 }}>
                <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink)' }}>{b.label}</span>
                <span style={{ flex: 1 }} />
                <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 12, color: 'var(--ink-2)' }}>{b.value}</span>
              </div>
              <div style={{ height: 5, background: 'var(--cream-2)', borderRadius: 3, overflow: 'hidden' }}>
                <div style={{ width: `${b.pct}%`, height: '100%', background: b.color || accent, borderRadius: 3 }} />
              </div>
            </div>
          )}
        </div>
      </div>
      {footer &&
      <div style={{ marginTop: 14, padding: 12, background: 'var(--cream)', borderRadius: 8, fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.55 }}>
          {footer}
        </div>
      }
    </div>);

}

// ====================================================================
// PAID SEARCH HQ, impression-share-loss as the brand-wide signal
// ====================================================================
function ResultsPpcHq({ data }) {
  const [campaignType, setCampaignType] = React.useState('all'); // all | search | pmax | brand
  const [timeRange] = React.useState('30d');

  // ---- headline KPIs (filter sensitive) ----
  // Headline KPIs reconcile to the network source of truth (window.LOCALACT_DATA.network).
  // 'all' = network paid-media totals: $473K spend · 14,800 leads · $32 CPL. Denominator 700.
  const kpis = {
    all:    { spend: '$473K', impressions: '21.0M', clicks: '1.06M', ctr: '5.0%', cpc: '$0.45', conv: '14,800', cvr: '1.40%', cpl: '$32', topLocations: 700 },
    search: { spend: '$283K', impressions: '10.2M', clicks: '591K',  ctr: '5.8%', cpc: '$0.48', conv: '9,220',  cvr: '1.56%', cpl: '$31', topLocations: 700 },
    pmax:   { spend: '$124K', impressions: '8.2M',  clicks: '319K',  ctr: '3.9%', cpc: '$0.39', conv: '3,300',  cvr: '1.03%', cpl: '$38', topLocations: 700 },
    brand:  { spend: '$46K',  impressions: '1.5M',  clicks: '82K',   ctr: '5.5%', cpc: '$0.56', conv: '1,260',  cvr: '1.54%', cpl: '$37', topLocations: 700 },
  }[campaignType];

  // ---- campaign type breakdown ----
  const campaignTypes = [
    { name: 'Search · Non-brand', spend: 237000, share: 50, impr: 8.7, clicks: 509000, ctr: 5.8, cpl: 30, leads: 7960, color: 'var(--sky)' },
    { name: 'Search · Brand',     spend: 46000,  share: 10, impr: 1.5, clicks: 82000,  ctr: 5.5, cpl: 37, leads: 1260, color: 'var(--violet)' },
    { name: 'Performance Max',    spend: 124000, share: 26, impr: 8.2, clicks: 319000, ctr: 3.9, cpl: 38, leads: 3300, color: 'var(--marigold)' },
    { name: 'Local Service',      spend: 36000,  share: 8,  impr: 1.3, clicks: 72000,  ctr: 5.5, cpl: 20, leads: 1820, color: 'var(--sage)' },
    { name: 'Display Remarketing',spend: 31000,  share: 6,  impr: 1.3, clicks: 77000,  ctr: 5.9, cpl: 67, leads: 460,  color: 'var(--terra)' },
  ];

  // ---- top keywords ----
  // ---- top keywords (Search tabs) ----
  const baseKeywords = [
    { kw: 'home cleaning near me',                mt: 'Phrase', impr: 412000, clicks: 38400, ctr: 9.3, cpc: 0.42, cpl: 18, qs: 9, conv: 1820 },
    { kw: 'best cleaning service [city]',         mt: 'Broad',  impr: 286000, clicks: 21800, ctr: 7.6, cpc: 0.38, cpl: 22, qs: 8, conv: 980 },
    { kw: 'deep cleaning service',                mt: 'Exact',  impr: 198000, clicks: 14200, ctr: 7.2, cpc: 0.52, cpl: 31, qs: 8, conv: 460 },
    { kw: 'freshnest',                            mt: 'Brand',  impr: 142000, clicks: 28400, ctr: 20.0, cpc: 0.31, cpl: 12, qs: 10, conv: 1240 },
    { kw: 'eco cleaning supplies',                mt: 'Phrase', impr: 124000, clicks: 9800,  ctr: 7.9, cpc: 0.46, cpl: 26, qs: 8, conv: 380 },
    { kw: 'move-out cleaning service',            mt: 'Phrase', impr: 86000,  clicks: 5200,  ctr: 6.0, cpc: 0.78, cpl: 48, qs: 6, conv: 110 },
    { kw: 'office cleaning service',              mt: 'Broad',  impr: 64000,  clicks: 3100,  ctr: 4.8, cpc: 0.62, cpl: 52, qs: 5, conv: 60  },
  ];
  // Brand-defense campaign: branded terms only (protect the FreshNest name).
  const brandKeywords = [
    { kw: 'freshnest',                 mt: 'Brand', impr: 142000, clicks: 28400, ctr: 20.0, cpc: 0.31, cpl: 12, qs: 10, conv: 1240 },
    { kw: 'freshnest near me',         mt: 'Brand', impr: 61000,  clicks: 12800, ctr: 21.0, cpc: 0.29, cpl: 11, qs: 10, conv: 540 },
    { kw: 'freshnest cleaning',        mt: 'Brand', impr: 38000,  clicks: 7600,  ctr: 20.0, cpc: 0.30, cpl: 12, qs: 10, conv: 320 },
    { kw: 'freshnest [city]',          mt: 'Brand', impr: 29000,  clicks: 5900,  ctr: 20.3, cpc: 0.32, cpl: 13, qs: 9,  conv: 240 },
    { kw: 'freshnest reviews',         mt: 'Brand', impr: 18000,  clicks: 3200,  ctr: 17.8, cpc: 0.28, cpl: 14, qs: 9,  conv: 90  },
    { kw: 'freshnest booking',         mt: 'Brand', impr: 12000,  clicks: 2600,  ctr: 21.7, cpc: 0.27, cpl: 10, qs: 10, conv: 180 },
    { kw: 'freshnest phone number',    mt: 'Brand', impr: 8400,   clicks: 1900,  ctr: 22.6, cpc: 0.26, cpl: 9,  qs: 10, conv: 70  },
  ];
  const keywords = campaignType === 'brand' ? brandKeywords : baseKeywords;

  // ---- PMax network creative + surface distribution (Google Ads PMax API) ----
  const pmaxSurfaces = [
    { channel: 'Search',   impr: 26, conv: 34, color: 'var(--ch-ppc)' },
    { channel: 'YouTube',  impr: 34, conv: 9,  color: '#e46c63' },
    { channel: 'Display',  impr: 20, conv: 6,  color: '#4d6989' },
    { channel: 'Maps',     impr: 12, conv: 36, color: 'var(--sage)' },
    { channel: 'Discover', impr: 6,  conv: 11, color: '#f28020' },
    { channel: 'Gmail',    impr: 2,  conv: 4,  color: 'var(--clay)' },
  ];
  const pmaxCreativesHq = [
    { id: 'h1', type: 'Video',    name: 'Deep-clean before / after · 15s', grad: 'linear-gradient(135deg,#fcdec5,#f6a663)', perf: 'Best', metric: '29% view-through', conv: 820 },
    { id: 'h2', type: 'Image',    name: 'Sparkling kitchen · square',       grad: 'linear-gradient(135deg,#e4f3eb,#95cccc)', perf: 'Best', metric: '6.0% CTR',        conv: 640 },
    { id: 'h3', type: 'Headline', name: '“Book a spotless home today”',    grad: 'linear-gradient(135deg,#e5eefd,#9fc0f6)', perf: 'Good', metric: 'Assoc. 2.2% CTR',  conv: 410 },
    { id: 'h4', type: 'Image',    name: 'Eco product shelf · landscape',    grad: 'linear-gradient(135deg,#fcf6e1,#f6de92)', perf: 'Good', metric: '4.3% CTR',        conv: 300 },
    { id: 'h5', type: 'Video',    name: 'Meet the crew · 30s',              grad: 'linear-gradient(135deg,#e0e5eb,#8fa0b5)', perf: 'Low',  metric: '11% view-through', conv: 120 },
    { id: 'h6', type: 'Image',    name: 'Move-out promo · vertical',        grad: 'linear-gradient(135deg,#fae6e4,#eea39d)', perf: 'Low',  metric: '1.8% CTR',        conv: 80  },
  ];
  const pmaxAssetGroupsHq = [
    { name: 'National Spring Refresh', strength: 'Excellent', spend: '$52K', conv: 1680, ctr: 5.7, best: 14, good: 22, low: 6 },
    { name: 'Recurring Plans',         strength: 'Good',      spend: '$41K', conv: 1080, ctr: 4.6, best: 9,  good: 24, low: 11 },
    { name: 'Eco Products',            strength: 'Average',   spend: '$31K', conv: 540,  ctr: 3.4, best: 5,  good: 19, low: 16, rec: '218 locations missing a vertical video asset' },
  ];

  // ---- search-term insights ----
  const searchTerms = [
    { term: 'cleaning service near me',     trend: 'rising',  imprDelta: 142, conv: 84, status: 'add' },
    { term: 'industrial cleaning austin',      trend: 'irrelevant', imprDelta: 12, conv: 0, status: 'negative' },
    { term: 'office deep clean services',      trend: 'rising',  imprDelta: 96, conv: 28, status: 'add' },
    { term: 'chemical free home cleaning',     trend: 'irrelevant', imprDelta: 38, conv: 0, status: 'negative' },
    { term: 'best eco cleaners near me',       trend: 'rising',  imprDelta: 71, conv: 22, status: 'add' },
  ];

  // ---- ad group performance ----
  const adGroups = [
    { name: 'Cleaning, Generic',          campaigns: 700, ads: 8, ctr: 5.4, cpl: 28, qs: 8.2, perf: 'top' },
    { name: 'Service Booking, Lead Gen',    campaigns: 700, ads: 6, ctr: 4.8, cpl: 38, qs: 7.6, perf: 'avg' },
    { name: 'Brand Defense',          campaigns: 700, ads: 4, ctr: 18.2, cpl: 12, qs: 9.8, perf: 'top' },
    { name: 'Local Pack, [City]',    campaigns: 700, ads: 12, ctr: 6.1, cpl: 24, qs: 8.4, perf: 'top' },
    { name: 'Holidays, Seasonal',    campaigns: 318, ads: 5, ctr: 3.2, cpl: 52, qs: 6.4, perf: 'low' },
    { name: 'Competitor Conquest',    campaigns: 142, ads: 6, ctr: 2.8, cpl: 68, qs: 5.2, perf: 'low' },
  ];

  // ---- ad/asset performance ----
  const ads = [
    { headline: 'Top-Rated Home Cleaning · Book Today', desc: 'Eco-certified crews. Book online. Recurring plans.', type: 'RSA', strength: 'Excellent',  ctr: 6.4, conv: 2840, status: 'top' },
    { headline: 'Office Cleaning · Free Walkthrough', desc: 'Trusted by Austin\'s best offices. Quote in 1 hr.', type: 'RSA', strength: 'Excellent',  ctr: 5.2, conv: 1240, status: 'top' },
    { headline: 'Deep Clean Special · This Week',   desc: 'Limited slots. Reserve online.',                     type: 'RSA', strength: 'Good',       ctr: 4.8, conv: 980,  status: 'avg' },
    { headline: 'Eco-Friendly Products Available',    desc: 'Plant-based, pet- & kid-safe options.',            type: 'RSA', strength: 'Average',    ctr: 2.1, conv: 180,  status: 'low' },
  ];

  // ---- extension performance ----
  const extensions = [
    { type: 'Sitelinks',     impr: 4.2, ctr: 5.8, conv: 2120, healthy: true,  note: 'Used on 96% of ads' },
    { type: 'Callouts',      impr: 4.0, ctr: 5.4, conv: 1840, healthy: true,  note: '12 active, refreshed monthly' },
    { type: 'Call extension',impr: 2.6, ctr: 7.2, conv: 1340, healthy: true,  note: 'Click-to-call on mobile' },
    { type: 'Location ext.', impr: 3.8, ctr: 6.1, conv: 1120, healthy: true,  note: 'GBP linked across all 700 locations' },
    { type: 'Promotion ext.',impr: 1.2, ctr: 4.2, conv: 280,  healthy: false, note: '8 locations missing seasonal promo' },
    { type: 'Image ext.',    impr: 0.4, ctr: 3.1, conv: 64,   healthy: false, note: 'Only 90 of 700 enabled' },
  ];

  // ---- device split ----
  const devices = [
    { name: 'Mobile',  share: 71, ctr: 5.4, cvr: 1.62, cpl: 26, color: 'var(--violet)' },
    { name: 'Desktop', share: 22, ctr: 4.2, cvr: 1.34, cpl: 38, color: 'var(--sky)' },
    { name: 'Tablet',  share: 7,  ctr: 3.8, cvr: 0.98, cpl: 48, color: 'var(--marigold)' },
  ];

  // ---- geo (top DMAs) ----
  const dmas = [
    { name: 'Austin, TX',         locations: 89,  spend: '$62K',  impr: '3.1M', clicks: '165K', cpl: 24, conv: 2374, qs: 8.6 },
    { name: 'Dallas–Ft. Worth',   locations: 108, spend: '$72K',  impr: '3.6M', clicks: '185K', cpl: 27, conv: 2421, qs: 8.4 },
    { name: 'Houston, TX',        locations: 79,  spend: '$46K',  impr: '2.3M', clicks: '118K', cpl: 29, conv: 1443, qs: 8.0 },
    { name: 'Phoenix, AZ',        locations: 44,  spend: '$28K',  impr: '1.3M', clicks: '62K',  cpl: 31, conv: 838,  qs: 7.8 },
    { name: 'Atlanta, GA',        locations: 54,  spend: '$33K',  impr: '1.5M', clicks: '72K',  cpl: 33, conv: 884,  qs: 7.6 },
    { name: 'Tampa, FL',          locations: 35,  spend: '$21K',  impr: '0.8M', clicks: '36K',  cpl: 38, conv: 489,  qs: 7.2 },
    { name: 'Other (61 DMAs)',    locations: 291, spend: '$211K', impr: '8.4M', clicks: '421K', cpl: 32, conv: 6351, qs: 7.4 },
  ];

  // ---- day-of-week × hour heatmap (lead conversions) ----
  const dows = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  const heat = (() => {
    const grid = [];
    for (let d = 0; d < 7; d++) {
      const row = [];
      for (let h = 0; h < 24; h++) {
        const lunch  = Math.max(0, 1 - Math.abs(h - 12) / 2.6);
        const dinner = Math.max(0, 1 - Math.abs(h - 18.5) / 3.2);
        // weekday spike for catering inquiries 10-12, weekend dinner shift
        const cateringMorn = (d < 5) ? Math.max(0, 1 - Math.abs(h - 10.5) / 2.2) * 0.8 : 0;
        const weekendBoost = (d >= 5 ? 1.10 : 1.0);
        const noise = ((d * 19 + h * 13) % 9) / 9 * 0.1;
        const v = Math.min(100, (lunch * 0.5 + dinner * 0.85 + cateringMorn + noise) * 100 * weekendBoost);
        row.push(Math.round(v));
      }
      grid.push(row);
    }
    return grid;
  })();
  const peakCell = (() => {
    let best = { d: 0, h: 0, v: 0 };
    heat.forEach((row, d) => row.forEach((v, h) => { if (v > best.v) best = { d, h, v }; }));
    return best;
  })();

  return (
    <div>
      {/* Filters */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14, flexWrap: 'wrap' }}>
        <div style={{ display: 'inline-flex', background: 'var(--cream)', border: '1px solid var(--cream-3)', borderRadius: 8, padding: 2 }}>
          {[
            { v: 'all',    l: 'All campaigns' },
            { v: 'search', l: 'Search' },
            { v: 'pmax',   l: 'Performance Max' },
            { v: 'brand',  l: 'Brand defense' },
          ].map(o => (
            <button key={o.v}
                    onClick={() => setCampaignType(o.v)}
                    style={{
                      padding: '6px 12px', background: campaignType === o.v ? 'var(--paper)' : 'transparent',
                      border: 'none', borderRadius: 6, fontSize: 12, fontWeight: 600,
                      color: campaignType === o.v ? 'var(--ink)' : 'var(--ink-3)',
                      cursor: 'pointer', boxShadow: campaignType === o.v ? '0 1px 2px rgba(0,0,0,0.06)' : 'none',
                    }}>{o.l}</button>
          ))}
        </div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>
          Last 30 days · {kpis.topLocations} of 700 locations active · Google Ads
        </div>
      </div>

      {/* Headline KPIs */}
      <div className="grid grid-4" style={{ marginBottom: 16 }}>
        <KpiCard label="Spend"        value={kpis.spend}       delta={4}   color="var(--sky)"      dotColor="var(--sky)"/>
        <KpiCard label="Conversions"  value={kpis.conv}        delta={11}  color="var(--sage)"     dotColor="var(--sage)"/>
        <KpiCard label="Cost / Lead"  value={kpis.cpl}         delta={-6}  invert color="var(--terra)" dotColor="var(--terra)"/>
        <KpiCard label="Conv. rate"   value={kpis.cvr}         delta={3}   color="var(--marigold)" dotColor="var(--marigold)"/>
      </div>
      <div className="grid grid-4" style={{ marginBottom: 18 }}>
        <KpiCard label="Impressions"  value={kpis.impressions} delta={6}   color="var(--ink-3)"    dotColor="var(--ink-3)"/>
        <KpiCard label="Clicks"       value={kpis.clicks}      delta={9}   color="var(--violet)"   dotColor="var(--violet)"/>
        <KpiCard label="CTR"          value={kpis.ctr}         delta={2}   color="var(--violet)"   dotColor="var(--violet)"/>
        <KpiCard label="Avg CPC"      value={kpis.cpc}         delta={-3}  invert color="var(--ink-3)" dotColor="var(--ink-3)"/>
      </div>

      <SourceNote>Source: Google Ads · CPL, CPC &amp; ROAS calculated by LOCALACT</SourceNote>

      {/* Campaign type breakdown */}
      <div className="card card-pad" style={{ marginBottom: 16 }}>
        <div className="card-header" style={{ marginBottom: 12 }}>
          <div>
            <div className="card-title">Spend by campaign type</div>
            <div className="card-sub">Where every dollar lands across the portfolio</div>
          </div>
        </div>
        <div style={{ display: 'flex', height: 14, background: 'var(--cream-2)', borderRadius: 4, overflow: 'hidden', marginBottom: 12 }}>
          {campaignTypes.map(c => (
            <div key={c.name} style={{ width: `${c.share}%`, background: c.color }} title={`${c.name}: ${c.share}%`}/>
          ))}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 0.7fr 0.7fr 0.7fr 0.7fr 0.7fr', gap: 8, padding: '6px 0 8px', borderBottom: '1px solid var(--cream-3)', fontSize: 10, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>
          <span>Type</span>
          <span style={{ textAlign: 'right' }}>Spend</span>
          <span style={{ textAlign: 'right' }}>Clicks</span>
          <span style={{ textAlign: 'right' }}>CTR</span>
          <span style={{ textAlign: 'right' }}>Leads</span>
          <span style={{ textAlign: 'right' }}>CPL</span>
        </div>
        {campaignTypes.map((c, i) => (
          <div key={c.name} style={{ display: 'grid', gridTemplateColumns: '2fr 0.7fr 0.7fr 0.7fr 0.7fr 0.7fr', gap: 8, padding: '10px 0', borderBottom: i === campaignTypes.length - 1 ? 'none' : '1px solid var(--cream-2)', alignItems: 'center', fontSize: 12.5 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ width: 8, height: 8, borderRadius: 2, background: c.color }}/>
              <span style={{ color: 'var(--ink)', fontWeight: 600 }}>{c.name}</span>
            </div>
            <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>${(c.spend/1000).toFixed(0)}K</div>
            <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-3)' }}>{(c.clicks/1000).toFixed(0)}K</div>
            <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>{c.ctr}%</div>
            <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>{c.leads.toLocaleString()}</div>
            <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: c.cpl <= 25 ? 'var(--sage)' : c.cpl <= 35 ? 'var(--ink-2)' : 'var(--terra)', fontWeight: 600 }}>${c.cpl}</div>
          </div>
        ))}
      </div>

      <SourceNote>Source: Google Ads</SourceNote>

      {/* PMax network creative + surface distribution — only on the PMax tab */}
      {campaignType === 'pmax' && (() => {
        const perfTone = { Best: 'var(--sage)', Good: 'var(--marigold)', Low: 'var(--terra)' };
        return (
          <div className="card card-pad" style={{ marginBottom: 16 }}>
            <div className="card-header" style={{ marginBottom: 14 }}>
              <div>
                <div className="card-title">Performance Max, creative &amp; surface distribution</div>
                <div className="card-sub">Network-wide asset ratings and where PMax auto-placed across Google · all 700 locations</div>
              </div>
              <button className="btn btn-quiet btn-sm" onClick={() => Thq('Creative library', 'Opening the network PMax asset library. Push winning creative to franchisee asset groups here.', 'info')}>Manage creative</button>
            </div>

            {/* Surface distribution */}
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '.06em', fontWeight: 600, marginBottom: 10 }}>Channel distribution inside PMax</div>
            <div style={{ display: 'flex', height: 26, borderRadius: 6, overflow: 'hidden', marginBottom: 10 }}>
              {pmaxSurfaces.map(s => <div key={s.channel} style={{ width: `${s.impr}%`, background: s.color }} title={`${s.channel}: ${s.impr}% of impressions`}/>)}
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 16, marginBottom: 22 }}>
              {pmaxSurfaces.map(s => (
                <div key={s.channel} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11.5 }}>
                  <span style={{ width: 10, height: 10, background: s.color, borderRadius: 2 }}/>
                  <strong>{s.channel}</strong>
                  <span style={{ color: 'var(--ink-3)' }}>{s.impr}% impr · {s.conv}% conv</span>
                </div>
              ))}
            </div>
            <div style={{ padding: '10px 12px', background: 'var(--cream)', borderRadius: 8, fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.55, marginBottom: 22 }}>
              <strong style={{ color: 'var(--ink-2)' }}>Read:</strong> Search + Maps take ~38% of impressions but drive ~70% of PMax conversions. YouTube and Display are top-of-funnel — judge them on view-through and brand-search lift, not last-click.
            </div>

            <SourceNote>Source: Meta</SourceNote>

      {/* Top creatives */}
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '.06em', fontWeight: 600, marginBottom: 10 }}>Top assets by performance</div>
            <div className="grid" style={{ gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 22 }}>
              {pmaxCreativesHq.map(c => (
                <div key={c.id} className="card" style={{ overflow: 'hidden', padding: 0 }}>
                  <div style={{ height: 88, background: c.grad, display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', padding: 8 }}>
                    <span style={{ fontSize: 10, fontWeight: 700, color: 'var(--ink-2)', background: 'rgba(255,255,255,.82)', borderRadius: 999, padding: '2px 8px' }}>{c.type}</span>
                    <span style={{ fontSize: 10, fontWeight: 700, color: '#fff', background: perfTone[c.perf], borderRadius: 999, padding: '2px 8px' }}>{c.perf}</span>
                  </div>
                  <div style={{ padding: '10px 12px' }}>
                    <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink)', lineHeight: 1.3 }}>{c.name}</div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontSize: 11, color: 'var(--ink-3)' }}>
                      <span style={{ fontFamily: 'var(--ff-mono)' }}>{c.metric}</span>
                      <span style={{ fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)', fontWeight: 600 }}>{c.conv.toLocaleString()} conv</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>

            {/* Asset groups + ad strength */}
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '.06em', fontWeight: 600, marginBottom: 10 }}>Asset groups, ad strength</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {pmaxAssetGroupsHq.map(g => {
                const total = g.best + g.good + g.low || 1;
                const sTone = g.strength === 'Excellent' ? 'var(--sage)' : g.strength === 'Good' ? 'var(--sky)' : 'var(--marigold)';
                const sBg = g.strength === 'Excellent' ? 'var(--sage-soft)' : g.strength === 'Good' ? 'var(--sky-soft)' : 'var(--marigold-soft)';
                return (
                  <div key={g.name} style={{ padding: '12px 14px', background: 'var(--cream)', borderRadius: 10 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
                      <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ink)', minWidth: 150 }}>{g.name}</div>
                      <span style={{ fontSize: 11, fontWeight: 700, color: sTone, background: sBg, borderRadius: 999, padding: '3px 10px' }}>{g.strength}</span>
                      <div style={{ flex: 1 }}/>
                      <span style={{ fontSize: 11.5, color: 'var(--ink-3)', fontFamily: 'var(--ff-mono)' }}>{g.spend} · {g.conv.toLocaleString()} conv · {g.ctr}% CTR</span>
                    </div>
                    <div style={{ display: 'flex', height: 20, borderRadius: 5, overflow: 'hidden', marginTop: 10 }}>
                      <div style={{ width: `${g.best / total * 100}%`, background: 'var(--sage)' }}/>
                      <div style={{ width: `${g.good / total * 100}%`, background: 'var(--marigold)' }}/>
                      <div style={{ width: `${g.low / total * 100}%`, background: 'var(--terra)' }}/>
                    </div>
                    <div style={{ display: 'flex', gap: 14, marginTop: 8, fontSize: 11, color: 'var(--ink-3)' }}>
                      <span><strong style={{ color: 'var(--sage)' }}>{g.best}</strong> Best</span>
                      <span><strong style={{ color: 'var(--marigold)' }}>{g.good}</strong> Good</span>
                      <span><strong style={{ color: 'var(--terra)' }}>{g.low}</strong> Low</span>
                      {g.rec && <span style={{ marginLeft: 'auto', color: 'var(--ink-2)' }}>→ {g.rec}</span>}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        );
      })()}

      <SourceNote>Source: Google Ads</SourceNote>

      {/* Top keywords + Search term insights */}
      <div className="grid grid-2" style={{ marginBottom: 16 }}>
        <div className="card card-pad">
          <div className="card-header" style={{ marginBottom: 12 }}>
            <div>
              <div className="card-title">Top keywords</div>
              <div className="card-sub">Highest-volume keywords across all 700 locations</div>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '2fr 0.7fr 0.7fr 0.6fr 0.6fr 0.5fr', gap: 8, padding: '6px 0 8px', borderBottom: '1px solid var(--cream-3)', fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>
            <span>Keyword</span>
            <span style={{ textAlign: 'right' }}>Impr.</span>
            <span style={{ textAlign: 'right' }}>Clicks</span>
            <span style={{ textAlign: 'right' }}>CTR</span>
            <span style={{ textAlign: 'right' }}>CPL</span>
            <span style={{ textAlign: 'right' }}>QS</span>
          </div>
          {keywords.map((k, i) => (
            <div key={k.kw} style={{ display: 'grid', gridTemplateColumns: '2fr 0.7fr 0.7fr 0.6fr 0.6fr 0.5fr', gap: 8, padding: '8px 0', borderBottom: i === keywords.length - 1 ? 'none' : '1px solid var(--cream-2)', alignItems: 'center', fontSize: 12 }}>
              <div>
                <div style={{ color: 'var(--ink)', fontWeight: 600 }}>{k.kw}</div>
                <div style={{ fontSize: 10, color: 'var(--ink-4)', marginTop: 1 }}>{k.mt}</div>
              </div>
              <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-3)' }}>{(k.impr/1000).toFixed(0)}K</div>
              <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-3)' }}>{(k.clicks/1000).toFixed(1)}K</div>
              <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>{k.ctr}%</div>
              <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: k.cpl <= 25 ? 'var(--sage)' : k.cpl <= 35 ? 'var(--ink-2)' : 'var(--terra)', fontWeight: 600 }}>${k.cpl}</div>
              <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: k.qs >= 8 ? 'var(--sage)' : k.qs >= 6 ? 'var(--marigold)' : 'var(--terra)', fontWeight: 700 }}>{k.qs}</div>
            </div>
          ))}
        </div>

        <div className="card card-pad">
          <div className="card-header" style={{ marginBottom: 12 }}>
            <div>
              <div className="card-title">Search term insights</div>
              <div className="card-sub">Queries to harvest into keywords or block as negatives</div>
            </div>
          </div>
          {searchTerms.map((t, i) => (
            <div key={t.term} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 0', borderBottom: i === searchTerms.length - 1 ? 'none' : '1px solid var(--cream-2)' }}>
              <span style={{
                width: 26, height: 26, borderRadius: '50%',
                background: t.status === 'add' ? 'var(--sage-soft)' : 'var(--terra-soft)',
                color: t.status === 'add' ? 'var(--sage)' : 'var(--terra)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 14, fontWeight: 700, flexShrink: 0,
              }}>{t.status === 'add' ? '+' : '−'}</span>
              <div style={{ flex: 1 }}>
                <div style={{ color: 'var(--ink)', fontWeight: 600, fontSize: 12.5 }}>{t.term}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 1 }}>
                  {t.status === 'add'
                    ? <>Trending up · <span style={{ fontFamily: 'var(--ff-mono)' }}>+{t.imprDelta}%</span> impressions · <span style={{ color: 'var(--sage)', fontWeight: 600 }}>{t.conv} conversions</span></>
                    : <>No conversions across portfolio · waste <span style={{ fontFamily: 'var(--ff-mono)' }}>~$320/mo</span></>
                  }
                </div>
              </div>
              <span style={{
                padding: '3px 8px', borderRadius: 4, fontSize: 9.5, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase',
                background: t.status === 'add' ? 'var(--sage-soft)' : 'var(--terra-soft)',
                color: t.status === 'add' ? 'var(--sage)' : 'var(--terra)',
              }}>{t.status === 'add' ? 'Add as keyword' : 'Add as negative'}</span>
            </div>
          ))}
        </div>
      </div>

      <SourceNote>Source: Google Ads · CPL calculated by LOCALACT</SourceNote>

      {/* Ad groups + Ads */}
      <div className="grid grid-2" style={{ marginBottom: 16 }}>
        <div className="card card-pad">
          <div className="card-header" style={{ marginBottom: 12 }}>
            <div>
              <div className="card-title">Ad group performance</div>
              <div className="card-sub">Top + bottom ad groups across all locations</div>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '2fr 0.7fr 0.6fr 0.7fr 0.6fr 0.7fr', gap: 8, padding: '6px 0 8px', borderBottom: '1px solid var(--cream-3)', fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>
            <span>Ad group</span>
            <span style={{ textAlign: 'right' }}>Ads</span>
            <span style={{ textAlign: 'right' }}>CTR</span>
            <span style={{ textAlign: 'right' }}>CPL</span>
            <span style={{ textAlign: 'right' }}>QS</span>
            <span style={{ textAlign: 'right' }}>Status</span>
          </div>
          {adGroups.map((g, i) => (
            <div key={g.name} style={{ display: 'grid', gridTemplateColumns: '2fr 0.7fr 0.6fr 0.7fr 0.6fr 0.7fr', gap: 8, padding: '9px 0', borderBottom: i === adGroups.length - 1 ? 'none' : '1px solid var(--cream-2)', alignItems: 'center', fontSize: 12 }}>
              <div>
                <div style={{ color: 'var(--ink)', fontWeight: 600 }}>{g.name}</div>
                <div style={{ fontSize: 10, color: 'var(--ink-4)', marginTop: 1 }}>{g.campaigns} campaigns</div>
              </div>
              <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-3)' }}>{g.ads}</div>
              <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>{g.ctr}%</div>
              <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: g.cpl <= 25 ? 'var(--sage)' : g.cpl <= 40 ? 'var(--ink-2)' : 'var(--terra)', fontWeight: 600 }}>${g.cpl}</div>
              <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: g.qs >= 8 ? 'var(--sage)' : g.qs >= 6.5 ? 'var(--marigold)' : 'var(--terra)', fontWeight: 700 }}>{g.qs.toFixed(1)}</div>
              <div style={{ textAlign: 'right' }}>
                <span style={{
                  display: 'inline-block', padding: '2px 6px', borderRadius: 4,
                  fontSize: 9, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase',
                  background: g.perf === 'top' ? 'var(--sage-soft)' : g.perf === 'low' ? 'var(--terra-soft)' : 'var(--cream-2)',
                  color:      g.perf === 'top' ? 'var(--sage)'      : g.perf === 'low' ? 'var(--terra)'     : 'var(--ink-3)',
                }}>{g.perf === 'top' ? 'Top' : g.perf === 'low' ? 'Lagging' : 'Avg'}</span>
              </div>
            </div>
          ))}
        </div>

        <div className="card card-pad">
          <div className="card-header" style={{ marginBottom: 12 }}>
            <div>
              <div className="card-title">Ad copy performance</div>
              <div className="card-sub">Responsive Search Ads · best to worst</div>
            </div>
          </div>
          {ads.map((ad, i) => (
            <div key={ad.headline} style={{ padding: '10px 0', borderBottom: i === ads.length - 1 ? 'none' : '1px solid var(--cream-2)' }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, marginBottom: 4 }}>
                <span style={{
                  padding: '2px 6px', borderRadius: 4, fontSize: 9, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase',
                  background: ad.status === 'top' ? 'var(--sage-soft)' : ad.status === 'low' ? 'var(--terra-soft)' : 'var(--cream-2)',
                  color:      ad.status === 'top' ? 'var(--sage)'      : ad.status === 'low' ? 'var(--terra)'     : 'var(--ink-3)',
                  flexShrink: 0,
                }}>{ad.strength}</span>
                <div style={{ flex: 1, fontSize: 12.5, color: 'var(--ink)', fontWeight: 600, lineHeight: 1.35 }}>{ad.headline}</div>
              </div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginBottom: 6, paddingLeft: 0, lineHeight: 1.4 }}>{ad.desc}</div>
              <div style={{ display: 'flex', gap: 14, fontSize: 10.5, color: 'var(--ink-3)', fontFamily: 'var(--ff-mono)' }}>
                <span>{ad.type}</span>
                <span>·</span>
                <span>CTR <strong style={{ color: 'var(--ink-2)' }}>{ad.ctr}%</strong></span>
                <span>·</span>
                <span>{ad.conv.toLocaleString()} conv.</span>
              </div>
            </div>
          ))}
        </div>
      </div>

      <SourceNote>Source: Google Ads</SourceNote>

      {/* Extensions */}
      <div className="card card-pad" style={{ marginBottom: 16 }}>
        <div className="card-header" style={{ marginBottom: 12 }}>
          <div>
            <div className="card-title">Ad extension performance</div>
            <div className="card-sub">Coverage and click-share across the portfolio</div>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
          {extensions.map(e => (
            <div key={e.type} style={{ padding: '12px 14px', background: 'var(--cream)', border: '1px solid ' + (e.healthy ? 'var(--cream-3)' : 'rgba(214, 116, 102, 0.40)'), borderRadius: 8, position: 'relative' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
                <span style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--ink-2)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{e.type}</span>
                {!e.healthy && <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--terra)' }}/>}
              </div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 6 }}>
                <span style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)' }}>{e.impr}M</span>
                <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>impr</span>
                <span style={{ flex: 1 }}/>
                <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 11.5, color: 'var(--ink-2)' }}>{e.ctr}% CTR</span>
              </div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', lineHeight: 1.4 }}>{e.note}</div>
              <div style={{ fontSize: 10.5, color: 'var(--ink-4)', marginTop: 6, fontFamily: 'var(--ff-mono)' }}>{e.conv.toLocaleString()} conversions</div>
            </div>
          ))}
        </div>
      </div>

      <SourceNote>Source: Google Ads</SourceNote>

      {/* Geo (DMAs) + Devices */}
      <div className="grid grid-2" style={{ marginBottom: 16 }}>
        <div className="card card-pad">
          <div className="card-header" style={{ marginBottom: 12 }}>
            <div>
              <div className="card-title">Top DMAs</div>
              <div className="card-sub">Where the volume lands · ranked by spend</div>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 0.6fr 0.7fr 0.7fr 0.6fr 0.5fr', gap: 8, padding: '6px 0 8px', borderBottom: '1px solid var(--cream-3)', fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>
            <span>DMA</span>
            <span style={{ textAlign: 'right' }}>Loc.</span>
            <span style={{ textAlign: 'right' }}>Spend</span>
            <span style={{ textAlign: 'right' }}>Clicks</span>
            <span style={{ textAlign: 'right' }}>CPL</span>
            <span style={{ textAlign: 'right' }}>QS</span>
          </div>
          {dmas.map((d, i) => (
            <div key={d.name} style={{ display: 'grid', gridTemplateColumns: '1.5fr 0.6fr 0.7fr 0.7fr 0.6fr 0.5fr', gap: 8, padding: '8px 0', borderBottom: i === dmas.length - 1 ? 'none' : '1px solid var(--cream-2)', alignItems: 'center', fontSize: 12 }}>
              <div style={{ color: 'var(--ink)', fontWeight: 600 }}>{d.name}</div>
              <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-3)' }}>{d.locations}</div>
              <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>{d.spend}</div>
              <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-3)' }}>{d.clicks}</div>
              <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: d.cpl <= 28 ? 'var(--sage)' : d.cpl <= 35 ? 'var(--ink-2)' : 'var(--terra)', fontWeight: 600 }}>${d.cpl}</div>
              <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: d.qs >= 8 ? 'var(--sage)' : d.qs >= 7 ? 'var(--marigold)' : 'var(--terra)', fontWeight: 700 }}>{d.qs.toFixed(1)}</div>
            </div>
          ))}
        </div>

        <div className="card card-pad">
          <div className="card-header" style={{ marginBottom: 12 }}>
            <div>
              <div className="card-title">Device split</div>
              <div className="card-sub">Mobile dominates lead volume</div>
            </div>
          </div>
          {devices.map(d => (
            <div key={d.name} style={{ marginBottom: 16, paddingBottom: 12, borderBottom: '1px solid var(--cream-2)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                <span style={{ width: 10, height: 10, borderRadius: '50%', background: d.color }}/>
                <div style={{ fontFamily: 'var(--ff-display)', fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{d.name}</div>
                <span style={{ flex: 1 }}/>
                <span style={{ fontSize: 12, color: 'var(--ink-3)', fontFamily: 'var(--ff-mono)' }}>{d.share}% share</span>
              </div>
              <div style={{ position: 'relative', height: 6, background: 'var(--cream-2)', borderRadius: 3, overflow: 'hidden', marginBottom: 8 }}>
                <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: `${d.share}%`, background: d.color, borderRadius: 3 }}/>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
                {[
                  { l: 'CTR',  v: d.ctr + '%' },
                  { l: 'CVR',  v: d.cvr + '%' },
                  { l: 'CPL',  v: '$' + d.cpl },
                ].map((s, i) => (
                  <div key={i} style={{ padding: '6px 8px', background: 'var(--cream)', borderRadius: 6 }}>
                    <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700 }}>{s.l}</div>
                    <div style={{ fontFamily: 'var(--ff-display)', fontSize: 13, fontWeight: 600, color: 'var(--ink)', marginTop: 1 }}>{s.v}</div>
                  </div>
                ))}
              </div>
            </div>
          ))}
          <div style={{ fontSize: 11.5, color: 'var(--ink-2)', lineHeight: 1.5 }}>
            <strong style={{ color: 'var(--ink)' }}>Mobile clicks convert 21% better than desktop.</strong> Tablet is a long tail, consider bid adjustments to reallocate to mobile.
          </div>
        </div>
      </div>

      <SourceNote>Source: Google Ads · CPL calculated by LOCALACT</SourceNote>

      {/* Time-of-day × Day-of-week heatmap */}
      <div className="card card-pad">
        <div className="card-header" style={{ marginBottom: 12 }}>
          <div>
            <div className="card-title">When leads come in</div>
            <div className="card-sub">Conversion volume by day-of-week and hour-of-day · last 30 days</div>
          </div>
          <div style={{ marginLeft: 'auto', fontSize: 11.5, color: 'var(--ink-3)' }}>
            Peak: <strong style={{ color: 'var(--ink)' }}>{dows[peakCell.d]} · {peakCell.h.toString().padStart(2,'0')}:00</strong>
          </div>
        </div>
        <div style={{ overflow: 'auto' }}>
          <div style={{ display: 'inline-grid', gridTemplateColumns: '36px repeat(24, 1fr)', gap: 2, minWidth: '100%' }}>
            <div/>
            {Array.from({ length: 24 }, (_, h) => (
              <div key={h} style={{ fontSize: 9, color: 'var(--ink-4)', textAlign: 'center', fontFamily: 'var(--ff-mono)' }}>
                {h % 3 === 0 ? h.toString().padStart(2,'0') : ''}
              </div>
            ))}
            {heat.map((row, d) => (
              <React.Fragment key={d}>
                <div style={{ fontSize: 10.5, color: 'var(--ink-3)', alignSelf: 'center', fontWeight: 600 }}>{dows[d]}</div>
                {row.map((v, h) => {
                  const a = v / 100;
                  // sky → violet ramp for paid search
                  const r = Math.round(232 - (232 - 126) * a);
                  const g = Math.round(238 - (238 - 87)  * a);
                  const b = Math.round(245 - (245 - 194) * a);
                  const bg = a < 0.08 ? 'var(--cream)' : `rgb(${r}, ${g}, ${b})`;
                  return (
                    <div key={h}
                         title={`${dows[d]} ${h.toString().padStart(2,'0')}:00 · index ${v}`}
                         style={{ height: 18, background: bg, borderRadius: 3, opacity: a < 0.08 ? 0.4 : 1 }}/>
                  );
                })}
              </React.Fragment>
            ))}
          </div>
        </div>
        <div style={{ marginTop: 10, fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.5 }}>
          Strongest conversions on weekday lunch (11:00–13:00, with a Mon–Wed catering inquiry spike at 10:00–11:00) and weekend dinner (Fri–Sun 17:00–20:00). Bid modifiers in these windows are paying for themselves at <strong style={{ color: 'var(--ink-2)' }}>+18% CVR</strong> vs flat-bid hours.
        </div>
      </div>
    </div>
  );
}
window.ResultsPpcHq = ResultsPpcHq;

// ====================================================================
// LSA HQ, dispute / lead-acceptance health as the brand-wide signal
// ====================================================================
function ResultsLsaHq({ data }) {
  return (
    <HqChannelShell
      data={data}
      channelKey="lsa"
      channelLabel="LSA"
      accent="var(--sage)"
      deltas={{ spend: 7, leads: 14, cpl: -9, roas: 0.6 }}
      locale={{
        underfundedTitle: 'Could absorb more lead volume',
        underfundedSub: 'Hitting daily cap, leads are spilling'
      }}
      healthSignal={
      <HqHealthSignal
        title="Brand-wide lead quality & disputes"
        sub="LSA charges are disputable, your dispute hit-rate determines true CPL"
        accent="var(--sage)"
        mainStat="32%"
        mainLabel="Avg. lead-rating rate"
        mainBar={{ pct: 32, label: 'target: 80% of charged leads rated' }}
        breakdown={[
        { label: 'Charged & accepted', value: '74%', pct: 74, color: 'var(--sage)' },
        { label: 'Disputed (credit recovered)', value: '12%', pct: 12, color: 'var(--marigold)' },
        { label: 'Disputed (rejected)', value: '8%', pct: 8, color: 'var(--terra)' },
        { label: 'Not yet rated (auto-accepts)', value: '6%', pct: 6, color: 'var(--ink-3)' }]
        }
        footer={<><strong style={{ color: 'var(--ink-2)' }}>Read:</strong> 38 of 700 locations rate &lt; 25% of leads, they auto-accept charges Google would credit back. Auto-rating saved enrolled locations $4,820 last month.</>}
        ctas={
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, width: '100%' }}>
              <div style={{ padding: '12px 14px', background: 'var(--sage-soft)', border: '1px solid var(--sage)', borderRadius: 10 }}>
                <div style={{ fontSize: 10.5, color: '#0d6b6b', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 6 }}>Recommended action</div>
                <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.5, marginBottom: 12 }}>
                  Roll out Lenny auto-rating to the <strong>38 locations rating &lt; 25% of leads</strong>. Every charged lead is rated within minutes, so Google credits back disputes they're currently auto-accepting, an est. <strong>$4,820+/mo</strong> recovered brand-wide.
                </div>
                <button className="btn btn-primary btn-sm" style={{ background: 'var(--sage)', borderColor: 'var(--sage)' }}
              onClick={() => Thq('Auto-rating rollout drafted', 'Lenny will start rating charged leads for the 38 flagged locations next billing cycle.', 'ok')}>
                  Roll out auto-rating →
                </button>
              </div>
            </div>
        } />

      } />);


}
window.ResultsLsaHq = ResultsLsaHq;

// ====================================================================
// LOCAL SEO HQ, AI-search visibility as the brand-wide signal
// ====================================================================
function ResultsSeoHq({ data }) {
  return (
    <HqChannelShell
      data={data}
      channelKey="seo"
      channelLabel="Local SEO"
      accent="var(--terra)"
      deltas={{ spend: 0, leads: 8, cpl: -4, roas: 0.2 }}
      locale={{
        underfundedTitle: 'Pages thinning, needs content',
        underfundedSub: 'Lowest velocity on local-page optimization'
      }}
      underfundedFooter={
      <div style={{ marginTop: 12, padding: 12, background: 'linear-gradient(135deg, var(--terra-soft), var(--marigold-soft))', borderRadius: 10 }}>
          <div style={{ fontSize: 10.5, color: '#917200', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 8 }}>Optimize all five pages</div>
          <div style={{ padding: '12px 14px', background: 'var(--paper)', border: '1px solid var(--terra)', borderRadius: 10 }}>
            <div style={{ fontSize: 10.5, color: '#a12118', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 6 }}>Recommended action</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.5, marginBottom: 12 }}>
              Refresh the <strong>5 thinning location pages</strong> on a quarterly cadence, schema, copy, fresh posts, and AI-search optimization pulled from the master playbook. Modeled <strong>+12 pts</strong> AI mention rate.
            </div>
            <button className="btn btn-primary btn-sm" style={{ background: 'var(--terra)', borderColor: 'var(--terra)' }}
            onClick={() => Thq('Page refresh scheduled', 'First quarterly refresh kicks off next week across the flagged location pages.', 'ok')}>
              Schedule quarterly refresh →
            </button>
          </div>
        </div>
      }
      healthSignal={
      <HqHealthSignal
        title="AI-search visibility"
        sub="How often your brand appears in ChatGPT, Perplexity, and Google AI Overview answers"
        accent="var(--terra)"
        mainStat="41%"
        mainLabel="AI mention rate"
        mainBar={{ pct: 41, label: '+9 pts MoM · brand index' }}
        breakdown={[
        { label: 'ChatGPT, branded queries', value: '52%', pct: 52, color: 'var(--terra)' },
        { label: 'Perplexity, branded queries', value: '47%', pct: 47, color: 'var(--marigold)' },
        { label: 'Google AI Overview, local queries', value: '38%', pct: 38, color: 'var(--sage)' },
        { label: 'Gemini, branded queries', value: '28%', pct: 28, color: 'var(--sky)' }]
        }
        footer={<><strong style={{ color: 'var(--ink-2)' }}>Read:</strong> AI-search referrals to location pages are up 3.4× YoY. Locations with structured data + fresh blog content get cited 2.1× more often than those without. Three brand-wide schema fixes would lift Gemini visibility ~12 pts.</>}
        ctas={
        <button className="btn btn-quiet btn-sm"
        onClick={() => Thq('AI-visibility plan',
        'Strategy Director will share the schema + content plan to lift AI mentions to 60%.', 'info')}>
              See the plan →
            </button>
        } />

      } />);


}
window.ResultsSeoHq = ResultsSeoHq;

// ====================================================================
// SOCIAL HQ, creative refresh cadence as the brand-wide signal
// ====================================================================
function ResultsSocialHq({ data }) {
  const [platform, setPlatform] = React.useState('all'); // all | meta | ig
  const [region, setRegion] = React.useState('all');     // all | northeast | southeast | midwest | central | west

  // ---- platform-segmented headline KPIs ----
  const kpis = {
    all:  { reach: '14.2M', impressions: '38.4M', engaged: '892K', ctr: '1.6%', cpe: '$0.42', leads: 412, costPerLead: '$22.40' },
    meta: { reach: '8.4M',  impressions: '21.6M', engaged: '494K', ctr: '1.4%', cpe: '$0.48', leads: 246, costPerLead: '$24.10' },
    ig:   { reach: '5.8M',  impressions: '16.8M', engaged: '398K', ctr: '1.9%', cpe: '$0.34', leads: 166, costPerLead: '$19.80' },
  }[platform];

  // ---- daily/hourly heatmap (day-of-week × hour-of-day, 7×24) ----
  // Engagement index 0–100. Higher = better engagement that hour.
  const dows = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  const heat = (() => {
    const grid = [];
    for (let d = 0; d < 7; d++) {
      const row = [];
      for (let h = 0; h < 24; h++) {
        // Lunch (11–13) and dinner (17–20) windows peak; weekends shift later.
        const lunchPeak  = Math.max(0, 1 - Math.abs(h - 12) / 3);
        const dinnerPeak = Math.max(0, 1 - Math.abs(h - 18.5) / 3.2);
        const weekendShift = (d >= 5 ? 1.15 : 1.0);
        const noise = ((d * 31 + h * 17) % 11) / 11 * 0.15;
        const v = Math.min(100, (lunchPeak * 0.55 + dinnerPeak * 0.78 + noise) * 100 * weekendShift);
        row.push(Math.round(v));
      }
      grid.push(row);
    }
    return grid;
  })();
  const peakCell = (() => {
    let best = { d: 0, h: 0, v: 0 };
    heat.forEach((row, d) => row.forEach((v, h) => { if (v > best.v) best = { d, h, v }; }));
    return best;
  })();

  // ---- demos ----
  const ageRows = [
    { label: '18–24', share: 12, eng: 1.2, color: 'var(--sky)' },
    { label: '25–34', share: 28, eng: 1.8, color: 'var(--violet)' },
    { label: '35–44', share: 31, eng: 2.1, color: 'var(--marigold)' },
    { label: '45–54', share: 18, eng: 1.6, color: 'var(--terra)' },
    { label: '55–64', share: 8,  eng: 1.0, color: 'var(--sage)' },
    { label: '65+',   share: 3,  eng: 0.7, color: 'var(--ink-3)' },
  ];
  const genderRows = [
    { label: 'Female', share: 56, color: 'var(--terra)' },
    { label: 'Male',   share: 41, color: 'var(--sky)' },
    { label: 'Unspecified', share: 3, color: 'var(--ink-3)' },
  ];

  // ---- top geos ----
  const geos = [
    { region: 'Central',   locations: 38, reach: '4.8M', engaged: '312K', ctr: 1.8, leads: 142 },
    { region: 'West',      locations: 34, reach: '3.7M', engaged: '252K', ctr: 1.8, leads: 112 },
    { region: 'Midwest',   locations: 37, reach: '2.9M', engaged: '168K', ctr: 1.4, leads: 74  },
    { region: 'Southeast', locations: 19, reach: '2.1M', engaged: '146K', ctr: 1.7, leads: 71  },
    { region: 'Northeast', locations: 14, reach: '1.4M', engaged: '92K',  ctr: 1.5, leads: 41  },
  ];

  // ---- top creatives ----
  const creatives = [
    { name: 'Deep clean transformation',      fmt: 'Reel',   plat: 'IG',    age: 18, eng: '4.8%', ctr: '2.4%', spend: '$1,840', perf: 'top' },
    { name: 'Family home testimonial',          fmt: 'Carousel', plat: 'FB+IG', age: 24, eng: '3.6%', ctr: '1.9%', spend: '$2,210', perf: 'top' },
    { name: 'Product bundle showcase',          fmt: 'Static', plat: 'FB',    age: 9,  eng: '2.4%', ctr: '1.6%', spend: '$980',   perf: 'avg' },
    { name: 'Eco tips & tricks · 30s',          fmt: 'Reel',   plat: 'IG',    age: 36, eng: '3.1%', ctr: '1.4%', spend: '$1,420', perf: 'avg' },
    { name: 'Spring clean motivation video',    fmt: 'Video',  plat: 'FB',    age: 67, eng: '1.6%', ctr: '0.9%', spend: '$1,680', perf: 'fatigued' },
    { name: 'Holiday hours · template',    fmt: 'Static', plat: 'FB+IG', age: 42, eng: '0.8%', ctr: '0.4%', spend: '$640',   perf: 'fatigued' },
  ];

  // ---- platform comparison ----
  const platforms = [
    { name: 'Facebook',  reach: '8.4M', engRate: 1.4, costEng: 0.48, leads: 246, mix: 'Feed 62 · Reels 21 · Stories 17', color: '#1877F2' },
    { name: 'Instagram', reach: '5.8M', engRate: 1.9, costEng: 0.34, leads: 166, mix: 'Reels 58 · Feed 27 · Stories 15', color: '#E1306C' },
  ];

  return (
    <div>
      {/* Platform / region filters */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14, flexWrap: 'wrap' }}>
        <div style={{ display: 'inline-flex', background: 'var(--cream)', border: '1px solid var(--cream-3)', borderRadius: 8, padding: 2 }}>
          {[
            { v: 'all',  l: 'All platforms' },
            { v: 'meta', l: 'Facebook' },
            { v: 'ig',   l: 'Instagram' },
          ].map(o => (
            <button key={o.v}
                    onClick={() => setPlatform(o.v)}
                    style={{
                      padding: '6px 12px',
                      background: platform === o.v ? 'var(--paper)' : 'transparent',
                      border: 'none',
                      borderRadius: 6,
                      fontSize: 12, fontWeight: 600,
                      color: platform === o.v ? 'var(--ink)' : 'var(--ink-3)',
                      cursor: 'pointer',
                      boxShadow: platform === o.v ? '0 1px 2px rgba(0,0,0,0.06)' : 'none',
                    }}>{o.l}</button>
          ))}
        </div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>
          Last 30 days · 700 locations · all paid + organic Social
        </div>
      </div>

      {/* Headline KPI strip */}
      <div className="grid grid-4" style={{ marginBottom: 16 }}>
        <KpiCard label="Reach"           value={kpis.reach}        delta={8}  color="var(--violet)"  dotColor="var(--violet)"/>
        <KpiCard label="Engagements"     value={kpis.engaged}      delta={12} color="var(--terra)"   dotColor="var(--terra)"/>
        <KpiCard label="Avg engagement rate" value={kpis.ctr}      delta={4}  color="var(--marigold)" dotColor="var(--marigold)"/>
        <KpiCard label="Leads attributed" value={kpis.leads}       delta={6}  color="var(--sage)"    dotColor="var(--sage)"/>
      </div>

      <SourceNote>Source: Meta · CPL &amp; ROAS calculated by LOCALACT</SourceNote>

      {/* Creative-fatigue alert (kept) */}
      <div className="card card-pad" style={{ marginBottom: 16, background: 'linear-gradient(135deg, var(--terra-softer), var(--paper) 70%)', border: '1px solid rgba(214, 116, 102, 0.30)' }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
          <span style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--terra-soft)', color: 'var(--terra)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14, fontWeight: 700, flexShrink: 0 }}>!</span>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 600, color: 'var(--ink)', marginBottom: 4 }}>62 locations need new creative</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.5 }}>
              Running ads &gt; 60 days old at frequency ≥ 4. CTR has dropped <strong>0.4 pts</strong> vs the fresh cohort. Engagement is the leading indicator, fatigue here predicts a CPL hit in 2–3 weeks.
            </div>
          </div>
          <button className="btn btn-quiet btn-sm" onClick={() => Thq('Creative brief drafted', 'Lenny generated a brief for 6 new ad variants based on top-performing themes. Review in Campaigns.', 'info')}>
            Draft creative brief →
          </button>
        </div>
      </div>

      {/* Day-of-week × Hour heatmap */}
      <div className="card card-pad" style={{ marginBottom: 16 }}>
        <div className="card-header" style={{ marginBottom: 12 }}>
          <div>
            <div className="card-title">When your audience engages</div>
            <div className="card-sub">Engagement rate index by day-of-week and hour-of-day · last 30 days</div>
          </div>
          <div style={{ marginLeft: 'auto', fontSize: 11.5, color: 'var(--ink-3)' }}>
            Peak: <strong style={{ color: 'var(--ink)' }}>{dows[peakCell.d]} · {peakCell.h.toString().padStart(2,'0')}:00</strong>
          </div>
        </div>
        <div style={{ overflow: 'auto' }}>
          <div style={{ display: 'inline-grid', gridTemplateColumns: '36px repeat(24, 1fr)', gap: 2, minWidth: '100%' }}>
            <div/>
            {Array.from({ length: 24 }, (_, h) => (
              <div key={h} style={{ fontSize: 9, color: 'var(--ink-4)', textAlign: 'center', fontFamily: 'var(--ff-mono)' }}>
                {h % 3 === 0 ? h.toString().padStart(2,'0') : ''}
              </div>
            ))}
            {heat.map((row, d) => (
              <React.Fragment key={d}>
                <div style={{ fontSize: 10.5, color: 'var(--ink-3)', alignSelf: 'center', fontWeight: 600 }}>{dows[d]}</div>
                {row.map((v, h) => {
                  const a = v / 100;
                  // marigold→terra ramp for engagement; ink dim for cold cells
                  const r = Math.round(248 - (248 - 214) * a);
                  const g = Math.round(180 + (116 - 180) * a);
                  const b = Math.round(127 + (102 - 127) * a);
                  const bg = a < 0.08 ? 'var(--cream)' : `rgb(${r}, ${g}, ${b})`;
                  return (
                    <div key={h}
                         title={`${dows[d]} ${h.toString().padStart(2,'0')}:00 · index ${v}`}
                         style={{ height: 18, background: bg, borderRadius: 3, opacity: a < 0.08 ? 0.4 : 1 }}/>
                  );
                })}
              </React.Fragment>
            ))}
          </div>
        </div>
        <div style={{ marginTop: 10, fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.5 }}>
          Strongest engagement on weekend evenings (Sat–Sun 17:00–20:00) and weekday lunch (11:00–13:00). Schedule new creative drops 2 hours ahead of these windows.
        </div>
      </div>

      <SourceNote>Source: Meta</SourceNote>

      {/* Demographics + Platform comparison side-by-side */}
      <div className="grid grid-2" style={{ marginBottom: 16 }}>
        {/* Age + gender */}
        <div className="card card-pad">
          <div className="card-header" style={{ marginBottom: 12 }}>
            <div>
              <div className="card-title">Demographics</div>
              <div className="card-sub">Who's engaging across all 700 locations</div>
            </div>
          </div>
          <div style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, marginBottom: 8 }}>Age cohort</div>
          {ageRows.map(r => (
            <div key={r.label} style={{ display: 'grid', gridTemplateColumns: '50px 1fr 60px 60px', gap: 10, alignItems: 'center', padding: '5px 0' }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-2)', fontFamily: 'var(--ff-mono)' }}>{r.label}</div>
              <div style={{ position: 'relative', height: 8, background: 'var(--cream-2)', borderRadius: 4, overflow: 'hidden' }}>
                <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: `${r.share / 35 * 100}%`, background: r.color, borderRadius: 4 }}/>
              </div>
              <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 11.5, color: 'var(--ink-3)', textAlign: 'right' }}>{r.share}%</div>
              <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 11.5, color: r.eng >= 1.8 ? 'var(--sage)' : r.eng >= 1.2 ? 'var(--ink-3)' : 'var(--terra)', textAlign: 'right', fontWeight: 600 }}>{r.eng}× idx</div>
            </div>
          ))}
          <div style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, marginTop: 14, marginBottom: 8 }}>Gender</div>
          <div style={{ display: 'flex', height: 14, background: 'var(--cream-2)', borderRadius: 4, overflow: 'hidden', marginBottom: 8 }}>
            {genderRows.map(g => (
              <div key={g.label} style={{ width: `${g.share}%`, background: g.color }} title={`${g.label}: ${g.share}%`}/>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 14, fontSize: 11, color: 'var(--ink-3)' }}>
            {genderRows.map(g => (
              <div key={g.label} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                <span style={{ width: 8, height: 8, borderRadius: 2, background: g.color }}/>
                {g.label} <strong style={{ color: 'var(--ink-2)' }}>{g.share}%</strong>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 12, padding: '10px 12px', background: 'var(--cream)', borderRadius: 8, fontSize: 11.5, color: 'var(--ink-2)', lineHeight: 1.5 }}>
            <strong>35–44 over-indexes 2.1×.</strong> Family + catering creative resonates strongest here, keep weight on it.
          </div>
        </div>

        {/* Platform comparison */}
        <div className="card card-pad">
          <div className="card-header" style={{ marginBottom: 12 }}>
            <div>
              <div className="card-title">Facebook vs Instagram</div>
              <div className="card-sub">Where engagement is happening, by platform</div>
            </div>
          </div>
          {platforms.map(p => (
            <div key={p.name} style={{ marginBottom: 14, paddingBottom: 12, borderBottom: '1px solid var(--cream-2)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                <span style={{ width: 10, height: 10, borderRadius: '50%', background: p.color }}/>
                <div style={{ fontFamily: 'var(--ff-display)', fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{p.name}</div>
                <span style={{ flex: 1 }}/>
                <span style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--ff-mono)' }}>{p.reach} reach</span>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, marginBottom: 8 }}>
                {[
                  { l: 'Engagement rate', v: p.engRate + '%' },
                  { l: 'Cost / engagement', v: '$' + p.costEng.toFixed(2) },
                  { l: 'Leads', v: p.leads },
                ].map((s, i) => (
                  <div key={i} style={{ padding: '6px 8px', background: 'var(--cream)', borderRadius: 6 }}>
                    <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700 }}>{s.l}</div>
                    <div style={{ fontFamily: 'var(--ff-display)', fontSize: 14, fontWeight: 600, color: 'var(--ink)', marginTop: 1 }}>{s.v}</div>
                  </div>
                ))}
              </div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--ff-mono)' }}>{p.mix}</div>
            </div>
          ))}
          <div style={{ fontSize: 11.5, color: 'var(--ink-2)', lineHeight: 1.5 }}>
            <strong style={{ color: 'var(--ink)' }}>Instagram engages harder, Facebook reaches wider.</strong> Reels are doing 1.4× the work of Feed posts on IG, that's where new creative should land first.
          </div>
        </div>
      </div>

      <SourceNote>Source: Meta</SourceNote>

      {/* Top geos */}
      <div className="card card-pad" style={{ marginBottom: 16 }}>
        <div className="card-header" style={{ marginBottom: 12 }}>
          <div>
            <div className="card-title">Performance by region</div>
            <div className="card-sub">Where social is delivering, ranked by engagement volume · region groupings will be franchisor-configurable</div>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 0.8fr 0.8fr 0.8fr 0.6fr 0.7fr', gap: 8, padding: '6px 10px 8px', borderBottom: '1px solid var(--cream-3)', fontSize: 10, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>
          <span>Region</span>
          <span style={{ textAlign: 'right' }}>Locations</span>
          <span style={{ textAlign: 'right' }}>Reach</span>
          <span style={{ textAlign: 'right' }}>Engaged</span>
          <span style={{ textAlign: 'right' }}>Eng. rate</span>
          <span style={{ textAlign: 'right' }}>Leads</span>
        </div>
        {geos.map((g, i) => (
          <div key={g.region} style={{ display: 'grid', gridTemplateColumns: '1.6fr 0.8fr 0.8fr 0.8fr 0.6fr 0.7fr', gap: 8, padding: '10px', borderBottom: i === geos.length - 1 ? 'none' : '1px solid var(--cream-2)', alignItems: 'center', fontSize: 12.5 }}>
            <div style={{ color: 'var(--ink)', fontWeight: 600 }}>{g.region}</div>
            <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-3)' }}>{g.locations}</div>
            <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>{g.reach}</div>
            <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>{g.engaged}</div>
            <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: g.ctr >= 1.7 ? 'var(--sage)' : g.ctr >= 1.4 ? 'var(--ink-2)' : 'var(--terra)', fontWeight: 600 }}>{g.ctr}%</div>
            <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>{g.leads}</div>
          </div>
        ))}
      </div>

      <SourceNote>Source: Meta</SourceNote>

      {/* Top creatives */}
      <div className="card card-pad">
        <div className="card-header" style={{ marginBottom: 12 }}>
          <div>
            <div className="card-title">Top + fatigued creatives</div>
            <div className="card-sub">What's working, what's worn out, across all 700 locations</div>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1.8fr 0.6fr 0.6fr 0.6fr 0.6fr 0.6fr 0.7fr 0.8fr', gap: 8, padding: '6px 10px 8px', borderBottom: '1px solid var(--cream-3)', fontSize: 10, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>
          <span>Asset</span>
          <span>Format</span>
          <span>Platform</span>
          <span style={{ textAlign: 'right' }}>Days live</span>
          <span style={{ textAlign: 'right' }}>Eng.</span>
          <span style={{ textAlign: 'right' }}>CTR</span>
          <span style={{ textAlign: 'right' }}>Spend</span>
          <span style={{ textAlign: 'right' }}>Status</span>
        </div>
        {creatives.map((c, i) => (
          <div key={c.name} style={{ display: 'grid', gridTemplateColumns: '1.8fr 0.6fr 0.6fr 0.6fr 0.6fr 0.6fr 0.7fr 0.8fr', gap: 8, padding: '10px', borderBottom: i === creatives.length - 1 ? 'none' : '1px solid var(--cream-2)', alignItems: 'center', fontSize: 12.5 }}>
            <div style={{ color: 'var(--ink)', fontWeight: 600 }}>{c.name}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{c.fmt}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{c.plat}</div>
            <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: c.age > 60 ? 'var(--terra)' : c.age > 30 ? 'var(--marigold)' : 'var(--ink-3)' }}>{c.age}d</div>
            <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>{c.eng}</div>
            <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>{c.ctr}</div>
            <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>{c.spend}</div>
            <div style={{ textAlign: 'right' }}>
              <span style={{
                display: 'inline-block',
                padding: '2px 7px',
                borderRadius: 4,
                fontSize: 9.5, fontWeight: 700,
                letterSpacing: '0.06em', textTransform: 'uppercase',
                background:
                  c.perf === 'top'      ? 'var(--sage-soft)' :
                  c.perf === 'fatigued' ? 'var(--terra-soft)' :
                                          'var(--cream-2)',
                color:
                  c.perf === 'top'      ? 'var(--sage)' :
                  c.perf === 'fatigued' ? 'var(--terra)' :
                                          'var(--ink-3)',
              }}>{c.perf === 'top' ? 'Top 10%' : c.perf === 'fatigued' ? 'Fatigued' : 'Average'}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
window.ResultsSocialHq = ResultsSocialHq;

// ====================================================================
// DEMAND GEN HQ, activation pitch (no perf data; channel isn't enrolled)
// ====================================================================
function ResultsDemandGenHq({ data }) {
  const [confirmActivate, setConfirmActivate] = useStateHQ(false);
  const totalLocations = data.playbookPortfolio?.totalLocations || data.hqRollup?.length || 142;
  const adoption = (data.playbookPortfolio?.channelAdoption || []).find((c) => c.channel === 'Demand Gen');

  // Modeled brand impact, anchored on the existing data.demandGenDetail.pitch
  // shape so franchisee + HQ pitches stay in lockstep, with portfolio scaling.
  const projReachM = 14.8; // total monthly reach (millions) across enrolled locations
  const projCplLift = -11; // % blended CPL improvement across paid channels
  const projBrandLift = +28; // % uplift in branded-search volume
  const projWouldBenefit = 96; // locations where DGen would clear minimum-volume bar

  return (
    <>
      {/* ============ PITCH HERO ============ */}
      <div className="card" style={{
        overflow: 'hidden', position: 'relative', marginBottom: 16,
        background: 'linear-gradient(135deg, #001132 0%, #001e40 50%, #4d6989 100%)',
        color: 'var(--cream)'
      }}>
        <div style={{ position: 'absolute', top: -50, right: -50, width: 240, height: 240, borderRadius: '50%', background: 'rgba(255,255,255,.05)' }} />
        <div style={{ position: 'absolute', bottom: -70, left: -40, width: 200, height: 200, borderRadius: '50%', background: 'rgba(214,184,77,.08)' }} />

        <div style={{ position: 'relative', padding: '32px 36px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
            <span style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '.12em', fontWeight: 700, padding: '4px 10px', background: 'var(--marigold)', color: 'var(--ink)', borderRadius: 4 }}>NEW · Brand-wide opportunity</span>
            <span style={{ fontSize: 11, color: 'rgba(250,246,239,.7)' }}>Not yet in your playbook</span>
          </div>

          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 38, fontWeight: 500, letterSpacing: '-0.025em', lineHeight: 1.05, marginBottom: 14, maxWidth: 720 }}>
            Demand Gen isn't in your playbook yet.
          </div>

          <div style={{ fontSize: 14, lineHeight: 1.6, color: 'rgba(250,246,239,.85)', maxWidth: 760, marginBottom: 22 }}>
            Demand Gen is Google's upper-funnel campaign type, placements across YouTube, Discover, and Gmail. For franchise brands, it builds the familiarity that lifts every paid channel's conversion rate. It's the play to run when paid-search demand starts to plateau and you need to manufacture more of it. Locations enrolled in Demand Gen for 90+ days see <strong style={{ color: 'var(--marigold)' }}>~28% more branded search</strong> and <strong style={{ color: 'var(--marigold)' }}>11% lower blended CPL</strong> across all paid channels.
          </div>

          {/* Modeled-impact KPI strip */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, padding: 18, background: 'rgba(255,255,255,.07)', borderRadius: 12, border: '1px solid rgba(255,255,255,.1)', marginBottom: 22 }}>
            {[
            { l: 'Modeled reach', v: `${projReachM}M/mo`, sub: 'unique users across portfolio' },
            { l: 'Blended CPL impact', v: `${projCplLift}%`, sub: 'on Search + LSA + Social' },
            { l: 'Branded-search lift', v: `+${projBrandLift}%`, sub: 'vs current 90-day baseline' },
            { l: 'Locations that benefit', v: `${projWouldBenefit} of ${totalLocations}`, sub: 'clear minimum-volume bar' }].
            map((k) =>
            <div key={k.l}>
                <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '.06em', color: 'rgba(250,246,239,.55)', marginBottom: 4, fontWeight: 600 }}>{k.l}</div>
                <div style={{ fontFamily: 'var(--ff-display)', fontSize: 26, fontWeight: 500, color: 'var(--cream)', letterSpacing: '-0.02em' }}>{k.v}</div>
                <div style={{ fontSize: 10.5, color: 'rgba(250,246,239,.55)', marginTop: 2 }}>{k.sub}</div>
              </div>
            )}
          </div>

          <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
            <button className="btn btn-primary btn-sm"
            onClick={() => setConfirmActivate(true)}
            style={{ background: 'var(--marigold)', color: 'var(--ink)', borderColor: 'var(--marigold)', fontWeight: 600 }}>
              Activate Demand Gen in playbook →
            </button>
            <button className="btn btn-quiet btn-sm"
            style={{ background: 'rgba(250,246,239,.1)', borderColor: 'rgba(250,246,239,.2)', color: 'var(--cream)' }}
            onClick={() => Thq('Pilot drafted',
            '5-location Demand Gen pilot proposed for top-ROAS units. Strategy Director will route for approval.', 'ok')}>
              Pilot in 5 locations first
            </button>
            <span style={{ fontSize: 11, color: 'rgba(250,246,239,.6)' }}>· {adoption ? `${adoption.enrolled} other Location3 brands already running` : '312 other Location3 brands already running'}</span>
          </div>
        </div>
      </div>

      <SourceNote>Estimated by LOCALACT</SourceNote>

      {/* ============ WHAT IT DOES + WHO IT'S FOR ============ */}
      <div className="grid grid-2" style={{ marginBottom: 16 }}>
        <div className="card card-pad">
          <div className="card-header" style={{ marginBottom: 12 }}>
            <div>
              <div className="card-title">What Demand Gen does</div>
              <div className="card-sub">Three jobs upper-funnel media handles for franchise brands</div>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {[
            { k: '1', t: 'Manufactures branded-search volume', d: 'Visual ads across YouTube, Discover, and Gmail. People who see them search your brand 4–8 weeks later, that\'s the cheapest paid-search lead you\'ll ever get.' },
            { k: '2', t: 'Lowers blended CPL across every channel', d: 'Familiarity raises Quality Score on Search and conversion rate on LSA + Social. Brands running DGen for 90+ days see 8–14% blended CPL drops.' },
            { k: '3', t: 'Lifts every Paid Search dollar', d: 'A user who saw your YouTube ad converts at 1.8× the rate of one who didn\'t. Your existing Search budget gets meaningfully more efficient.' }].
            map((s) =>
            <div key={s.k} style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                <span style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--cream)', color: 'var(--violet)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--ff-display)', fontSize: 14, fontWeight: 600, flexShrink: 0 }}>{s.k}</span>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', marginBottom: 3 }}>{s.t}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.5 }}>{s.d}</div>
                </div>
              </div>
            )}
          </div>
        </div>

        <div className="card card-pad">
          <div className="card-header" style={{ marginBottom: 12 }}>
            <div>
              <div className="card-title">Locations that would benefit most</div>
              <div className="card-sub">Top 5 modeled, paid-search demand plateauing, brand-search headroom</div>
            </div>
          </div>
          {(() => {
            // Pick 5 high-spend, high-paid-search-IS-loss locations from the rollup as the "best fit" cohort.
            const candidates = [...(data.hqRollup || [])].
            filter((r) => r.services.includes('ppc') && r.score >= 80).
            sort((a, b) => b.spend - a.spend).
            slice(0, 5).
            map((r) => ({
              ...r,
              modeledLift: Math.round(r.leads * 0.18 + 6), // +18% leads, modest floor
              cplCut: Math.round(8 + (95 - r.score) * 0.4)
            }));
            return candidates.map((r, i) =>
            <div key={r.unit} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: '10px 6px',
              borderBottom: i === candidates.length - 1 ? 'none' : '1px solid var(--cream-2)'
            }}>
                <span style={{
                width: 22, height: 22, borderRadius: '50%', background: 'var(--violet-soft, #e0e5eb)',
                color: 'var(--violet)', display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 11, fontWeight: 700
              }}>{i + 1}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink)' }}>{r.unit}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-4)' }}>{r.city}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 12.5, color: 'var(--sage)', fontWeight: 600 }}>+{r.modeledLift} leads/mo</div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-4)' }}>−{r.cplCut}% blended CPL</div>
                </div>
              </div>
            );
          })()}
        </div>
      </div>

      <SourceNote>Estimated by LOCALACT</SourceNote>

      {/* ============ WHEN TO RUN IT ============ */}
      <div className="card card-pad" style={{ marginBottom: 16 }}>
        <div className="card-header" style={{ marginBottom: 14 }}>
          <div>
            <div className="card-title">Why activate now</div>
            <div className="card-sub">Three signals from your portfolio that say it's time</div>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
          {[
          { tag: 'SIGNAL', t: 'Paid Search IS-loss to budget is rising', d: '21% of impressions lost to budget brand-wide, up from 14% Q1. Adding DGen lifts Quality Score so existing budget wins more auctions.' },
          { tag: 'SIGNAL', t: 'Branded-search volume flat 6 months', d: 'Total branded queries across 700 locations grew +1.4% YoY vs +18% for paid clicks. You\'re harvesting demand, not creating it.' },
          { tag: 'SIGNAL', t: '312 peer L3 brands already running', d: 'Comparable franchise brands run DGen at $400–800/mo per location. Your blended CPL is 14% above peer median, DGen closes that gap.' }].
          map((s, i) =>
          <div key={i} style={{ padding: 14, background: 'var(--cream)', borderRadius: 10 }}>
              <div style={{ fontSize: 9.5, color: 'var(--violet)', fontWeight: 700, letterSpacing: '.1em', marginBottom: 6 }}>{s.tag}</div>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', marginBottom: 6, lineHeight: 1.3 }}>{s.t}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.5 }}>{s.d}</div>
            </div>
          )}
        </div>
      </div>

      <SourceNote>Source: Google Ads + FreshNest CRM</SourceNote>

      {/* ============ ACTIVATION CONFIRM MODAL ============ */}
      {confirmActivate &&
      <window.ModalPortal><div onClick={() => setConfirmActivate(false)} style={{
        position: 'fixed', inset: 0, background: 'rgba(28,24,20,.45)', zIndex: 1200,
        display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24
      }}>
          <div onClick={(e) => e.stopPropagation()} style={{
          background: 'var(--paper)', borderRadius: 14, maxWidth: 540, width: '100%',
          padding: 28, boxShadow: '0 24px 80px rgba(28,24,20,.35)'
        }}>
            <div style={{ fontSize: 9.5, color: 'var(--violet)', fontWeight: 700, letterSpacing: '.12em', marginBottom: 8 }}>PLAYBOOK ACTIVATION</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 24, fontWeight: 500, letterSpacing: '-0.02em', marginBottom: 12 }}>
              Activate Demand Gen across the playbook?
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', lineHeight: 1.55, marginBottom: 18 }}>
              Activating makes Demand Gen available to all <strong style={{ color: 'var(--ink-2)' }}>{totalLocations} locations</strong> and notifies your Strategy Director. Locations enroll opt-in, no auto-enrollment, no auto-billing.
            </div>
            <div style={{ padding: 14, background: 'var(--cream)', borderRadius: 10, marginBottom: 22, fontSize: 12.5, color: 'var(--ink-2)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                <span style={{ color: 'var(--ink-3)' }}>Recommended local spend</span>
                <strong>$400 – $800/mo per location</strong>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                <span style={{ color: 'var(--ink-3)' }}>Corporate co-fund (optional)</span>
                <strong>$25K/mo brand creative pool</strong>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: 'var(--ink-3)' }}>Time to first campaign live</span>
                <strong>~14 days from activation</strong>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
              <button className="btn btn-ghost btn-sm" onClick={() => setConfirmActivate(false)}>Cancel</button>
              <button className="btn btn-primary btn-sm"
            style={{ background: 'var(--violet)', borderColor: 'var(--violet)' }}
            onClick={() => {
              setConfirmActivate(false);
              Thq('Demand Gen activated', `Available to all ${totalLocations} locations. Strategy Director notified, they\'ll reach out within 1 business day with the rollout plan.`, 'ok');
            }}>
                Activate playbook-wide →
              </button>
            </div>
          </div>
        </div></window.ModalPortal>
      }
    </>);

}
window.ResultsDemandGenHq = ResultsDemandGenHq;