// ====================================================================
// ENTERPRISE REPORTING, corporate-only premium analytics surface.
// Heavy charts, custom-report builder, data-connection upsells.
// ====================================================================

const { useState: useStateER, useEffect: useEffectER, useRef: useRefER, useMemo: useMemoER } = React;

// ----- shared chart helpers -------------------------------------------------
function ERPath({ pts, w, h, color, fill, smooth = true }) {
  if (!pts || !pts.length) return null;
  const max = Math.max(...pts);
  const min = Math.min(...pts);
  const range = max - min || 1;
  const sx = (i) => i / (pts.length - 1) * w;
  const sy = (v) => h - (v - min) / range * h;
  let d = '';
  if (smooth) {
    pts.forEach((p, i) => {
      const x = sx(i),y = sy(p);
      if (i === 0) d += `M ${x} ${y}`;else
      {
        const px = sx(i - 1),py = sy(pts[i - 1]);
        const cx1 = px + (x - px) / 2,cx2 = x - (x - px) / 2;
        d += ` C ${cx1} ${py}, ${cx2} ${y}, ${x} ${y}`;
      }
    });
  } else {
    pts.forEach((p, i) => {d += `${i === 0 ? 'M' : 'L'} ${sx(i)} ${sy(p)} `;});
  }
  const fillPath = fill ? `${d} L ${w} ${h} L 0 ${h} Z` : null;
  return (
    <>
      {fillPath && <path d={fillPath} fill={fill} opacity="0.18" />}
      <path d={d} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </>);

}

function ERMultiLine({ series, w = 720, h = 220, labels }) {
  // shared y-axis across all series so they compare correctly
  const all = series.flatMap((s) => s.pts);
  const max = Math.max(...all),min = Math.min(...all);
  const range = max - min || 1;
  const padL = 40,padR = 12,padT = 12,padB = 26;
  const cw = w - padL - padR,ch = h - padT - padB;
  const sx = (i) => padL + i / (series[0].pts.length - 1) * cw;
  const sy = (v) => padT + ch - (v - min) / range * ch;
  const yTicks = 4;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', display: 'block' }}>
      {/* gridlines */}
      {Array.from({ length: yTicks + 1 }).map((_, i) => {
        const y = padT + ch / yTicks * i;
        const tickV = max - range / yTicks * i;
        return (
          <g key={i}>
            <line x1={padL} x2={w - padR} y1={y} y2={y} stroke="var(--cream-3)" strokeWidth="1" strokeDasharray={i === yTicks ? '0' : '2 4'} />
            <text x={padL - 6} y={y + 3} fontSize="9.5" fill="var(--ink-4)" textAnchor="end" fontFamily="var(--ff-mono)">
              {tickV >= 1000 ? (tickV / 1000).toFixed(0) + 'k' : tickV.toFixed(0)}
            </text>
          </g>);

      })}
      {/* x labels */}
      {labels && labels.map((l, i) =>
      <text key={i} x={sx(i)} y={h - 8} fontSize="9.5" fill="var(--ink-4)" textAnchor="middle" fontFamily="var(--ff-mono)">{l}</text>
      )}
      {/* lines */}
      {series.map((s, si) => {
        let d = '';
        s.pts.forEach((p, i) => {
          const x = sx(i),y = sy(p);
          if (i === 0) d += `M ${x} ${y}`;else
          {
            const px = sx(i - 1),py = sy(s.pts[i - 1]);
            const cx1 = px + (x - px) / 2,cx2 = x - (x - px) / 2;
            d += ` C ${cx1} ${py}, ${cx2} ${y}, ${x} ${y}`;
          }
        });
        return (
          <g key={si}>
            <path d={d} fill="none" stroke={s.color} strokeWidth="2.25" strokeLinecap="round" strokeLinejoin="round" />
            {s.pts.map((p, i) =>
            <circle key={i} cx={sx(i)} cy={sy(p)} r="2.5" fill={s.color} />
            )}
          </g>);

      })}
    </svg>);

}

function ERBarChart({ items, w = 640, h = 200, valFmt }) {
  const max = Math.max(...items.map((i) => i.v));
  const padL = 90,padR = 16,padT = 8,padB = 8;
  const cw = w - padL - padR,ch = h - padT - padB;
  const rowH = ch / items.length;
  const barH = Math.min(20, rowH - 8);
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', display: 'block' }}>
      {items.map((it, i) => {
        const y = padT + i * rowH + (rowH - barH) / 2;
        const bw = it.v / max * cw;
        return (
          <g key={i}>
            <text x={padL - 10} y={y + barH / 2 + 3.5} fontSize="11" fill="var(--ink-2)" textAnchor="end" fontWeight="600">{it.label}</text>
            <rect x={padL} y={y} width={cw} height={barH} fill="var(--cream-2)" rx="3" />
            <rect x={padL} y={y} width={bw} height={barH} fill={it.color} rx="3" />
            <text x={padL + bw - 6} y={y + barH / 2 + 3.5} fontSize="10.5" fill="var(--cream)" textAnchor="end" fontFamily="var(--ff-mono)" fontWeight="700">
              {valFmt ? valFmt(it.v) : it.v.toLocaleString()}
            </text>
          </g>);

      })}
    </svg>);

}

function ERFunnel({ stages }) {
  // Log-scaled widths so 62M impressions don't crush 2.8k revenue to a sliver.
  // Conversion percentages still reflect raw counts.
  const logVals = stages.map(s => Math.log10(s.v));
  const logMax = Math.max(...logVals);
  const logMin = Math.min(...logVals);
  const logRange = (logMax - logMin) || 1;
  // Smallest stage = 22% width, largest = 100%.
  const widthFor = v => 22 + ((Math.log10(v) - logMin) / logRange) * 78;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <div style={{ display: 'flex', justifyContent: 'flex-end', fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, marginBottom: 2 }}>
        Bars on log scale · % = stage conversion
      </div>
      {stages.map((s, i) => {
        const pct = widthFor(s.v);
        const conv = i > 0 ? (s.v / stages[i - 1].v * 100).toFixed(1) : null;
        return (
          <div key={i} style={{ position: 'relative' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 4 }}>
              <div style={{ flex: 1, fontSize: 12, color: 'var(--ink-2)', fontWeight: 600 }}>{s.label}</div>
              <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink)', fontFamily: 'var(--ff-mono)' }}>{s.v.toLocaleString()}</div>
              {conv != null &&
              <div style={{ fontSize: 10.5, color: parseFloat(conv) >= 25 ? 'var(--ok)' : parseFloat(conv) >= 8 ? 'var(--marigold)' : 'var(--ink-4)', fontFamily: 'var(--ff-mono)', fontWeight: 700, minWidth: 48, textAlign: 'right' }}>
                  {conv}%
                </div>
              }
            </div>
            <div style={{ height: 10, background: 'var(--cream-2)', borderRadius: 5, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: pct + '%', background: `linear-gradient(90deg, ${s.color}, ${s.color}cc)`, borderRadius: 5 }} />
            </div>
          </div>);

      })}
    </div>);

}

function ERHeatBlock({ value, max, color }) {
  const intensity = Math.max(0.08, Math.min(1, value / max));
  return (
    <div style={{
      background: color, opacity: 0.15 + intensity * 0.75,
      aspectRatio: '1', borderRadius: 4,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: intensity > 0.55 ? 'var(--cream)' : 'var(--ink-2)',
      fontSize: 10, fontWeight: 700, fontFamily: 'var(--ff-mono)'
    }} title={value.toLocaleString()}>
      {value > 999 ? (value / 1000).toFixed(1) + 'k' : value}
    </div>);

}

// ============================================================================
// MAIN PAGE
// ============================================================================
function EnterpriseReportingPage({ data }) {
  const [tab, setTab] = useStateER('overview');
  const [range, setRange] = useStateER('last30');
  const [customOpen, setCustomOpen] = useStateER(false);
  const [connectModal, setConnectModal] = useStateER(null);

  return (
    <div className="page-wrap">

      <ERHero onCustom={() => setCustomOpen(true)} range={range} setRange={setRange} />

      {/* Tab strip */}
      <div className="tabs" style={{ marginTop: 18, marginBottom: 18, borderBottom: '1px solid var(--cream-3)' }}>
        {[
        { v: 'overview', label: 'Executive overview' },
        { v: 'campaigns', label: 'National campaigns' },
        { v: 'funnel', label: 'Funnel & attribution' },
        { v: 'audience', label: 'Audiences & geo' },
        { v: 'connect', label: 'Data connections', phase2: true },
        { v: 'custom', label: 'Custom reports' }].
        map((t) =>
        <button key={t.v} onClick={() => setTab(t.v)}
        className={`tab ${tab === t.v ? 'active' : ''}`}>
            {t.label}
            {t.dot && <span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: 'var(--marigold)', marginLeft: 6, verticalAlign: 'middle' }} />}
            {t.phase2 && <span style={{ fontSize: 9, padding: '1px 6px', borderRadius: 8, background: 'var(--la-brand-quaternary-100)', color: 'var(--la-brand-quaternary-700)', fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', marginLeft: 6, verticalAlign: 'middle' }}>Phase 2</span>}
          </button>
        )}
      </div>

      {tab === 'overview' && <EROverviewTab onConnect={setConnectModal} setTab={setTab} />}
      {tab === 'campaigns' && <ERCampaignsTab range={range} />}
      {tab === 'funnel' && <ERFunnelTab />}
      {tab === 'audience' && <ERAudienceTab />}
      {tab === 'connect' && <ERConnectTab onConnect={setConnectModal} />}
      {tab === 'custom' && <ERCustomTab onOpen={() => setCustomOpen(true)} />}

      {customOpen && <ERCustomReportModal onClose={() => setCustomOpen(false)} />}
      {connectModal && <ERConnectModal source={connectModal} onClose={() => setConnectModal(null)} />}
    </div>);

}
window.EnterpriseReportingPage = EnterpriseReportingPage;

// ============================================================================
// HERO, premium framing, KPI strip
// ============================================================================
function ERHero({ onCustom, range, setRange }) {
  return (
    <div style={{
      background: "linear-gradient(115deg, var(--la-brand-secondary-900) 0%, rgba(0,17,37,0.55) 52%, rgba(0,17,37,0.15) 100%), url('brand/cover-streaks.png')",
      backgroundSize: 'cover, cover', backgroundPosition: 'center, right center', backgroundRepeat: 'no-repeat, no-repeat',
      borderRadius: 16, padding: '24px 28px', color: 'var(--cream)', position: 'relative', overflow: 'hidden'
    }}>
      {/* subtle depth glow */}
      <div style={{ position: 'absolute', left: 220, bottom: -120, width: 280, height: 280, borderRadius: '50%', background: 'radial-gradient(circle, rgba(246,166,99,0.14), transparent 65%)' }} />

      <div style={{ position: 'relative', display: 'flex', alignItems: 'flex-start', gap: 18, marginBottom: 22, flexWrap: 'wrap' }}>
        <div style={{ flex: 1, minWidth: 280 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <span style={{ padding: '3px 8px', background: 'rgba(246,166,99,0.18)', color: '#f6a663', fontSize: 10, fontWeight: 700, borderRadius: 4, letterSpacing: '0.08em', textTransform: 'uppercase', border: '1px solid rgba(246,166,99,0.35)' }}>★ Enterprise tier</span>
            <span style={{ fontSize: 11, color: 'rgba(250,246,239,0.55)', fontFamily: 'var(--ff-mono)' }}>v2026.4 · refreshed 8 min ago</span>
          </div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 32, fontWeight: 500, letterSpacing: '-0.02em', marginBottom: 6, lineHeight: 1.1 }}>
            Enterprise Reporting.
          </div>
          <div style={{ fontSize: 14, color: 'rgba(250,246,239,0.78)', maxWidth: 580, lineHeight: 1.5 }}>
            Every national campaign, every funnel stage, every dollar of attributed revenue across all 700 locations, live, exportable, and built around <strong style={{ color: '#f6a663', fontWeight: 600 }}>your sources of truth</strong>.
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-end', color: "rgb(255, 255, 255)" }}>
          <select value={range} onChange={(e) => setRange(e.target.value)}
          style={{ padding: '8px 12px', background: 'rgba(255,255,255,0.08)', color: 'var(--cream)', border: '1px solid rgba(255,255,255,0.18)', borderRadius: 8, fontSize: 12.5, fontWeight: 600, fontFamily: 'var(--ff-sans)' }}>
            <option value="last7">Last 7 days</option>
            <option value="last30">Last 30 days</option>
            <option value="last90">Last 90 days</option>
            <option value="qtd">Quarter to date</option>
            <option value="ytd">Year to date</option>
            <option value="custom">Custom range…</option>
          </select>
          <div style={{ display: 'flex', gap: 8 }}>
            <button onClick={() => T('Report scheduled', "PDF + .xlsx will land in your inbox every Monday at 8am.", 'ok')}
            style={{ padding: '8px 14px', background: 'rgba(255,255,255,0.06)', color: 'var(--cream)', border: '1px solid rgba(255,255,255,0.18)', borderRadius: 8, fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>
              Schedule
            </button>
            <button onClick={() => T('Export started', 'Combined .xlsx + .pdf · 6 sheets · downloading now.', 'ok')}
            style={{ padding: '8px 14px', background: 'rgba(255,255,255,0.06)', color: 'var(--cream)', border: '1px solid rgba(255,255,255,0.18)', borderRadius: 8, fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>
              ↓ Export
            </button>
          </div>
        </div>
      </div>

      {/* KPI strip */}
      <div style={{ position: 'relative', display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 1, background: 'rgba(255,255,255,0.08)', borderRadius: 12, overflow: 'hidden', border: '1px solid rgba(255,255,255,0.12)' }}>
        {[
        { lbl: 'Attributed revenue', v: '$1.88M', d: '+18.4%', dPos: true, spark: [40, 38, 44, 42, 50, 56, 54, 62, 68, 64, 72, 78, 82, 88], col: '#f6a663' },
        { lbl: 'Marketing-sourced leads', v: '14,800', d: '+11.2%', dPos: true, spark: [180, 195, 210, 198, 220, 232, 240, 252, 260, 268, 274, 282, 290, 298], col: '#4d6989' },
        { lbl: 'Blended CAC', v: '$71.02', d: '−6.8%', dPos: true, spark: [72, 70, 68, 71, 67, 65, 64, 62, 60, 58, 57, 56, 54.5, 54.1], col: '#56adad' },
        { lbl: 'Marketing ROI', v: '4.0x', d: '+0.4x', dPos: true, spark: [3.8, 3.9, 4.0, 4.1, 4.0, 4.2, 4.3, 4.4, 4.3, 4.5, 4.5, 4.6, 4.6, 4.6], col: '#669bf1' },
        { lbl: 'Attribution coverage', v: '96%', d: 'CRM + GA4', dPos: true, spark: [88, 89, 90, 91, 92, 93, 93, 94, 94, 95, 95, 95, 96, 96], col: '#56adad' }].
        map((k, i) =>
        <div key={i} style={{ background: 'rgba(20,16,30,0.62)', padding: '14px 16px' }}>
            <div style={{ fontSize: 10, color: 'rgba(250,246,239,0.55)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600, marginBottom: 4 }}>{k.lbl}</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 26, fontWeight: 500, color: 'var(--cream)', letterSpacing: '-0.015em', marginBottom: 4 }}>{k.v}</div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span style={{ fontSize: 11, color: k.warn ? '#f6a663' : k.dPos ? '#56adad' : '#e46c63', fontWeight: 600, fontFamily: 'var(--ff-mono)' }}>
                {k.warn ? '⚠ ' : k.dPos ? '↗ ' : '↘ '}{k.d}
              </span>
              <svg viewBox="0 0 60 18" width="60" height="18" style={{ opacity: 0.85 }}>
                <ERPath pts={k.spark} w={60} h={18} color={k.col} />
              </svg>
            </div>
          </div>
        )}
      </div>
    </div>);

}

// ============================================================================
// FORECAST, demand & seasonality, powered by Google Trends + Analytics
// ============================================================================
// 20 weeks: 12 actual + 8 forecast. Left axis = attributed revenue ($k/wk),
// right axis = Google Trends search-interest index (0–100), which leads demand
// by ~2–3 weeks. mode='blend' overlays both; mode='trends' shows Trends alone.
function ERForecastChart({ mode, w = 780, h = 300 }) {
  const W = 20, HIST = 12;
  const padL = 46, padR = 46, padT = 20, padB = 32;
  const cw = w - padL - padR, ch = h - padT - padB;
  const sx = (i) => padL + i / (W - 1) * cw;
  const revMin = 40, revMax = 150;
  const syR = (v) => padT + ch - (v - revMin) / (revMax - revMin) * ch;
  const syT = (v) => padT + ch - v / 100 * ch;

  // ---- data ----
  const revHist = [58, 61, 60, 64, 63, 67, 66, 70, 72, 71, 76, 80];
  const fcIdx = [11, 12, 13, 14, 15, 16, 17, 18, 19];
  const revMed = [80, 84, 89, 95, 102, 108, 112, 109, 104];
  const revBand = [0, 4, 6, 9, 12, 16, 20, 24, 29];
  const trHist = [44, 46, 45, 50, 54, 57, 60, 63, 67, 70, 74, 79];
  const trMed = [79, 85, 90, 94, 97, 96, 92, 86, 80];
  const trBand = [0, 3, 5, 7, 9, 11, 13, 15, 17];

  const labels = { 0: 'Apr', 4: 'May', 8: 'Jun', 12: 'Jul', 16: 'Aug' };
  const REV = '#4d6989', TR = '#669bf1';

  const spath = (arr, sy) => {
    let d = '';
    arr.forEach(([i, v], k) => {
      const x = sx(i), y = sy(v);
      if (k === 0) d += `M ${x} ${y}`;else
      {
        const [pi, pv] = arr[k - 1];
        const px = sx(pi), py = sy(pv);
        d += ` C ${px + (x - px) / 2} ${py}, ${x - (x - px) / 2} ${y}, ${x} ${y}`;
      }
    });
    return d;
  };
  const cone = (med, band, sy) => {
    let d = `M ${sx(fcIdx[0])} ${sy(med[0])}`;
    fcIdx.forEach((i, k) => d += ` L ${sx(i)} ${sy(med[k] + band[k])}`);
    for (let k = fcIdx.length - 1; k >= 0; k--) d += ` L ${sx(fcIdx[k])} ${sy(med[k] - band[k])}`;
    return d + ' Z';
  };

  const showRev = mode === 'blend';
  const trPrimary = mode === 'trends';

  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', display: 'block' }}>
      {/* gridlines + left (revenue) axis */}
      {Array.from({ length: 5 }).map((_, i) => {
        const y = padT + ch / 4 * i;
        const rv = revMax - (revMax - revMin) / 4 * i;
        const tv = 100 - 25 * i;
        return (
          <g key={i}>
            <line x1={padL} x2={w - padR} y1={y} y2={y} stroke="var(--cream-3)" strokeWidth="1" strokeDasharray={i === 4 ? '0' : '2 4'} />
            {showRev &&
            <text x={padL - 7} y={y + 3} fontSize="9.5" fill={REV} textAnchor="end" fontFamily="var(--ff-mono)">${rv.toFixed(0)}k</text>}
            <text x={w - padR + 7} y={y + 3} fontSize="9.5" fill={TR} textAnchor="start" fontFamily="var(--ff-mono)">{tv}</text>
          </g>);
      })}
      {/* forecast region shade + today divider */}
      <rect x={sx(HIST - 1)} y={padT} width={w - padR - sx(HIST - 1)} height={ch} fill="var(--violet-soft)" opacity="0.35" />
      <line x1={sx(HIST - 1)} x2={sx(HIST - 1)} y1={padT} y2={padT + ch} stroke="var(--ink-4)" strokeWidth="1" strokeDasharray="3 3" />
      <text x={sx(HIST - 1) + 6} y={padT + 11} fontSize="9" fill="var(--ink-4)" fontFamily="var(--ff-mono)" fontWeight="700" style={{ textTransform: 'uppercase', letterSpacing: '0.05em' }}>Forecast →</text>

      {/* x labels */}
      {Object.entries(labels).map(([i, l]) =>
      <text key={i} x={sx(+i)} y={h - 9} fontSize="9.5" fill="var(--ink-4)" textAnchor="middle" fontFamily="var(--ff-mono)">{l}</text>)}

      {/* ---- Trends: cone (only when primary) ---- */}
      {trPrimary && <path d={cone(trMed, trBand, syT)} fill={TR} opacity="0.14" />}
      {/* Trends actual */}
      <path d={spath(trHist.map((v, i) => [i, v]), syT)} fill="none" stroke={TR} strokeWidth={trPrimary ? 2.5 : 1.75} strokeLinecap="round" opacity={trPrimary ? 1 : 0.75} />
      {/* Trends forecast (dashed) */}
      <path d={spath(fcIdx.map((i, k) => [i, trMed[k]]), syT)} fill="none" stroke={TR} strokeWidth={trPrimary ? 2.5 : 1.75} strokeDasharray="5 4" strokeLinecap="round" opacity={trPrimary ? 1 : 0.75} />

      {/* ---- Revenue (blend only): cone + actual + forecast ---- */}
      {showRev &&
      <>
        <path d={cone(revMed, revBand, syR)} fill={REV} opacity="0.16" />
        <path d={spath(revHist.map((v, i) => [i, v]), syR)} fill="none" stroke={REV} strokeWidth="2.5" strokeLinecap="round" />
        <path d={spath(fcIdx.map((i, k) => [i, revMed[k]]), syR)} fill="none" stroke={REV} strokeWidth="2.5" strokeDasharray="5 4" strokeLinecap="round" />
        {revHist.map((v, i) => <circle key={i} cx={sx(i)} cy={syR(v)} r="2.5" fill={REV} />)}
      </>}
      {trPrimary && trHist.map((v, i) => <circle key={i} cx={sx(i)} cy={syT(v)} r="2.5" fill={TR} />)}
    </svg>);
}

// Rising search themes, top query clusters from Google Ads search terms,
// scored against Google Trends rising queries. Drives the demand call-outs.
const RISING_KEYWORDS = [
{ kw: 'deep cleaning service', idx: 92, mom: 41, spark: [40, 44, 48, 52, 58, 66, 74, 84, 92] },
{ kw: 'move-out cleaning', idx: 78, mom: 33, spark: [38, 40, 42, 47, 52, 58, 64, 71, 78] },
{ kw: 'spring cleaning near me', idx: 88, mom: 27, spark: [52, 55, 58, 62, 68, 74, 80, 85, 88] },
{ kw: 'recurring house cleaning', idx: 71, mom: 18, spark: [50, 52, 54, 57, 60, 63, 66, 69, 71] },
{ kw: 'carpet cleaning', idx: 64, mom: 12, spark: [50, 51, 53, 55, 57, 59, 61, 63, 64] }];

// ============================================================================
// OVERVIEW TAB
// ============================================================================
function EROverviewTab({ onConnect, setTab }) {
  const months = ['May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr'];
  const [fcMode, setFcMode] = useStateER('blend');
  return (
    <>
      {/* Trend + composition row */}
      <div className="grid" style={{ gridTemplateColumns: '1.45fr 1fr', gap: 16, marginBottom: 16 }}>
        <div className="card card-pad">
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
            <span style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700 }}>National performance · trailing 12 months</span>
            <span style={{ flex: 1 }} />
            <button className="btn btn-quiet btn-xs" onClick={() => T('Compare mode', 'Side-by-side YoY view enabled.', 'info')}>YoY compare</button>
          </div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)', marginBottom: 14 }}>Revenue, leads &amp; spend pacing</div>
          <ERMultiLine
            labels={months}
            series={[
            { name: 'Attributed revenue ($k)', color: '#4d6989', pts: [180, 195, 210, 218, 232, 245, 258, 272, 264, 278, 296, 312] },
            { name: 'Marketing Qualified Leads (MQLs)', color: '#f6a663', pts: [820, 880, 940, 985, 1020, 1080, 1135, 1180, 1140, 1210, 1265, 1310] },
            { name: 'Spend ($k)', color: '#56adad', pts: [56, 58, 62, 64, 68, 70, 72, 74, 72, 76, 78, 80] }]
            }
            w={780} h={260} />
          
          <div style={{ display: 'flex', gap: 16, marginTop: 12, flexWrap: 'wrap', fontSize: 11.5 }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 10, height: 3, background: '#4d6989', borderRadius: 2 }} /> Attributed revenue</span>
            <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 10, height: 3, background: '#f6a663', borderRadius: 2 }} /> Marketing Qualified Leads (MQLs)</span>
            <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 10, height: 3, background: '#56adad', borderRadius: 2 }} /> Spend</span>
          </div>
        </div>

        {/* Channel mix donut */}
        <div className="card card-pad">
          <div style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 4 }}>Revenue by channel · last 30 days</div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)', marginBottom: 18 }}>Where the money came from</div>

          <ERDonut items={[
          { label: 'Paid Search', v: 38.2, color: '#4d6989' },
          { label: 'Local Service Ads', v: 22.4, color: '#f6a663' },
          { label: 'Programmatic', v: 14.6, color: '#669bf1' },
          { label: 'National Social', v: 11.8, color: '#e46c63' },
          { label: 'Local SEO / Organic', v: 9.2, color: '#56adad' },
          { label: 'Other', v: 3.8, color: '#a9a9ae' }]
          } />
        </div>
      </div>

      <SourceNote>Source: Google Ads + FreshNest CRM · revenue attributed by LOCALACT</SourceNote>

      {/* ===== Demand & seasonality (predictive) ===== */}
      <div className="grid" style={{ gridTemplateColumns: '1.45fr 1fr', gap: 16, marginBottom: 16 }}>
        {/* Forecast chart */}
        <div className="card card-pad">
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700 }}>Predictive · demand &amp; seasonality</span>
            <span style={{ flex: 1 }} />
            {/* mode toggle */}
            <div style={{ display: 'inline-flex', background: 'var(--cream-2)', borderRadius: 999, padding: 2 }}>
              {[{ v: 'blend', l: 'Trends + Analytics' }, { v: 'trends', l: 'Trends only' }].map((m) =>
                <button key={m.v} onClick={() => setFcMode(m.v)} style={{
                  padding: '5px 12px', borderRadius: 999, border: 'none', cursor: 'pointer',
                  fontSize: 11, fontWeight: 700, letterSpacing: '0.01em',
                  background: fcMode === m.v ? 'var(--paper)' : 'transparent',
                  color: fcMode === m.v ? 'var(--ink)' : 'var(--ink-3)',
                  boxShadow: fcMode === m.v ? 'var(--shadow-sm, 0 1px 3px rgba(0,40,87,0.12))' : 'none',
                  transition: 'all .12s',
                }}>{m.l}</button>
              )}
            </div>
          </div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)', marginBottom: 4 }}>8-week demand forecast</div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.5, marginBottom: 12, maxWidth: 560 }}>
            {fcMode === 'blend'
              ? <>Attributed revenue projected forward against the <strong style={{ color: '#669bf1' }}>Google Trends search-interest index</strong>, which leads booked demand by ~2–3 weeks. Shaded band = 80% confidence range.</>
              : <>Raw <strong style={{ color: '#669bf1' }}>Google Trends search interest</strong> for your service categories, the leading demand signal on its own, before Analytics attribution.</>}
          </div>

          <ERForecastChart mode={fcMode} />

          <div style={{ display: 'flex', gap: 16, marginTop: 10, flexWrap: 'wrap', fontSize: 11.5, alignItems: 'center' }}>
            {fcMode === 'blend' &&
            <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 12, height: 3, background: '#4d6989', borderRadius: 2 }} /> Attributed revenue ($k/wk)</span>}
            <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 12, height: 3, background: '#669bf1', borderRadius: 2 }} /> Search interest (0–100)</span>
            <span style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--ink-4)' }}><span style={{ width: 12, height: 0, borderTop: '2px dashed var(--ink-4)' }} /> Forecast</span>
          </div>

          <div style={{ marginTop: 14, padding: '12px 14px', background: 'var(--sage-soft)', borderRadius: 10, display: 'flex', gap: 12, alignItems: 'flex-start' }}>
            <span style={{ width: 22, height: 22, borderRadius: 6, background: 'var(--ok)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 700, flexShrink: 0 }}>↑</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--ink)', marginBottom: 2 }}>Demand ramps ~3 weeks out, act ahead of the curve</div>
              <div style={{ fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.5 }}>
                Search interest is up 18% in 4 weeks and forecast to peak late July. Per the playbook, pre-fund metro Search now rather than chasing the spike. Est. <strong>+$28k</strong> incremental revenue if funded this week.
              </div>
              <div style={{ display: 'flex', gap: 8, marginTop: 8, flexWrap: 'wrap' }}>
                <button className="btn btn-primary btn-xs" onClick={() => window.dispatchEvent(new CustomEvent('go-page', { detail: 'budget' }))} style={{ background: 'var(--violet)', borderColor: 'var(--violet)' }}>Adjust budget →</button>
                <button className="btn btn-quiet btn-xs" onClick={() => T('Forecast method', 'Blended model: Google Trends leading index + GA4/Google Ads attribution, fit on trailing 52 weeks. Cone = 80% confidence.', 'info')}>How this is modeled</button>
              </div>
            </div>
          </div>
        </div>

        {/* Rising demand keywords */}
        <div className="card card-pad">
          <div style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 4 }}>Rising demand · this network</div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)', marginBottom: 4 }}>Categories heating up</div>
          <div style={{ fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.5, marginBottom: 14 }}>
            Top query clusters from your Google Ads search terms, scored against Google Trends rising queries.
          </div>
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {RISING_KEYWORDS.map((k, i) =>
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: i < RISING_KEYWORDS.length - 1 ? '1px solid var(--cream-2)' : 'none' }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{k.kw}</div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-4)', fontFamily: 'var(--ff-mono)', marginTop: 2 }}>Search interest {k.idx}</div>
                </div>
                <svg viewBox="0 0 64 22" width="64" height="22" style={{ flexShrink: 0 }}>
                  <ERPath pts={k.spark} w={64} h={22} color="#669bf1" fill="#669bf1" />
                </svg>
                <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 12, fontWeight: 700, color: 'var(--ok)', minWidth: 44, textAlign: 'right' }}>+{k.mom}%</span>
              </div>
            )}
          </div>
          <div style={{ marginTop: 12, fontSize: 10.5, color: 'var(--ink-4)', lineHeight: 1.5 }}>
            Δ = month-over-month change in search interest. Feed these into seasonal creative and keyword expansion.
          </div>
        </div>
      </div>

      <SourceNote>Estimated by LOCALACT · demand indexed to Google Trends</SourceNote>

      {/* Insight cards */}
      <div className="grid grid-3" style={{ gap: 12, marginBottom: 16 }}>
        {[
        { tag: 'Up trend', tagBg: 'var(--ok-soft, #e4f3eb)', tagFg: 'var(--ok)', t: 'National Social ROAS up 0.9x', d: 'Summer Deep-Clean creative is outperforming the spring baseline by 38%. Worth pushing more spend Jul 1 – Aug 15.' },
        { tag: 'Watch', tagBg: 'var(--marigold-soft)', tagFg: '#725900', t: 'Programmatic CTR softening', d: 'CTR dropped 14bps WoW across metro DMAs. Likely creative fatigue, recommend a refresh cycle.' },
        { tag: 'Action', tagBg: 'var(--terra-soft)', tagFg: 'var(--terra)', t: '6 locations under-pacing brand', d: 'Plano, Frisco, Round Rock, McKinney, Allen, Sugar Land at ≤72% of regional CAC efficiency. Coaching call queued.' }].
        map((c, i) =>
        <div key={i} className="card card-pad">
            <span style={{ display: 'inline-block', padding: '3px 8px', background: c.tagBg, color: c.tagFg, fontSize: 10, fontWeight: 700, borderRadius: 4, letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 10 }}>{c.tag}</span>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 15, fontWeight: 600, color: 'var(--ink)', marginBottom: 6, lineHeight: 1.3 }}>{c.t}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.5 }}>{c.d}</div>
          </div>
        )}
      </div>

      {/* Connections nudge, only for the 32% gap */}
      <div style={{
        position: 'relative', overflow: 'hidden', borderRadius: 14, padding: '20px 24px',
        background: 'linear-gradient(120deg, rgba(77,105,137,0.10) 0%, rgba(246,166,99,0.10) 100%)',
        border: '1px solid var(--violet-soft)', marginBottom: 16
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 18, flexWrap: 'wrap' }}>
          <div style={{ flex: 1, minWidth: 280 }}>
            <div style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 6 }}>Close the 32% attribution gap</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 20, fontWeight: 600, color: 'var(--ink)', marginBottom: 6 }}>Connect your CRM, GA4 &amp; field-service tools</div>
            <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5, maxWidth: 680 }}>
              You're tracking digital touchpoints today, but 4% of revenue still posts as "direct / unknown." Pipe in <strong>GA4</strong>, <strong>Salesforce</strong>, and your <strong>field-service or POS system</strong> and we'll close the loop on every booked job, ticket, and revenue line.
            </div>
          </div>
          <button className="btn btn-primary btn-sm" onClick={() => setTab('connect')} style={{ background: 'var(--violet)', borderColor: 'var(--violet)' }}>
            Set up data connections →
          </button>
        </div>
      </div>
    </>);

}

// ----- mini donut --------------------------------------------------------
function ERDonut({ items }) {
  const total = items.reduce((a, b) => a + b.v, 0);
  const r = 60,cx = 80,cy = 80,sw = 22;
  let acc = 0;
  return (
    <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
      <svg viewBox="0 0 160 160" width="160" height="160" style={{ flexShrink: 0 }}>
        <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--cream-2)" strokeWidth={sw} />
        {items.map((it, i) => {
          const start = acc / total * 2 * Math.PI - Math.PI / 2;
          const end = (acc + it.v) / total * 2 * Math.PI - Math.PI / 2;
          acc += it.v;
          const x1 = cx + r * Math.cos(start),y1 = cy + r * Math.sin(start);
          const x2 = cx + r * Math.cos(end),y2 = cy + r * Math.sin(end);
          const large = end - start > Math.PI ? 1 : 0;
          const d = `M ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2}`;
          return <path key={i} d={d} stroke={it.color} strokeWidth={sw} fill="none" strokeLinecap="butt" />;
        })}
        <text x={cx} y={cy - 4} textAnchor="middle" fontSize="10" fill="var(--ink-3)" fontFamily="var(--ff-mono)" style={{ textTransform: 'uppercase', letterSpacing: '0.06em' }}>30-day</text>
        <text x={cx} y={cy + 14} textAnchor="middle" fontSize="20" fontWeight="600" fill="var(--ink)" fontFamily="var(--ff-display)">$1.88M</text>
      </svg>
      <div style={{ flex: 1, display: 'grid', gap: 6 }}>
        {items.map((it, i) =>
        <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11.5 }}>
            <span style={{ width: 9, height: 9, background: it.color, borderRadius: 2 }} />
            <span style={{ flex: 1, color: 'var(--ink-2)', fontWeight: 600 }}>{it.label}</span>
            <span style={{ fontFamily: 'var(--ff-mono)', color: 'var(--ink-3)', fontWeight: 600 }}>{it.v.toFixed(1)}%</span>
          </div>
        )}
      </div>
    </div>);

}

// ============================================================================
// CAMPAIGNS TAB, every national campaign, deep dive
// ============================================================================
function ERCampaignsTab({ range = 'last30' }) {
  const campaigns = [
  { id: 'move', name: 'Move-In / Move-Out Season', status: 'live', window: 'May 15 – Aug 31', spend: 142800, impr: 4.12e6, clicks: 62800, leads: 1840, mqls: 920, rev: 412000, cpl: 77.61, roas: 2.88, hue: '#e46c63' },
  { id: 'summer', name: 'Summer Deep-Clean Push', status: 'live', window: 'Jun 1 – Jul 31', spend: 84200, impr: 2.84e6, clicks: 41200, leads: 1120, mqls: 612, rev: 248000, cpl: 75.18, roas: 2.94, hue: '#e46c63' },
  { id: 'b2school', name: 'Back-to-School Home Reset', status: 'live', window: 'Jul 15 – Sep 5', spend: 56400, impr: 1.92e6, clicks: 28400, leads: 740, mqls: 384, rev: 168000, cpl: 76.21, roas: 2.98, hue: '#4d6989' },
  { id: 'natbr', name: 'Always-On National Brand', status: 'live', window: 'Continuous', spend: 312600, impr: 18.4e6, clicks: 184200, leads: 4120, mqls: 1840, rev: 768000, cpl: 75.87, roas: 2.46, hue: '#669bf1' },
  { id: 'lsa', name: 'Local Services Ads (national pool)', status: 'live', window: 'Continuous', spend: 196800, impr: 8.2e6, clicks: 94200, leads: 3680, mqls: 2240, rev: 624000, cpl: 53.48, roas: 3.17, hue: '#56adad' },
  { id: 'progr', name: 'Enterprise Programmatic', status: 'live', window: 'Continuous', spend: 184600, impr: 24.8e6, clicks: 36400, leads: 924, mqls: 412, rev: 218000, cpl: 199.78, roas: 1.18, hue: '#f6a663' },
  { id: 'spring', name: 'Spring Cleaning Kickoff', status: 'ended', window: 'Feb 15 – May 15', spend: 68400, impr: 2.4e6, clicks: 38400, leads: 1240, mqls: 720, rev: 296000, cpl: 55.16, roas: 4.33, hue: '#a9a9ae' }];

  // Human-readable reporting window, anchored to the demo "today" (Jul 14, 2026).
  const RANGE_LABELS = {
    last7:  { label: 'Last 7 days',     dates: 'Jul 8 – Jul 14, 2026' },
    last30: { label: 'Last 30 days',    dates: 'Jun 15 – Jul 14, 2026' },
    last90: { label: 'Last 90 days',    dates: 'Apr 16 – Jul 14, 2026' },
    qtd:    { label: 'Quarter to date', dates: 'Jul 1 – Jul 14, 2026' },
    ytd:    { label: 'Year to date',    dates: 'Jan 1 – Jul 14, 2026' },
    custom: { label: 'Custom range',    dates: 'set in the date picker' },
  };
  const rl = RANGE_LABELS[range] || RANGE_LABELS.last30;

  const [sel, setSel] = useStateER(campaigns[0]);
  const [sortKey, setSortKey] = useStateER('leads'); // 'leads' (desc) | 'cpl' (asc, lower is better)
  const [liveOnly, setLiveOnly] = useStateER(false);

  const rows = campaigns
    .filter((c) => !liveOnly || c.status === 'live')
    .sort((a, b) => sortKey === 'cpl' ? a.cpl - b.cpl : b.leads - a.leads);
  const liveCount = campaigns.filter((c) => c.status === 'live').length;

  const ctrlStyle = (on) => ({
    padding: '5px 10px', fontSize: 11, fontWeight: 600, fontFamily: 'var(--ff-ui)', cursor: 'pointer',
    border: '1px solid ' + (on ? 'var(--violet)' : 'var(--cream-3)'), borderRadius: 8,
    background: on ? 'var(--violet-soft)' : 'var(--paper)', color: on ? 'var(--violet)' : 'var(--ink-2)',
  });

  return (
    <>
      {/* table */}
      <div className="card" style={{ overflow: 'hidden', marginBottom: 16 }}>
        <div style={{ padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 10, borderBottom: '1px solid var(--cream-3)', flexWrap: 'wrap' }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
              <span style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 600, color: 'var(--ink)' }}>National campaigns</span>
              <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>· {liveCount} live</span>
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>
              Metrics for <strong style={{ color: 'var(--ink-2)' }}>{rl.label}</strong> · {rl.dates}
            </div>
          </div>
          <span style={{ flex: 1 }} />
          <button style={ctrlStyle(liveOnly)} onClick={() => setLiveOnly((v) => !v)}>Live only</button>
          <span style={{ fontSize: 11, color: 'var(--ink-4)', fontWeight: 600 }}>Sort</span>
          <button style={ctrlStyle(sortKey === 'leads')} onClick={() => setSortKey('leads')}>Leads</button>
          <button style={ctrlStyle(sortKey === 'cpl')} onClick={() => setSortKey('cpl')}>Cost / lead</button>
          <button className="btn btn-ghost btn-xs" onClick={() => T('Export started', 'Campaign breakdown · downloading .xlsx', 'ok')}>Export</button>
        </div>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
            <thead>
              <tr style={{ background: 'var(--cream)', color: 'var(--ink-3)', fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                {['Campaign', 'Window', 'Spend', 'Impressions', 'Clicks', 'Leads', 'MQLs', 'Revenue', 'CPL', 'ROAS', ''].map((h) =>
                <th key={h} style={{ padding: '10px 14px', textAlign: h === 'Campaign' || h === 'Window' || !h ? 'left' : 'right', fontWeight: 700, borderBottom: '1px solid var(--cream-3)' }}>{h}</th>
                )}
              </tr>
            </thead>
            <tbody>
              {rows.map((c) => {
                const isSel = sel.id === c.id;
                return (
                  <tr key={c.id} onClick={() => setSel(c)}
                  style={{ borderBottom: '1px solid var(--cream-2)', background: isSel ? 'var(--violet-soft)' : 'transparent', cursor: 'pointer' }}>
                    <td style={{ padding: '12px 14px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <span style={{ width: 8, height: 28, background: c.hue, borderRadius: 2, flexShrink: 0 }} />
                        <div>
                          <div style={{ fontWeight: 600, color: 'var(--ink)' }}>{c.name}</div>
                          <div style={{ fontSize: 10.5, color: c.status === 'live' ? 'var(--ok)' : 'var(--ink-4)', fontFamily: 'var(--ff-mono)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700 }}>● {c.status}</div>
                        </div>
                      </div>
                    </td>
                    <td style={{ padding: '12px 14px', color: 'var(--ink-3)', fontFamily: 'var(--ff-mono)' }}>{c.window}</td>
                    <td style={{ padding: '12px 14px', textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>${(c.spend / 1000).toFixed(1)}k</td>
                    <td style={{ padding: '12px 14px', textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-3)' }}>{(c.impr / 1e6).toFixed(2)}M</td>
                    <td style={{ padding: '12px 14px', textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-3)' }}>{c.clicks.toLocaleString()}</td>
                    <td style={{ padding: '12px 14px', textAlign: 'right', fontFamily: 'var(--ff-mono)', fontWeight: 700, color: 'var(--ink)' }}>{c.leads.toLocaleString()}</td>
                    <td style={{ padding: '12px 14px', textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>{c.mqls.toLocaleString()}</td>
                    <td style={{ padding: '12px 14px', textAlign: 'right', fontFamily: 'var(--ff-mono)', fontWeight: 700, color: 'var(--ink)' }}>${(c.rev / 1000).toFixed(0)}k</td>
                    <td style={{ padding: '12px 14px', textAlign: 'right', fontFamily: 'var(--ff-mono)', color: 'var(--ink-3)' }}>${c.cpl.toFixed(0)}</td>
                    <td style={{ padding: '12px 14px', textAlign: 'right', fontFamily: 'var(--ff-mono)', fontWeight: 700, color: c.roas >= 3 ? 'var(--ok)' : c.roas >= 2 ? 'var(--marigold)' : 'var(--terra)' }}>{c.roas.toFixed(2)}x</td>
                    <td style={{ padding: '12px 14px', color: 'var(--ink-4)', fontSize: 14 }}>›</td>
                  </tr>);

              })}
            </tbody>
          </table>
        </div>
      </div>

      <SourceNote>Source: Google Ads + FreshNest CRM · revenue attributed by LOCALACT</SourceNote>

      {/* detail */}
      <ERCampaignDetail c={sel} />
    </>);

}

function ERCampaignDetail({ c }) {
  // synthesize 14-day series scaled to spend/leads
  const days = Array.from({ length: 14 }, (_, i) => i);
  const seed = c.id.charCodeAt(0) + c.id.charCodeAt(1);
  const wave = (i, off, amp) => Math.sin((i + off) / 2.4) * amp + Math.cos((i + off) / 1.6) * amp * 0.4;
  const spendPts = days.map((i) => Math.max(0.5, c.spend / 14000 + wave(i, seed, 1.4)));
  const leadPts = days.map((i) => Math.max(1, c.leads / 14 + wave(i, seed + 3, 5)));
  const revPts = days.map((i) => Math.max(2, c.rev / 14000 + wave(i, seed + 7, 2.2)));
  const clickPts = days.map((i) => Math.max(1, c.clicks / 1400 + wave(i, seed + 5, 4)));
  const cplPts = days.map((i) => Math.max(1, c.cpl + wave(i, seed + 9, c.cpl * 0.12)));
  const dayLabels = days.map((i) => i % 2 === 0 ? `D${i + 1}` : '');

  // Layerable metrics — the user toggles which series overlay on the trend.
  const METRICS = [
  { key: 'spend', name: 'Spend ($k)', color: '#56adad', pts: spendPts },
  { key: 'leads', name: 'Leads', color: c.hue, pts: leadPts },
  { key: 'rev', name: 'Revenue ($k)', color: '#f6a663', pts: revPts },
  { key: 'clicks', name: 'Clicks (÷100)', color: '#669bf1', pts: clickPts },
  { key: 'cpl', name: 'Cost / lead ($)', color: '#b57edc', pts: cplPts }];

  const [active, setActive] = useStateER({ spend: true, leads: true, rev: true, clicks: false, cpl: false });
  const toggle = (k) => setActive((a) => {
    const next = { ...a, [k]: !a[k] };
    if (!Object.values(next).some(Boolean)) return a; // keep at least one series on
    return next;
  });
  const series = METRICS.filter((m) => active[m.key]);

  return (
    <div className="grid" style={{ gridTemplateColumns: '1.3fr 1fr', gap: 16, marginBottom: 16 }}>
      {/* daily trend */}
      <div className="card card-pad">
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
          <span style={{ width: 10, height: 10, background: c.hue, borderRadius: 2 }} />
          <span style={{ fontSize: 11, color: c.hue, textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700 }}>Daily trend</span>
          <span style={{ flex: 1 }} />
          <span style={{ fontSize: 10.5, color: 'var(--ink-4)', fontFamily: 'var(--ff-mono)' }}>{c.window}</span>
        </div>
        <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)', marginBottom: 4 }}>{c.name}</div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginBottom: 12 }}>Click any campaign above to explore it · tap a metric to layer it on the chart.</div>

        {/* metric toggles */}
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 12 }}>
          {METRICS.map((m) => {
            const on = active[m.key];
            return (
              <button key={m.key} onClick={() => toggle(m.key)} style={{
                display: 'inline-flex', alignItems: 'center', gap: 6, padding: '5px 10px', fontSize: 11, fontWeight: 600,
                fontFamily: 'var(--ff-ui)', cursor: 'pointer', borderRadius: 999,
                border: '1px solid ' + (on ? m.color : 'var(--cream-3)'),
                background: on ? m.color + '1A' : 'var(--paper)', color: on ? 'var(--ink)' : 'var(--ink-4)',
              }}>
                <span style={{ width: 9, height: 9, borderRadius: '50%', background: on ? m.color : 'var(--cream-3)' }} />
                {m.name}
              </button>);
          })}
        </div>

        <ERMultiLine labels={dayLabels} series={series} w={620} h={240} />
      </div>

      {/* breakdown */}
      <div className="card card-pad">
        <div style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 4 }}>By placement</div>
        <div style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 600, color: 'var(--ink)', marginBottom: 14 }}>Where leads came from</div>
        <ERBarChart items={[
        { label: 'Google Search', v: Math.round(c.leads * 0.42), color: '#4285F4' },
        { label: 'Meta · IG', v: Math.round(c.leads * 0.22), color: '#E1306C' },
        { label: 'Meta · FB', v: Math.round(c.leads * 0.14), color: '#1877F2' },
        { label: 'Programmatic', v: Math.round(c.leads * 0.10), color: '#f6a663' },
        { label: 'YouTube', v: Math.round(c.leads * 0.08), color: '#FF0000' },
        { label: 'TikTok', v: Math.round(c.leads * 0.04), color: '#000000' }]
        } h={220} />
      </div>
    </div>);

}

// ============================================================================
// FUNNEL TAB
// ============================================================================
function ERFunnelTab() {
  return (
    <>
      <div className="grid" style={{ gridTemplateColumns: '1.1fr 1fr', gap: 16, marginBottom: 16 }}>
        <div className="card card-pad">
          <div style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 4 }}>Full-funnel · last 30 days</div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)', marginBottom: 18 }}>Impressions → Revenue</div>
          <ERFunnel stages={[
          { label: 'Impressions', v: 62400000, color: '#4d6989' },
          { label: 'Clicks / engagements', v: 648400, color: '#4d6989' },
          { label: 'Site / landing visits', v: 412800, color: '#8fa0b5' },
          { label: 'Leads', v: 14800, color: '#4d6989' },
          { label: 'Marketing Qualified Leads (MQLs)', v: 9600, color: '#f6a663' },
          { label: 'Sales Qualified Leads (SQLs) / booked jobs', v: 6660, color: '#e46c63' },
          { label: 'Booked revenue', v: 1880, color: '#56adad' }]
          } />
          <div style={{ marginTop: 16, padding: '10px 12px', background: 'var(--cream)', borderRadius: 8, fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.5 }}>
            <strong style={{ color: 'var(--ink-2)' }}>Reading this funnel:</strong> Click→lead conv (3.4%) and lead→MQL (55%) both beat L3 peer median (2.8% / 48%). MQL→SQL is the bottleneck, see below.
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {/* MQL→SQL bottleneck */}
          <div className="card card-pad">
            <div style={{ fontSize: 11, color: 'var(--terra)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 4 }}>Bottleneck</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)', marginBottom: 12 }}>62.8% MQL → SQL</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-3)', lineHeight: 1.55, marginBottom: 14 }}>
              You're losing 2,908 MQLs to scheduling friction each month. Top reasons (from CRM notes): unanswered after-hours calls (38%), booking pushed past the requested date (28%), no follow-up within 24h (22%).
            </div>
            <ERBarChart items={[
            { label: 'Unanswered AH', v: 1108, color: '#e46c63' },
            { label: 'Date pushed', v: 814, color: '#f6a663' },
            { label: 'No 24h reply', v: 640, color: '#f6a663' },
            { label: 'Pricing pull', v: 346, color: '#a9a9ae' }]
            } h={140} valFmt={(v) => v.toLocaleString()} />
          </div>

          {/* Attribution model toggle */}
          <div className="card card-pad">
            <div style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 4 }}>Attribution model</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 600, color: 'var(--ink)', marginBottom: 12 }}>Last-touch vs. data-driven</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 8 }}>
              {[
              { ch: 'Paid Search', lt: 38, dd: 31, col: '#4d6989' },
              { ch: 'LSA', lt: 22, dd: 18, col: '#f6a663' },
              { ch: 'Programmatic', lt: 14, dd: 23, col: '#669bf1' },
              { ch: 'Social', lt: 12, dd: 18, col: '#e46c63' }].
              map((r) =>
              <div key={r.ch} style={{ padding: 10, background: 'var(--cream)', borderRadius: 8 }}>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-3)', fontWeight: 600, marginBottom: 6 }}>{r.ch}</div>
                  <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, height: 50 }}>
                    <div style={{ flex: 1, height: r.lt + '%', background: 'var(--cream-3)', borderRadius: '3px 3px 0 0' }} title={'Last-touch ' + r.lt + '%'} />
                    <div style={{ flex: 1, height: r.dd + '%', background: r.col, borderRadius: '3px 3px 0 0' }} title={'Data-driven ' + r.dd + '%'} />
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 9.5, fontFamily: 'var(--ff-mono)', color: 'var(--ink-4)', marginTop: 4 }}>
                    <span>{r.lt}%</span><span>{r.dd}%</span>
                  </div>
                </div>
              )}
            </div>
            <div style={{ marginTop: 10, fontSize: 11, color: 'var(--ink-4)' }}>Light = last-touch · solid = data-driven (multi-touch)</div>
          </div>
        </div>
      </div>

      <SourceNote>Source: Google Ads + FreshNest CRM · funnel modeled by LOCALACT</SourceNote>

      {/* path-to-conversion table */}
      <div className="card card-pad">
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 600, color: 'var(--ink)' }}>Top conversion paths</div>
          <span style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>Most common touchpoint sequences leading to a booked job</span>
        </div>
        {[
        { path: ['Programmatic display', 'Paid search · brand', 'GBP listing'], share: 18.4, conv: '4.2%', leads: 2614 },
        { path: ['Paid search · non-brand', 'Site retarget', 'Paid search · brand'], share: 14.8, conv: '5.8%', leads: 2103 },
        { path: ['Local SEO · GBP', 'LSA call'], share: 12.6, conv: '7.4%', leads: 1790 },
        { path: ['Meta · IG awareness', 'Paid search · brand', 'LSA call'], share: 9.4, conv: '6.1%', leads: 1336 },
        { path: ['Direct / unknown', 'GBP listing', 'Phone call'], share: 8.2, conv: '8.8%', leads: 1165 },
        { path: ['YouTube pre-roll', 'Paid search · non-brand', 'Site form'], share: 6.8, conv: '3.2%', leads: 966 }].
        map((row, i) =>
        <div key={i} style={{ padding: '12px 0', borderBottom: '1px solid var(--cream-2)', display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 24, fontSize: 10.5, color: 'var(--ink-4)', fontWeight: 700, fontFamily: 'var(--ff-mono)' }}>#{i + 1}</div>
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
              {row.path.map((p, pi) =>
            <React.Fragment key={pi}>
                  <span style={{ padding: '4px 9px', background: 'var(--cream)', borderRadius: 6, fontSize: 11.5, color: 'var(--ink-2)', fontWeight: 600 }}>{p}</span>
                  {pi < row.path.length - 1 && <span style={{ color: 'var(--ink-4)', fontSize: 10 }}>→</span>}
                </React.Fragment>
            )}
            </div>
            <div style={{ width: 80, textAlign: 'right', fontSize: 12, fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)', fontWeight: 600 }}>{row.share}%</div>
            <div style={{ width: 60, textAlign: 'right', fontSize: 12, fontFamily: 'var(--ff-mono)', color: 'var(--ink-3)' }}>{row.conv}</div>
            <div style={{ width: 80, textAlign: 'right', fontSize: 12, fontFamily: 'var(--ff-mono)', color: 'var(--ink)', fontWeight: 700 }}>{row.leads.toLocaleString()}</div>
          </div>
        )}
        <div style={{ display: 'flex', fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, paddingTop: 10 }}>
          <span style={{ width: 24 }} />
          <span style={{ flex: 1 }}>Path</span>
          <span style={{ width: 80, textAlign: 'right' }}>Share</span>
          <span style={{ width: 60, textAlign: 'right' }}>Conv</span>
          <span style={{ width: 80, textAlign: 'right' }}>Leads</span>
        </div>
      </div>
    </>);

}

// ============================================================================
// AUDIENCE / GEO TAB
// ============================================================================
function ERAudienceTab() {
  // 5 regions × 6 metric "weeks" heatmap — canonical FreshNest region set
  const regions = ['Northeast', 'Southeast', 'Midwest', 'Central', 'West'];
  const weeks = ['W18', 'W19', 'W20', 'W21', 'W22', 'W23'];
  const heatVals = [
  [124, 148, 172, 188, 204, 226],
  [218, 246, 272, 298, 314, 338],
  [162, 188, 214, 236, 258, 276],
  [184, 220, 258, 274, 296, 312],
  [142, 168, 192, 210, 238, 252]];

  const heatMax = 350;

  return (
    <>
      <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
        {/* Regional heat */}
        <div className="card card-pad">
          <div style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 4 }}>Regional revenue · weekly</div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 600, color: 'var(--ink)', marginBottom: 4 }}>Revenue heatmap by region</div>
          <div style={{ fontSize: 10.5, color: 'var(--ink-4)', marginBottom: 14, fontStyle: 'italic' }}>Placeholder regions · region groupings will be franchisor-configurable.</div>
          <div style={{ display: 'grid', gridTemplateColumns: '120px repeat(6, 1fr)', gap: 6 }}>
            <div />
            {weeks.map((w) => <div key={w} style={{ fontSize: 10, color: 'var(--ink-4)', fontFamily: 'var(--ff-mono)', textAlign: 'center', fontWeight: 600 }}>{w}</div>)}
            {regions.map((r, ri) =>
            <React.Fragment key={r}>
                <div style={{ fontSize: 11.5, color: 'var(--ink-2)', fontWeight: 600, alignSelf: 'center' }}>{r}</div>
                {heatVals[ri].map((v, vi) =>
              <ERHeatBlock key={vi} value={v} max={heatMax} color="#4d6989" />
              )}
              </React.Fragment>
            )}
          </div>
          <div style={{ marginTop: 12, fontSize: 11, color: 'var(--ink-3)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <span>Less</span>
            <span style={{ display: 'inline-flex', gap: 2 }}>
              {[0.18, 0.34, 0.5, 0.68, 0.86].map((o, i) => <span key={i} style={{ width: 16, height: 8, background: '#4d6989', opacity: o, borderRadius: 1 }} />)}
            </span>
            <span>More</span>
            <span style={{ flex: 1 }} />
            <span style={{ fontFamily: 'var(--ff-mono)' }}>$ in thousands</span>
          </div>
        </div>

        {/* Customer demographics */}
        <div className="card card-pad">
          <div style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 4 }}>Audience profile</div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 600, color: 'var(--ink)', marginBottom: 14 }}>Who's converting</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <div>
              <div style={{ fontSize: 10.5, color: 'var(--ink-4)', textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.05em', marginBottom: 6 }}>Age</div>
              {[
              { g: '25–34', v: 18 },
              { g: '35–44', v: 32 },
              { g: '45–54', v: 24 },
              { g: '55–64', v: 16 },
              { g: '65+', v: 10 }].
              map((b, i) =>
              <div key={i} style={{ marginBottom: 6 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, marginBottom: 2 }}>
                    <span style={{ color: 'var(--ink-2)', fontWeight: 600 }}>{b.g}</span>
                    <span style={{ color: 'var(--ink-3)', fontFamily: 'var(--ff-mono)' }}>{b.v}%</span>
                  </div>
                  <div style={{ height: 6, background: 'var(--cream-2)', borderRadius: 3 }}>
                    <div style={{ width: b.v * 3 + '%', height: '100%', background: '#4d6989', borderRadius: 3 }} />
                  </div>
                </div>
              )}
            </div>
            <div>
              <div style={{ fontSize: 10.5, color: 'var(--ink-4)', textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.05em', marginBottom: 6 }}>HHI</div>
              {[
              { g: '<$50k', v: 12 },
              { g: '$50–100k', v: 28 },
              { g: '$100–150k', v: 32 },
              { g: '$150–200k', v: 18 },
              { g: '$200k+', v: 10 }].
              map((b, i) =>
              <div key={i} style={{ marginBottom: 6 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, marginBottom: 2 }}>
                    <span style={{ color: 'var(--ink-2)', fontWeight: 600 }}>{b.g}</span>
                    <span style={{ color: 'var(--ink-3)', fontFamily: 'var(--ff-mono)' }}>{b.v}%</span>
                  </div>
                  <div style={{ height: 6, background: 'var(--cream-2)', borderRadius: 3 }}>
                    <div style={{ width: b.v * 3 + '%', height: '100%', background: '#f6a663', borderRadius: 3 }} />
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      <SourceNote>Source: FreshNest CRM · attribution by LOCALACT</SourceNote>

      {/* Top DMAs */}
      <div className="card card-pad" style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 600, color: 'var(--ink)' }}>Top performing DMAs</div>
          <span style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>Ranked by revenue per location</span>
          <span style={{ flex: 1 }} />
          <button className="btn btn-quiet btn-xs" onClick={() => T('Geo report exported', 'All DMAs · CSV', 'ok')}>Export all DMAs</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
          {[
          { name: 'Austin–Round Rock', locs: 4, rev: 412, lift: '+22.4%', col: '#4d6989' },
          { name: 'Dallas–Fort Worth', locs: 6, rev: 386, lift: '+18.6%', col: '#4d6989' },
          { name: 'Denver–Boulder', locs: 3, rev: 348, lift: '+14.2%', col: '#f6a663' },
          { name: 'San Diego', locs: 2, rev: 322, lift: '+11.8%', col: '#f6a663' },
          { name: 'Atlanta', locs: 3, rev: 284, lift: '+8.4%', col: '#e46c63' },
          { name: 'Salt Lake City', locs: 2, rev: 248, lift: '+5.2%', col: '#e46c63' }].
          map((d, i) =>
          <div key={i} style={{ padding: '12px 14px', background: 'var(--cream)', borderRadius: 10, display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 30, height: 30, borderRadius: 8, background: d.col, color: 'var(--cream)', fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontFamily: 'var(--ff-mono)' }}>#{i + 1}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink)' }}>{d.name}</div>
                <div style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>{d.locs} locations</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: 13, fontFamily: 'var(--ff-mono)', fontWeight: 700, color: 'var(--ink)' }}>${d.rev}k</div>
                <div style={{ fontSize: 10.5, color: 'var(--ok)', fontFamily: 'var(--ff-mono)', fontWeight: 700 }}>{d.lift}</div>
              </div>
            </div>
          )}
        </div>
      </div>
    </>);

}

// ============================================================================
// CONNECTIONS TAB, the upsell
// ============================================================================
const DATA_SOURCES = [
{ id: 'ga4', name: 'Google Analytics 4', cat: 'Web analytics', logo: 'GA4', col: '#F9AB00', status: 'connected', val: 'Web traffic, on-site events, ecommerce', plan: 'Included', cta: null },
{ id: 'gads', name: 'Google Ads', cat: 'Paid media', logo: 'GA', col: '#4285F4', status: 'connected', val: 'Search, PMax, YouTube', plan: 'Included', cta: null },
{ id: 'meta', name: 'Meta Ads', cat: 'Paid media', logo: 'M', col: '#0866FF', status: 'connected', val: 'Facebook + Instagram ad performance', plan: 'Included', cta: null },
{ id: 'gbp', name: 'Google Business Profile', cat: 'Local', logo: 'GBP', col: '#34A853', status: 'connected', val: 'Calls, directions, listing engagement', plan: 'Included', cta: null },
{ id: 'ga4', name: 'Google Analytics 4', cat: 'Measurement', logo: 'GA4', col: '#E8710A', status: 'available', val: 'Site sessions, conversions, and channel attribution', plan: 'Included', recommend: true, cta: 'Connect' },
{ id: 'sf', name: 'Salesforce', cat: 'CRM', logo: 'SF', col: '#00A1E0', status: 'available', val: 'Closed-loop revenue · MQL→SQL→Won attribution', plan: 'Custom quote', recommend: true, cta: 'Connect' },
{ id: 'hubspot', name: 'HubSpot', cat: 'CRM', logo: 'HS', col: '#FF7A59', status: 'available', val: 'Lead lifecycle, lifecycle stages, deal value', plan: 'Custom quote', cta: 'Connect' },
{ id: 'shopify', name: 'Shopify', cat: 'E-commerce', logo: 'SH', col: '#7AB55C', status: 'available', val: 'Online order revenue, attribution to ad spend', plan: 'Custom quote', cta: 'Connect' },
{ id: 'mc', name: 'Mailchimp', cat: 'Email', logo: 'MC', col: '#FFE01B', status: 'available', val: 'Email engagement, lifecycle, audience overlap', plan: 'Custom quote', cta: 'Connect' }];

// Anything outside the mainstream set (field-service, POS, warehouses) is
// offered through a single "Custom connector" path, talk-to-us / scoped build.
const CUSTOM_SOURCES = [
{ id: 'st', name: 'ServiceTitan', cat: 'Field service' },
{ id: 'square', name: 'Square POS', cat: 'Point of sale' },
{ id: 'tt', name: 'TikTok Ads', cat: 'Paid media' },
{ id: 'snow', name: 'Snowflake / BigQuery', cat: 'Data warehouse' }];


function ERConnectTab({ onConnect }) {
  const connected = DATA_SOURCES.filter((d) => d.status === 'connected');
  const available = DATA_SOURCES.filter((d) => d.status === 'available');
  return (
    <>
      {/* Phase 2 marker */}
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '14px 16px', marginBottom: 16, borderRadius: 14, background: 'var(--la-brand-quaternary-50)', border: '1px solid var(--la-brand-quaternary-200)' }}>
        <span style={{ flexShrink: 0, marginTop: 1, width: 22, height: 22, borderRadius: '50%', background: 'var(--la-brand-quaternary-500)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>
        </span>
        <div>
          <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--la-brand-quaternary-800)', letterSpacing: '0.02em', textTransform: 'uppercase', marginBottom: 3 }}>Coming in Phase 2</div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.55, maxWidth: 720 }}>Self-serve data connectors are on the Phase 2 roadmap. The sources below preview what you'll be able to pipe into LOCALACT.</div>
        </div>
      </div>
      {/* Hero / pitch */}
      <div className="card card-pad" style={{ marginBottom: 16, background: 'linear-gradient(120deg, var(--violet-soft) 0%, transparent 60%)' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 18, flexWrap: 'wrap' }}>
          <div style={{ flex: 1, minWidth: 280 }}>
            <div style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 6 }}>Your data warehouse</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 24, fontWeight: 600, color: 'var(--ink)', marginBottom: 8, letterSpacing: '-0.015em' }}>Pipe your sources of truth into LOCALACT.</div>
            <div style={{ fontSize: 13.5, color: 'var(--ink-2)', lineHeight: 1.55, maxWidth: 720 }}>
              Right now you're seeing <strong>68% of revenue</strong> attributed back to a marketing source. The remaining 32% is "direct / unknown", phone walk-ins, repeat customers, and brand searches we can't tie to a campaign without your CRM and field-service data. Connect them and we close the loop, write the data back, and rebuild every report on top.
            </div>
          </div>
          <div style={{ display: 'flex', gap: 18, alignItems: 'center', padding: '12px 16px', background: 'var(--paper)', borderRadius: 10, border: '1px solid var(--cream-3)' }}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: 'var(--ff-display)', fontSize: 28, fontWeight: 600, color: 'var(--ink)' }}>{connected.length}</div>
              <div style={{ fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Connected</div>
            </div>
            <div style={{ width: 1, height: 36, background: 'var(--cream-3)' }} />
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: 'var(--ff-display)', fontSize: 28, fontWeight: 600, color: 'var(--violet)' }}>{available.length}</div>
              <div style={{ fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Available</div>
            </div>
          </div>
        </div>
      </div>

      {/* Connected */}
      <div className="section-label">
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--ok)' }} />
          Connected sources
          <span className="count">{connected.length} live · syncing on schedule</span>
        </span>
      </div>
      <div className="grid grid-2" style={{ gap: 10, marginBottom: 22 }}>
        {connected.map((s) => <ERSourceCard key={s.id} s={s} />)}
      </div>

      {/* Available */}
      <div className="section-label">
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--violet)' }} />
          Available connections
          <span className="count">{available.length} sources · add-on pricing</span>
        </span>
      </div>
      <div className="grid grid-2" style={{ gap: 10 }}>
        {available.map((s) => <ERSourceCard key={s.id} s={s} onConnect={onConnect} />)}
      </div>

      {/* Custom connector */}
      <div className="section-label" style={{ marginTop: 22 }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--ink-4)' }} />
          Custom connector
          <span className="count">field-service, POS &amp; data warehouses · scoped build</span>
        </span>
      </div>
      <div className="card card-pad">
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, flexWrap: 'wrap' }}>
          <div style={{ flex: 1, minWidth: 280 }}>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 15, fontWeight: 600, color: 'var(--ink)', marginBottom: 4 }}>Need something not listed?</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-3)', lineHeight: 1.5, marginBottom: 12, maxWidth: 640 }}>Field-service platforms, point-of-sale, niche ad networks, and internal data warehouses connect through a custom, scoped build. Tell us your source of truth and we'll pipe it in via API or SQL.</div>
            <div style={{ display: 'flex', gap: 7, flexWrap: 'wrap' }}>
              {CUSTOM_SOURCES.map((c) => (
                <span key={c.id} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, fontWeight: 600, color: 'var(--ink-2)', background: 'var(--cream)', border: '1px solid var(--cream-3)', padding: '4px 10px', borderRadius: 999 }}>
                  {c.name}<span style={{ color: 'var(--ink-4)', fontWeight: 500 }}>· {c.cat}</span>
                </span>
              ))}
            </div>
          </div>
          <button className="btn btn-primary btn-sm" onClick={() => onConnect && onConnect({ name: 'Custom connector', logo: 'API', col: 'var(--la-brand-secondary-500)', val: 'Pipe any field-service, POS, or warehouse source via API or SQL.', plan: 'Custom quote', cta: 'Talk to us' })} style={{ background: 'var(--violet)', borderColor: 'var(--violet)' }}>Talk to us →</button>
        </div>
      </div>
    </>);

}

function ERSourceCard({ s, onConnect }) {
  const isConnected = s.status === 'connected';
  return (
    <div className="card card-pad" style={{ position: 'relative', borderColor: s.recommend ? 'var(--violet)' : undefined }}>
      {s.recommend &&
      <div style={{ position: 'absolute', top: 12, right: 12, padding: '3px 8px', background: 'var(--violet)', color: 'var(--cream)', fontSize: 9.5, fontWeight: 700, borderRadius: 4, letterSpacing: '0.06em', textTransform: 'uppercase' }}>★ Recommended</div>
      }
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        <div style={{ width: 44, height: 44, borderRadius: 8, background: s.col, color: '#fff', fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, flexShrink: 0, fontFamily: 'var(--ff-mono)' }}>{s.logo}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
            <span style={{ fontFamily: 'var(--ff-display)', fontSize: 14.5, fontWeight: 600, color: 'var(--ink)' }}>{s.name}</span>
            <span style={{ fontSize: 10, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>· {s.cat}</span>
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 4, lineHeight: 1.4 }}>{s.val}</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 10 }}>
            {isConnected ?
            <>
                <span style={{ fontSize: 10.5, color: 'var(--ok)', fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase' }}>● Live</span>
                <span style={{ fontSize: 10.5, color: 'var(--ink-4)', fontFamily: 'var(--ff-mono)' }}>· last sync 4m ago</span>
                <span style={{ flex: 1 }} />
                <button className="btn btn-quiet btn-xs" onClick={() => T(`${s.name} settings`, 'Opening connection settings…', 'info')}>Manage</button>
              </> :

            <>
                <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--violet)', fontFamily: 'var(--ff-mono)' }}>{s.plan}</span>
                <span style={{ flex: 1 }} />
                <button className="btn btn-primary btn-sm" onClick={() => onConnect && onConnect(s)} style={{ background: 'var(--violet)', borderColor: 'var(--violet)' }}>{s.cta}</button>
              </>
            }
          </div>
        </div>
      </div>
    </div>);

}

function ERConnectModal({ source, onClose }) {
  return (
    <window.ModalPortal><div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(20,16,30,0.7)', zIndex: 9000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: 'var(--paper)', borderRadius: 14, width: '100%', maxWidth: 540, padding: 28, boxShadow: '0 20px 60px rgba(0,0,0,0.4)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
          <div style={{ width: 52, height: 52, borderRadius: 10, background: source.col, color: '#fff', fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, fontFamily: 'var(--ff-mono)' }}>{source.logo}</div>
          <div>
            <div style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 2 }}>Connect data source</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 600, color: 'var(--ink)' }}>{source.name}</div>
          </div>
        </div>

        <div style={{ padding: '14px 16px', background: 'var(--cream)', borderRadius: 10, marginBottom: 16 }}>
          <div style={{ fontSize: 11.5, color: 'var(--ink-2)', lineHeight: 1.55 }}><strong>What you'll unlock:</strong> {source.val}</div>
        </div>

        <div style={{ marginBottom: 16 }}>
          <div style={{ fontSize: 10.5, color: 'var(--ink-4)', textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.06em', marginBottom: 8 }}>Setup</div>
          {[
          'Authenticate via OAuth (or API key for custom warehouses)',
          'Choose which objects to sync (we recommend all of them)',
          'Pick refresh cadence, every 15 min, hourly, or daily',
          'Map fields to LOCALACT entities (locations, leads, revenue)',
          'Backfill the last 18 months · runs in background, ~24h'].
          map((step, i) =>
          <div key={i} style={{ display: 'flex', gap: 10, marginBottom: 6, fontSize: 12, color: 'var(--ink-2)' }}>
              <span style={{ width: 18, height: 18, borderRadius: '50%', background: 'var(--violet-soft)', color: 'var(--violet)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700, flexShrink: 0 }}>{i + 1}</span>
              <span>{step}</span>
            </div>
          )}
        </div>

        <div style={{ padding: '14px 16px', background: 'var(--violet-soft)', borderRadius: 10, marginBottom: 18 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div>
              <div style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.06em' }}>Add-on pricing</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-2)', marginTop: 2 }}>Scoped to your data volume · 30-day cancellation</div>
            </div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 24, fontWeight: 600, color: 'var(--ink)' }}>{source.plan}</div>
          </div>
        </div>

        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <span style={{ fontSize: 11, color: 'var(--ink-4)' }}>Goes live in ~24h after auth</span>
          <span style={{ flex: 1 }} />
          <button className="btn btn-ghost btn-sm" onClick={onClose}>Not now</button>
          <button className="btn btn-primary btn-sm" style={{ background: 'var(--violet)', borderColor: 'var(--violet)' }} onClick={() => {onClose();T(`${source.name} · request submitted`, 'Sarah will call you within 24h to walk through OAuth + scoping.', 'ok');}}>
            {source.cta === 'Talk to us' ? 'Schedule a call →' : 'Authenticate & connect →'}
          </button>
        </div>
      </div>
    </div></window.ModalPortal>);

}

// ============================================================================
// CUSTOM REPORTS TAB
// ============================================================================
function ERCustomTab({ onOpen }) {
  const reports = [
  { name: 'Weekly Exec Summary', owner: 'Sarah Reyes', cadence: 'Mon 8:00 AM', status: 'live', subs: 6, lastRun: '2d ago', icon: '' },
  { name: 'Monthly Franchise Council Deck', owner: 'Sarah Reyes', cadence: '1st of month', status: 'live', subs: 18, lastRun: '8d ago', icon: '' },
  { name: 'CMO Quarterly Board Pack', owner: 'Sarah Reyes', cadence: 'Quarterly', status: 'live', subs: 4, lastRun: '32d ago', icon: '📑' },
  { name: 'Spring Cleaning Postmortem', owner: 'Lenny', cadence: 'One-off', status: 'draft', subs: 0, lastRun: '–', icon: '📝' },
  { name: 'Multi-touch Attribution Audit', owner: 'Sarah Reyes', cadence: 'Bi-weekly', status: 'live', subs: 3, lastRun: '4d ago', icon: '' }];


  const examples = [
  { title: 'Region vs region YoY', desc: 'Compare any 2 regions across full P&L for the trailing 4 quarters.', tag: 'Strategy' },
  { title: 'Cohort lifetime value', desc: 'LTV by customer acquisition source, segmented by location tier.', tag: 'Finance' },
  { title: 'Promo lift vs control', desc: 'Holdout-tested incremental revenue per campaign, with confidence intervals.', tag: 'Measurement' },
  { title: 'Performance by time of day', desc: 'Hour-of-day & day-of-week lead-to-booking funnel, per channel.', tag: 'Operations' },
  { title: 'Locations vs related locations', desc: 'Match-pair benchmarking of each location against demographically similar FreshNest locations in the network.', tag: 'Coaching' },
  { title: 'Brand awareness MoM', desc: 'Search volume, GBP discovery, and share of search trended monthly.', tag: 'Brand' }];


  return (
    <>
      {/* Hero pitch */}
      <div className="card card-pad" style={{ marginBottom: 16, background: 'linear-gradient(120deg, rgba(246,166,99,0.10) 0%, transparent 55%)' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, flexWrap: 'wrap' }}>
          <div style={{ flex: 1, minWidth: 280 }}>
            <div style={{ fontSize: 11, color: '#ac8800', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 6 }}>Custom reporting</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 600, color: 'var(--ink)', marginBottom: 8, letterSpacing: '-0.015em' }}>Need a view we don't have? We'll build it.</div>
            <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.55, maxWidth: 700 }}>
              Replace the PowerBI dashboards your team hates. Our analytics team scopes, builds, and maintains custom reports, delivered as a live URL, scheduled email, or piped back into your warehouse.
            </div>
            <div style={{ marginTop: 14, display: 'flex', gap: 18, flexWrap: 'wrap' }}>
              {[
              { v: '3–5', l: 'business days from request to first draft' },
              { v: 'Custom', l: 'quote per custom report' },
              { v: 'Quote', l: 'to maintain & evolve' }].
              map((s, i) =>
              <div key={i}>
                  <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 600, color: 'var(--ink)' }}>{s.v}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>{s.l}</div>
                </div>
              )}
            </div>
          </div>
          <button className="btn btn-ghost btn-sm" onClick={onOpen} style={{ color: '#ac8800', borderColor: 'rgba(172,136,0,0.35)' }}>Get Pricing for a Custom Report →</button>
        </div>
      </div>

      {/* Existing custom reports */}
      <div className="section-label">
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--ok)' }} />
          Your custom reports
          <span className="count">{reports.length} reports · running on schedule</span>
        </span>
      </div>
      <div className="card" style={{ marginBottom: 22, overflow: 'hidden' }}>
        {reports.map((r, i) =>
        <div key={i} style={{ padding: '14px 18px', borderBottom: i < reports.length - 1 ? '1px solid var(--cream-2)' : 'none', display: 'flex', alignItems: 'center', gap: 14 }}>
            <span style={{ fontSize: 22 }}>{r.icon}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)' }}>{r.name}</div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>by {r.owner} · {r.cadence} · {r.subs} subscribers · last run {r.lastRun}</div>
            </div>
            <span style={{ padding: '3px 8px', background: r.status === 'live' ? 'var(--ok-soft, #e4f3eb)' : 'var(--cream-2)', color: r.status === 'live' ? 'var(--ok)' : 'var(--ink-3)', fontSize: 10, fontWeight: 700, borderRadius: 4, textTransform: 'uppercase', letterSpacing: '0.05em' }}>{r.status}</span>
            <button className="btn btn-quiet btn-xs" onClick={() => T(r.name, 'Opening live report in new tab…', 'info')}>Open</button>
            <button className="btn btn-quiet btn-xs" onClick={() => T('Subscribers updated', `${r.name} · subscriber list editable`, 'info')}>Subscribers</button>
            <button className="btn btn-ghost btn-xs" onClick={() => T('Refining report', `${r.name} · request sent to analytics team`, 'info')}>Refine</button>
          </div>
        )}
      </div>

      {/* Idea gallery */}
      <div className="section-label">
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 8, height: 8, borderRadius: 2, background: '#ac8800' }} />
          Popular custom reports
          <span className="count">Quick-start templates · click to scope</span>
        </span>
      </div>
      <div className="grid grid-3" style={{ gap: 10 }}>
        {examples.map((ex, i) =>
        <div key={i} className="card card-pad" style={{ cursor: 'pointer' }} onClick={onOpen}
        onMouseEnter={(e) => {e.currentTarget.style.borderColor = '#ac8800';e.currentTarget.style.transform = 'translateY(-2px)';}}
        onMouseLeave={(e) => {e.currentTarget.style.borderColor = '';e.currentTarget.style.transform = '';}}>
            <div style={{ fontSize: 9.5, color: '#ac8800', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 6 }}>{ex.tag}</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 14.5, fontWeight: 600, color: 'var(--ink)', marginBottom: 6 }}>{ex.title}</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.5 }}>{ex.desc}</div>
            <div style={{ marginTop: 10, fontSize: 11, color: '#ac8800', fontWeight: 600 }}>Scope this report →</div>
          </div>
        )}
      </div>
    </>);

}

function ERCustomReportModal({ onClose }) {
  const [title, setTitle] = useStateER('');
  const [purpose, setPurpose] = useStateER('');
  const [audience, setAudience] = useStateER('exec');
  const [cadence, setCadence] = useStateER('weekly');
  const [delivery, setDelivery] = useStateER(['email']);
  const [metrics, setMetrics] = useStateER(['revenue']);
  const [urgency, setUrgency] = useStateER('standard');

  const toggle = (set, val) => set === metrics ?
  metrics.includes(val) ? setMetrics(metrics.filter((x) => x !== val)) : setMetrics([...metrics, val]) :
  delivery.includes(val) ? setDelivery(delivery.filter((x) => x !== val)) : setDelivery([...delivery, val]);

  const allMetrics = [
  { v: 'revenue', l: 'Revenue / sales' },
  { v: 'leads', l: 'Leads / MQLs / SQLs' },
  { v: 'cac', l: 'CAC / CPL' },
  { v: 'roas', l: 'ROAS / ROI' },
  { v: 'funnel', l: 'Funnel conv rates' },
  { v: 'channel', l: 'Channel mix' },
  { v: 'geo', l: 'Geo / location-level' },
  { v: 'cohort', l: 'Cohort / LTV' },
  { v: 'attribution', l: 'Multi-touch attribution' },
  { v: 'reviews', l: 'Reputation / reviews' }];


  return (
    <window.ModalPortal><div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(20,16,30,0.7)', zIndex: 9000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: 'var(--paper)', borderRadius: 14, width: '100%', maxWidth: 720, padding: 28, boxShadow: '0 20px 60px rgba(0,0,0,0.4)', maxHeight: '92vh', overflow: 'auto' }}>
        <div style={{ fontSize: 11, color: '#ac8800', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 6 }}>📨 Custom report request</div>
        <div style={{ fontFamily: 'var(--ff-display)', fontSize: 24, fontWeight: 600, color: 'var(--ink)', marginBottom: 4, letterSpacing: '-0.015em' }}>What report should we build?</div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 20 }}>Our analytics team scopes within 1 business day. Most custom reports ship in 3–5 days. Pricing by custom quote.</div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
          <div>
            <label style={{ fontSize: 10.5, color: 'var(--ink-4)', textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.06em', marginBottom: 6, display: 'block' }}>Report name</label>
            <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="e.g. Weekly Region P&L"
            style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--cream-3)', borderRadius: 8, fontSize: 13, background: 'var(--cream)', boxSizing: 'border-box', fontFamily: 'var(--ff-sans)' }} />
          </div>
          <div>
            <label style={{ fontSize: 10.5, color: 'var(--ink-4)', textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.06em', marginBottom: 6, display: 'block' }}>Audience</label>
            <select value={audience} onChange={(e) => setAudience(e.target.value)}
            style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--cream-3)', borderRadius: 8, fontSize: 13, background: 'var(--cream)', boxSizing: 'border-box' }}>
              <option value="exec">C-suite / executive</option>
              <option value="board">Board / investors</option>
              <option value="franchisee">Franchisee council</option>
              <option value="ops">Operations team</option>
              <option value="finance">Finance team</option>
              <option value="marketing">Marketing team</option>
            </select>
          </div>
        </div>

        <div style={{ marginBottom: 14 }}>
          <label style={{ fontSize: 10.5, color: 'var(--ink-4)', textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.06em', marginBottom: 6, display: 'block' }}>What questions should this answer?</label>
          <textarea value={purpose} onChange={(e) => setPurpose(e.target.value)} placeholder="e.g. How is each region pacing against last year's revenue and lead targets? Where is CAC trending up?"
          style={{ width: '100%', minHeight: 80, padding: 12, border: '1px solid var(--cream-3)', borderRadius: 8, fontSize: 13, lineHeight: 1.5, background: 'var(--cream)', resize: 'vertical', boxSizing: 'border-box', fontFamily: 'var(--ff-sans)' }} />
        </div>

        <div style={{ marginBottom: 14 }}>
          <label style={{ fontSize: 10.5, color: 'var(--ink-4)', textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.06em', marginBottom: 8, display: 'block' }}>Metrics to include</label>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {allMetrics.map((m) => {
              const on = metrics.includes(m.v);
              return (
                <button key={m.v} onClick={() => toggle(metrics, m.v)}
                style={{ padding: '6px 12px', borderRadius: 999, border: on ? '1px solid #ac8800' : '1px solid var(--cream-3)', background: on ? 'rgba(194,134,68,0.12)' : 'var(--paper)', color: on ? '#ac8800' : 'var(--ink-2)', fontSize: 11.5, fontWeight: 600, cursor: 'pointer' }}>
                  {on ? '✓ ' : ''}{m.l}
                </button>);

            })}
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12, marginBottom: 14 }}>
          <div>
            <label style={{ fontSize: 10.5, color: 'var(--ink-4)', textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.06em', marginBottom: 6, display: 'block' }}>Cadence</label>
            <select value={cadence} onChange={(e) => setCadence(e.target.value)}
            style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--cream-3)', borderRadius: 8, fontSize: 13, background: 'var(--cream)', boxSizing: 'border-box' }}>
              <option value="live">Live dashboard</option>
              <option value="daily">Daily</option>
              <option value="weekly">Weekly</option>
              <option value="biweekly">Bi-weekly</option>
              <option value="monthly">Monthly</option>
              <option value="quarterly">Quarterly</option>
              <option value="oneoff">One-off</option>
            </select>
          </div>
          <div>
            <label style={{ fontSize: 10.5, color: 'var(--ink-4)', textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.06em', marginBottom: 6, display: 'block' }}>Urgency</label>
            <select value={urgency} onChange={(e) => setUrgency(e.target.value)}
            style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--cream-3)', borderRadius: 8, fontSize: 13, background: 'var(--cream)', boxSizing: 'border-box' }}>
              <option value="rush">Rush · 48h (expedite quote)</option>
              <option value="standard">Standard · 3–5 days</option>
              <option value="exploratory">Exploratory · no deadline</option>
            </select>
          </div>
          <div>
            <label style={{ fontSize: 10.5, color: 'var(--ink-4)', textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.06em', marginBottom: 6, display: 'block' }}>Delivery</label>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4, paddingTop: 4 }}>
              {[{ v: 'email', l: 'Email PDF' }, { v: 'dash', l: 'Live dashboard' }, { v: 'sheets', l: 'Google Sheets' }, { v: 'wh', l: 'Pipe to warehouse' }].map((d) =>
              <label key={d.v} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'var(--ink-2)', cursor: 'pointer' }}>
                  <input type="checkbox" checked={delivery.includes(d.v)} onChange={() => toggle(delivery, d.v)} />
                  {d.l}
                </label>
              )}
            </div>
          </div>
        </div>

        <div style={{ padding: '12px 14px', background: 'rgba(194,134,68,0.08)', borderRadius: 8, fontSize: 11.5, color: 'var(--ink-2)', marginBottom: 18, lineHeight: 1.5 }}>
          <strong style={{ color: '#ac8800', fontWeight: 700 }}>What happens next:</strong> Sarah Reyes (your Strategy Director) and our analytics team review within 1 business day, schedule a 30-min scoping call, and return a sample mockup before we build.
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontSize: 11, color: 'var(--ink-4)' }}>Custom quote · cancellable anytime</span>
          <span style={{ flex: 1 }} />
          <button className="btn btn-ghost btn-sm" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary btn-sm" disabled={!title.trim() || !purpose.trim()}
          style={{ background: '#ac8800', borderColor: '#ac8800' }}
          onClick={() => {onClose();T('Custom report submitted', `"${title}" sent to Sarah · expect a scoping reply within 1 business day.`, 'ok');}}>
            Submit request →
          </button>
        </div>
      </div>
    </div></window.ModalPortal>);

}