// ====================================================================
// RESULTS PAGE, channel-specific deep dives
// Tabs: Overview · Paid Search · LSA · Local SEO · Social · Demand Gen · Leads
// ====================================================================
const { useState: useStateR, useMemo: useMemoR } = React;

// --------------------------------------------------------------------
// Tiny chart primitives, kept local to results so they don't pollute
// --------------------------------------------------------------------

// Donut
function ResultsDonut({ segments, size = 140, strokeW = 22, center }) {
  const total = segments.reduce((a, s) => a + s.value, 0);
  const C = 2 * Math.PI * (size / 2 - strokeW / 2);
  let acc = 0;
  return (
    <div style={{ position: 'relative', width: size, height: size }}>
      <svg width={size} height={size} style={{ transform: 'rotate(-90deg)' }}>
        <circle cx={size/2} cy={size/2} r={size/2 - strokeW/2} fill="none" stroke="var(--cream-2)" strokeWidth={strokeW}/>
        {segments.map((s, i) => {
          const len = (s.value / total) * C;
          const dash = `${len} ${C - len}`;
          const offset = -acc;
          acc += len;
          return <circle key={i} cx={size/2} cy={size/2} r={size/2 - strokeW/2} fill="none" stroke={s.color} strokeWidth={strokeW} strokeDasharray={dash} strokeDashoffset={offset}/>;
        })}
      </svg>
      {center && <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column' }}>{center}</div>}
    </div>
  );
}

// Horizontal stacked bar (1 row)
function StackedRow({ segments, h = 12, radius = 6 }) {
  const total = segments.reduce((a, s) => a + s.value, 0);
  return (
    <div style={{ display: 'flex', height: h, borderRadius: radius, overflow: 'hidden', background: 'var(--cream-2)' }}>
      {segments.map((s, i) => (
        <div key={i} title={`${s.label}: ${s.value}`} style={{ width: `${(s.value/total)*100}%`, background: s.color }}/>
      ))}
    </div>
  );
}

// Lightweight horizontal bar list, for terms / keywords / pages
function HBars({ rows, max, valKey = 'value', labelKey = 'label', color = 'var(--terra)', formatter }) {
  const m = max || Math.max(...rows.map(r => r[valKey])) * 1.1;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {rows.map((r, i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 60px', gap: 12, alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: 12.5, fontWeight: 500, marginBottom: 4 }}>{r[labelKey]}</div>
            <div style={{ height: 7, borderRadius: 4, background: 'var(--cream-2)', overflow: 'hidden' }}>
              <div style={{ width: `${(r[valKey]/m)*100}%`, height: '100%', background: r.color || color, borderRadius: 4 }}/>
            </div>
          </div>
          <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 12, color: 'var(--ink-2)', textAlign: 'right' }}>
            {formatter ? formatter(r[valKey]) : r[valKey].toLocaleString()}
          </div>
        </div>
      ))}
    </div>
  );
}

// Impression-share gauge, 0–100 fill with lost-share segments
function ISGauge({ won, lostBudget, lostRank, height = 36 }) {
  return (
    <div>
      <div style={{ display: 'flex', height, borderRadius: 8, overflow: 'hidden', background: 'var(--cream-2)', border: '1px solid var(--line)' }}>
        <div style={{ width: `${won}%`, background: 'var(--sage)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink)', fontSize: 11.5, fontWeight: 600 }}>
          {won >= 12 ? `Won ${won}%` : ''}
        </div>
        <div style={{ width: `${lostBudget}%`, background: 'var(--marigold)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink)', fontSize: 11.5, fontWeight: 600 }}>
          {lostBudget >= 12 ? `Lost · budget ${lostBudget}%` : ''}
        </div>
        <div style={{ width: `${lostRank}%`, background: 'var(--clay)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink)', fontSize: 11.5, fontWeight: 600 }}>
          {lostRank >= 12 ? `Lost · rank ${lostRank}%` : ''}
        </div>
      </div>
      <div style={{ display: 'flex', gap: 14, marginTop: 8, fontSize: 11, color: 'var(--ink-3)' }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}><span style={{ width: 10, height: 10, background: 'var(--sage)', borderRadius: 2 }}/>Impressions won</span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}><span style={{ width: 10, height: 10, background: 'var(--marigold)', borderRadius: 2 }}/>Lost, budget</span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}><span style={{ width: 10, height: 10, background: 'var(--clay)', borderRadius: 2 }}/>Lost, rank/quality</span>
      </div>
    </div>
  );
}

// --------------------------------------------------------------------
// ENROLLMENT OPPORTUNITY CARD, used when a channel isn't enrolled
// for the bare variant. Renders the same hero treatment as the
// Demand Gen pitch but parameterized off a dormantChannels[] row.
// --------------------------------------------------------------------
function EnrollmentOpportunityCard({ channelKey, dormantChannels }) {
  const dormant = (dormantChannels || []).find(d => d.key === channelKey);
  const meta = {
    lsa:    { tab: 'Local Services Ads',  blurb: 'Top-of-Maps placement that bills only when a Google-verified lead calls. Lowest-CPL channel for service businesses.', surfaces: ['Google Maps top block', 'Local Services Ads carousel', 'Phone-call leads'] },
    seo:    { tab: 'Local SEO',           blurb: 'Localized pages, content, citations, and on-page work that compounds. Earns leads without paying per click.', surfaces: ['Google organic results', 'Map Pack rankings', 'Branded long-tail terms'] },
    llm:    { tab: 'Listings',            blurb: 'NAP accuracy across 42 directories. Bad NAP suppresses paid ads and breaks the conversion path. Required, not optional.', surfaces: ['Google Business Profile', 'Yelp · Apple Maps · Bing', '38 mid-tier directories'] },
    social: { tab: 'Social Ads',          blurb: 'Paid creative on Meta and Instagram. Awareness, retargeting, promo pushes. Pairs with Search.', surfaces: ['Meta feed', 'Instagram Reels & Stories', 'Audience Network'] },
    lseo:   { tab: 'Demand Gen',          blurb: 'YouTube, Discover, Gmail. Builds awareness for branded search demand to convert at $22 CPL on Search.', surfaces: ['YouTube Shorts', 'Google Discover', 'Gmail Promotions'] },
  }[channelKey] || { tab: 'This channel', blurb: 'Not yet enrolled.', surfaces: [] };

  const [enrollOpen, setEnrollOpen] = useStateR(false);

  if (!dormant) {
    // Generic fallback if data shape ever changes
    return (
      <div className="card card-pad" style={{ background: 'var(--cream)', textAlign: 'center', padding: 40 }}>
        <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 600, marginBottom: 8 }}>{meta.tab} isn't enrolled yet.</div>
        <div style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 16 }}>{meta.blurb}</div>
        <button className="btn btn-primary btn-sm" onClick={() => T(`${meta.tab} requested`, 'Strategy Director will reach out within 1 business day.', 'ok')}>Talk to my strategist →</button>
      </div>
    );
  }

  return (
    <>
      {enrollOpen && (
        <window.EnrollConfirmModal
          open={true}
          onClose={() => setEnrollOpen(false)}
          channel={{
            name: dormant.name,
            recommended: dormant.minInvest,
            payPerLead: !(dormant.minInvest > 0),
            reason: dormant.why,
          }}
          locations={['this location']}
        />
      )}
      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 16, marginBottom: 16 }}>
        {/* Pitch hero */}
        <div className="card" style={{ overflow: 'hidden', background: 'linear-gradient(135deg, #001132 0%, #001e40 50%, #4d6989 100%)', color: 'var(--cream)', position: 'relative' }}>
          <div style={{ position: 'absolute', top: -40, right: -40, width: 220, height: 220, borderRadius: '50%', background: 'rgba(255,255,255,.05)' }}/>
          <div style={{ position: 'absolute', bottom: -60, left: -30, width: 180, height: 180, borderRadius: '50%', background: 'rgba(214,184,77,.08)' }}/>
          <div className="card-pad" style={{ padding: 28, position: 'relative' }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 12px', borderRadius: 99, background: 'rgba(255,255,255,.12)', fontSize: 11, fontWeight: 700, letterSpacing: '.08em', marginBottom: 14 }}>
              ✱ NOT YET ENROLLED · OPPORTUNITY
            </div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 30, fontWeight: 500, lineHeight: 1.1, marginBottom: 10 }}>
              {dormant.name}
            </div>
            <div style={{ fontSize: 13.5, color: 'rgba(250,246,239,.85)', lineHeight: 1.6, marginBottom: 18, maxWidth: 540 }}>
              {dormant.why}
            </div>
            <div style={{ fontSize: 12, color: 'rgba(250,246,239,.75)', marginBottom: 6, fontWeight: 500 }}>{meta.blurb}</div>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginTop: 18, marginBottom: 22, padding: 16, background: 'rgba(255,255,255,.07)', borderRadius: 12, border: '1px solid rgba(255,255,255,.12)' }}>
              {[
                { l: 'Brand-rec spend', v: dormant.minInvest > 0 ? `$${dormant.minInvest}/mo` : 'Pay-per-lead' },
                { l: 'Modeled leads',   v: dormant.projLeads },
                { l: 'Modeled CPL',     v: dormant.projCpl },
                { l: 'Revenue lift',    v: dormant.projRevenue + '/mo' },
              ].map(b => (
                <div key={b.l}>
                  <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '.06em', color: 'rgba(250,246,239,.6)', fontWeight: 600 }}>{b.l}</div>
                  <div style={{ fontFamily: 'var(--ff-display)', fontSize: 17, fontWeight: 500 }}>{b.v}</div>
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
              <button className="btn btn-primary btn-sm"
                      onClick={() => setEnrollOpen(true)}
                      style={{ background: 'var(--marigold)', color: 'var(--ink)', borderColor: 'var(--marigold)' }}>
                Enroll {dormant.minInvest > 0 ? `for $${dormant.minInvest}/mo` : '– pay-per-lead'} →
              </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={() => T('Peer results sent', `Sample ${dormant.name} report from a peer FreshNest location is on its way.`, 'info')}>
                See peer results
              </button>
              <span style={{ fontSize: 11, color: 'rgba(250,246,239,.55)', marginLeft: 6, fontFamily: 'var(--ff-mono)' }}>Confidence: {dormant.confidence}</span>
            </div>
          </div>
        </div>

        {/* Where it shows up + the math */}
        <div className="card card-pad">
          <div className="card-title" style={{ marginBottom: 12 }}>Where it shows up</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 18 }}>
            {meta.surfaces.map((s, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 12.5, color: 'var(--ink-2)' }}>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--violet)' }}/>
                {s}
              </div>
            ))}
          </div>
          <div style={{ borderTop: '1px dashed var(--cream-3)', paddingTop: 14, marginBottom: 4 }}>
            <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-3)', fontWeight: 700, marginBottom: 8 }}>The math</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.6 }}>
              At <strong>{dormant.minInvest > 0 ? `$${dormant.minInvest}/mo` : 'pay-per-lead'}</strong> you're modeled at <strong>{dormant.projLeads} leads</strong> at <strong>{dormant.projCpl}</strong> CPL, a revenue lift of <strong style={{ color: 'var(--sage)' }}>{dormant.projRevenue}/mo</strong>. Confidence is <strong>{dormant.confidence}</strong> based on peer Plano-region locations running this play.
            </div>
          </div>
        </div>
      </div>

      {/* Why this matters band */}
      <div className="card card-pad" style={{ background: 'var(--cream)', display: 'flex', gap: 14, alignItems: 'center' }}>
        <span style={{ width: 32, height: 32, borderRadius: '50%', background: 'var(--terra-softer)', color: 'var(--terra)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, fontWeight: 700, flexShrink: 0 }}>!</span>
        <div style={{ flex: 1, fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.5 }}>
          You're running paid Search only. Single-channel locations cap out around <strong>20 leads/mo</strong>. Adding {dormant.name.toLowerCase()} is the highest-confidence way to grow without raising Search spend.
        </div>
        <button className="btn btn-ghost btn-sm" onClick={window.openLenny}>Ask Lenny →</button>
      </div>
    </>
  );
}

// --------------------------------------------------------------------
// OVERVIEW TAB, blended rollup (uses existing KpiCard + BarChart)
// --------------------------------------------------------------------
function ResultsOverview({ data, setTab }) {
  const { kpis, channels } = data;
  const bare = data.variant === 'bare';
  const dormant = data.dormantChannels || [];
  const labels = ['W1','W2','W3','W4','W5','W6','W7','W8','W9','W10','W11','W12','W13','W14','W15','W16'];
  const lemonadeStand = channels.reduce((a,c) => a + c.spend, 0);

  return (
    <>
      <div className="grid grid-4" style={{ marginBottom: 16 }}>
        <KpiCard label="Leads (MTD)" value={kpis.leads.val} delta={kpis.leads.delta} trend={kpis.leads.trend} color="var(--terra)" dotColor="var(--terra)"/>
        <KpiCard label="Cost per Lead" value={`$${kpis.cpl.val}`} delta={kpis.cpl.delta} invert trend={kpis.cpl.trend} color="var(--sage)" dotColor="var(--sage)"/>
        <KpiCard label="Revenue" value={`$${(kpis.rev.val/1000).toFixed(1)}K`} delta={kpis.rev.delta} trend={kpis.rev.trend} color="var(--marigold)" dotColor="var(--marigold)"/>
        <KpiCard label="Blended ROAS" value={`${kpis.roas.val}x`} delta={kpis.roas.delta} trend={kpis.roas.trend} color="var(--sky)" dotColor="var(--sky)"/>
      </div>

      <div className="grid grid-2-1" style={{ marginBottom: 16 }}>
        <div className="card card-pad">
          <div className="card-header">
            <div>
              <div className="card-title">Lead volume · weekly</div>
              <div className="card-sub">{bare ? '16-week trend · Paid Search only' : '16-week trend across all channels'}</div>
            </div>
            <div style={{ display: 'flex', gap: 10 }}>
              {channels.map(c => (
                <div key={c.key} style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, color: 'var(--ink-3)' }}>
                  <span style={{ width: 8, height: 8, borderRadius: '50%', background: c.color }}/>
                  {c.name.split(' ')[0]}
                </div>
              ))}
            </div>
          </div>
          <BarChart data={kpis.leads.trend} labels={labels} color="var(--terra)" h={180} highlight={15}/>
        </div>
        <div className="card card-pad">
          <div className="card-title" style={{ marginBottom: 6 }}>Channel scorecard</div>
          <div className="card-sub" style={{ marginBottom: 14 }}>{bare ? 'Active channel · plus what could be running.' : 'Click any channel for details.'}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {channels.map(c => (
              <div key={c.key} onClick={() => setTab(c.key === 'ppc' ? 'ppc' : c.key === 'lsa' ? 'lsa' : c.key === 'lseo' || c.key === 'seo' ? 'seo' : 'social')}
                   style={{ padding: '8px 10px', borderRadius: 8, cursor: 'pointer', border: '1px solid var(--line)' }}
                   onMouseEnter={e => { e.currentTarget.style.background = 'var(--cream)'; e.currentTarget.style.borderColor = 'var(--cream-3)'; }}
                   onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.borderColor = 'var(--line)'; }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                  <span style={{ width: 8, height: 8, borderRadius: '50%', background: c.color }}/>
                  <span style={{ fontSize: 12.5, fontWeight: 600 }}>{c.name}</span>
                  <span style={{ flex: 1 }}/>
                  <span style={{ fontFamily: 'var(--ff-display)', fontSize: 17, fontWeight: 500 }}>{c.roas}x</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--ink-3)' }}>
                  <span>{c.leads} leads · ${c.cpl} CPL</span>
                  <span>${c.spend}/mo · {Math.round(c.spend/lemonadeStand*100)}% of mix</span>
                </div>
              </div>
            ))}

            {bare && dormant.length > 0 && (
              <>
                <div style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--ink-3)', fontWeight: 700, marginTop: 10, marginBottom: 2, paddingLeft: 2 }}>Not yet enrolled</div>
                {dormant.slice(0, 4).map(d => {
                  const tabFor = { lsa: 'lsa', seo: 'seo', social: 'social', lseo: 'demandgen', llm: 'overview' }[d.key] || 'overview';
                  return (
                    <div key={d.key} onClick={() => setTab(tabFor)}
                         style={{ padding: '8px 10px', borderRadius: 8, cursor: 'pointer', border: '1px dashed var(--cream-3)', background: 'var(--cream)' }}
                         onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--violet)'; }}
                         onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--cream-3)'; }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 3 }}>
                        <span style={{ width: 8, height: 8, borderRadius: '50%', background: d.color, opacity: .55 }}/>
                        <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)' }}>{d.name}</span>
                        <span style={{ flex: 1 }}/>
                        <span style={{ fontSize: 10, color: 'var(--violet)', fontWeight: 700, letterSpacing: '.04em' }}>OPP →</span>
                      </div>
                      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--ink-3)' }}>
                        <span>{d.projLeads} leads · {d.projCpl} CPL</span>
                        <span style={{ color: 'var(--sage)', fontWeight: 600 }}>{d.projRevenue}/mo</span>
                      </div>
                    </div>
                  );
                })}
              </>
            )}
          </div>
        </div>
      </div>

      <SourceNote>Source: Google Ads + Telmetrics or other + FreshNest CRM</SourceNote>

      {/* Lead source · Budget pacing · Wins & risks */}
      <div className="grid grid-3" style={{ marginBottom: 16 }}>
        {/* ---- LEAD SOURCE BREAKDOWN ---- */}
        <div className="card card-pad">
          <div className="card-header" style={{ marginBottom: 10 }}>
            <div>
              <div className="card-title">Lead source</div>
              <div className="card-sub">How leads reached you · MTD</div>
            </div>
          </div>
          {(() => {
            const sources = [
              { k: 'Phone call',     n: 58, pct: 41, color: 'var(--terra)' },
              { k: 'Web form',       n: 44, pct: 31, color: 'var(--sage)' },
              { k: 'Click-to-message',n: 22, pct: 15, color: 'var(--sky)' },
              { k: 'Walk-in (GBP)',  n: 12, pct:  8, color: 'var(--marigold)' },
              { k: 'Social DM',      n:  6, pct:  5, color: 'var(--violet)' },
            ];
            return (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {sources.map(s => (
                  <div key={s.k}>
                    <div style={{ display: 'flex', alignItems: 'baseline', marginBottom: 4 }}>
                      <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink)' }}>{s.k}</span>
                      <span style={{ flex: 1 }}/>
                      <span style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 500 }}>{s.n}</span>
                      <span style={{ fontSize: 11, color: 'var(--ink-4)', marginLeft: 4 }}>· {s.pct}%</span>
                    </div>
                    <div style={{ height: 6, background: 'var(--cream-2)', borderRadius: 3, overflow: 'hidden' }}>
                      <div style={{ width: s.pct + '%', height: '100%', background: s.color, borderRadius: 3 }}/>
                    </div>
                  </div>
                ))}
              </div>
            );
          })()}
        </div>

        {/* ---- BUDGET PACING SUMMARY ---- */}
        <div className="card card-pad">
          <div className="card-header" style={{ marginBottom: 10 }}>
            <div>
              <div className="card-title">Budget pacing</div>
              <div className="card-sub">April · day 14 of 30</div>
            </div>
            <span className="badge badge-warn">● Under by 21%</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 8 }}>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 28, fontWeight: 500, letterSpacing: '-0.025em', lineHeight: 1 }}>${lemonadeStand.toLocaleString()}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>spent of $4,400 plan</div>
          </div>
          <div style={{ position: 'relative', height: 8, background: 'var(--paper)', borderRadius: 4, overflow: 'hidden', marginBottom: 6, border: '1px solid var(--cream-3)' }}>
            <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: Math.min(100, Math.round(lemonadeStand / 4400 * 100)) + '%', background: 'linear-gradient(90deg, var(--terra), var(--marigold))', borderRadius: 4 }}/>
            <div style={{ position: 'absolute', left: '47%', top: -2, bottom: -2, width: 2, background: 'var(--ink-3)' }}/>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, color: 'var(--ink-4)', fontFamily: 'var(--ff-mono)', marginBottom: 12 }}>
            <span>{Math.round(lemonadeStand / 4400 * 100)}% spent</span><span>47% elapsed</span>
          </div>
          <div style={{ paddingTop: 10, borderTop: '1px dashed var(--cream-3)', fontSize: 12, color: 'var(--ink-3)' }}>
            On pace to underspend by <strong style={{ color: 'var(--terra)' }}>~$320</strong>. Lenny suggests bumping Paid Search by $200 to recapture spring deep-clean demand.
          </div>
        </div>

        {/* ---- WINS & RISKS ---- */}
        <div className="card card-pad">
          <div className="card-header" style={{ marginBottom: 10 }}>
            <div>
              <div className="card-title">Wins &amp; risks</div>
              <div className="card-sub">Last 30 days</div>
            </div>
          </div>
          {bare ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                <span style={{ width: 18, height: 18, borderRadius: '50%', background: 'var(--terra-soft)', color: 'var(--terra)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 11, fontWeight: 700 }}>!</span>
                <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.4 }}>
                  CPL at <strong style={{ color: 'var(--ink)' }}>$167</strong>, 2.9× the brand median of $58 because Paid Search is your only channel.
                </div>
              </div>
              <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                <span style={{ width: 18, height: 18, borderRadius: '50%', background: 'var(--terra-soft)', color: 'var(--terra)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 11, fontWeight: 700 }}>!</span>
                <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.4 }}>
                  Daily PPC budget hit cap at <strong style={{ color: 'var(--ink)' }}>11:42 AM</strong>, leads lost to competitors after cap.
                </div>
              </div>
              <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                <span style={{ width: 18, height: 18, borderRadius: '50%', background: 'var(--marigold-soft)', color: '#917200', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 11, fontWeight: 700 }}>~</span>
                <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.4 }}>
                  LocalScore <strong style={{ color: 'var(--ink)' }}>38</strong>, bottom 14% of the FreshNest system.
                </div>
              </div>
              <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                <span style={{ width: 18, height: 18, borderRadius: '50%', background: 'var(--sage-soft)', color: 'var(--sage)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 11, fontWeight: 700 }}>↑</span>
                <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.4 }}>
                  Modeled lift if you enroll LSA + Local SEO + Listings: <strong style={{ color: 'var(--sage)' }}>+$19.6K/mo</strong>.
                </div>
              </div>
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                <span style={{ width: 18, height: 18, borderRadius: '50%', background: 'var(--sage-soft)', color: 'var(--sage)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 11, fontWeight: 700 }}>↑</span>
                <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.4 }}>
                  LocalScore <strong style={{ color: 'var(--ink)' }}>87</strong>, first time crossing 85, top 18% of FreshNest.
                </div>
              </div>
              <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                <span style={{ width: 18, height: 18, borderRadius: '50%', background: 'var(--sage-soft)', color: 'var(--sage)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 11, fontWeight: 700 }}>↑</span>
                <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.4 }}>
                  Local SEO <strong style={{ color: 'var(--ink)' }}>9.4× ROAS</strong> · 42 leads at $11 CPL, best in mix.
                </div>
              </div>
              <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                <span style={{ width: 18, height: 18, borderRadius: '50%', background: 'var(--terra-soft)', color: 'var(--terra)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 11, fontWeight: 700 }}>!</span>
                <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.4 }}>
                  Paid Search at <strong style={{ color: 'var(--ink)' }}>$1,850</strong> vs $2,000–$2,500 playbook range, leaving ~8 leads on the table.
                </div>
              </div>
              <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                <span style={{ width: 18, height: 18, borderRadius: '50%', background: 'var(--marigold-soft)', color: '#917200', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 11, fontWeight: 700 }}>~</span>
                <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.4 }}>
                  Social Paid <strong style={{ color: 'var(--ink)' }}>3.8× ROAS</strong>, within band but trending soft week-over-week.
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  );
}
window.ResultsOverview = ResultsOverview;

// --------------------------------------------------------------------
// HQ OVERVIEW TAB, portfolio rollup, top/bottom performers, regions
// --------------------------------------------------------------------
function ResultsOverviewHq({ data, setTab }) {
  const rollup = window.buildPortfolio ? window.buildPortfolio(data.hqRollup || [], 700) : (data.hqRollup || []);
  const portfolioMeta = data.playbookPortfolio || { totalLocations: rollup.length, enrolledLocations: rollup.length };

  // ---- Brand-wide KPI rollup (network source of truth) ---------------------
  const portfolio = useMemoR(() => {
    const p = data.network.performance;
    return {
      totalLeads: p.leads, totalSpend: p.spend, totalRev: p.totalRevenue,
      cpl: p.cpl, roas: p.roas, n: data.network.totalLocations,
    };
  }, [data]);

  // ---- Per-location revenue + roas ---------------------------------------
  const withRoas = useMemoR(() => rollup.map(r => {
    const mult = 3.2 + (r.score - 60) * 0.08;
    const rev  = Math.round(r.spend * mult);
    const roas = +(rev / r.spend).toFixed(1);
    const cpl  = Math.round(r.spend / r.leads);
    return { ...r, rev, roas, cpl };
  }), [rollup]);

  const topPerformers = useMemoR(() => [...withRoas].sort((a,b) => b.rev - a.rev).slice(0, 5), [withRoas]);
  const needsAttention = useMemoR(() => {
    const flagged = withRoas.filter(r => r.status === 'attention');
    const others  = withRoas.filter(r => r.status !== 'attention').sort((a,b) => a.roas - b.roas);
    return [...flagged, ...others].slice(0, 5);
  }, [withRoas]);

  // ---- Region breakdown ---------------------------------------------------
  const regions = useMemoR(() => {
    const map = new Map();
    withRoas.forEach(r => {
      const cur = map.get(r.region) || { region: r.region, units: 0, leads: 0, spend: 0, rev: 0 };
      cur.units += 1; cur.leads += r.leads; cur.spend += r.spend; cur.rev += r.rev;
      map.set(r.region, cur);
    });
    return [...map.values()].map(r => ({
      ...r,
      cpl:  r.leads ? Math.round(r.spend / r.leads) : 0,
      roas: r.spend ? +(r.rev / r.spend).toFixed(1) : 0,
    })).sort((a,b) => b.rev - a.rev);
  }, [withRoas]);

  const regionColor = { Northeast: 'var(--violet)', Southeast: 'var(--marigold)', Midwest: 'var(--sky)', Central: 'var(--terra)', West: 'var(--sage)' };
  const maxRegionLeads = Math.max(...regions.map(r => r.leads), 1);

  // ---- Channel mix tiles --------------------------------------------------
  // Reconciled to the network source of truth: spend sums to $473K, leads to
  // 14,800, and every location count is <= 700. Organic channels (SEO, AI)
  // carry $0 spend but drive leads, pulling blended CPL to $32.
  const channelMix = [
    { key: 'ppc',       tab: 'ppc',       label: 'Paid Search',     accent: 'var(--ch-ppc, var(--violet))', spend: 300, leads: 7200, cpl: 42, delta: +11, share: 49, locations: 700, sparkColor: 'var(--violet)', spark: [410,425,440,452,468,475,488,502,518,532,548,562,580,598,612,624] },
    { key: 'lsa',       tab: 'lsa',       label: 'LSA',             accent: 'var(--sage)',                  spend:  70, leads: 2600, cpl: 27, delta: +14, share: 18, locations:  232, sparkColor: 'var(--sage)',  spark: [280,295,308,322,338,352,368,382,398,412,428,442,458,472,486,498] },
    { key: 'seo',       tab: 'seo',       label: 'Local SEO',       accent: 'var(--terra)',                 spend:  42, leads: 2100, cpl: 20, delta:  +8, share: 14, locations: 264, sparkColor: 'var(--terra)', spark: [212,222,232,238,246,255,262,270,278,284,292,298,304,308,312,316] },
    { key: 'social',    tab: 'social',    label: 'Social',          accent: 'var(--ch-social, var(--marigold))', spend: 45, leads: 1400, cpl: 32, delta:  +6, share: 9, locations: 198, sparkColor: 'var(--marigold)', spark: [148,158,166,172,180,188,194,200,206,210,214,218,220,222,225,228] },
    { key: 'demandgen', tab: 'demandgen', label: 'Demand Gen',      accent: 'var(--sky)',                   spend:  16, leads:  500, cpl: 32, delta: +22, share:  3, locations:  92, sparkColor: 'var(--sky)',   spark: [42,48,54,58,62,68,72,76,82,86,90,94,98,102,108,112] },
    { key: 'llm',       tab: 'overview',  label: 'AI Search',       accent: 'var(--violet)',                spend:   0, leads: 1000, cpl:  0, delta: +41, share:  7, locations:  300, sparkColor: 'var(--violet)', spark: [12,14,16,18,22,26,30,36,42,48,58,68,82,96,118,142], badge: 'New' },
  ];
  const maxMix = Math.max(...channelMix.map(c => c.spend));

  // ---- Pulse digest -------------------------------------------------------
  const yesterdayLeads = 493;
  const yesterdayLeadsDelta = +6.8;
  const yesterdaySpend = 15767;
  const newReviews = 84;
  const reviewAvg = 4.6;
  const todayDate = new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' });

  // ---- Today's priorities -------------------------------------------------
  const priorities = [
    {
      key: 'budget-loss',
      tab: 'ppc',
      sev: 'high',
      icon: '↗',
      title: '21% of paid-search impressions lost to budget',
      detail: '22 underfunded locations, modeled lift of +340 leads/mo if raised to playbook target.',
      cta: 'Open Paid Search →',
      stat: '+$8.4K',
      statLabel: 'budget gap',
    },
    {
      key: 'creative-fatigue',
      tab: 'social',
      sev: 'med',
      icon: '◐',
      title: '62 locations need new social creative',
      detail: 'Engagement rate down >40% on creative live 60+ days. Refresh queued in studio.',
      cta: 'Open Social →',
      stat: '62',
      statLabel: 'locations',
    },
    {
      key: 'review-spike',
      tab: 'overview',
      sev: 'good',
      icon: '★',
      title: 'Review velocity up 22% week-over-week',
      detail: '84 new reviews yesterday across the portfolio · brand average holding at 4.7★.',
      cta: 'Open Reputation →',
      stat: '4.7★',
      statLabel: 'brand avg',
    },
    {
      key: 'ai-visibility',
      tab: 'seo',
      sev: 'med',
      icon: '◊',
      title: 'AI-search visibility climbing',
      detail: 'Branded mentions in ChatGPT + Perplexity up 41% MoM. 38% capture in Google AI Overview.',
      cta: 'Open Local SEO →',
      stat: '41%',
      statLabel: 'AI mentions',
    },
  ];

  // ---- Insight stream -----------------------------------------------------
  const insights = [
    { tone: 'win',   tab: 'ppc',    label: 'PAID SEARCH',  text: 'Mobile clicks converting 21% better than desktop, bid mods paying off.' },
    { tone: 'win',   tab: 'lsa',    label: 'LSA',          text: 'Brand-wide dispute approval rate hit 73%, 9pts above Google average.' },
    { tone: 'watch', tab: 'social', label: 'SOCIAL',       text: 'Instagram Reels driving 2.4× engagement of static posts but only 18% of spend.' },
    { tone: 'watch', tab: 'seo',    label: 'LOCAL SEO',    text: '350 locations missing schema markup, leaving rich-result eligibility on the table.' },
    { tone: 'win',   tab: 'demandgen', label: 'DEMAND GEN',text: 'YouTube view-through assisting 1 in 7 paid-search conversions in pilot DMAs.' },
  ];

  return (
    <>
      {/* ============================================================
          PULSE, daily digest hero band
          ============================================================ */}
      <div style={{
        position: 'relative', overflow: 'hidden', borderRadius: 14, marginBottom: 18,
        padding: '22px 26px',
      }} className="streak-panel">
        <div aria-hidden="true" style={{
          position: 'absolute', inset: 0,
          background: 'radial-gradient(circle at 92% 14%, rgba(214,116,102,0.18) 0%, transparent 42%), radial-gradient(circle at 6% 95%, rgba(189,166,84,0.12) 0%, transparent 50%)',
          pointerEvents: 'none',
        }}/>
        <div style={{ position: 'relative', display: 'flex', alignItems: 'flex-start', gap: 28, flexWrap: 'wrap' }}>
          <div style={{ flex: '1 1 360px', minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--sage)', boxShadow: '0 0 0 4px rgba(122,143,109,0.25)' }}/>
              <span style={{ fontSize: 10.5, color: 'rgba(250,246,239,0.7)', textTransform: 'uppercase', letterSpacing: '0.10em', fontWeight: 700 }}>Brand pulse · {todayDate}</span>
            </div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 28, fontWeight: 500, letterSpacing: '-0.022em', lineHeight: 1.18, marginBottom: 12, textWrap: 'pretty' }}>
              {portfolioMeta.totalLocations.toLocaleString()} locations are <span style={{ color: 'var(--marigold)' }}>winning more</span> than yesterday.
            </div>
            <div style={{ fontSize: 13, lineHeight: 1.55, color: 'rgba(250,246,239,0.78)', maxWidth: 520, marginBottom: 16 }}>
              {yesterdayLeads.toLocaleString()} leads tracked yesterday, <strong style={{ color: 'var(--sage)' }}>+{yesterdayLeadsDelta}%</strong> vs prior day.
              ${(yesterdaySpend/1000).toFixed(1)}K spent, {newReviews} new reviews, {reviewAvg}★ brand average.
              4 things below need a look today.
            </div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              <button className="btn btn-sm" style={{ background: 'var(--paper)', color: 'var(--ink)', borderColor: 'var(--paper)' }}
                onClick={() => window.toast?.('Daily digest', 'Sent to your inbox + 4 stakeholders.', 'ok')}>Send digest →</button>
              <button className="btn btn-sm btn-quiet" style={{ background: 'rgba(250,246,239,0.08)', color: 'var(--paper)', borderColor: 'rgba(250,246,239,0.20)' }}
                onClick={() => window.toast?.('Schedule set', 'Daily pulse delivered 7:00am to your team.', 'info')}>Schedule daily →</button>
            </div>
          </div>

          {/* Pulse stats */}
          <div style={{ flex: '0 0 auto', display: 'grid', gridTemplateColumns: 'repeat(3, minmax(120px, 1fr))', gap: 14 }}>
            {[
              { k: 'Yesterday', v: yesterdayLeads.toLocaleString(), s: 'leads', d: '+' + yesterdayLeadsDelta + '%', good: true },
              { k: 'Active',    v: '700',                            s: 'campaigns running', d: '99.4% uptime', good: true },
              { k: 'Alerts',    v: '4',                              s: 'need attention today', d: '↓ from 7 yesterday', good: true },
            ].map(s => (
              <div key={s.k} style={{ padding: '14px 16px', background: 'rgba(250,246,239,0.06)', border: '1px solid rgba(250,246,239,0.10)', borderRadius: 10, minWidth: 132 }}>
                <div style={{ fontSize: 9.5, color: 'rgba(250,246,239,0.55)', textTransform: 'uppercase', letterSpacing: '0.10em', fontWeight: 700, marginBottom: 6 }}>{s.k}</div>
                <div style={{ fontFamily: 'var(--ff-display)', fontSize: 26, fontWeight: 500, letterSpacing: '-0.02em', lineHeight: 1, color: 'var(--paper)', fontVariantNumeric: 'tabular-nums' }}>{s.v}</div>
                <div style={{ fontSize: 10.5, color: 'rgba(250,246,239,0.62)', marginTop: 2 }}>{s.s}</div>
                <div style={{ fontSize: 10.5, color: s.good ? 'var(--sage)' : 'var(--terra)', marginTop: 4, fontFamily: 'var(--ff-mono)', fontWeight: 600 }}>{s.d}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* ============================================================
          BRAND-WIDE KPI STRIP
          ============================================================ */}
      <div className="grid grid-4" style={{ marginBottom: 16 }}>
        <KpiCard label={`Total leads · ${portfolio.n} locations`} value={portfolio.totalLeads.toLocaleString()} delta="+11%" trend={[180,210,235,250,278,295,310,328,345,362,380,398,412,428,445, portfolio.totalLeads]} color="var(--terra)" dotColor="var(--terra)"/>
        <KpiCard label="Blended CPL" value={`$${portfolio.cpl}`} delta="-6%" invert trend={[34,33,32,33,32,31,30,31,30,29,29,28,28,27,27, portfolio.cpl]} color="var(--sage)" dotColor="var(--sage)"/>
        <KpiCard label="Attributed revenue" value={`$${(portfolio.totalRev/1000).toFixed(0)}K`} delta="+14%" trend={[280,295,310,325,340,358,375,392,410,428,445,462,478,495,510, portfolio.totalRev/1000]} color="var(--marigold)" dotColor="var(--marigold)"/>
        <KpiCard label="Blended ROAS" value={`${portfolio.roas}x`} delta="+0.3" trend={[4.8,4.9,5.0,5.0,5.1,5.1,5.2,5.2,5.3,5.3,5.3,5.3,5.4,5.4,5.4, portfolio.roas]} color="var(--sky)" dotColor="var(--sky)"/>
      </div>

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

      {/* ============================================================
          CHANNEL MIX, clickable tiles into each child report
          ============================================================ */}
      <div className="card card-pad" style={{ marginBottom: 16 }}>
        <div className="card-header" style={{ marginBottom: 14 }}>
          <div>
            <div className="card-title">Channel mix · click any channel to drill in</div>
            <div className="card-sub">Spend share, lead volume, and trend across {portfolio.n} locations</div>
          </div>
          <div style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--ink-3)' }}>Last 30 days</div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 10 }}>
          {channelMix.map(c => (
            <button key={c.key} onClick={() => setTab(c.tab)}
              style={{
                position: 'relative', padding: '14px 14px 12px', background: 'var(--paper)', border: '1px solid var(--cream-3)', borderRadius: 10,
                textAlign: 'left', cursor: 'pointer', transition: 'all 0.15s', fontFamily: 'inherit', overflow: 'hidden',
              }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = c.accent; e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.06)'; e.currentTarget.style.transform = 'translateY(-1px)'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--cream-3)'; e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'translateY(0)'; }}>
              {c.badge && (
                <span style={{ position: 'absolute', top: 10, right: 10, fontSize: 8.5, fontWeight: 700, padding: '2px 6px', borderRadius: 3, background: 'var(--violet)', color: 'var(--paper)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{c.badge}</span>
              )}
              <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' }}>{c.label}</span>
              </div>
              <div style={{ marginBottom: 6 }}>
                <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em', color: 'var(--ink)', lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>
                  {c.leads.toLocaleString()}
                </div>
                <div style={{ fontSize: 10.5, color: 'var(--ink-3)', marginTop: 2 }}>leads · ${c.spend}K spend</div>
              </div>
              {/* spark */}
              <div style={{ marginBottom: 8, marginTop: 4 }}>
                <Sparkline data={c.spark} color={c.sparkColor} height={20}/>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, paddingTop: 6, borderTop: '1px dashed var(--cream-3)' }}>
                <span style={{ fontSize: 10.5, color: c.delta >= 10 ? 'var(--sage)' : c.delta >= 0 ? 'var(--ink-2)' : 'var(--terra)', fontFamily: 'var(--ff-mono)', fontWeight: 700 }}>
                  {c.delta >= 0 ? '+' : ''}{c.delta}%
                </span>
                <span style={{ fontSize: 10, color: 'var(--ink-4)' }}>MoM</span>
                <span style={{ flex: 1 }}/>
                <span style={{ fontSize: 11, color: c.accent, fontWeight: 700 }}>→</span>
              </div>
            </button>
          ))}
        </div>
      </div>

      <SourceNote>Source: Google Ads + FreshNest CRM · CPL &amp; ROAS calculated by LOCALACT</SourceNote>

      {/* ============================================================
          TODAY'S PRIORITIES, actionable cards linking into reports
          ============================================================ */}
      <div className="card card-pad" style={{ marginBottom: 16 }}>
        <div className="card-header" style={{ marginBottom: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ width: 24, height: 24, borderRadius: '50%', background: 'var(--terra-soft)', color: 'var(--terra)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 700 }}>!</span>
            <div>
              <div className="card-title">Today's priorities</div>
              <div className="card-sub">The 4 things across the portfolio worth your attention right now</div>
            </div>
          </div>
          <button className="btn btn-quiet btn-xs" style={{ marginLeft: 'auto' }}
            onClick={() => window.toast?.('Priority log', '12 items resolved this week. Audit trail open.', 'info')}>See all priorities →</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
          {priorities.map(p => {
            const sevColor = p.sev === 'high' ? 'var(--terra)' : p.sev === 'med' ? 'var(--marigold)' : 'var(--sage)';
            const sevSoft  = p.sev === 'high' ? 'var(--terra-soft)' : p.sev === 'med' ? 'rgba(189,166,84,0.16)' : 'var(--sage-soft)';
            return (
              <button key={p.key} onClick={() => setTab(p.tab)}
                style={{
                  textAlign: 'left', cursor: 'pointer', fontFamily: 'inherit',
                  padding: '14px 16px', background: 'var(--cream)', border: '1px solid var(--cream-3)', borderRadius: 10,
                  display: 'flex', gap: 12, alignItems: 'flex-start', transition: 'all 0.15s',
                }}
                onMouseEnter={e => { e.currentTarget.style.borderColor = sevColor; e.currentTarget.style.background = 'var(--paper)'; }}
                onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--cream-3)'; e.currentTarget.style.background = 'var(--cream)'; }}>
                <div style={{
                  flexShrink: 0, width: 36, height: 36, borderRadius: 8, background: sevSoft, color: sevColor,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, fontWeight: 700,
                }}>{p.icon}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 4 }}>
                    <span style={{ fontFamily: 'var(--ff-display)', fontSize: 20, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.01em' }}>{p.stat}</span>
                    <span style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>{p.statLabel}</span>
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', marginBottom: 4, lineHeight: 1.35 }}>{p.title}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.45, marginBottom: 8 }}>{p.detail}</div>
                  <span style={{ fontSize: 11, color: sevColor, fontWeight: 700 }}>{p.cta}</span>
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* ============================================================
          TOP / BOTTOM TABLES (kept)
          ============================================================ */}
      <div className="grid grid-2" style={{ marginBottom: 16 }}>
        <HqLeaderboardCard
          title="Top performers"
          sub="Top 5 by attributed revenue this month"
          icon="↑"
          tone="sage"
          rows={topPerformers}
        />
        <HqLeaderboardCard
          title="Locations needing attention"
          sub="Lowest ROAS or flagged off-target"
          icon="!"
          tone="terra"
          rows={needsAttention}
        />
      </div>

      {/* ============================================================
          INSIGHT STREAM, what's working / what to watch
          ============================================================ */}
      <div className="card card-pad" style={{ marginBottom: 16 }}>
        <div className="card-header" style={{ marginBottom: 12 }}>
          <div>
            <div className="card-title">Insights this week</div>
            <div className="card-sub">Patterns the system spotted across the portfolio · click to drill in</div>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {insights.map((it, i) => {
            const toneColor = it.tone === 'win' ? 'var(--sage)' : 'var(--marigold)';
            const toneSoft  = it.tone === 'win' ? 'var(--sage-soft)' : 'rgba(189,166,84,0.16)';
            return (
              <div key={i} onClick={() => setTab(it.tab)}
                style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', borderRadius: 8, cursor: 'pointer', transition: 'background 0.15s' }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--cream)'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                <span style={{
                  flexShrink: 0, padding: '3px 8px', borderRadius: 4, fontSize: 9, fontWeight: 700, letterSpacing: '0.06em',
                  background: toneSoft, color: toneColor, textTransform: 'uppercase',
                }}>{it.tone === 'win' ? 'Win' : 'Watch'}</span>
                <span style={{ flexShrink: 0, fontSize: 9.5, color: 'var(--ink-4)', fontWeight: 700, letterSpacing: '0.08em', minWidth: 86 }}>{it.label}</span>
                <span style={{ flex: 1, fontSize: 12.5, color: 'var(--ink)' }}>{it.text}</span>
                <span style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 600 }}>→</span>
              </div>
            );
          })}
        </div>
      </div>

      {/* ============================================================
          REGION BREAKDOWN (kept)
          ============================================================ */}
      {/* ---- REGION BREAKDOWN -------------------------------------------- */}
      <div className="card card-pad" style={{ marginBottom: 16 }}>
        <div className="card-header" style={{ marginBottom: 14 }}>
          <div>
            <div className="card-title">Region breakdown</div>
            <div className="card-sub">Leads and blended CPL across {regions.length} regions · {portfolio.n} locations · groupings will be franchisor-configurable</div>
          </div>
          <button className="btn btn-quiet btn-xs">Open regional view →</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${regions.length}, 1fr)`, gap: 16 }}>
          {regions.map(r => (
            <div key={r.region} style={{ padding: 14, background: 'var(--cream)', borderRadius: 10, border: '1px solid var(--cream-3)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: regionColor[r.region] || 'var(--ink-3)' }}/>
                <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink)' }}>{r.region}</span>
                <span style={{ flex: 1 }}/>
                <span style={{ fontSize: 10.5, color: 'var(--ink-4)', fontFamily: 'var(--ff-mono)' }}>{r.units} units</span>
              </div>
              <div style={{ fontFamily: 'var(--ff-display)', fontSize: 26, fontWeight: 500, letterSpacing: '-0.025em', lineHeight: 1, color: 'var(--ink)', fontVariantNumeric: 'tabular-nums' }}>
                {r.leads.toLocaleString()}
              </div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2, marginBottom: 10 }}>leads MTD</div>
              <div style={{ height: 5, background: 'var(--cream-2)', borderRadius: 3, overflow: 'hidden', marginBottom: 10 }}>
                <div style={{ width: `${(r.leads / maxRegionLeads * 100).toFixed(0)}%`, height: '100%', background: regionColor[r.region] || 'var(--ink-3)' }}/>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, paddingTop: 8, borderTop: '1px dashed var(--cream-3)' }}>
                <div>
                  <div style={{ color: 'var(--ink-4)', fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600 }}>Blended CPL</div>
                  <div style={{ fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)', fontSize: 13, fontWeight: 600, marginTop: 2 }}>${r.cpl}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ color: 'var(--ink-4)', fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600 }}>ROAS</div>
                  <div style={{ fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)', fontSize: 13, fontWeight: 600, marginTop: 2 }}>{r.roas}x</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

    </>
  );
}
window.ResultsOverviewHq = ResultsOverviewHq;

// Reusable leaderboard table for the HQ overview.
function HqLeaderboardCard({ title, sub, icon, tone, rows }) {
  const dotBg = tone === 'sage' ? 'var(--sage-soft)' : 'var(--terra-soft)';
  const dotFg = tone === 'sage' ? 'var(--sage)'      : 'var(--terra)';
  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 }}>{icon}</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' }}>Leads</span>
        <span style={{ textAlign: 'right' }}>CPL</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={() => window.toast(r.unit, `${r.leads} leads · $${r.cpl} CPL · ${r.roas}x ROAS · open location?`, '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.leads}</div>
          <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>${r.cpl}</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>
  );
}
window.HqLeaderboardCard = HqLeaderboardCard;

// --------------------------------------------------------------------
// PAID SEARCH TAB, campaigns, PMax channels, brand vs non-brand, search terms
// --------------------------------------------------------------------
function ResultsPpc({ data }) {
  const d = data.ppcDetail;
  const [stOpen, setStOpen] = useStateR(null);
  const [confirmNeg, setConfirmNeg] = useStateR(null);

  const brandSplit = [
    { label: 'Brand',     value: d.brandSplit.brand.spend,     color: 'var(--brand-navy)' },
    { label: 'Non-Brand', value: d.brandSplit.nonBrand.spend,  color: 'var(--ch-ppc)' },
    { label: 'PMax',      value: d.brandSplit.pmax.spend,      color: 'var(--ch-lseo)' },
  ];

  const reallocateCta = d.brandSplit.nonBrand.lostShareBudget >= 20;

  return (
    <>
      {/* Headline KPIs */}
      <div className="grid grid-4" style={{ marginBottom: 16 }}>
        <KpiCard label="Spend" value={`$${d.summary.spend.toLocaleString()}`} color="var(--ch-ppc)" dotColor="var(--ch-ppc)"/>
        <KpiCard label="Leads" value={d.summary.leads} delta={18} color="var(--terra)" dotColor="var(--terra)"/>
        <KpiCard label="Cost / Lead" value={`$${d.summary.cpl}`} delta={-12} invert color="var(--sage)" dotColor="var(--sage)"/>
        <KpiCard label="ROAS" value={`${d.summary.roas}x`} delta={9} color="var(--marigold)" dotColor="var(--marigold)"/>
      </div>

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

      {/* Brand vs Non-Brand callout */}
      <div className="card card-pad" style={{ marginBottom: 16 }}>
        <div className="card-header" style={{ marginBottom: 14 }}>
          <div>
            <div className="card-title">Brand vs Non-Brand</div>
            <div className="card-sub">Where your search budget is going, and where impression share is leaking.</div>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', gap: 28, alignItems: 'center' }}>
          <ResultsDonut segments={brandSplit} size={170} strokeW={26} center={
            <>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '.08em', fontWeight: 600 }}>Search spend</div>
              <div style={{ fontFamily: 'var(--ff-display)', fontSize: 26, fontWeight: 500, lineHeight: 1 }}>${d.summary.spend.toLocaleString()}</div>
            </>
          }/>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 16 }}>
            {[
              { tag: 'Brand',     row: d.brandSplit.brand,    color: 'var(--brand-navy)', sub: "Your name & branded variants" },
              { tag: 'Non-Brand', row: d.brandSplit.nonBrand, color: 'var(--ch-ppc)',     sub: "Generic terms, conquest, intent" },
              { tag: 'PMax',      row: d.brandSplit.pmax,     color: 'var(--ch-lseo)',    sub: "Auto-placed across Google" },
            ].map(({ tag, row, color, sub }) => (
              <div key={tag} style={{ padding: 14, background: 'var(--cream)', borderRadius: 10, borderLeft: `3px solid ${color}` }}>
                <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 4 }}>
                  <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-2)' }}>{tag}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{row.share}% mix</div>
                </div>
                <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 500, lineHeight: 1.1 }}>${row.spend.toLocaleString()}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>{sub}</div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, marginTop: 10, fontSize: 11.5 }}>
                  <div><span style={{ color: 'var(--ink-3)' }}>Leads</span> <strong>{row.leads}</strong></div>
                  <div><span style={{ color: 'var(--ink-3)' }}>CPL</span> <strong>${row.cpl}</strong></div>
                  <div><span style={{ color: 'var(--ink-3)' }}>ROAS</span> <strong>{row.roas}x</strong></div>
                  {row.impressionShare !== undefined && <div><span style={{ color: 'var(--ink-3)' }}>IS</span> <strong>{row.impressionShare}%</strong></div>}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Impression share gauges */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, marginTop: 22 }}>
          <div>
            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-2)', marginBottom: 8 }}>Brand · Impression Share</div>
            <ISGauge won={d.brandSplit.brand.impressionShare} lostBudget={d.brandSplit.brand.lostShareBudget} lostRank={d.brandSplit.brand.lostShareRank}/>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 6 }}>Healthy. You're capturing 78% of brand searches in your area.</div>
          </div>
          <div>
            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-2)', marginBottom: 8 }}>Non-Brand · Impression Share</div>
            <ISGauge won={d.brandSplit.nonBrand.impressionShare} lostBudget={d.brandSplit.nonBrand.lostShareBudget} lostRank={d.brandSplit.nonBrand.lostShareRank}/>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 6 }}>{d.brandSplit.nonBrand.lostShareBudget}% of impressions lost to <strong>budget</strong>, every $1 of brand spend earns 2.3× the leads.</div>
          </div>
        </div>

        {reallocateCta && (
          <div style={{ marginTop: 18, padding: '14px 16px', background: 'linear-gradient(135deg, var(--terra-soft), var(--marigold-soft))', borderRadius: 12, display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--cream)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18 }}></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 600 }}>Reallocate $200 from Non-Brand to Brand</div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>Non-Brand is losing 30% of impressions to budget, but Brand has higher ROAS (7.8x) and is only 17% of mix. Lenny modeled +6 incremental leads / mo.</div>
            </div>
            <button className="btn btn-primary btn-sm" onClick={() => T('Reallocation drafted', '$200/mo proposed shift Non-Brand → Brand. Awaiting your approval in Budget.', 'ok')}>Reallocate</button>
            <button className="btn btn-quiet btn-sm" onClick={() => T('Math', 'Brand IS = 78% (healthy). Non-Brand losing 30% IS to budget. Brand ROAS 7.8x vs Non-Brand 4.4x.', 'info')}>Show math</button>
          </div>
        )}
      </div>

      <SourceNote>Source: Google Ads</SourceNote>

      {/* Campaign breakdown */}
      <div className="card" style={{ marginBottom: 16, overflow: 'hidden' }}>
        <div className="card-pad" style={{ paddingBottom: 12 }}>
          <div className="card-title">Campaign breakdown</div>
          <div className="card-sub">Each campaign in your Google Ads account, with attribution rolled up.</div>
        </div>
        <table className="tbl">
          <thead>
            <tr>
              <th>Campaign</th><th>Type</th>
              <th style={{ textAlign: 'right' }}>Spend</th>
              <th style={{ textAlign: 'right' }}>Leads</th>
              <th style={{ textAlign: 'right' }}>CPL</th>
              <th style={{ textAlign: 'right' }}>ROAS</th>
              <th style={{ textAlign: 'right' }}>CTR</th>
              <th style={{ textAlign: 'right' }}>Imp. Share</th>
              <th/>
            </tr>
          </thead>
          <tbody>
            {d.campaigns.map((c, i) => (
              <tr key={i}>
                <td><strong>{c.name}</strong></td>
                <td><span className="badge badge-neutral">{c.type}</span></td>
                <td style={{ textAlign: 'right' }} className="mono">${c.spend}</td>
                <td style={{ textAlign: 'right' }} className="strong">{c.leads}</td>
                <td style={{ textAlign: 'right' }} className="mono">${c.cpl}</td>
                <td style={{ textAlign: 'right' }} className="strong">{c.roas}x</td>
                <td style={{ textAlign: 'right' }} className="mono">{c.ctr}%</td>
                <td style={{ textAlign: 'right' }}>
                  {c.impressionShare > 0 ? (
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                      <span className="mono">{c.impressionShare}%</span>
                      {c.lostBudget >= 20 && <span className="badge badge-warn" style={{ fontSize: 10 }}>−{c.lostBudget}% budget</span>}
                    </span>
                  ) : <span style={{ color: 'var(--ink-4)' }}>–</span>}
                </td>
                <td>
                  <span className={`badge ${c.status === 'opportunity' ? 'badge-warn' : 'badge-ok'}`} style={{ fontSize: 10 }}>
                    {c.status === 'opportunity' ? 'OPP' : 'OK'}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

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

      {/* PMax channel attribution */}
      <div className="card card-pad" style={{ marginBottom: 16 }}>
        <div className="card-header" style={{ marginBottom: 14 }}>
          <div>
            <div className="card-title">Performance Max, channel attribution</div>
            <div className="card-sub">Where your PMax campaign actually showed. PMax auto-places across all Google surfaces.</div>
          </div>
          <button className="btn btn-quiet btn-sm" onClick={() => T('Asset health', 'PMax asset group "Spring Refresh", 87% Excellent, all assets approved. No bottlenecks.', 'info')}>Asset health</button>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
          <div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '.06em', fontWeight: 600, marginBottom: 10 }}>Impression share by surface</div>
            <StackedRow segments={d.pmaxChannels.map(c => ({ label: c.channel, value: c.impr, color: c.color }))} h={28} radius={6}/>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, marginTop: 12, fontSize: 11.5 }}>
              {d.pmaxChannels.map((c, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <span style={{ width: 10, height: 10, background: c.color, borderRadius: 2 }}/>
                  <strong>{c.channel}</strong>
                  <span style={{ color: 'var(--ink-3)' }}>{c.share}%</span>
                </div>
              ))}
            </div>
          </div>
          <div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '.06em', fontWeight: 600, marginBottom: 10 }}>Conversions by surface</div>
            <HBars rows={d.pmaxChannels.map(c => ({ label: c.channel, value: c.conv, color: c.color }))} formatter={v => v.toFixed(1)}/>
            <div style={{ marginTop: 14, padding: 12, background: 'var(--cream)', borderRadius: 8, fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.55 }}>
              <strong style={{ color: 'var(--ink-2)' }}>Read:</strong> Search and Maps drive ~70% of PMax conversions despite ~30% of impressions. YouTube/Display are pure top-of-funnel, judge them on view-through and brand-search lift, not last-click.
            </div>
          </div>
        </div>
      </div>

      <SourceNote>Source: Google Ads</SourceNote>

      {/* PMax creative performance */}
      {(() => {
        const perfTone = { Best: 'var(--sage)', Good: 'var(--marigold)', Low: 'var(--terra)' };
        const perfBg = { Best: 'var(--sage-soft)', Good: 'var(--marigold-soft)', Low: 'var(--terra-soft)' };
        const groups = d.pmaxAssetGroups || [];
        const creatives = d.pmaxCreatives || [];
        const sum = (g) => ['headlines', 'images', 'videos'].reduce((a, k) => a + g[k].best + g[k].good + g[k].low, 0);
        return (
          <div className="card card-pad" style={{ marginBottom: 16 }}>
            <div className="card-header" style={{ marginBottom: 14 }}>
              <div>
                <div className="card-title">Performance Max, creative performance</div>
                <div className="card-sub">Google rates every asset Best / Good / Low. Feed the winners, replace the Low ones to lift ad strength.</div>
              </div>
              <button className="btn btn-quiet btn-sm" onClick={() => T('Creative studio', 'Opening the PMax asset group editor. Swap low-rated assets and add fresh creative here.', 'info')}>Manage assets</button>
            </div>

            {/* Top individual 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 }}>
              {creatives.map((c) => (
                <div key={c.id} className="card" style={{ overflow: 'hidden', padding: 0 }}>
                  <div style={{ height: 92, background: c.grad, position: 'relative', 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.toFixed(1)} 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 }}>
              {groups.map((g) => {
                const best = ['headlines', 'images', 'videos'].reduce((a, k) => a + g[k].best, 0);
                const good = ['headlines', 'images', 'videos'].reduce((a, k) => a + g[k].good, 0);
                const low = ['headlines', 'images', 'videos'].reduce((a, k) => a + g[k].low, 0);
                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: 130 }}>{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.toFixed(1)} conv · {g.ctr}% CTR</span>
                    </div>
                    <div style={{ marginTop: 10 }}>
                      <StackedRow segments={[
                        { label: 'Best', value: best, color: 'var(--sage)' },
                        { label: 'Good', value: good, color: 'var(--marigold)' },
                        { label: 'Low', value: low, color: 'var(--terra)' },
                      ]} h={20} radius={5}/>
                    </div>
                    <div style={{ display: 'flex', gap: 14, marginTop: 8, fontSize: 11, color: 'var(--ink-3)' }}>
                      <span><strong style={{ color: 'var(--sage)' }}>{best}</strong> Best</span>
                      <span><strong style={{ color: 'var(--marigold)' }}>{good}</strong> Good</span>
                      <span><strong style={{ color: 'var(--terra)' }}>{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>

      {/* Search terms */}
      <div className="card" style={{ marginBottom: 16, overflow: 'hidden' }}>
        <div className="card-pad" style={{ paddingBottom: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <div className="card-title">Search terms</div>
            <div className="card-sub">What people typed to find you. Add irrelevant terms as negative keywords with one click.</div>
          </div>
          <div style={{ display: 'flex', gap: 6, alignItems: 'center', fontSize: 11, color: 'var(--ink-3)' }}>
            <span style={{ width: 10, height: 10, background: 'var(--sage-soft)', borderRadius: 2, border: '1px solid var(--sage)' }}/>Converting
            <span style={{ width: 10, height: 10, background: 'var(--clay-soft, #fdf0e4)', borderRadius: 2, border: '1px solid var(--clay)', marginLeft: 8 }}/>Suggested negative
          </div>
        </div>
        <table className="tbl">
          <thead>
            <tr>
              <th>Search Term</th>
              <th style={{ textAlign: 'right' }}>Impr.</th>
              <th style={{ textAlign: 'right' }}>Clicks</th>
              <th style={{ textAlign: 'right' }}>Conv.</th>
              <th style={{ textAlign: 'right' }}>CPL</th>
              <th>Type</th>
              <th/>
            </tr>
          </thead>
          <tbody>
            {d.searchTerms.map((t, i) => {
              const isNeg = t.status === 'negative';
              return (
                <tr key={i} style={{ background: isNeg ? 'rgba(184,132,109,.06)' : t.status === 'good' ? 'rgba(82,184,148,.05)' : 'transparent' }}>
                  <td style={{ fontFamily: 'var(--ff-mono)', fontSize: 12.5 }}>{t.term}</td>
                  <td style={{ textAlign: 'right' }} className="mono">{t.impr.toLocaleString()}</td>
                  <td style={{ textAlign: 'right' }} className="mono">{t.clicks}</td>
                  <td style={{ textAlign: 'right' }} className="strong">{t.conv}</td>
                  <td style={{ textAlign: 'right' }} className="mono">{t.cpl ? `$${t.cpl}` : '–'}</td>
                  <td>
                    {t.status === 'brand' && <span className="badge" style={{ background: 'var(--brand-navy)', color: 'var(--cream)', fontSize: 10 }}>BRAND</span>}
                    {t.status === 'good'  && <span className="badge badge-ok" style={{ fontSize: 10 }}>CONVERTING</span>}
                    {t.status === 'negative' && <span className="badge" style={{ background: 'var(--clay)', color: 'var(--cream)', fontSize: 10 }}>NO CONVERSIONS</span>}
                  </td>
                  <td>
                    {isNeg ? (
                      <button className="btn btn-quiet btn-xs" onClick={() => setConfirmNeg(t)}>+ Add Negative</button>
                    ) : (
                      <button className="btn btn-quiet btn-xs" onClick={() => T('Term details', `${t.term}, ${t.clicks} clicks, ${t.conv} conv. Top match: "${t.term} near me".`, 'info')}>Details</button>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        <div className="card-pad" style={{ paddingTop: 12, fontSize: 11.5, color: 'var(--ink-3)', borderTop: '1px solid var(--line)' }}>
          <strong style={{ color: 'var(--ink-2)' }}>Already negated for this account:</strong> 
          {d.existingNegatives.map(n => <span key={n} className="badge badge-neutral" style={{ marginRight: 4, fontSize: 10 }}>{n}</span>)}
        </div>
      </div>

      <SourceNote>Source: Google Ads</SourceNote>

      {/* Add negative confirmation */}
      <Modal open={!!confirmNeg} onClose={() => setConfirmNeg(null)} title="Add as negative keyword?" sub={confirmNeg?.term}
        footer={<>
          <button className="btn btn-ghost btn-sm" onClick={() => setConfirmNeg(null)}>Cancel</button>
          <button className="btn btn-primary btn-sm" onClick={() => { T('Negative added', `"${confirmNeg.term}" added to all Search campaigns. Will save ~$${Math.round(confirmNeg.clicks * 1.4)}/mo.`, 'ok'); setConfirmNeg(null); }}>Add Negative</button>
        </>}>
        {confirmNeg && (
          <div>
            <div style={{ padding: 14, background: 'var(--cream)', borderRadius: 10, marginBottom: 14 }}>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', fontWeight: 600, letterSpacing: '.06em' }}>Search term</div>
              <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 16, fontWeight: 600, marginTop: 4 }}>{confirmNeg.term}</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12, marginTop: 12, fontSize: 12 }}>
                <div><span style={{ color: 'var(--ink-3)' }}>Impressions</span><div style={{ fontWeight: 600 }}>{confirmNeg.impr.toLocaleString()}</div></div>
                <div><span style={{ color: 'var(--ink-3)' }}>Clicks</span><div style={{ fontWeight: 600 }}>{confirmNeg.clicks}</div></div>
                <div><span style={{ color: 'var(--ink-3)' }}>Conversions</span><div style={{ fontWeight: 600 }}>{confirmNeg.conv}</div></div>
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.5 }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <input type="radio" name="match" defaultChecked/> Phrase match, only block when query contains "{confirmNeg.term}"
              </label>
              <label style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <input type="radio" name="match"/> Exact match, only block this exact query
              </label>
            </div>
            <div style={{ marginTop: 12, fontSize: 11.5, color: 'var(--ink-3)' }}>Applies to all Search campaigns. PMax has its own negative list, handled separately.</div>
          </div>
        )}
      </Modal>
    </>
  );
}
window.ResultsPpc = ResultsPpc;

// --------------------------------------------------------------------
// CHANNEL RESULTS — "By channel" view: each enrolled channel broken out
// --------------------------------------------------------------------
function ResultsByChannel({ data, setTab }) {
  const { channels } = data;
  const total = channels.reduce((a, c) => a + c.spend, 0) || 1;
  const tabFor = (k) => k === 'ppc' ? 'ppc' : k === 'lsa' ? 'lsa' : (k === 'lseo' || k === 'seo') ? 'seo' : 'social';
  return (
    <>
      <div className="grid grid-3" style={{ marginBottom: 16 }}>
        {channels.map(c => (
          <div key={c.key} className="card card-pad" style={{ cursor: 'pointer', transition: 'box-shadow .15s, transform .15s' }}
               onClick={() => setTab(tabFor(c.key))}
               onMouseEnter={e => { e.currentTarget.style.boxShadow = 'var(--sh-2)'; e.currentTarget.style.transform = 'translateY(-2px)'; }}
               onMouseLeave={e => { e.currentTarget.style.boxShadow = ''; e.currentTarget.style.transform = ''; }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
              <span style={{ width: 9, height: 9, borderRadius: '50%', background: c.color }}/>
              <span style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)' }}>{c.name}</span>
              <span style={{ flex: 1 }}/>
              <span style={{ fontSize: 10, color: 'var(--ink-4)', fontWeight: 700, letterSpacing: '.04em' }}>OPEN →</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 10 }}>
              <span style={{ fontFamily: 'var(--ff-display)', fontSize: 30, fontWeight: 500 }}>{c.roas}x</span>
              <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>ROAS</span>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px 12px', fontSize: 12, color: 'var(--ink-2)' }}>
              <div><span style={{ color: 'var(--ink-4)' }}>Leads</span> · <strong>{c.leads}</strong></div>
              <div><span style={{ color: 'var(--ink-4)' }}>CPL</span> · <strong>${c.cpl}</strong></div>
              <div><span style={{ color: 'var(--ink-4)' }}>Spend</span> · <strong>${c.spend}/mo</strong></div>
              <div><span style={{ color: 'var(--ink-4)' }}>Mix</span> · <strong>{Math.round(c.spend / total * 100)}%</strong></div>
            </div>
            <div style={{ height: 6, background: 'var(--cream-2)', borderRadius: 3, overflow: 'hidden', marginTop: 12 }}>
              <div style={{ width: Math.round(c.spend / total * 100) + '%', height: '100%', background: c.color, borderRadius: 3 }}/>
            </div>
          </div>
        ))}
      </div>
      <SourceNote>Source: Google Ads + Telmetrics or other + FreshNest CRM · combined across all enrolled locations</SourceNote>
    </>
  );
}
window.ResultsByChannel = ResultsByChannel;

// --------------------------------------------------------------------
// CHANNEL RESULTS — "By location" view: each location broken out (HQ)
// --------------------------------------------------------------------
function ResultsByLocation({ data }) {
  const rollup = window.buildPortfolio ? window.buildPortfolio(data.hqRollup || [], 700) : (data.hqRollup || []);
  const rows = rollup.map(r => {
    const mult = 3.2 + (r.score - 60) * 0.08;
    const rev  = Math.round(r.spend * mult);
    const roas = +(rev / r.spend).toFixed(1);
    const cpl  = Math.round(r.spend / r.leads);
    return { unit: r.unit, city: r.city, leads: r.leads, cpl, roas };
  }).sort((a, b) => b.roas - a.roas);
  return (
    <>
      <div className="card card-pad" style={{ marginBottom: 16 }}>
        <div className="card-header" style={{ marginBottom: 12 }}>
          <div>
            <div className="card-title">All locations</div>
            <div className="card-sub">Every enrolled location, ranked by blended ROAS · click to open</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' }}>Leads</span>
          <span style={{ textAlign: 'right' }}>CPL</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={() => window.toast(r.unit, `${r.leads} leads · $${r.cpl} CPL · ${r.roas}x ROAS · open location?`, '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.leads}</div>
            <div style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>${r.cpl}</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>
      <SourceNote>Source: LOCALACT portfolio rollup · {rows.length} enrolled locations</SourceNote>
    </>
  );
}
window.ResultsByLocation = ResultsByLocation;

Object.assign(window, { ResultsDonut, StackedRow, HBars, ISGauge, EnrollmentOpportunityCard });
