// Results, Services, Budget, Campaigns, Listings, Reviews, Benchmarks, HQ, Invoice, Settings
const { useState: useStateP, useEffect: useEffectP } = React;

const T = (...args) => window.toast(...args);
const openLenny = () => window.dispatchEvent(new CustomEvent('open-lenny'));

// ====================================================================
// RESULTS
// ====================================================================
function ResultsPage({ data, persona, density }) {
  const [tab, setTab] = useStateP('overview');
  const [view, setView] = useStateP('combined'); // combined | channel | location (overview tab only)
  const [range, setRange] = useStateP({ preset: 'last30', start: new Date(2026, 2, 29), end: new Date(2026, 3, 27), compare: false });

  const isHq = persona === 'hq';

  // View-mode options for the Channel Results (overview) tab. Per-location only
  // makes sense at the corporate/HQ level; a single location just sees combined vs by-channel.
  const viewOpts = isHq
    ? [['combined', 'Combined'], ['channel', 'By channel'], ['location', 'By location']]
    : [['combined', 'Combined'], ['channel', 'By channel']];

  // Owner / Simple view, plain-language results summary for location personas.
  if (density === 'simple' && !isHq) {
    return <window.SimpleResults data={data}/>;
  }

  const tabDescriptions = {
    overview: isHq ?
    'Brand-wide rollup across all locations, click any channel for portfolio-level details.' :
    'All channels combined, click any channel for details.',
    ppc: 'Paid Search · Google Ads + Performance Max',
    lsa: 'Local Services Ads · pay-per-lead, lead rating, dispute credits',
    seo: 'Local SEO · GSC keywords, traffic sources, content optimization log',
    social: 'Paid Social · Meta + IG · creative, audience, seasonal initiatives',
    demandgen: 'Demand Gen · upper-funnel awareness across YouTube, Discover, Gmail'
  };

  const overviewSub = view === 'channel'
    ? 'Each enrolled channel, broken out individually.'
    : view === 'location'
    ? 'Each enrolled location, broken out individually.'
    : isHq ? 'All locations, all enrolled channels combined.' : 'All enrolled channels combined.';

  const tabTitles = {
    overview: { title: 'Channel Results.', sub: overviewSub },
    ppc: { title: 'Paid Search.', sub: isHq ? 'Google Ads, Search + Performance Max · portfolio-aggregated.' : 'Google Ads, Search + Performance Max.' },
    lsa: { title: 'Local Services Ads.', sub: isHq ? 'Pay-per-lead leads from Google\'s top-of-search pack · portfolio-aggregated.' : 'Pay-per-lead leads from Google\'s top-of-search pack.' },
    seo: { title: 'Local SEO.', sub: isHq ? 'Organic search, Maps, and on-page content · portfolio-aggregated.' : 'Organic search, Maps, and on-page content.' },
    social: { title: 'Social.', sub: isHq ? 'Paid Meta and Instagram · portfolio-aggregated.' : 'Paid Meta and Instagram, awareness, traffic, leads.' },
    demandgen: { title: 'Demand Gen.', sub: isHq ? 'Upper-funnel awareness · portfolio-aggregated.' : 'Upper-funnel awareness, YouTube, Discover, Gmail.' }
  };

  return (
    <div className="page active">
      <div className="page-header">
        <div>
          <div className="page-title">{tabTitles[tab].title}</div>
          <div className="page-sub">{tabTitles[tab].sub}</div>
        </div>
        <div className="page-actions">
          {tab === 'overview' && (
            <div style={{ display: 'inline-flex', background: 'var(--cream-2)', border: '1px solid var(--cream-3)', borderRadius: 999, padding: 3, gap: 2 }}>
              {viewOpts.map(([k, l]) => (
                <button key={k} onClick={() => setView(k)}
                  style={{
                    background: view === k ? 'var(--paper)' : 'transparent',
                    color: view === k ? 'var(--ink)' : 'var(--ink-3)',
                    border: 'none', borderRadius: 999, padding: '5px 12px',
                    fontSize: 12, fontWeight: 600, cursor: 'pointer',
                    boxShadow: view === k ? '0 1px 3px rgba(0,0,0,0.08)' : 'none',
                    fontFamily: 'inherit', whiteSpace: 'nowrap'
                  }}>{l}</button>
              ))}
            </div>
          )}
          <DateRangePicker value={range} onChange={(v) => {setRange(v);T('Range updated', `Showing ${v.preset && v.preset !== 'custom' ? window.DRP_PRESET_LABEL?.(v.preset) || 'selected range' : `${v.start.getMonth() + 1}/${v.start.getDate()} – ${v.end.getMonth() + 1}/${v.end.getDate()}`}`, 'info');}} align="right" />
          <button className="btn btn-primary btn-sm" onClick={() => T('Exporting results', 'CSV + PDF queued, I\'ll email you when ready.', 'ok')}>Export {Icon.arrow}</button>
        </div>
      </div>

      <div className="tabs">
        {[
        ['overview', 'Overview'],
        ['ppc', 'Paid Search'],
        ['lsa', 'LSA'],
        ['seo', 'Local SEO'],
        ['social', 'Social'],
        ['demandgen', 'Demand Gen']].
        map(([k, l]) =>
        <button key={k} className={`tab ${tab === k ? 'active' : ''}`} onClick={() => setTab(k)}>
            {l}
            {k === 'demandgen' && <span className="badge" style={{ marginLeft: 6, fontSize: 9, background: 'var(--marigold)', color: 'var(--ink)', padding: '1px 5px' }}>NEW</span>}
          </button>
        )}
      </div>

      {tab !== 'overview' && <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 14 }}>{tabDescriptions[tab]}</div>}

      {tab === 'overview' && view === 'channel' && <window.ResultsByChannel data={data} setTab={setTab} />}
      {tab === 'overview' && view === 'location' && isHq && <window.ResultsByLocation data={data} />}
      {tab === 'overview' && (view === 'combined' || (view === 'location' && !isHq)) && (isHq ? <ResultsOverviewHq data={data} setTab={setTab} /> : <ResultsOverview data={data} setTab={setTab} />)}
      {tab === 'ppc' && (isHq ? <ResultsPpcHq data={data} /> : <ResultsPpc data={data} />)}
      {tab === 'lsa' && (isHq ? <ResultsLsaHq data={data} /> : data.variant === 'bare' ? <window.EnrollmentOpportunityCard channelKey="lsa" dormantChannels={data.dormantChannels} /> : <ResultsLsa data={data} />)}
      {tab === 'seo' && (isHq ? <ResultsSeoHq data={data} /> : data.variant === 'bare' ? <window.EnrollmentOpportunityCard channelKey="seo" dormantChannels={data.dormantChannels} /> : <ResultsSeo data={data} />)}
      {tab === 'social' && (isHq ? <ResultsSocialHq data={data} /> : data.variant === 'bare' ? <window.EnrollmentOpportunityCard channelKey="social" dormantChannels={data.dormantChannels} /> : <ResultsSocial data={data} />)}
      {tab === 'demandgen' && (isHq ? <ResultsDemandGenHq data={data} /> : <ResultsDemandGen data={data} />)}
    </div>);

}
window.ResultsPage = ResultsPage;

// ====================================================================
// SERVICES, Initiatives grouped by playbook role, w/ playbook recommendations
// ====================================================================

// Playbook-role metadata per service key. Drives tier grouping, "why it matters",
// and the playbook recommendation strip on each card.
const PLAYBOOK_ROLES = {
  'gs-local': { tier: 'core', role: 'High-intent demand', why: 'Captures people searching "home cleaning near me" right now. Lowest CPL channel. Playbook priority #1.', rec: 1500, recLabel: 'Playbook target $1,500/mo' },
  'lsa-local': { tier: 'core', role: 'Pay-per-lead', why: 'Top-of-Maps placement. Pay only when a lead calls, Google verifies them for cleaning services.', rec: 600, recLabel: 'Playbook target $600/mo' },
  'meta-local': { tier: 'core', role: 'Awareness + retargeting', why: 'Builds familiarity, retargets Search visitors, runs seasonal promos. Not a lead engine on its own.', rec: 800, recLabel: 'Playbook target $800/mo' },
  'lseo': { tier: 'foundation', role: 'Organic foundation', why: 'Localized pages, content, and citations. Lifts Quality Score on every paid channel.', rec: null, recLabel: 'Required by playbook' },
  'llm': { tier: 'foundation', role: '42 directory presence', why: 'NAP accuracy across the web. Required for paid ads to convert efficiently.', rec: null, recLabel: 'Required by playbook' },
  'localact': { tier: 'foundation', role: 'Platform + LMT', why: 'This dashboard plus your dedicated Local Marketing Team strategist.', rec: null, recLabel: 'Required for support' },
  'meta-mothers': { tier: 'promo', role: 'Limited-time promo', why: "Three-week fall refresh campaign. Corporate funds creative + matches your spend up to $200.", rec: null, recLabel: 'Limited window' },
  'lsa-setup': { tier: 'addon', role: 'One-time setup', why: 'Required when first enrolling LSA. Covers verification, license, and profile build.', rec: null, recLabel: 'One-time fee' }
};

function ServicesPage({ data, persona }) {
  if (persona === 'hq') return <ServicesPageHq data={data} />;
  return <ServicesPageFranchisee data={data} />;
}
window.ServicesPage = ServicesPage;

// ====================================================================
// SERVICES, HQ persona: brand-wide marketing stack
// Page flow:
//   1. KPI strip (the decision-quality metrics)
//   2. Active brand campaigns (Mother's Day pinned)
//   3. National marketing programs ($10k–$200k/mo, brand-funded)
//   4. Local marketing stack (per-location, by tier)
//   5. Broadcast announcement modal entry
// ====================================================================
function ServicesPageHq({ data }) {
  const hq = data.hqServices || {};
  const totalLocations = 700;
  const [reqOpen, setReqOpen] = useStateP(null); // recommend-to-locations
  const [broadcastOpen, setBroadcastOpen] = useStateP(false);
  const [natlDetail, setNatlDetail] = useStateP(null); // national program detail
  const [requestOpen, setRequestOpen] = useStateP(false); // request new service
  const [creativeOpen, setCreativeOpen] = useStateP(null); // creative kit modal

  const fmtPct = (e, t) => Math.round(e / t * 100);

  // ---- ACTIVE CAMPAIGNS (limited-time, time-sensitive corporate decisions) ----
  const campaigns = [
  {
    key: 'fall',
    name: 'Fall Deep-Clean Bundle',
    tagline: 'Seasonal deep-clean bundle + refill kit · 4-week run',
    window: 'Sep 1 – Sep 28',
    enrollDeadline: 'Aug 22',
    enrolled: hq.fall?.enrolled ?? 318,
    total: hq.fall?.total ?? totalLocations,
    corpFunded: 'Creative + media match',
    locMatch: 'Up to $250 / location',
    channel: 'Meta Ads · GBP posts · email',
    status: 'enrolling',
    hue: '#d5711c'
  }];


  // ---- NATIONAL MARKETING PROGRAMS (corporate-funded, brand-wide, big-budget) ----
  const national = [
  {
    key: 'natlSearch',
    name: 'National Brand Search',
    tagline: 'Always-on protection on branded queries',
    channel: 'Google Search · YouTube',
    monthly: 18000,
    band: [12000, 28000],
    reach: '4.2M impressions / mo',
    lift: '+11% branded CTR YoY',
    kpi: 'Brand defense + lead spillover',
    hue: 'var(--brand-navy)',
    status: 'active'
  },
  {
    key: 'natlSocial',
    name: 'National Social',
    tagline: 'Brand awareness + cultural moments',
    channel: 'Meta · TikTok · YouTube Shorts',
    monthly: 42000,
    band: [25000, 75000],
    reach: '11.8M video views / mo',
    lift: '+8 pts brand recall',
    kpi: 'Top-of-funnel familiarity',
    hue: '#4d6989',
    status: 'active'
  },
  {
    key: 'natlProgrammatic',
    name: 'Enterprise Programmatic',
    tagline: 'CTV + display retargeting at scale',
    channel: 'CTV · Display · DOOH',
    monthly: 65000,
    band: [40000, 200000],
    reach: '24M+ impressions / mo',
    lift: '+14% in-store visit lift',
    kpi: 'Geo-fenced visit attribution',
    hue: '#4d6989',
    status: 'active'
  }];

  const natlTotal = national.reduce((s, n) => s + n.monthly, 0);

  // ---- LOCAL MARKETING STACK (per-location services) ----
  const local = [
  // Foundation
  { key: 'lseo', name: 'Local SEO', role: 'Organic foundation', what: 'Localized pages, content, citations, and AI/LLM visibility (ChatGPT, Perplexity, Gemini). Lifts Quality Score on every paid channel.',
    enrolled: hq.seo?.enrolled ?? 18, total: hq.seo?.total ?? totalLocations, target: '$449/mo per location · brand-recommended', tier: 'foundation', primary: 'recommend' },
  { key: 'localfoundation', name: 'Local Foundation', role: 'Setup & onboarding', what: 'GBP cleanup, NAP audit, schema, conversion tracking. Required before paid channels turn on.',
    enrolled: 700, total: totalLocations, target: '$1,200 one-time · per new location', tier: 'foundation', primary: 'configure' },
  { key: 'listings', name: 'Listings Management', role: '42 directory presence', what: 'NAP accuracy across the web, monitored daily. Required for paid ads to convert efficiently.',
    enrolled: hq.listings?.enrolled ?? 24, total: hq.listings?.total ?? totalLocations, target: '$79/mo per location · brand-required', tier: 'foundation', primary: 'configure' },
  // Core paid
  { key: 'gs-local', name: 'Local Google Search Program', role: 'High-intent demand', what: 'Captures people searching "home cleaning service near me" right now. Lowest-CPL channel. Playbook priority #1.',
    enrolled: hq.ppc?.enrolled ?? 14, total: hq.ppc?.total ?? totalLocations, target: '$1,500/mo per location · playbook target', tier: 'core', primary: 'enroll' },
  { key: 'lsa', name: 'Local Services Ads', role: 'Pay-per-lead', what: "Top-of-Maps placement. Pay only when a homeowner calls, Google verifies them.",
    enrolled: 198, total: totalLocations, target: '$600/mo per location · cap-controlled', tier: 'core', primary: 'enroll' },
  { key: 'meta', name: 'Local Meta Ads', role: 'Awareness + retargeting', what: 'Builds familiarity, retargets Search visitors, runs seasonal promos. Not a primary lead engine.',
    enrolled: hq.meta?.enrolled ?? 9, total: hq.meta?.total ?? totalLocations, target: '$800/mo per location · playbook target', tier: 'core', primary: 'recommend' },
  // Reputation
  { key: 'reputation', name: 'Reputation Management', role: 'Reviews + responses', what: 'AI-drafted review replies, sentiment tracking, theme extraction across all platforms.',
    enrolled: hq.reviews?.enrolled ?? 5, total: hq.reviews?.total ?? totalLocations, target: '$149/mo per location', tier: 'platform', primary: 'recommend', phase2: true }];


  const tierMeta = {
    foundation: { label: 'Foundation', color: 'var(--violet)', bg: 'var(--violet-soft, rgba(77,105,137,0.10))' },
    core: { label: 'Core paid', color: 'var(--terra)', bg: 'var(--terra-soft)' },
    platform: { label: 'Reputation', color: '#8fa0b5', bg: 'rgba(107,142,155,0.12)' }
  };
  const grouped = ['foundation', 'core', 'platform'].map((t) => ({
    tier: t, meta: tierMeta[t], items: local.filter((c) => c.tier === t)
  })).filter((g) => g.items.length);

  // KPI roll-ups
  const localEnrolledTotal = local.reduce((s, x) => s + x.enrolled, 0);
  const localCapacity = local.reduce((s, x) => s + x.total, 0);
  const adoption = Math.round(localEnrolledTotal / localCapacity * 100);
  const underEnrolled = local.filter((x) => x.enrolled / x.total < 0.6).length;

  return (
    <div className="page active">
      <div className="page-header">
        <div>
          <div className="page-title">Command Center.</div>
          <div className="page-sub">Active campaigns, national programs, and the per-location services rolling out across {totalLocations} locations.</div>
        </div>
        <div className="page-actions">
          <button className="btn btn-ghost btn-sm" onClick={() => setBroadcastOpen(true)}>📣 Broadcast to franchisees</button>
          <button className="btn btn-ghost btn-sm" onClick={() => T('Catalog exported', 'CSV with enrollment + national spend is queued, emailing you now.', 'ok')}>Export</button>
          <button className="btn btn-primary btn-sm" onClick={() => setRequestOpen(true)}>Request new service</button>
        </div>
      </div>

      {/* ============ KPI STRIP ============ */}
      <div className="grid grid-4" style={{ gap: 14, marginBottom: 22 }}>
        <div className="card card-pad streak-panel">
          <div style={{ fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'rgba(250,246,239,.65)', fontWeight: 700, marginBottom: 6 }}> National spend</div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 28, fontWeight: 500, lineHeight: 1, letterSpacing: '-0.02em' }}>${(natlTotal / 1000).toFixed(0)}k<span style={{ fontSize: 12, color: 'rgba(250,246,239,.6)', fontWeight: 400 }}>/mo</span></div>
          <div style={{ fontSize: 11, color: 'rgba(250,246,239,.7)', marginTop: 6 }}>{national.length} programs running</div>
        </div>
        <div className="card card-pad">
          <div style={{ fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-4)', fontWeight: 700, marginBottom: 6 }}> Local stack adoption</div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 28, fontWeight: 500, lineHeight: 1, letterSpacing: '-0.02em', color: 'var(--ink)' }}>{adoption}<span style={{ fontSize: 14, color: 'var(--ink-3)', fontWeight: 400 }}>%</span></div>
          <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 6 }}>{localEnrolledTotal} of {localCapacity} possible enrollments</div>
        </div>
        <div className="card card-pad">
          <div style={{ fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-4)', fontWeight: 700, marginBottom: 6 }}>⚠ Under-enrolled</div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 28, fontWeight: 500, lineHeight: 1, letterSpacing: '-0.02em', color: 'var(--terra)' }}>{underEnrolled}<span style={{ fontSize: 14, color: 'var(--ink-3)', fontWeight: 400 }}> svcs</span></div>
          <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 6 }}>Below 60% adoption, recommend or push</div>
        </div>
        <div className="card card-pad" style={{ background: 'var(--marigold-soft)', borderColor: 'var(--marigold)' }}>
          <div style={{ fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 700, marginBottom: 6 }}> Active campaigns</div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 28, fontWeight: 500, lineHeight: 1, letterSpacing: '-0.02em', color: 'var(--ink)' }}>{campaigns.length}</div>
          <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 6 }}>{campaigns[0].name} · enrollment closes {campaigns[0].enrollDeadline}</div>
        </div>
      </div>

      {/* ============ ACTIVE BRAND CAMPAIGNS (pinned at top) ============ */}
      <div style={{ marginBottom: 28 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 12 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 11px', borderRadius: 999, background: 'var(--marigold)', color: 'var(--ink)', fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em' }}>
             Active Brand Campaigns
          </span>
          <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>Limited-window pushes · enrollment closes soon</span>
        </div>
        {campaigns.map((c) => {
          const pct = fmtPct(c.enrolled, c.total);
          return (
            <div key={c.key} className="card" style={{ overflow: 'hidden', position: 'relative', border: '1px solid ' + c.hue, boxShadow: '0 4px 14px rgba(212,101,138,0.10)' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', minHeight: 200 }}>
                {/* LEFT, campaign content */}
                <div style={{ padding: '24px 28px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', gap: 18 }}>
                  <div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                      <span style={{ fontSize: 11, color: c.hue, textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700 }}>Limited-time campaign</span>
                      <span style={{ width: 4, height: 4, borderRadius: '50%', background: 'var(--ink-4)' }} />
                      <span style={{ fontSize: 11, color: 'var(--terra)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em' }}>Closes {c.enrollDeadline}</span>
                    </div>
                    <div style={{ fontFamily: 'var(--ff-display)', fontSize: 28, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.02em', lineHeight: 1.15, marginBottom: 6 }}>{c.name}</div>
                    <div style={{ fontSize: 14, color: 'var(--ink-2)', marginBottom: 16, lineHeight: 1.45 }}>{c.tagline}</div>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, fontSize: 12 }}>
                      <div><div style={{ fontSize: 10, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Window</div><div style={{ fontWeight: 600, color: 'var(--ink-2)', marginTop: 2 }}>{c.window}</div></div>
                      <div><div style={{ fontSize: 10, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Corporate funds</div><div style={{ fontWeight: 600, color: 'var(--ink-2)', marginTop: 2 }}>{c.corpFunded}</div></div>
                      <div><div style={{ fontSize: 10, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Local match</div><div style={{ fontWeight: 600, color: 'var(--ink-2)', marginTop: 2 }}>{c.locMatch}</div></div>
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                    <button className="btn btn-primary btn-sm" onClick={() => T(`${c.name} · enrolling all`, `Adding ${c.total - c.enrolled} more locations · franchisees notified.`, 'ok')}>Enroll all locations</button>
                    <button className="btn btn-ghost btn-sm" onClick={() => setReqOpen({ svc: { name: c.name, enrolled: c.enrolled, total: c.total }, mode: 'recommend' })}>Recommend to specific cohorts</button>
                    <button className="btn btn-quiet btn-sm" onClick={() => setCreativeOpen(c)}>View creative kit</button>
                  </div>
                </div>
                {/* RIGHT, enrollment dial */}
                <div style={{ background: 'linear-gradient(135deg, ' + c.hue + ' 0%, #bf281c 100%)', color: 'var(--cream)', padding: '24px 28px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
                  <div>
                    <div style={{ fontSize: 10.5, color: 'rgba(250,246,239,.65)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 8 }}>Enrollment</div>
                    <div style={{ fontFamily: 'var(--ff-display)', fontSize: 56, fontWeight: 500, lineHeight: 1, letterSpacing: '-0.03em' }}>{c.enrolled}<span style={{ fontSize: 22, color: 'rgba(250,246,239,.55)', fontWeight: 400 }}> / {c.total}</span></div>
                    <div style={{ fontSize: 12.5, color: 'rgba(250,246,239,.78)', marginTop: 4 }}>{pct}% of locations enrolled</div>
                    <div style={{ marginTop: 14, height: 8, background: 'rgba(255,255,255,.18)', borderRadius: 4, overflow: 'hidden' }}>
                      <div style={{ width: pct + '%', height: '100%', background: 'var(--cream)', borderRadius: 4 }} />
                    </div>
                  </div>
                  <div style={{ marginTop: 16, padding: 12, background: 'rgba(255,255,255,.10)', borderRadius: 10, fontSize: 11.5, lineHeight: 1.5 }}>
                    <div style={{ fontSize: 10, color: 'rgba(250,246,239,.6)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, marginBottom: 4 }}>Channel mix</div>
                    {c.channel}
                  </div>
                </div>
              </div>
            </div>);

        })}
      </div>

      {/* ============ NATIONAL MARKETING PROGRAMS ============ */}
      <div style={{ marginBottom: 28 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 4 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 11px', borderRadius: 999, background: 'var(--brand-navy)', color: 'var(--cream)', fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em' }}>
             National Programs
          </span>
          <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>Brand-funded · always-on · ${(natlTotal / 1000).toFixed(0)}k/mo blended</span>
        </div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 14, marginTop: 2 }}>Nationwide campaigns running with $10k–$200k/mo budgets. Decisions live with corporate marketing, locations don't opt in or out.</div>
        <div className="grid grid-3" style={{ gap: 14 }}>
          {national.map((n) => {
            const pctOfBand = (n.monthly - n.band[0]) / (n.band[1] - n.band[0]) * 100;
            return (
              <div key={n.key} className="card card-pad" style={{ position: 'relative' }}>
                <span style={{ position: 'absolute', top: 14, right: 14, fontSize: 9.5, fontWeight: 700, padding: '2px 8px', borderRadius: 999, background: 'var(--sage-soft, rgba(122,156,128,0.18))', color: 'var(--sage)', letterSpacing: '0.04em', textTransform: 'uppercase' }}>● Active</span>
                <div style={{ fontFamily: 'var(--ff-display)', fontSize: 17, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.01em', lineHeight: 1.25, marginBottom: 4 }}>{n.name}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 14, lineHeight: 1.45 }}>{n.tagline}</div>

                {/* Big spend dial */}
                <div style={{ padding: '14px 14px 12px', background: 'var(--cream)', borderRadius: 10, marginBottom: 12 }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 6 }}>
                    <span style={{ fontSize: 10, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700 }}>Monthly spend</span>
                    <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 11, color: 'var(--ink-3)' }}>${(n.band[0] / 1000).toFixed(0)}k–${(n.band[1] / 1000).toFixed(0)}k band</span>
                  </div>
                  <div style={{ fontFamily: 'var(--ff-display)', fontSize: 30, fontWeight: 500, color: 'var(--ink)', lineHeight: 1, letterSpacing: '-0.02em' }}>${(n.monthly / 1000).toFixed(0)}k</div>
                  <div style={{ marginTop: 10, height: 6, background: 'var(--cream-2)', borderRadius: 3, position: 'relative' }}>
                    <div style={{ width: pctOfBand + '%', height: '100%', background: n.hue, borderRadius: 3 }} />
                  </div>
                </div>

                {/* Stats */}
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, fontSize: 11.5, marginBottom: 12 }}>
                  <div style={{ padding: 8, background: 'var(--cream)', borderRadius: 6 }}>
                    <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700 }}>Reach</div>
                    <div style={{ fontWeight: 600, color: 'var(--ink-2)', marginTop: 2 }}>{n.reach}</div>
                  </div>
                  <div style={{ padding: 8, background: 'var(--cream)', borderRadius: 6 }}>
                    <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700 }}>Lift</div>
                    <div style={{ fontWeight: 600, color: 'var(--sage)', marginTop: 2 }}>{n.lift}</div>
                  </div>
                </div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginBottom: 14, lineHeight: 1.5 }}>
                  <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700, marginBottom: 2 }}>Channels</div>
                  {n.channel}
                </div>

                <div style={{ display: 'flex', gap: 8 }}>
                  <button className="btn btn-primary btn-sm" style={{ flex: 1 }} onClick={() => setNatlDetail(n)}>Adjust budget</button>
                  <button className="btn btn-ghost btn-sm" onClick={() => T(`${n.name} · creative`, 'Opening creative library, geo splits, and reporting.', 'info')}>Creative</button>
                </div>
              </div>);

          })}
        </div>
      </div>

      {/* ============ LOCAL MARKETING STACK ============ */}
      <div style={{ marginBottom: 22 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 4 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 11px', borderRadius: 999, background: 'var(--terra)', color: 'var(--cream)', fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em' }}>
             Local Stack
          </span>
          <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>Per-location services · franchisees opt in</span>
        </div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 14, marginTop: 2 }}>Services that run at each location. Corporate sets the playbook target; locations enroll.</div>

        {/* Lenny inline recommendation */}
        <div className="card card-pad" style={{ marginBottom: 16, background: 'linear-gradient(135deg, var(--violet-soft, rgba(77,105,137,0.08)), var(--paper) 60%)', border: '1px solid var(--violet-soft, rgba(77,105,137,0.18))' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
            <div style={{ flexShrink: 0, width: 48, height: 48, borderRadius: '50%', background: 'var(--paper)', border: '2px solid var(--cream-3)', overflow: 'hidden' }}>
              <window.LennyLlama size={48} mood="thinking" bg="circle" />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 4 }}>Lenny's recommendation</div>
              <div style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 600, lineHeight: 1.35, marginBottom: 8, color: 'var(--ink)' }}>
                Roll out <strong style={{ color: 'var(--violet)' }}>Local SEO</strong> to the {(local.find(s => s.key === 'lseo')?.total ?? totalLocations) - (local.find(s => s.key === 'lseo')?.enrolled ?? 0)} locations not yet enrolled.
              </div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.5, marginBottom: 12 }}>
                Modeled <strong style={{ color: 'var(--sage)' }}>+6 leads/mo per location</strong> · ~<strong style={{ color: 'var(--sage)' }}>$22 lower blended CPL</strong> across the brand.
              </div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                <button className="btn btn-primary btn-sm" onClick={() => T('LSEO rollout queued', `Enrolling ${(local.find(s => s.key === 'lseo')?.total ?? totalLocations) - (local.find(s => s.key === 'lseo')?.enrolled ?? 0)} remaining locations · Strategy Director notified.`, 'ok')}>Enroll all remaining</button>
                <button className="btn btn-ghost btn-sm" onClick={() => T('Pilot scheduled', 'Picking the 25 lowest-LSEO locations for a regional pilot.', 'info')}>Pilot a cohort first</button>
              </div>
            </div>
          </div>
        </div>

        {grouped.map((group) =>
        <div key={group.tier} style={{ marginBottom: 16 }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 10 }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 10px', borderRadius: 999, background: group.meta.bg, color: group.meta.color, fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em' }}>
                {group.meta.label}
              </span>
              <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>{group.items.length} service{group.items.length !== 1 ? 's' : ''}</span>
            </div>
            <div className="grid grid-2" style={{ gap: 14 }}>
              {group.items.map((svc) => {
              const pct = fmtPct(svc.enrolled, svc.total);
              const fullyEnrolled = svc.enrolled === svc.total;
              return (
                <div key={svc.key} className="card card-pad" style={{ position: 'relative' }}>
                    {svc.isNew &&
                  <span style={{ position: 'absolute', top: 14, right: 14, fontSize: 9.5, fontWeight: 700, padding: '2px 7px', borderRadius: 999, background: 'var(--marigold)', color: 'var(--ink)', letterSpacing: '0.04em' }}>NEW</span>
                  }
                    {svc.phase2 &&
                  <span style={{ position: 'absolute', top: 14, right: 14, fontSize: 9, fontWeight: 700, padding: '2px 8px', borderRadius: 999, background: 'var(--la-brand-quaternary-100)', color: 'var(--la-brand-quaternary-700)', letterSpacing: '0.04em', textTransform: 'uppercase' }}>Coming in Phase 2</span>
                  }
                    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginBottom: 10 }}>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.01em', lineHeight: 1.25 }}>{svc.name}</div>
                        <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 2, textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>{svc.role}</div>
                      </div>
                    </div>
                    <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.45, marginBottom: 14, minHeight: 38 }}>{svc.what}</div>
                    <div style={{ marginBottom: 12 }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', fontSize: 11, marginBottom: 4 }}>
                        <span style={{ color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Enrolled</span>
                        <span style={{ fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)' }}>
                          <strong style={{ color: 'var(--ink)', fontWeight: 700 }}>{svc.enrolled}</strong> of {svc.total} · {pct}%
                        </span>
                      </div>
                      <div style={{ height: 6, background: 'var(--cream-2)', borderRadius: 3, overflow: 'hidden' }}>
                        <div style={{ width: pct + '%', height: '100%', background: fullyEnrolled ? 'var(--sage)' : pct >= 50 ? 'var(--marigold)' : 'var(--terra)', transition: 'width .25s ease' }} />
                      </div>
                    </div>
                    <div style={{ padding: '8px 10px', background: 'var(--cream)', borderRadius: 8, fontSize: 11.5, color: 'var(--ink-3)', marginBottom: 12 }}>
                      <strong style={{ color: 'var(--ink-2)', fontWeight: 600 }}>Brand target:</strong> {svc.target}
                    </div>
                    <div style={{ display: 'flex', gap: 8 }}>
                      {svc.primary === 'enroll' &&
                    <>
                          <button className="btn btn-primary btn-sm" style={{ flex: 1 }} onClick={() => T(`${svc.name} · enrolling all`, `Adding the remaining ${svc.total - svc.enrolled} locations.`, 'ok')}>Enroll all</button>
                          <button className="btn btn-ghost btn-sm" onClick={() => setReqOpen({ svc, mode: 'recommend' })}>Recommend</button>
                        </>
                    }
                      {svc.primary === 'recommend' &&
                    <>
                          <button className="btn btn-primary btn-sm" style={{ flex: 1 }} onClick={() => setReqOpen({ svc, mode: 'recommend' })}>Recommend to locations</button>
                          <button className="btn btn-ghost btn-sm" onClick={() => T(`${svc.name} · enrolling all`, `Adding the remaining ${svc.total - svc.enrolled} locations.`, 'ok')}>Enroll all</button>
                        </>
                    }
                      {svc.primary === 'configure' &&
                    <>
                          <button className="btn btn-primary btn-sm" style={{ flex: 1 }} onClick={() => T(`${svc.name} · configure`, 'Opening brand-level settings: pricing, contract, rollout cadence.', 'info')}>Configure</button>
                          {!fullyEnrolled && <button className="btn btn-ghost btn-sm" onClick={() => T(`${svc.name} · enrolling all`, `Adding the remaining ${svc.total - svc.enrolled} locations.`, 'ok')}>Enroll all</button>}
                        </>
                    }
                    </div>
                  </div>);

            })}
            </div>
          </div>
        )}
      </div>

      {/* Modals */}
      {reqOpen && <ServicePlansRecommendModal svc={reqOpen.svc} totalLocations={totalLocations} onClose={() => setReqOpen(null)} />}
      {broadcastOpen && <BroadcastModal totalLocations={totalLocations} onClose={() => setBroadcastOpen(false)} />}
      {natlDetail && <NationalProgramDetail program={natlDetail} onClose={() => setNatlDetail(null)} />}
      {requestOpen && <RequestServiceModal onClose={() => setRequestOpen(false)} />}
      {creativeOpen && <CreativeKitModal campaign={creativeOpen} onClose={() => setCreativeOpen(null)} />}
    </div>);

}
window.ServicesPageHq = ServicesPageHq;

// ====================================================================
// BROADCAST MODAL, corporate sends a message to franchisees
// ====================================================================
function BroadcastModal({ totalLocations, onClose }) {
  const [audience, setAudience] = useStateP('all');
  const [topic, setTopic] = useStateP('announcement');
  const [subject, setSubject] = useStateP('');
  const [body, setBody] = useStateP('');
  const [pin, setPin] = useStateP(true);

  const audienceOptions = [
  { v: 'all', label: `All ${totalLocations} franchisees`, desc: 'Lands on every location\'s Home page.' },
  { v: 'under', label: 'Under-enrolled locations', desc: 'Locations with <60% local-stack adoption.' },
  { v: 'top', label: 'Top-performing locations', desc: 'Star tier · high LocalScore.' },
  { v: 'attn', label: 'Locations needing attention', desc: 'Below LocalScore 75 or trending down.' }];

  const topicOptions = [
  { v: 'announcement', label: '📣 Announcement', hue: 'var(--brand-navy)' },
  { v: 'campaign', label: ' Campaign launch', hue: '#e46c63' },
  { v: 'training', label: '🎓 Training / playbook', hue: 'var(--violet)' },
  { v: 'urgent', label: '⚠ Urgent action', hue: 'var(--terra)' }];


  return (
    <window.ModalPortal><div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(36,30,28,0.55)', zIndex: 9000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: 'var(--paper)', borderRadius: 14, width: '100%', maxWidth: 620, padding: 24, boxShadow: '0 20px 60px rgba(0,0,0,0.25)', maxHeight: '90vh', overflow: 'auto' }}>
        <div style={{ fontSize: 11, color: 'var(--brand-navy)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 6 }}>📣 Broadcast to franchisees</div>
        <div style={{ fontFamily: 'var(--ff-display)', fontSize: 20, fontWeight: 600, color: 'var(--ink)', marginBottom: 4 }}>Send a message brand-wide</div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 18 }}>Posts to franchisee Home pages and triggers an email + push notification.</div>

        <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, marginBottom: 8 }}>Topic</div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 16 }}>
          {topicOptions.map((t) =>
            <button key={t.v} onClick={() => setTopic(t.v)}
            style={{ padding: '7px 13px', borderRadius: 999, fontSize: 12, fontWeight: 600, cursor: 'pointer',
              background: topic === t.v ? t.hue : 'transparent',
              color: topic === t.v ? 'var(--cream)' : 'var(--ink-2)',
              border: '1px solid ' + (topic === t.v ? t.hue : 'var(--cream-3)') }}>
              {t.label}
            </button>
            )}
        </div>

        <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, marginBottom: 8 }}>Audience</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 16 }}>
          {audienceOptions.map((opt) =>
            <label key={opt.v} style={{ display: 'flex', gap: 10, padding: '10px 12px', border: audience === opt.v ? '2px solid var(--brand-navy)' : '1px solid var(--cream-3)', borderRadius: 10, cursor: 'pointer', background: audience === opt.v ? 'rgba(43,79,135,0.06)' : 'var(--paper)', margin: audience === opt.v ? 0 : '1px' }}>
              <input type="radio" checked={audience === opt.v} onChange={() => setAudience(opt.v)} style={{ marginTop: 2 }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>{opt.label}</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{opt.desc}</div>
              </div>
            </label>
            )}
        </div>

        <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, marginBottom: 6 }}>Subject</div>
        <input type="text" value={subject} onChange={(e) => setSubject(e.target.value)} placeholder="e.g. Mother's Day enrollment closes Friday"
          style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--cream-3)', borderRadius: 8, fontFamily: 'var(--ff-sans)', fontSize: 13, color: 'var(--ink)', background: 'var(--cream)', boxSizing: 'border-box', marginBottom: 12 }} />

        <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, marginBottom: 6 }}>Message</div>
        <textarea value={body} onChange={(e) => setBody(e.target.value)} placeholder="What you want franchisees to know, do, or read…"
          style={{ width: '100%', minHeight: 110, padding: 12, border: '1px solid var(--cream-3)', borderRadius: 8, fontFamily: 'var(--ff-sans)', fontSize: 13, lineHeight: 1.5, color: 'var(--ink)', background: 'var(--cream)', resize: 'vertical', boxSizing: 'border-box', marginBottom: 12 }} />

        <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, color: 'var(--ink-2)', cursor: 'pointer', marginBottom: 18 }}>
          <input type="checkbox" checked={pin} onChange={(e) => setPin(e.target.checked)} />
          Pin to franchisee Home for 7 days
        </label>

        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontSize: 11, color: 'var(--ink-4)' }}>Sends email + push notification immediately</span>
          <span style={{ flex: 1 }} />
          <button className="btn btn-ghost btn-sm" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary btn-sm" disabled={!subject.trim()} onClick={() => {
              onClose();
              T('Broadcast sent', `"${subject}" delivered to ${audience === 'all' ? totalLocations + ' franchisees' : audience + ' cohort'}.`, 'ok');
            }}>Send broadcast →</button>
        </div>
      </div>
    </div></window.ModalPortal>);

}
window.BroadcastModal = BroadcastModal;

// ====================================================================
// NATIONAL PROGRAM DETAIL, adjust monthly budget within band
// ====================================================================
function NationalProgramDetail({ program, onClose }) {
  const [budget, setBudget] = useStateP(program.monthly);
  const annual = budget * 12;
  return (
    <window.ModalPortal><div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(36,30,28,0.55)', 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: 24, boxShadow: '0 20px 60px rgba(0,0,0,0.25)' }}>
        <div style={{ fontSize: 11, color: program.hue, textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 6 }}>National program</div>
        <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 600, color: 'var(--ink)', marginBottom: 4 }}>{program.name}</div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 18 }}>{program.tagline}</div>

        <div style={{ padding: 18, background: 'var(--cream)', borderRadius: 12, marginBottom: 18 }}>
          <div style={{ fontSize: 10.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 8 }}>Monthly budget</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 12 }}>
            <span style={{ fontFamily: 'var(--ff-display)', fontSize: 38, fontWeight: 500, color: 'var(--ink)', letterSpacing: '-0.02em' }}>${(budget / 1000).toFixed(0)}k</span>
            <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>/ month · ${(annual / 1000).toFixed(0)}k annual</span>
          </div>
          <input type="range" min={program.band[0]} max={program.band[1]} step="1000" value={budget} onChange={(e) => setBudget(+e.target.value)} style={{ width: '100%' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, color: 'var(--ink-4)', marginTop: 4 }}>
            <span>${(program.band[0] / 1000).toFixed(0)}k floor</span>
            <span>${(program.band[1] / 1000).toFixed(0)}k ceiling</span>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, fontSize: 12, marginBottom: 18 }}>
          <div style={{ padding: 12, background: 'var(--cream)', borderRadius: 8 }}>
            <div style={{ fontSize: 10, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700 }}>Reach</div>
            <div style={{ fontWeight: 600, color: 'var(--ink-2)', marginTop: 2 }}>{program.reach}</div>
          </div>
          <div style={{ padding: 12, background: 'var(--cream)', borderRadius: 8 }}>
            <div style={{ fontSize: 10, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700 }}>Lift</div>
            <div style={{ fontWeight: 600, color: 'var(--sage)', marginTop: 2 }}>{program.lift}</div>
          </div>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontSize: 11, color: 'var(--ink-4)' }}>Strategy Director will confirm before billing changes</span>
          <span style={{ flex: 1 }} />
          <button className="btn btn-ghost btn-sm" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary btn-sm" onClick={() => {onClose();T(`${program.name} · budget request`, `New budget $${(budget / 1000).toFixed(0)}k/mo queued for review.`, 'ok');}}>Request change →</button>
        </div>
      </div>
    </div></window.ModalPortal>);

}
window.NationalProgramDetail = NationalProgramDetail;

// ====================================================================
// REQUEST NEW SERVICE MODAL, corporate scopes a new offering with the SD
// ====================================================================
function RequestServiceModal({ onClose }) {
  const [category, setCategory] = useStateP('paid-media');
  const [name, setName] = useStateP('');
  const [problem, setProblem] = useStateP('');
  const [scope, setScope] = useStateP('national');
  const [urgency, setUrgency] = useStateP('quarter');
  const [budget, setBudget] = useStateP('10-25k');

  const categories = [
  { v: 'paid-media', label: 'Paid media', desc: 'New ad channel, format, or platform' },
  { v: 'organic', label: 'Organic / SEO', desc: 'Content, technical, or local SEO play' },
  { v: 'reputation', label: 'Reputation / CRM', desc: 'Reviews, loyalty, lifecycle, retention' },
  { v: 'data', label: 'Data / measurement', desc: 'Attribution, dashboards, custom reporting' },
  { v: 'creative', label: 'Creative / production', desc: 'Photo, video, design at scale' },
  { v: 'other', label: 'Something else', desc: "Tell us in the description" }];


  return (
    <window.ModalPortal><div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(36,30,28,0.55)', zIndex: 9000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: 'var(--paper)', borderRadius: 14, width: '100%', maxWidth: 640, padding: 24, boxShadow: '0 20px 60px rgba(0,0,0,0.25)', maxHeight: '92vh', overflow: 'auto' }}>
        <div style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 6 }}>📨 New service request</div>
        <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 600, color: 'var(--ink)', marginBottom: 4, letterSpacing: '-0.015em' }}>What do you want to add to the stack?</div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 18 }}>Your Strategy Director, Sarah Reyes, scopes and prices new programs. Most come back with a proposal in 3–5 business days.</div>

        <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, marginBottom: 8 }}>Category</div>
        <div className="grid grid-2" style={{ gap: 6, marginBottom: 16 }}>
          {categories.map((c) =>
            <label key={c.v} style={{ display: 'flex', gap: 8, padding: '8px 10px', border: category === c.v ? '2px solid var(--violet)' : '1px solid var(--cream-3)', borderRadius: 8, cursor: 'pointer', background: category === c.v ? 'var(--violet-soft, rgba(77,105,137,0.06))' : 'var(--paper)', margin: category === c.v ? 0 : '1px' }}>
              <input type="radio" checked={category === c.v} onChange={() => setCategory(c.v)} style={{ marginTop: 1 }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink)' }}>{c.label}</div>
                <div style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>{c.desc}</div>
              </div>
            </label>
            )}
        </div>

        <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, marginBottom: 6 }}>Working name</div>
        <input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. CTV Geo-Conquest, Email Lifecycle 2.0, Local Influencer pilot"
          style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--cream-3)', borderRadius: 8, fontFamily: 'var(--ff-sans)', fontSize: 13, color: 'var(--ink)', background: 'var(--cream)', boxSizing: 'border-box', marginBottom: 12 }} />

        <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, marginBottom: 6 }}>What problem does this solve?</div>
        <textarea value={problem} onChange={(e) => setProblem(e.target.value)} placeholder="What outcome are you chasing? Which locations or moments matter most? Any constraints we should know about?"
          style={{ width: '100%', minHeight: 90, padding: 12, border: '1px solid var(--cream-3)', borderRadius: 8, fontFamily: 'var(--ff-sans)', fontSize: 13, lineHeight: 1.5, color: 'var(--ink)', background: 'var(--cream)', resize: 'vertical', boxSizing: 'border-box', marginBottom: 14 }} />

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12, marginBottom: 18 }}>
          <div>
            <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, marginBottom: 6 }}>Scope</div>
            <select value={scope} onChange={(e) => setScope(e.target.value)}
              style={{ width: '100%', padding: '8px 10px', border: '1px solid var(--cream-3)', borderRadius: 8, fontSize: 12.5, color: 'var(--ink)', background: 'var(--cream)' }}>
              <option value="national">National (all locations)</option>
              <option value="regional">Regional pilot</option>
              <option value="cohort">Specific cohort</option>
              <option value="single">Single location</option>
            </select>
          </div>
          <div>
            <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, marginBottom: 6 }}>Urgency</div>
            <select value={urgency} onChange={(e) => setUrgency(e.target.value)}
              style={{ width: '100%', padding: '8px 10px', border: '1px solid var(--cream-3)', borderRadius: 8, fontSize: 12.5, color: 'var(--ink)', background: 'var(--cream)' }}>
              <option value="month">Within 30 days</option>
              <option value="quarter">This quarter</option>
              <option value="next-q">Next quarter</option>
              <option value="exploratory">Exploratory</option>
            </select>
          </div>
          <div>
            <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, marginBottom: 6 }}>Budget band</div>
            <select value={budget} onChange={(e) => setBudget(e.target.value)}
              style={{ width: '100%', padding: '8px 10px', border: '1px solid var(--cream-3)', borderRadius: 8, fontSize: 12.5, color: 'var(--ink)', background: 'var(--cream)' }}>
              <option value="under-10k">Under $10k/mo</option>
              <option value="10-25k">$10k – $25k/mo</option>
              <option value="25-75k">$25k – $75k/mo</option>
              <option value="75k+">$75k+/mo</option>
              <option value="unsure">Not sure yet</option>
            </select>
          </div>
        </div>

        <div style={{ padding: '10px 12px', background: 'var(--violet-soft, rgba(77,105,137,0.08))', borderRadius: 8, fontSize: 11.5, color: 'var(--ink-2)', marginBottom: 16, lineHeight: 1.5 }}>
          <strong style={{ color: 'var(--violet)', fontWeight: 700 }}>What happens next:</strong> Sarah reviews within 1 business day, schedules a 30-min scoping call, and returns a proposal with timing, pricing, and expected impact.
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontSize: 11, color: 'var(--ink-4)' }}>Goes to your Strategy Director · CC'd to Lenny</span>
          <span style={{ flex: 1 }} />
          <button className="btn btn-ghost btn-sm" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary btn-sm" disabled={!name.trim() || !problem.trim()} onClick={() => {
              onClose();
              T('Request submitted', `"${name}" sent to Sarah Reyes · expect a reply within 1 business day.`, 'ok');
            }}>Send request →</button>
        </div>
      </div>
    </div></window.ModalPortal>);

}
window.RequestServiceModal = RequestServiceModal;

// ====================================================================
// CREATIVE KIT MODAL, preview + download all assets for a campaign
// ====================================================================
function CreativeKitModal({ campaign, onClose }) {
  const c = campaign;
  const [tab, setTab] = useStateP('ads');

  const tabs = [
  { v: 'ads', label: 'Meta ads', count: 6 },
  { v: 'gbp', label: 'GBP posts', count: 4 },
  { v: 'email', label: 'Email templates', count: 3 },
  { v: 'social', label: 'Organic social', count: 8 },
  { v: 'print', label: 'Print / in-store', count: 5 }];


  // Hero swatches per tab, colorful blocks stand in for real creative
  const ads = [
  { h: 'Fall bundle hero · square', size: '1080×1080', bg: 'linear-gradient(135deg,#d5711c,#8c4a13)' },
  { h: 'Family bundle · story', size: '1080×1920', bg: 'linear-gradient(160deg,#ce9e07,#d5711c)' },
  { h: 'Fall bundle hero · landscape', size: '1200×628', bg: 'linear-gradient(135deg,#8c4a13,#66360d)' },
  { h: 'Family bundle · square', size: '1080×1080', bg: 'linear-gradient(135deg,#e5d38f,#d5711c)' },
  { h: 'Reels carousel · 4 cards', size: '1080×1920', bg: 'linear-gradient(180deg,#d5711c,#442409)' },
  { h: 'Reels CTA · vertical', size: '1080×1920', bg: 'linear-gradient(180deg,#b35f18,#d5711c)' }];

  const gbp = [
  { h: 'Fall Deep-Clean Bundle · launch post', date: 'Aug 29', bg: 'linear-gradient(135deg,#d5711c,#b35f18)' },
  { h: 'New seasonal bundle · spotlight', date: 'Sep 5', bg: 'linear-gradient(135deg,#ce9e07,#d5711c)' },
  { h: 'Family bundle weekend', date: 'Sep 13', bg: 'linear-gradient(135deg,#8c4a13,#d5711c)' },
  { h: 'Last call · fall bundle ends', date: 'Sep 24', bg: 'linear-gradient(135deg,#66360d,#8c4a13)' }];

  const emails = [
  { h: 'Save the date · Fall Deep-Clean Bundle returns', open: '34% open · 4.4% click' },
  { h: 'New this season · deep-clean bundle + refill kit', open: 'New send' },
  { h: 'Reminder · fall bundle ends Sep 28', open: 'New send' }];

  const social = Array.from({ length: 8 }, (_, i) => ({
    h: ['Fall refresh teaser', 'Family bundle carousel', 'Behind the scenes', 'Customer-favorite UGC', 'Seasonal product spotlight', 'Deep-clean TikTok', 'Customer testimonial', 'Last-call countdown'][i],
    bg: ['linear-gradient(135deg,#d5711c,#66360d)', 'linear-gradient(135deg,#ce9e07,#d5711c)', 'linear-gradient(135deg,#8c4a13,#d5711c)', 'linear-gradient(135deg,#e5d38f,#8c4a13)', 'linear-gradient(135deg,#b35f18,#442409)', 'linear-gradient(135deg,#d5711c,#66360d)', 'linear-gradient(135deg,#ce9e07,#b35f18)', 'linear-gradient(135deg,#8c4a13,#442409)'][i]
  }));
  const print = [
  { h: 'Shelf talker · fall bundle insert', size: '4×6 in' },
  { h: 'Window cling · "Fall refresh is here"', size: '12×18 in' },
  { h: 'Counter card · family bundle QR', size: '5×7 in' },
  { h: 'Receipt insert', size: '3×4 in' },
  { h: 'Staff training one-pager', size: '8.5×11 in' }];


  return (
    <window.ModalPortal><div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(36,30,28,0.55)', zIndex: 9000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: 'var(--paper)', borderRadius: 14, width: '100%', maxWidth: 760, boxShadow: '0 20px 60px rgba(0,0,0,0.25)', maxHeight: '92vh', display: 'flex', flexDirection: 'column' }}>
        {/* Header */}
        <div style={{ padding: '20px 24px 16px', borderBottom: '1px solid var(--cream-3)' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
            <div style={{ width: 56, height: 56, borderRadius: 10, background: 'linear-gradient(135deg,' + (c.hue || '#d5711c') + ',#8c4a13)', flexShrink: 0, position: 'relative', overflow: 'hidden' }}>
              <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24 }}>🍂</div>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 11, color: c.hue || '#d5711c', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 4 }}>Creative kit</div>
              <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.015em', lineHeight: 1.2 }}>{c.name || 'Fall Deep-Clean Bundle'}</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2 }}>{c.window || 'Sep 1 – Sep 28'} · {ads.length + gbp.length + emails.length + social.length + print.length} assets · brand-approved</div>
            </div>
            <button onClick={onClose} style={{ background: 'transparent', border: 'none', fontSize: 20, color: 'var(--ink-3)', cursor: 'pointer', padding: 4 }}>×</button>
          </div>

          {/* Tab bar */}
          <div style={{ display: 'flex', gap: 4, marginTop: 16, overflowX: 'auto' }}>
            {tabs.map((t) =>
              <button key={t.v} onClick={() => setTab(t.v)}
              style={{ padding: '7px 12px', borderRadius: 8, border: 'none', cursor: 'pointer', fontSize: 12.5, fontWeight: 600, background: tab === t.v ? 'var(--ink)' : 'transparent', color: tab === t.v ? 'var(--cream)' : 'var(--ink-2)', whiteSpace: 'nowrap' }}>
                {t.label} <span style={{ opacity: 0.55, marginLeft: 4 }}>{t.count}</span>
              </button>
              )}
          </div>
        </div>

        {/* Body */}
        <div style={{ padding: '18px 24px', overflowY: 'auto', flex: 1 }}>
          {tab === 'ads' &&
            <div className="grid grid-3" style={{ gap: 12 }}>
              {ads.map((a, i) =>
              <div key={i} style={{ borderRadius: 10, overflow: 'hidden', border: '1px solid var(--cream-3)' }}>
                  <div style={{ aspectRatio: '1/1', background: a.bg, position: 'relative' }}>
                    <div style={{ position: 'absolute', top: 8, left: 8, padding: '3px 7px', background: 'rgba(0,0,0,0.4)', borderRadius: 4, fontSize: 9.5, color: 'var(--cream)', fontWeight: 600, letterSpacing: '0.04em' }}>{a.size}</div>
                  </div>
                  <div style={{ padding: '8px 10px', background: 'var(--paper)' }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink)', marginBottom: 2 }}>{a.h}</div>
                    <button className="btn btn-quiet btn-xs" onClick={() => T('Asset downloaded', `${a.h} · saved to Downloads`, 'ok')}>Download</button>
                  </div>
                </div>
              )}
            </div>
            }
          {tab === 'gbp' &&
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {gbp.map((g, i) =>
              <div key={i} style={{ display: 'flex', gap: 12, padding: 12, border: '1px solid var(--cream-3)', borderRadius: 10 }}>
                  <div style={{ width: 80, height: 80, borderRadius: 8, background: g.bg, flexShrink: 0 }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700, marginBottom: 2 }}>Scheduled · {g.date}</div>
                    <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', marginBottom: 4 }}>{g.h}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.45 }}>Auto-posts to all {24} GBP profiles on launch day. Edit copy per location available.</div>
                  </div>
                  <button className="btn btn-quiet btn-xs" onClick={() => T('GBP post · preview', `${g.h} opens in editor.`, 'info')}>Preview</button>
                </div>
              )}
            </div>
            }
          {tab === 'email' &&
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {emails.map((e, i) =>
              <div key={i} style={{ padding: 14, border: '1px solid var(--cream-3)', borderRadius: 10, background: 'var(--cream)' }}>
                  <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
                    <div style={{ width: 40, height: 40, borderRadius: 8, background: 'linear-gradient(135deg,#e46c63,#a12118)', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--cream)', fontSize: 18 }}>✉</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', marginBottom: 2 }}>{e.h}</div>
                      <div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--ff-mono)' }}>{e.open}</div>
                    </div>
                    <button className="btn btn-quiet btn-xs" onClick={() => T('Email · preview', `${e.h} opens in editor.`, 'info')}>Preview</button>
                  </div>
                </div>
              )}
            </div>
            }
          {tab === 'social' &&
            <div className="grid grid-4" style={{ gap: 10 }}>
              {social.map((s, i) =>
              <div key={i} style={{ borderRadius: 8, overflow: 'hidden', border: '1px solid var(--cream-3)' }}>
                  <div style={{ aspectRatio: '1/1', background: s.bg }} />
                  <div style={{ padding: '6px 8px', background: 'var(--paper)', fontSize: 11, color: 'var(--ink-2)', fontWeight: 600 }}>{s.h}</div>
                </div>
              )}
            </div>
            }
          {tab === 'print' &&
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {print.map((p, i) =>
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', border: '1px solid var(--cream-3)', borderRadius: 8 }}>
                  <div style={{ width: 32, height: 32, borderRadius: 6, background: 'var(--marigold-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--marigold)', fontSize: 14 }}>📄</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink)' }}>{p.h}</div>
                    <div style={{ fontSize: 10.5, color: 'var(--ink-3)', fontFamily: 'var(--ff-mono)' }}>{p.size}</div>
                  </div>
                  <button className="btn btn-quiet btn-xs" onClick={() => T('Print asset · downloaded', `${p.h} · print-ready PDF saved`, 'ok')}>Download PDF</button>
                </div>
              )}
            </div>
            }
        </div>

        {/* Footer */}
        <div style={{ padding: '14px 24px', borderTop: '1px solid var(--cream-3)', display: 'flex', alignItems: 'center', gap: 10, background: 'var(--cream)' }}>
          <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>Co-op funds match up to $200/loc on local placements</span>
          <span style={{ flex: 1 }} />
          <button className="btn btn-ghost btn-sm" onClick={() => T('Kit downloaded', 'All 26 assets zipped, saving to Downloads.', 'ok')}>Download all (.zip)</button>
          <button className="btn btn-primary btn-sm" onClick={() => {onClose();T('Kit shared', `${c.name || 'Creative kit'} pushed to franchisee Home pages.`, 'ok');}}>Share to franchisees →</button>
        </div>
      </div>
    </div></window.ModalPortal>);

}
window.CreativeKitModal = CreativeKitModal;

// Lightweight modal: pick how many locations to surface this recommendation to,
// add a note, and "send." Persists nothing, toast only. Mirrors the request-change
// modal pattern from the Playbook governance card so HQ flows feel consistent.
function ServicePlansRecommendModal({ svc, totalLocations, onClose }) {
  const remaining = svc.total - svc.enrolled;
  const [scope, setScope] = useStateP('all'); // 'all' | 'lowest' | 'pilot'
  const [note, setNote] = useStateP('');
  const scopeCount = scope === 'all' ? remaining : scope === 'lowest' ? Math.min(20, remaining) : Math.min(10, remaining);
  return (
    <window.ModalPortal><div onClick={onClose}
      style={{ position: 'fixed', inset: 0, background: 'rgba(36,30,28,0.55)', 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: 24, boxShadow: '0 20px 60px rgba(0,0,0,0.25)' }}>
        <div style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 6 }}>Recommend to locations</div>
        <div style={{ fontFamily: 'var(--ff-display)', fontSize: 20, fontWeight: 600, color: 'var(--ink)', marginBottom: 4 }}>{svc.name}</div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 16 }}>
          {svc.enrolled} of {svc.total} enrolled · <strong style={{ color: 'var(--ink-2)' }}>{remaining}</strong> eligible to recommend.
        </div>
        <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600, marginBottom: 8 }}>Recommend to</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
          {[
            { v: 'all', title: `All ${remaining} eligible locations`, desc: 'Push to every location not yet enrolled.' },
            { v: 'lowest', title: `${Math.min(20, remaining)} lowest-performing locations`, desc: 'Bottom quartile by LocalScore, biggest expected lift.' },
            { v: 'pilot', title: `${Math.min(10, remaining)} pilot locations`, desc: 'Lenny picks a representative cohort for measurement.' }].
            map((opt) =>
            <label key={opt.v} style={{ display: 'flex', gap: 10, padding: 12, border: scope === opt.v ? '2px solid var(--violet)' : '1px solid var(--cream-3)', borderRadius: 10, cursor: 'pointer', background: scope === opt.v ? 'var(--violet-soft, rgba(77,105,137,0.06))' : 'var(--paper)', margin: scope === opt.v ? 0 : '1px' }}>
              <input type="radio" name="scope" checked={scope === opt.v} onChange={() => setScope(opt.v)} style={{ marginTop: 2 }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', marginBottom: 2 }}>{opt.title}</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{opt.desc}</div>
              </div>
            </label>
            )}
        </div>
        <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600, marginBottom: 6 }}>Note to franchisees (optional)</div>
        <textarea
            value={note}
            onChange={(e) => setNote(e.target.value)}
            placeholder="Why this matters for them, what to expect, when corporate funding kicks in…"
            style={{ width: '100%', minHeight: 90, padding: 12, border: '1px solid var(--cream-3)', borderRadius: 8, fontFamily: 'var(--ff-sans)', fontSize: 13, lineHeight: 1.5, color: 'var(--ink)', background: 'var(--cream)', resize: 'vertical', boxSizing: 'border-box' }} />
          
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 16 }}>
          <span style={{ fontSize: 11, color: 'var(--ink-4)' }}>Posts to each location's Home page · expires in 14 days</span>
          <span style={{ flex: 1 }} />
          <button className="btn btn-ghost btn-sm" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary btn-sm" onClick={() => {
              onClose();
              T(`${svc.name} · recommended to ${scopeCount} locations`, "They'll see it on their Home page · Lenny will nudge if they haven't acted in 7 days.", 'ok');
            }}>Send recommendation →</button>
        </div>
      </div>
    </div></window.ModalPortal>);

}
window.ServicePlansRecommendModal = ServicePlansRecommendModal;

// ====================================================================
// SERVICES, franchisee persona: original marketing-services view
// ====================================================================
function ServicesPageFranchisee({ data }) {
  const { services } = data;
  const [svcDetail, setSvcDetail] = useStateP(null);
  const [showMath, setShowMath] = useStateP(false);
  const [subTab, setSubTab] = useStateP('initiatives');
  const [addOpen, setAddOpen] = useStateP(false);       // "Add a service" picker
  const [enrollTarget, setEnrollTarget] = useStateP(null); // channel for the confirm panel
  const svcToChannel = (s) => {
    const r = PLAYBOOK_ROLES[s.key] || {};
    return { name: s.name, recommended: r.rec || 300, payPerLead: s.key === 'lsa', reason: r.why || s.desc };
  };

  // Read the budget mode (synced from the Budget page via localStorage).
  // Smart Budget ('simple') is the pre-selected default everywhere.
  const variant = data.variant || 'star';
  const [budgetMode, setBudgetMode] = useStateP(() => {
    try {
      const k = `localact_budget_mode_${variant}`;
      const stored = localStorage.getItem(k);
      if (stored === 'simple' || stored === 'advanced') return stored;
    } catch {}
    return 'simple';
  });
  const [confirmSelfManaged, setConfirmSelfManaged] = useStateP(false);
  const switchBudgetMode = (m) => {
    if (m === 'advanced' && budgetMode !== 'advanced') { setConfirmSelfManaged(true); return; }
    applyBudgetMode(m);
  };
  const applyBudgetMode = (m) => {
    setBudgetMode(m);
    try {
      localStorage.setItem(`localact_budget_mode_${variant}`, m);
      localStorage.setItem('localact_budget_mode_active', m);
    } catch {}
    if (window.T) window.T(
      m === 'simple' ? 'Switched to Smart Budget' : 'Switched to Self-managed budget',
      m === 'simple' ? 'You set the total, LOCALACT manages the mix and rebalances it monthly.' : 'You manage spend per channel. Monthly auto-rebalancing is off.',
      'info'
    );
  };
  // Stay in sync if the Budget page changes it
  useEffectP(() => {
    const handler = (e) => {
      if (e.key === `localact_budget_mode_${variant}` && (e.newValue === 'simple' || e.newValue === 'advanced')) {
        setBudgetMode(e.newValue);
      }
    };
    window.addEventListener('storage', handler);
    return () => window.removeEventListener('storage', handler);
  }, [variant]);

  // Franchisees only see Locations-audience initiatives.
  const visible = services.filter((s) => s.audience === 'Locations All' || s.audience === 'Locations Limited');

  // ---- Bucket by enrollment / recommendation state ----
  // 1. Active  , currently enrolled and (for tier with rec) on/above target
  // 2. Recommended, not enrolled, but playbook-essential (core or foundation)
  // 3. Promo   , promo tier, not enrolled (limited-window opportunities)
  // 4. Below   , enrolled but underspending vs playbook target
  // 5. AddOn   , addon tier, not enrolled (extras Lenny isn't pushing)
  const buckets = { active: [], recommended: [], promo: [], below: [], addon: [] };
  visible.forEach((s) => {
    const r = PLAYBOOK_ROLES[s.key];
    if (!r) return;
    const totalSpend = (s.corporateBudget || 0) + (s.localBudget || 0);
    const isBelow = s.enrolled && r.rec && totalSpend < r.rec;
    if (r.tier === 'promo' && !s.enrolled) {
      buckets.promo.push(s);
    } else if (s.enrolled && isBelow) {
      buckets.below.push(s);
    } else if (s.enrolled) {
      buckets.active.push(s);
    } else if (r.tier === 'core' || r.tier === 'foundation') {
      buckets.recommended.push(s);
    } else {
      buckets.addon.push(s);
    }
  });

  // Live promos still drive the page-header copy
  const livePromos = buckets.promo;

  // Simple mode: ONE total budget (synced with the Budget page via localStorage),
  // auto-split by Lenny across enrolled budget-based initiatives.
  const budgetBased = visible.filter((s) => s.type === 'Budget Based' && s.enrolled);
  let simpleTotal = 0;
  try { simpleTotal = parseInt(localStorage.getItem('localact_budget_simple_total') || '', 10) || 0; } catch (err) {}
  if (!simpleTotal) simpleTotal = budgetBased.reduce((s, i) => s + (i.corporateBudget || 0) + (i.localBudget || 0), 0);
  const simpleAlloc = budgetMode === 'simple' && window.autoAllocate ? ((window.autoAllocate(simpleTotal, budgetBased) || {}).allocations || {}) : null;

  // Stats
  const enrolledCount = visible.filter((s) => s.enrolled).length;
  const totalCount = visible.length;
  const onTarget = visible.filter((s) => {
    const r = PLAYBOOK_ROLES[s.key];
    return s.enrolled && r && r.rec && (s.localBudget || 0) + (s.corporateBudget || 0) >= r.rec;
  }).length;
  const belowTarget = visible.filter((s) => {
    const r = PLAYBOOK_ROLES[s.key];
    return s.enrolled && r && r.rec && (s.localBudget || 0) + (s.corporateBudget || 0) < r.rec;
  }).length;

  return (
    <div className="page active svc-page">
      <div className="page-header">
        <div>
          <div className="page-title">Marketing Strategy.</div>
          <div className="page-sub">Every play in the <strong style={{ color: 'var(--violet)' }}>FreshNest playbook v3.2</strong>, mapped to your location. <strong style={{ color: 'var(--ink)' }}>{enrolledCount} of {totalCount}</strong> enrolled · <strong style={{ color: onTarget === enrolledCount ? 'var(--sage)' : 'var(--marigold)' }}>{onTarget} on target</strong>{belowTarget > 0 && <>, <strong style={{ color: '#917200' }}>{belowTarget} below</strong></>}.</div>
        </div>
        <div className="page-actions">
          <button className="btn btn-ghost btn-sm" onClick={() => window.dispatchEvent(new CustomEvent('go-page', { detail: 'bench' }))}>View playbook</button>
          <button className="btn btn-ghost btn-sm" onClick={() => T('Strategy call requested', 'Sarah K. will reach out in 24h. Invite headed to your inbox.', 'ok')}>Book strategy call</button>
          <button className="btn btn-primary btn-sm" onClick={() => setAddOpen(true)}>+ Add a service</button>
        </div>
      </div>

      {/* Sub-tabs: Initiatives (the plan) vs Geo-targeting (where ads run) */}
      <div style={{ display: 'flex', gap: 2, margin: '2px 0 18px', borderBottom: '1px solid var(--line)' }}>
        {[['initiatives', 'Initiatives'], ['geo', 'Geo-targeting']].map(([k, l]) => (
          <button key={k} onClick={() => setSubTab(k)} style={{
            background: 'none', border: 'none', cursor: 'pointer', padding: '10px 16px',
            fontFamily: 'var(--ff-ui)', fontSize: 13.5, fontWeight: subTab === k ? 700 : 500,
            color: subTab === k ? 'var(--brand-navy)' : 'var(--ink-3)',
            borderBottom: subTab === k ? '2px solid var(--terra)' : '2px solid transparent', marginBottom: -1,
          }}>{l}</button>
        ))}
      </div>

      {subTab === 'initiatives' && <React.Fragment>

      {/* Budget mode strip, synced with Budget page */}
      <div style={{
        background: budgetMode === 'simple' ? 'var(--violet-soft, rgba(77,105,137,0.08))' : 'var(--cream-2)',
        border: '1px solid ' + (budgetMode === 'simple' ? 'rgba(77,105,137,0.18)' : 'var(--cream-3)'),
        borderRadius: 10,
        padding: '8px 14px',
        display: 'flex',
        alignItems: 'center',
        gap: 12,
        marginBottom: 14,
        fontSize: 12
      }}>
        <span style={{ fontSize: 10, fontWeight: 700, color: budgetMode === 'simple' ? 'var(--violet)' : 'var(--ink-3)', background: 'var(--paper)', padding: '3px 8px', borderRadius: 999, letterSpacing: '0.04em', textTransform: 'uppercase', flexShrink: 0 }}>{budgetMode === 'simple' ? 'Smart Budget' : 'Self-managed'}</span>
        {budgetMode === 'simple' ?
        <span style={{ flex: 1, display: 'flex', alignItems: 'baseline', gap: 8, flexWrap: 'wrap', color: 'var(--ink-2)', minWidth: 0 }}>
            <strong style={{ fontFamily: 'var(--ff-display)', fontSize: 17, fontWeight: 600, color: 'var(--ink)' }}>{'$' + simpleTotal.toLocaleString()}<span style={{ fontSize: 11, fontWeight: 400, color: 'var(--ink-3)' }}>/mo</span></strong>
            <span>You set the total, LOCALACT manages the mix and rebalances it monthly.</span>
          </span> :
        <span style={{ flex: 1, color: 'var(--ink-2)' }}>You manage a budget per initiative, no monthly auto-rebalancing. Switch to Smart Budget to let the platform optimize the mix.</span>
        }
        <div style={{ display: 'inline-flex', background: 'var(--paper)', border: '1px solid var(--cream-3)', borderRadius: 999, padding: 2, gap: 1, flexShrink: 0 }}>
          {[
          { k: 'simple', l: 'Smart' },
          { k: 'advanced', l: 'Self-managed' }].
          map(o => (
          <button key={o.k} onClick={() => switchBudgetMode(o.k)}
            style={{
              background: budgetMode === o.k ? 'var(--ink)' : 'transparent',
              color: budgetMode === o.k ? 'var(--cream)' : 'var(--ink-3)',
              border: 'none',
              borderRadius: 999,
              padding: '3px 11px',
              fontSize: 10.5,
              fontWeight: 600,
              cursor: 'pointer'
            }}>{o.l}</button>
          ))}
        </div>
        <button className="btn btn-ghost btn-xs" onClick={() => window.dispatchEvent(new CustomEvent('go-page', { detail: 'budget' }))}>{budgetMode === 'simple' ? 'Adjust total →' : 'Open Budget →'}</button>
      </div>
      {confirmSelfManaged && <window.SelfManagedConfirmModal onCancel={() => setConfirmSelfManaged(false)} onConfirm={() => { setConfirmSelfManaged(false); applyBudgetMode('advanced'); }} />}

      {/* Lenny insight */}
      <div className="lenny-card" style={{ marginBottom: 16, padding: '10px 16px', display: 'flex', gap: 12, alignItems: 'center' }}>
        <div style={{ width: 36, height: 36, background: 'var(--paper)', border: '2px solid var(--cream-3)', borderRadius: '50%', overflow: 'hidden', flexShrink: 0, position: 'relative', zIndex: 1 }}>
          <LennyLlama size={36} mood="happy" bg="circle" />
        </div>
        <div style={{ position: 'relative', zIndex: 1, flex: 1, minWidth: 0, lineHeight: 1.45 }}>
          <span style={{ fontFamily: 'var(--ff-display)', fontSize: 13.5, fontWeight: 600 }}>Your stack is 80% optimized for recurring cleans. </span>
          <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>The Fall Refresh Promo is the last meaningful gap, est. +3 to 5 deep-clean bookings based on 22 FreshNest peers.</span>
        </div>
        <button className="btn btn-terra btn-xs" style={{ position: 'relative', zIndex: 1, flexShrink: 0 }} onClick={() => setShowMath(true)}>See the math</button>
      </div>

      {/* Prominent, always-available enrollment entry */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '16px 20px', marginBottom: 16, borderRadius: 14, background: 'linear-gradient(135deg, var(--brand-navy), #33506e)', color: 'var(--cream)' }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 17, fontWeight: 600 }}>Add a marketing service</div>
          <div style={{ fontSize: 12.5, color: 'rgba(250,246,239,.82)', marginTop: 3, lineHeight: 1.5 }}>Browse everything in your FreshNest playbook and enroll in two clicks — choose who pays, set the budget, confirm your territory, and we launch next Monday.</div>
        </div>
        <button className="btn btn-sm" style={{ background: 'var(--marigold)', color: 'var(--ink)', border: 'none', flexShrink: 0, fontWeight: 700 }} onClick={() => setAddOpen(true)}>Add a service →</button>
      </div>

      {/* 1 · Active Services */}
      {buckets.active.length > 0 && <>
        <div className="section-label">
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--sage)' }} />
            Active Initiatives
            <span className="count">{buckets.active.length} running now · on or above playbook target</span>
          </span>
        </div>
        <div className="grid grid-3">
          {buckets.active.map((s) => <InitiativeCard key={s.key} svc={s} simpleAmount={simpleAlloc ? simpleAlloc[s.key] : null} onOpen={() => setSvcDetail(s)} />)}
        </div>
      </>}

      {/* 2 · Recommended Services */}
      {buckets.recommended.length > 0 && <>
        <div className="section-label">
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--violet)' }} />
            Recommended Initiatives
            <span className="count">{buckets.recommended.length} suggested · core plays Lenny thinks you should add next</span>
          </span>
        </div>
        <div className="grid grid-3">
          {buckets.recommended.map((s) => <InitiativeCard key={s.key} svc={s} simpleAmount={simpleAlloc ? simpleAlloc[s.key] : null} onOpen={() => setSvcDetail(s)} />)}
        </div>
      </>}

      {/* 3 · Promo Opportunities */}
      {buckets.promo.length > 0 && <>
        <div className="section-label" style={{ color: '#a12118' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#e46c63', animation: 'pulse 2s infinite' }} />
            Promo Opportunities
            <span className="count" style={{ color: '#a12118' }}>{buckets.promo.length} live · limited windows, often corporate-funded</span>
          </span>
        </div>
        {buckets.promo.map((s) => <PromoCard key={s.key} svc={s} onOpen={() => setSvcDetail(s)} />)}
      </>}

      {/* 4 · Below-Target Services */}
      {buckets.below.length > 0 && <>
        <div className="section-label">
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--marigold)' }} />
            Below-Target Initiatives
            <span className="count">{buckets.below.length} enrolled but underspending vs the playbook range</span>
          </span>
        </div>
        <div className="grid grid-3">
          {buckets.below.map((s) => <InitiativeCard key={s.key} svc={s} simpleAmount={simpleAlloc ? simpleAlloc[s.key] : null} onOpen={() => setSvcDetail(s)} />)}
        </div>
      </>}

      {/* 5 · Add-On Options */}
      {buckets.addon.length > 0 && <>
        <div className="section-label">
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--ink-4)' }} />
            Add-On Options
            <span className="count">{buckets.addon.length} available · extras and one-time setups, not currently recommended</span>
          </span>
        </div>
        <div className="grid grid-3">
          {buckets.addon.map((s) => <InitiativeCard key={s.key} svc={s} simpleAmount={simpleAlloc ? simpleAlloc[s.key] : null} onOpen={() => setSvcDetail(s)} />)}
        </div>
      </>}

      <style>{`@keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } } .svc-page .section-label { margin: 16px 0 10px; } .svc-page .grid-3 { gap: 14px; }`}</style>

      <Modal open={!!svcDetail} onClose={() => setSvcDetail(null)} title={svcDetail?.name} sub={svcDetail?.product}
      footer={<>
          <button className="btn btn-ghost btn-sm" onClick={() => setSvcDetail(null)}>Close</button>
          {svcDetail?.enrolled ?
        <button className="btn btn-ghost btn-sm" onClick={() => {setSvcDetail(null);T('Paused', `${svcDetail.name} paused. Resume anytime.`, 'warn');}}>Pause initiative</button> :
        <button className="btn btn-terra btn-sm" onClick={() => { const s = svcDetail; setSvcDetail(null); setEnrollTarget(svcToChannel(s)); }}>Add to my plan</button>}
        </>}>
        {svcDetail &&
        <div>
            <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.6, marginBottom: 14 }}>{svcDetail.desc}</div>
            <InitiativeBudgetBox svc={svcDetail} />

            {svcDetail.requiresKeys && svcDetail.requiresKeys.length > 0 &&
          <div style={{ marginBottom: 14 }}>
                <div style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 600, marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Required alongside</div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {svcDetail.requiresKeys.map((k) => {
                const req = data.services.find((x) => x.key === k);
                return req ? <span key={k} className="badge badge-info">{req.name}</span> : null;
              })}
                </div>
              </div>
          }

            <div style={{ fontSize: 12, color: 'var(--ink-3)', fontWeight: 600, marginBottom: 8 }}>What's included</div>
            <ul style={{ margin: 0, paddingLeft: 18, fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.8 }}>
              <li>Dedicated strategist from Location3</li>
              <li>Monthly performance report and insights</li>
              <li>Creative refresh every 6 weeks</li>
              <li>Real-time lead forwarding to your CRM</li>
              <li>Lenny continuously tunes targeting and budget</li>
            </ul>
          </div>
        }
      </Modal>

      <Modal open={showMath} onClose={() => setShowMath(false)} title="Lenny's math · Fall Refresh Promo projection" sub="Based on 22 peer locations with a similar service mix">
        <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.7 }}>
          <div style={{ marginBottom: 14 }}>
            Your peer cohort (home services franchisees, &lt; 3mi to dense office, $1,500-3,000 PPC spend) sees these results when running the Fall Refresh Promo:
          </div>
          <div style={{ padding: '14px 16px', background: 'var(--cream)', borderRadius: 10, fontFamily: 'var(--ff-mono)', fontSize: 12, color: 'var(--ink-2)', marginBottom: 14 }}>
            $200 corporate + $150 your spend = $350 over 3 weeks<br />
            ÷ $38 CPL (peer median on Meta)<br />
            = ~9 deep-clean leads<br />
            × 45% booking rate<br />
            × $220 avg job<br />
            = <strong style={{ color: 'var(--ok)' }}>+$890 revenue</strong> (net $540 after your share)
          </div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>Confidence: High. 18 of 22 peers hit ≥ 8 leads in the campaign window.</div>
        </div>
      </Modal>
      </React.Fragment>}

      {subTab === 'geo' && <GeoTargeting variant={variant} />}

      {/* Add-a-service picker — every playbook service, enroll in two clicks */}
      <Modal open={addOpen} onClose={() => setAddOpen(false)} width={620}
        title="Add a service" sub="Everything in your FreshNest playbook. Enroll in two clicks.">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {visible.map((s) => {
            const r = PLAYBOOK_ROLES[s.key] || {};
            return (
              <div key={s.key} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', border: '1px solid var(--cream-3)', borderRadius: 10, background: s.enrolled ? 'var(--cream)' : 'var(--paper)' }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)' }}>{s.name}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 1 }}>{r.role || s.product}{r.rec ? ` · $${r.rec}/mo recommended` : (s.key === 'lsa' ? ' · pay-per-lead' : '')}</div>
                </div>
                {s.enrolled
                  ? <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--sage)', background: 'var(--sage-soft)', padding: '4px 10px', borderRadius: 999 }}>✓ Enrolled</span>
                  : <button className="btn btn-primary btn-sm" onClick={() => { setAddOpen(false); setEnrollTarget(svcToChannel(s)); }}>Review &amp; enroll →</button>}
              </div>
            );
          })}
        </div>
      </Modal>

      {enrollTarget && (
        <window.EnrollConfirmModal open={true} onClose={() => setEnrollTarget(null)}
          channel={enrollTarget}
          locations={[(data.location && data.location.name) || 'this location']}
          owner={(data.location && data.location.operator) || 'your LOCALACT strategist'} />
      )}
    </div>);

}
window.ServicesPageFranchisee = ServicesPageFranchisee;

// ====================================================================
// GEO-TARGETING, local operator sub-tab of Strategy.
// Two visual layers on a stylized ZIP map: (1) protected territory =
// every owned ZIP (dashed navy boundary), (2) targeted area = the subset
// currently running ads (filled coral). Local users can file change
// requests that route to corporate for approval — mocked, no backend.
// Real geo polygons are a next-release item.
// ====================================================================
function GeoTargeting({ variant = 'star' }) {
  // Austin Downtown mock territory. targeted = currently running ads.
  const OWNED = [
    { zip: '78701', name: 'Downtown',    targeted: true,  pin: true, leads: 22, cpl: 41, trend: 'up',   rec: 'keep' },
    { zip: '78703', name: 'Clarksville', targeted: true,  leads: 15, cpl: 52, trend: 'up',   rec: 'keep' },
    { zip: '78702', name: 'East Austin', targeted: true,  leads: 18, cpl: 47, trend: 'up',   rec: 'keep' },
    { zip: '78705', name: 'UT / North',  targeted: true,  leads: 12, cpl: 58, trend: 'flat', rec: 'keep' },
    { zip: '78751', name: 'Hyde Park',   targeted: true,  leads: 6,  cpl: 74, trend: 'down', rec: 'review' },
    { zip: '78704', name: 'S. Congress', targeted: true,  leads: 14, cpl: 49, trend: 'up',   rec: 'keep' },
    { zip: '78731', name: 'NW Hills',    targeted: false, demand: 'High',   searches: 320, recommend: true },
    { zip: '78722', name: 'Cherrywood',  targeted: false, demand: 'High',   searches: 260, recommend: true },
    { zip: '78745', name: 'S. Austin',   targeted: false, demand: 'High',   searches: 300, recommend: true },
    { zip: '78741', name: 'Riverside',   targeted: false, demand: 'Medium', searches: 180, recommend: false },
    { zip: '78756', name: 'Rosedale',    targeted: false, demand: 'Medium', searches: 150, recommend: false },
    { zip: '78723', name: 'Windsor Pk',  targeted: false, demand: 'Low',    searches: 90,  recommend: false },
  ];
  const ADJACENT = [
    { zip: '78753', name: 'N. Lamar',    demand: 'High',   searches: 240, recommend: true },
    { zip: '78717', name: 'Avery Ranch', demand: 'Medium', searches: 160, recommend: false },
    { zip: '78759', name: 'Arboretum',   demand: 'Medium', searches: 140, recommend: false },
    { zip: '78748', name: 'Cherry Ck',   demand: 'Low',    searches: 80,  recommend: false },
  ];
  const targeted = OWNED.filter(z => z.targeted);
  const ownedNotTargeted = OWNED.filter(z => !z.targeted);

  const KEY = 'localact_geo_requests_' + variant;
  const [pending, setPending] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem(KEY) || '[]'); } catch (e) { return []; }
  });
  const [modal, setModal] = React.useState(null);
  const savePending = (next) => {
    setPending(next);
    try { localStorage.setItem(KEY, JSON.stringify(next)); } catch (e) {}
  };
  const submit = (payload) => {
    const now = new Date();
    const entry = {
      id: now.getTime(), kind: payload.kind, label: payload.label, detail: payload.detail,
      when: now.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) + ' · ' + now.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' }),
      status: 'Awaiting corporate approval',
    };
    savePending([entry].concat(pending));
    setModal(null);
    window.T && window.T('Request sent to corporate', payload.label + ' · routed to Sarah Reyes, Strategy Director', 'ok');
  };
  const withdraw = (id) => {
    savePending(pending.filter(p => p.id !== id));
    window.T && window.T('Request withdrawn', 'Removed before corporate reviewed it.', 'info');
  };

  const MARK = [
    { zip: '78701', x: 330, y: 250, targeted: true },
    { zip: '78705', x: 300, y: 178, targeted: true },
    { zip: '78751', x: 372, y: 182, targeted: true },
    { zip: '78703', x: 268, y: 218, targeted: true },
    { zip: '78702', x: 388, y: 240, targeted: true },
    { zip: '78704', x: 322, y: 292, targeted: true },
    { zip: '78731', x: 250, y: 150, targeted: false },
    { zip: '78723', x: 452, y: 178, targeted: false },
    { zip: '78722', x: 430, y: 250, targeted: false },
    { zip: '78741', x: 402, y: 360, targeted: false },
    { zip: '78745', x: 322, y: 416, targeted: false },
    { zip: '78756', x: 250, y: 300, targeted: false },
  ];
  const PROTECTED = '300,118 384,108 410,150 434,205 438,262 408,322 430,378 388,420 322,440 262,418 246,356 216,314 232,256 244,188 266,146';
  const TARGETED = '300,150 372,150 402,202 406,252 360,292 300,302 260,270 254,206 274,168';

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, marginBottom: 16, flexWrap: 'wrap' }}>
        <div style={{ flex: 1, minWidth: 320 }}>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 19, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.01em', marginBottom: 4 }}>Where your ads run</div>
          <div style={{ fontSize: 13, color: 'var(--ink-3)', lineHeight: 1.55, maxWidth: 640 }}>
            Your <strong style={{ color: 'var(--brand-navy)' }}>protected territory</strong> is every ZIP you own. Your <strong style={{ color: '#b5651b' }}>targeted area</strong> is the subset actively running ads today. Corporate owns territory boundaries — use the request actions to propose a change.
          </div>
        </div>
        <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase', color: 'var(--ink-4)', background: 'var(--cream-2)', border: '1px solid var(--cream-3)', padding: '5px 10px', borderRadius: 999, whiteSpace: 'nowrap', marginTop: 2 }}>Stylized map · real geo polygons next release</span>
      </div>

      <div className="card" style={{ padding: 20, marginBottom: 16 }}>
        <div style={{ marginBottom: 14 }}>
          <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 11.5, color: 'var(--ink-3)' }}><strong style={{ color: 'var(--ink)' }}>{OWNED.length}</strong> ZIPs owned · <strong style={{ color: '#b5651b' }}>{targeted.length}</strong> running ads</span>
        </div>
        <div style={{ position: 'relative', borderRadius: 16, overflow: 'hidden', border: '1px solid var(--line)' }}>
          <svg viewBox="0 0 640 480" width="100%" style={{ display: 'block', background: '#e9ecef' }} role="img" aria-label="Territory map">
            <defs>
              <radialGradient id="geoGlow" cx="50%" cy="50%" r="50%">
                <stop offset="0%" stopColor="#f6a663" stopOpacity="0.55" />
                <stop offset="55%" stopColor="#f6a663" stopOpacity="0.20" />
                <stop offset="100%" stopColor="#f6a663" stopOpacity="0" />
              </radialGradient>
            </defs>
            <path d="M -20,360 C 60,340 90,400 60,470 L -20,470 Z" fill="#cfe0ef" />
            <path d="M 470,470 C 500,420 560,430 620,410 L 640,470 Z" fill="#cfe0ef" />
            <g stroke="#dfe2e6" strokeWidth="1">
              {[80,160,240,320,400,480,560].map(x => <line key={'v'+x} x1={x} y1="0" x2={x} y2="480" />)}
              {[60,120,180,240,300,360,420].map(y => <line key={'h'+y} x1="0" y1={y} x2="640" y2={y} />)}
            </g>
            <g stroke="#ffffff" strokeWidth="5" fill="none" strokeLinecap="round">
              <path d="M 0,150 C 180,120 360,180 640,140" />
              <path d="M 40,0 C 120,180 100,340 180,480" />
              <path d="M 640,300 C 460,280 300,360 120,340" />
              <path d="M 330,0 L 330,480" />
            </g>
            <g fontFamily="var(--ff-ui)" fontSize="11" fill="#8a9099" fontWeight="600">
              <text x="322" y="46" textAnchor="middle" fill="#5a6069" fontSize="16" fontWeight="700" letterSpacing="1">AUSTIN</text>
              <text x="150" y="120" textAnchor="middle">NW Hills</text>
              <text x="486" y="150" textAnchor="middle">Windsor Park</text>
              <text x="150" y="300" textAnchor="middle">Rosedale</text>
              <text x="500" y="300" textAnchor="middle">Mueller</text>
              <text x="322" y="465" textAnchor="middle">South Austin</text>
              <text x="470" y="380" textAnchor="middle">Riverside</text>
            </g>
            <polygon points={PROTECTED} fill="rgba(0,40,87,0.10)" stroke="#4d6989" strokeWidth="2.5" strokeDasharray="7 5" strokeLinejoin="round" />
            <polygon points={TARGETED} fill="rgba(246,166,99,0.40)" stroke="#d98436" strokeWidth="2.5" strokeLinejoin="round" />
            <circle cx="330" cy="222" r="98" fill="url(#geoGlow)" />
            {MARK.map(m => (
              <g key={m.zip} transform={'translate(' + (m.x - 24) + ',' + (m.y - 9) + ')'}>
                <rect width="48" height="18" rx="9" fill={m.targeted ? '#f6a663' : '#ffffff'} stroke={m.targeted ? '#d98436' : '#4d6989'} strokeWidth="1.2" strokeDasharray={m.targeted ? '0' : '3 2'} />
                <text x="24" y="13" textAnchor="middle" fontFamily="var(--ff-mono)" fontSize="10.5" fontWeight="700" fill={m.targeted ? '#3f2708' : '#002857'}>{m.zip}</text>
              </g>
            ))}
            <g transform="translate(318,196)">
              <ellipse cx="12" cy="33" rx="7" ry="2.4" fill="rgba(0,40,87,0.25)" />
              <path d="M12 0C5.4 0 0 5.3 0 11.9 0 20.6 12 31 12 31s12-10.4 12-19.1C24 5.3 18.6 0 12 0z" fill="#002857" />
              <circle cx="12" cy="11.6" r="4.4" fill="#fff" />
            </g>
          </svg>
        </div>
        <div style={{ display: 'flex', gap: 22, flexWrap: 'wrap', marginTop: 16, fontSize: 12, color: 'var(--ink-2)' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 22, height: 15, borderRadius: 4, background: 'rgba(0,40,87,0.10)', border: '2px dashed #4d6989' }} />
            Protected territory · owned ZIPs
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 22, height: 15, borderRadius: 4, background: 'rgba(246,166,99,0.55)', border: '2px solid #d98436' }} />
            Targeted area · ads running
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <svg width="13" height="17" viewBox="0 0 24 31" fill="none"><path d="M12 0C5.4 0 0 5.3 0 11.9 0 20.6 12 31 12 31s12-10.4 12-19.1C24 5.3 18.6 0 12 0z" fill="#002857"/><circle cx="12" cy="11.6" r="4.4" fill="#fff"/></svg>
            Your location
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 22, height: 15, borderRadius: 4, background: '#fff', border: '1.5px dashed #4d6989' }} />
            Owned · not yet targeted
          </span>
        </div>
      </div>

      <div className="card card-pad" style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4, flexWrap: 'wrap' }}>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 15, fontWeight: 600, color: 'var(--ink)' }}>Request a change</div>
          <span style={{ fontSize: 11, color: 'var(--ink-4)', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--terra-3)' }} />
            Every request routes to corporate for approval
          </span>
        </div>
        <div style={{ fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.5, marginBottom: 14, maxWidth: 640 }}>Lenny pre-fills each request with a recommendation — accept it or adjust before sending.</div>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <button className="btn btn-terra btn-sm" onClick={() => setModal('expand')}>Request to expand targeting</button>
          <button className="btn btn-ghost btn-sm" onClick={() => setModal('adjust')}>Request to adjust / remove ZIPs</button>
          <button className="btn btn-ghost btn-sm" onClick={() => setModal('review')}>Request a territory review</button>
        </div>
      </div>

      {pending.length > 0 && (
        <div className="card card-pad">
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-4)', marginBottom: 10 }}>Requests routed to corporate ({pending.length})</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {pending.map(p => (
              <div key={p.id} style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '11px 13px', background: 'var(--cream)', borderRadius: 10, border: '1px solid var(--line)' }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink)' }}>{p.label}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2, lineHeight: 1.5 }}>{p.detail}</div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-4)', marginTop: 4 }}>Submitted {p.when} · to Sarah Reyes, Strategy Director</div>
                </div>
                <span className="badge badge-warn" style={{ flexShrink: 0 }}>{p.status}</span>
                <button className="btn btn-ghost btn-xs" style={{ flexShrink: 0 }} onClick={() => withdraw(p.id)}>Withdraw</button>
              </div>
            ))}
          </div>
        </div>
      )}

      {modal && <GeoRequestModal kind={modal} targeted={targeted} ownedNotTargeted={ownedNotTargeted} adjacent={ADJACENT} onClose={() => setModal(null)} onSubmit={submit} />}
    </div>
  );
}
window.GeoTargeting = GeoTargeting;

function GeoRequestModal({ kind, targeted, ownedNotTargeted, adjacent, onClose, onSubmit }) {
  const demandColor = (d) => d === 'High' ? 'var(--sage)' : d === 'Medium' ? '#917200' : 'var(--ink-4)';
  const trendGlyph = (t) => t === 'up' ? { s: '▲', c: 'var(--ok)' } : t === 'down' ? { s: '▼', c: 'var(--bad)' } : { s: '–', c: 'var(--ink-4)' };

  const recExpand = ownedNotTargeted.filter(z => z.recommend).map(z => z.zip);
  const recClaim = adjacent.filter(z => z.recommend).map(z => z.zip);

  const cfg = {
    expand: { title: 'Request to expand targeting', sub: 'Turn on ads in ZIPs you already own. Adding ZIPs raises your daily budget, so corporate confirms the spend before it goes live.', initial: recExpand },
    adjust: { title: 'Request to adjust / remove ZIPs', sub: 'Change which owned ZIPs run ads. Removing a ZIP triggers a performance review so corporate can confirm you are not cutting a channel that is still converting.', initial: targeted.map(z => z.zip) },
    review: { title: 'Request a territory review', sub: 'Propose a change to your protected boundary — claim an adjacent ZIP or flag an overlap with a neighboring location. A Strategy Director reviews every boundary change.', initial: recClaim },
  }[kind];

  const [sel, setSel] = React.useState(cfg.initial);
  const [reason, setReason] = React.useState('');
  const toggle = (zip) => setSel(a => a.indexOf(zip) >= 0 ? a.filter(x => x !== zip) : a.concat(zip));

  const removals = kind === 'adjust' ? targeted.filter(z => sel.indexOf(z.zip) < 0) : [];
  const canSubmit = kind === 'review' ? (reason.trim().length > 3 || sel.length > 0)
    : kind === 'adjust' ? removals.length > 0
    : sel.length > 0;

  const REC = { display: 'flex', gap: 10, alignItems: 'flex-start', padding: '12px 14px', marginBottom: 16, background: 'var(--terra-softer)', border: '1px solid var(--terra-3)', borderRadius: 12 };
  const chipBtn = (on) => ({ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', width: '100%', textAlign: 'left', fontFamily: 'var(--ff-ui)', fontSize: 12.5, padding: '10px 12px', borderRadius: 10, border: on ? '1.5px solid var(--terra)' : '1px solid var(--cream-3)', background: on ? 'var(--terra-soft)' : 'var(--paper)', color: 'var(--ink)' });
  const box = (on) => ({ width: 16, height: 16, borderRadius: 4, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', border: on ? 'none' : '1.5px solid var(--cream-3)', background: on ? 'var(--terra)' : 'var(--paper)', color: '#fff', fontSize: 11 });
  const recTag = { fontSize: 8.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', color: '#b5651b', background: 'var(--coral-soft)', padding: '2px 6px', borderRadius: 999 };

  const doSubmit = () => {
    const zipsTxt = sel.join(', ') || '—';
    let detail;
    if (kind === 'expand') {
      detail = 'Add ' + sel.length + ' ZIP' + (sel.length !== 1 ? 's' : '') + ': ' + zipsTxt + ' · recommend +' + '$300/mo (est. 4–8 more qualified leads/mo). Affects spend · needs approval.';
    } else if (kind === 'adjust') {
      detail = 'Remove ' + removals.length + ' ZIP' + (removals.length !== 1 ? 's' : '') + ': ' + removals.map(z => z.zip).join(', ') + ' · pending ZIP performance review before ads pause.';
    } else {
      detail = 'Boundary review' + (sel.length ? ' · claim ' + zipsTxt : '') + (reason.trim() ? ' · “' + reason.trim() + '”' : '');
    }
    onSubmit({ kind, label: cfg.title, detail });
  };

  return (
    <Modal open onClose={onClose} title={cfg.title} sub={cfg.sub}
      footer={<>
        <span style={{ fontSize: 11, color: 'var(--ink-4)', display: 'inline-flex', alignItems: 'center', gap: 6 }}>Routes to corporate · Sarah Reyes, Strategy Director</span>
        <span style={{ flex: 1 }} />
        <button className="btn btn-ghost btn-sm" onClick={onClose}>Cancel</button>
        <button className="btn btn-terra btn-sm" style={{ opacity: canSubmit ? 1 : 0.5, pointerEvents: canSubmit ? 'auto' : 'none' }} onClick={doSubmit}>Send request to corporate</button>
      </>}>
      <div>
        <div style={REC}>
          <div style={{ width: 30, height: 30, borderRadius: '50%', overflow: 'hidden', flexShrink: 0, background: 'var(--paper)', border: '1.5px solid var(--cream-3)' }}>
            <LennyLlama size={30} mood="thinking" bg="circle" />
          </div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.55 }}>
            {kind === 'expand' && <><strong style={{ color: 'var(--ink)' }}>Lenny recommends {recExpand.length} ZIPs.</strong> 78731, 78722 and 78745 show the highest unserved search demand in your territory. Adding them typically needs <strong>+{'$300'}/mo</strong> and returns an estimated <strong style={{ color: 'var(--ok)' }}>4–8 qualified leads/mo</strong>, based on peer FreshNest locations of similar size.</>}
            {kind === 'adjust' && <><strong style={{ color: 'var(--ink)' }}>Lenny flags 1 ZIP for review.</strong> 78751 (Hyde Park) is at {'$74'} CPL with lead volume trending down. The rest are converting — keep them live. Uncheck any ZIP to propose removing it.</>}
            {kind === 'review' && <><strong style={{ color: 'var(--ink)' }}>Lenny recommends claiming 78753.</strong> It shows high demand in your search logs and isn’t assigned to another FreshNest location. Boundary changes need a Strategy Director sign-off.</>}
          </div>
        </div>

        {kind === 'review' && (
          <div style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 6 }}>Why request a review?</div>
            <textarea value={reason} onChange={e => setReason(e.target.value)} rows={3}
              placeholder="e.g. A competitor opened nearby — requesting 78753 be added to our protected territory."
              style={{ width: '100%', boxSizing: 'border-box', padding: '10px 12px', fontSize: 13, fontFamily: 'var(--ff-ui)', border: '1px solid var(--line)', borderRadius: 10, outline: 'none', background: 'var(--cream)', color: 'var(--ink)', resize: 'vertical' }} />
          </div>
        )}

        <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 8 }}>
          {kind === 'expand' ? 'Owned ZIPs not yet running ads' : kind === 'adjust' ? 'Currently running ads — uncheck to propose removal' : 'Adjacent ZIPs to claim (optional)'}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {(kind === 'expand' ? ownedNotTargeted : kind === 'adjust' ? targeted : adjacent).map(z => {
            const on = sel.indexOf(z.zip) >= 0;
            const tg = z.trend ? trendGlyph(z.trend) : null;
            return (
              <button key={z.zip} onClick={() => toggle(z.zip)} style={chipBtn(on)}>
                <span style={box(on)}>{on ? '✓' : ''}</span>
                <span style={{ fontFamily: 'var(--ff-mono)', fontWeight: 700, width: 48 }}>{z.zip}</span>
                <span style={{ flex: 1, color: 'var(--ink-2)' }}>{z.name}</span>
                {kind === 'adjust' ? (
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 12, fontSize: 11.5, color: 'var(--ink-3)' }}>
                    <span>{z.leads} leads</span>
                    <span>{'$' + z.cpl} CPL</span>
                    <span style={{ color: tg.c, fontWeight: 700 }}>{tg.s}</span>
                    {z.rec === 'review' ? <span style={{ fontSize: 8.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', color: '#a12118', background: 'var(--berry-soft)', padding: '2px 6px', borderRadius: 999 }}>Review</span> : <span style={{ fontSize: 8.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', color: '#0a6666', background: 'var(--sage-soft)', padding: '2px 6px', borderRadius: 999 }}>Converting</span>}
                  </span>
                ) : (
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10, fontSize: 11.5 }}>
                    <span style={{ color: demandColor(z.demand), fontWeight: 700 }}>{z.demand} demand</span>
                    <span style={{ color: 'var(--ink-3)' }}>{z.searches}/mo</span>
                    {z.recommend && <span style={recTag}>Recommended</span>}
                  </span>
                )}
              </button>
            );
          })}
        </div>

        <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          {kind === 'expand' && <>
            <span>Adding <strong style={{ color: 'var(--ink)' }}>{sel.length}</strong> ZIP{sel.length !== 1 ? 's' : ''}.</span>
            <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-3)', background: 'var(--cream-2)', padding: '3px 8px', borderRadius: 999 }}>Affects spend</span>
            <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--violet)', background: 'var(--violet-soft)', padding: '3px 8px', borderRadius: 999 }}>Needs approval</span>
          </>}
          {kind === 'adjust' && (removals.length > 0
            ? <><span>Proposing to remove <strong style={{ color: 'var(--ink)' }}>{removals.length}</strong> ZIP{removals.length !== 1 ? 's' : ''}.</span><span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: '#a12118', background: 'var(--berry-soft)', padding: '3px 8px', borderRadius: 999 }}>Performance review required</span></>
            : <span>Uncheck a ZIP to propose removing it — corporate reviews its performance first.</span>)}
          {kind === 'review' && <span>{sel.length || reason.trim() ? 'A Strategy Director reviews and applies approved boundary changes.' : 'Add a reason or select an adjacent ZIP to submit.'}</span>}
        </div>
      </div>
    </Modal>
  );
}
window.GeoRequestModal = GeoRequestModal;
function InitiativeBudgetBox({ svc }) {
  if (svc.type === 'Flat Fee') {
    return (
      <div style={{ padding: '14px 16px', background: 'var(--cream)', borderRadius: 10, marginBottom: 14, display: 'flex', alignItems: 'baseline', gap: 10, justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span style={{ fontFamily: 'var(--ff-display)', fontSize: 32, fontWeight: 500 }}>${svc.fee}</span>
          <span style={{ color: 'var(--ink-3)', fontSize: 12 }}>/month</span>
        </div>
        <span className="badge badge-neutral">Flat fee</span>
      </div>);

  }
  if (svc.type === 'One Time Fee') {
    return (
      <div style={{ padding: '14px 16px', background: 'var(--cream)', borderRadius: 10, marginBottom: 14, display: 'flex', alignItems: 'baseline', gap: 10, justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span style={{ fontFamily: 'var(--ff-display)', fontSize: 32, fontWeight: 500 }}>${svc.fee}</span>
          <span style={{ color: 'var(--ink-3)', fontSize: 12 }}>one-time</span>
        </div>
        <span className="badge badge-neutral">One-time</span>
      </div>);

  }
  // Budget Based, dual breakdown
  const total = (svc.corporateBudget || 0) + (svc.localBudget || 0);
  return (
    <div style={{ marginBottom: 14, borderRadius: 12, overflow: 'hidden', border: '1px solid var(--line)' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
        <div style={{ padding: '14px 16px', background: 'var(--cream)', borderRight: '1px solid var(--line)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
            <span style={{ fontSize: 10, padding: '2px 6px', borderRadius: 4, background: 'var(--brand-navy)', color: 'var(--cream)', fontWeight: 700, letterSpacing: '0.04em' }}>CORP</span>
            <span style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 600 }}>Corporate-funded</span>
          </div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 24, fontWeight: 500, color: 'var(--ink-2)' }}>${(svc.corporateBudget || 0).toLocaleString()}<span style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 400 }}> /mo</span></div>
        </div>
        <div style={{ padding: '14px 16px', background: 'var(--paper)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
            <span style={{ fontSize: 10, padding: '2px 6px', borderRadius: 4, background: 'var(--terra)', color: 'var(--cream)', fontWeight: 700, letterSpacing: '0.04em' }}>YOU</span>
            <span style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 600 }}>Your local spend</span>
          </div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 28, fontWeight: 500, color: 'var(--ink)' }}>${(svc.localBudget || 0).toLocaleString()}<span style={{ fontSize: 12, color: 'var(--ink-3)', fontWeight: 400 }}> /mo</span></div>
        </div>
      </div>
      <div style={{ padding: '8px 16px', background: 'var(--cream-2)', fontSize: 11, color: 'var(--ink-3)', display: 'flex', justifyContent: 'space-between' }}>
        <span>Combined monthly budget</span>
        <strong style={{ color: 'var(--ink)', fontFamily: 'var(--ff-mono)' }}>${total.toLocaleString()}/mo</strong>
      </div>
      {svc.dates &&
      <div style={{ padding: '8px 16px', background: 'var(--marigold-soft)', fontSize: 11, color: 'var(--ink-2)', borderTop: '1px solid var(--line)' }}>
          <strong>Runs:</strong> {svc.dates}
        </div>
      }
    </div>);

}

function InitiativeCard({ svc, onOpen, simpleAmount }) {
  const isFlat = svc.type === 'Flat Fee';
  const isOneTime = svc.type === 'One Time Fee';
  const isBudget = svc.type === 'Budget Based';
  const corp = svc.corporateBudget || 0;
  const local = svc.localBudget || 0;
  const auto = isBudget && svc.enrolled && simpleAmount != null; // Simple mode: Lenny-allocated share
  const total = auto ? simpleAmount : corp + local;
  const role = PLAYBOOK_ROLES[svc.key] || {};
  const rec = role.rec;

  // Status: active-on-target | active-below | available-recommended | available-optional
  let status, statusBg, statusFg, statusLabel, accent;
  if (svc.enrolled) {
    if (rec && total < rec) {
      status = 'below';statusBg = 'var(--marigold-soft)';statusFg = '#917200';
      statusLabel = '● Below target';accent = 'var(--marigold)';
    } else {
      status = 'active';statusBg = 'var(--sage-soft)';statusFg = '#085050';
      statusLabel = '● Active';accent = 'var(--sage)';
    }
  } else if (rec) {
    status = 'recommend';statusBg = 'var(--terra-softer)';statusFg = 'var(--terra)';
    statusLabel = 'Recommended';accent = 'var(--terra)';
  } else {
    status = 'available';statusBg = 'var(--cream-2)';statusFg = 'var(--ink-3)';
    statusLabel = 'Available';accent = 'var(--cream-3)';
  }

  const money = isBudget ? (svc.enrolled ? total : rec || 0) : svc.fee;
  const moneySuffix = isOneTime ? 'one-time' : isFlat ? '/mo flat' : svc.enrolled ? '/mo' : '/mo suggested';

  return (
    <div className="card" style={{
      padding: '14px 16px', display: 'flex', flexDirection: 'column',
      opacity: status === 'available' ? 0.95 : 1
    }}>
      {/* Header: product · role eyebrow, name, status pill */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8, marginBottom: 6 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 10, color: 'var(--ink-4)', fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase', marginBottom: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {svc.product}{role.role && <span style={{ color: 'var(--violet)' }}> · {role.role}</span>}
          </div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 15, fontWeight: 600, color: 'var(--ink)', lineHeight: 1.25 }}>{svc.name}</div>
        </div>
        <span style={{ fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 999, background: statusBg, color: statusFg, whiteSpace: 'nowrap', flexShrink: 0 }}>{statusLabel}</span>
      </div>

      {/* Why this matters, clamped to 2 lines */}
      <div style={{ fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.5, marginBottom: 10, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
        {role.why || svc.desc}
      </div>

      {/* Money row */}
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 8, flexWrap: 'wrap' }}>
        <span style={{ fontFamily: 'var(--ff-display)', fontSize: 20, fontWeight: 600, color: 'var(--ink)' }}>{'$' + money.toLocaleString()}</span>
        <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>{moneySuffix}</span>
        {auto &&
        <span style={{ fontSize: 9.5, fontWeight: 700, padding: '2px 7px', borderRadius: 999, background: 'var(--violet-soft, rgba(77,105,137,0.12))', color: 'var(--violet)' }}> Lenny-allocated</span>
        }
        {!auto && isBudget && svc.enrolled && corp > 0 &&
        <span style={{ fontSize: 9.5, fontWeight: 700, padding: '2px 7px', borderRadius: 999, background: 'var(--brand-navy)', color: 'var(--cream)', letterSpacing: '0.03em' }}>{'CORP $' + corp}</span>
        }
      </div>

      {/* Playbook target bar */}
      {isBudget && rec && svc.enrolled &&
      <div style={{ marginBottom: 8 }}>
          <div style={{ height: 3, background: 'var(--cream-2)', borderRadius: 2, overflow: 'hidden', marginBottom: 3 }}>
            <div style={{ height: '100%', width: Math.min(100, total / rec * 100) + '%', background: total >= rec ? 'var(--sage)' : 'var(--marigold)', borderRadius: 2 }} />
          </div>
          <div style={{ fontSize: 10, color: 'var(--ink-4)', fontFamily: 'var(--ff-mono)' }}>
            {total >= rec ? 'At playbook target · $' + rec.toLocaleString() + '/mo' : Math.round(total / rec * 100) + '% of $' + rec.toLocaleString() + ' playbook target'}
          </div>
        </div>
      }

      {/* Live performance metric */}
      {svc.metric && svc.enrolled &&
      <div style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--ink-2)', fontFamily: 'var(--ff-mono)', marginBottom: 10, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {svc.metric}
        </div>
      }

      <div style={{ flex: 1 }} />
      <button
        className={'btn btn-xs ' + (status === 'recommend' ? 'btn-terra' : 'btn-ghost')}
        style={{ width: '100%', justifyContent: 'center' }}
        onClick={onOpen}>
        {svc.enrolled ? 'Manage' : status === 'recommend' ? 'Enroll →' : 'Learn more'}
      </button>
    </div>);

}

// ====================================================================
// PROMO CARD, featured limited-time service ribbon
// ====================================================================
function PromoCard({ svc, onOpen }) {
  const corp = svc.corporateBudget || 0;
  const local = svc.localBudget || 0;
  return (
    <div style={{
      position: 'relative', overflow: 'hidden',
      background: 'linear-gradient(110deg, #fef9f4 0%, #fdf5f4 50%, #fdf0e4 100%)',
      borderRadius: 16,
      border: '1px solid var(--cream-3)',
      padding: '14px 18px',
      display: 'grid',
      gridTemplateColumns: '1fr auto',
      gap: 18,
      alignItems: 'center',
      boxShadow: 'var(--sh-1)'
    }}>
      {/* Decorative bg shape */}
      <div style={{ position: 'absolute', right: -40, top: -40, width: 200, height: 200, borderRadius: '50%', background: 'rgba(212, 101, 138, 0.08)' }} />

      <div style={{ position: 'relative', zIndex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
          <span style={{ fontSize: 10, color: '#a12118', fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', padding: '3px 8px', background: 'rgba(212, 101, 138, 0.15)', borderRadius: 999 }}>Limited window</span>
          <span style={{ fontSize: 11, color: '#a12118', fontWeight: 600, fontFamily: 'var(--ff-mono)' }}>Runs {svc.dates}</span>
        </div>
        <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)', marginBottom: 4, letterSpacing: '-0.01em' }}>{svc.name}</div>
        <div style={{ fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.5, marginBottom: 10, maxWidth: 580 }}>{svc.desc}</div>

        <div style={{ display: 'flex', gap: 18, alignItems: 'center', flexWrap: 'wrap' }}>
          <div>
            <div style={{ fontSize: 9.5, color: 'var(--ink-4)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Corporate funds</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 500 }}>${corp}<span style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 400 }}>/promo</span></div>
          </div>
          <div style={{ width: 1, height: 28, background: 'var(--cream-3)' }} />
          <div>
            <div style={{ fontSize: 9.5, color: 'var(--ink-4)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em' }}>You add</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 500 }}>${local}<span style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 400 }}>/promo</span></div>
          </div>
          <div style={{ width: 1, height: 28, background: 'var(--cream-3)' }} />
          <div>
            <div style={{ fontSize: 9.5, color: 'var(--ink-4)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Peer estimate</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 500, color: 'var(--ok)' }}>+9 leads</div>
          </div>
        </div>
      </div>

      <div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-end' }}>
        <button className="btn btn-terra btn-sm" onClick={() => {T('Enrolled in promo', `${svc.name} added, strategist will confirm creative.`, 'ok');}}>
          Enroll in promo →
        </button>
        <button className="btn btn-ghost btn-sm" onClick={onOpen}>See details</button>
      </div>
    </div>);

}

// ====================================================================
// BUDGET, sliders driven by visible Initiatives
// ====================================================================
function BudgetPage({ data }) {
  // Visible Budget Based initiatives (Locations audiences only).
  const budgetInits = data.services.filter((s) =>
  s.type === 'Budget Based' && (s.audience === 'Locations All' || s.audience === 'Locations Limited') && s.enrolled
  );
  const flatInits = data.services.filter((s) =>
  s.type === 'Flat Fee' && (s.audience === 'Locations All' || s.audience === 'Locations Limited') && s.enrolled
  );

  // ---- Mode toggle ----
  // Smart Budget ('simple') is the pre-selected default everywhere.
  // Persisted per-location in localStorage so toggle survives reload.
  const variant = data.variant || 'star';
  const STORAGE_KEY = `localact_budget_mode_${variant}`;
  const [mode, setMode] = useStateP(() => {
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored === 'simple' || stored === 'advanced') return stored;
    } catch {}
    return 'simple';
  });
  useEffectP(() => {
    try { localStorage.setItem(STORAGE_KEY, mode); } catch {}
    // Cross-page sync to Initiatives header
    try { localStorage.setItem('localact_budget_mode_active', mode); } catch {}
  }, [mode]);
  // Confirmation friction before leaving Smart Budget for Self-managed
  const [confirmSelfM, setConfirmSelfM] = useStateP(false);
  const pickMode = (m) => {
    if (m === 'advanced' && mode !== 'advanced') { setConfirmSelfM(true); return; }
    setMode(m);
  };

  // Per-initiative slider state, keyed by Initiative key.
  const initialLocal = {};
  budgetInits.forEach((s) => {initialLocal[s.key] = s.localBudget || 0;});
  const [localSpend, setLocalSpend] = useStateP(initialLocal);
  const setOne = (k, v) => setLocalSpend((prev) => ({ ...prev, [k]: v }));

  // When Simple Mode commits an allocation, push it into Advanced sliders too
  const commitSimple = (allocations) => {
    setLocalSpend(prev => ({ ...prev, ...allocations }));
  };

  const dirty = budgetInits.some((s) => localSpend[s.key] !== (s.localBudget || 0));
  const localTotal = budgetInits.reduce((sum, s) => sum + (localSpend[s.key] || 0), 0);
  const corpTotal = budgetInits.reduce((sum, s) => sum + (s.corporateBudget || 0), 0);
  const flatTotal = flatInits.reduce((sum, s) => sum + s.fee, 0);
  const paidTotal = localTotal; // your paid spend only
  const allInTotal = localTotal + flatTotal; // your true monthly bill
  const spentPct = 68;
  const elapsedPct = 47;
  const dayOf = 14;
  const totalDays = 30;
  const daysLeft = totalDays - dayOf;
  const spentDollars = Math.round(spentPct * paidTotal / 100);
  const remainingDollars = paidTotal - spentDollars;
  const dailyTargetRest = daysLeft > 0 ? Math.round(remainingDollars / daysLeft) : 0;
  // Run-rate forecast: project spend at current daily pace
  const dailyPace = spentDollars / dayOf;
  const forecast = Math.round(dailyPace * totalDays);
  const forecastDelta = forecast - paidTotal;
  const onPace = Math.abs(forecastDelta) < paidTotal * 0.05;

  // Peer median per-initiative (system avg). Pulled from playbook recommended.
  const PEER_MEDIAN = {
    'gs-local': 1500, 'lsa-local': 600, 'meta-local': 800, 'meta-mothers': 350
  };

  // Peer median mix percentages, total = 100, based on $1500+600+800
  const peerTotalMix = Object.values(PEER_MEDIAN).reduce((a, b) => a + b, 0) - 350; // exclude promo
  const yourMixPcts = budgetInits.map((s) => ({
    key: s.key, name: s.name, color: s.color,
    your: localSpend[s.key] || 0,
    yourPct: paidTotal > 0 ? (localSpend[s.key] || 0) / paidTotal * 100 : 0,
    peer: PEER_MEDIAN[s.key] || 0,
    peerPct: peerTotalMix > 0 ? (PEER_MEDIAN[s.key] || 0) / peerTotalMix * 100 : 0
  }));

  // Slider config, min/max/optimal use peer median as anchor when available.
  const cfg = (s) => {
    const base = PEER_MEDIAN[s.key] || s.localBudget || 100;
    return {
      min: Math.max(50, Math.round(base * 0.25 / 50) * 50),
      max: Math.max(500, Math.round(base * 2.5 / 100) * 100),
      peer: PEER_MEDIAN[s.key] || null,
      optimal: `$${Math.round(base * 1.05)}–$${Math.round(base * 1.4)}`
    };
  };

  return (
    <div className="page active">
      <div className="page-header">
        <div>
          <div className="page-title">Budget &amp; Spend.</div>
          <div className="page-sub">{mode === 'simple'
            ? <>You set the total, <strong style={{ color: 'var(--violet)' }}>LOCALACT manages the mix</strong>, rebalancing monthly on performance, competition, testing, and impression share. Every move is logged below.</>
            : <>Adjust paid-media spend per channel, no monthly auto-rebalancing. Lenny models impact live and shows where you sit vs. <strong style={{ color: 'var(--violet)' }}>FreshNest peer medians</strong>.</>
          }</div>
        </div>
        <div className="page-actions" style={{ alignItems: 'center', gap: 12 }}>
          {/* Mode toggle */}
          <div style={{ display: 'inline-flex', background: 'var(--cream-2)', border: '1px solid var(--cream-3)', borderRadius: 999, padding: 3, gap: 2 }}>
            {[
              { k: 'simple', l: 'Smart Budget', sub: 'you set the total' },
              { k: 'advanced', l: 'Self-managed', sub: 'per channel' }
            ].map(o => (
              <button key={o.k} onClick={() => pickMode(o.k)}
                style={{
                  background: mode === o.k ? 'var(--paper)' : 'transparent',
                  color: mode === o.k ? 'var(--ink)' : 'var(--ink-3)',
                  border: 'none',
                  borderRadius: 999,
                  padding: '6px 14px',
                  fontSize: 12,
                  fontWeight: 600,
                  cursor: 'pointer',
                  boxShadow: mode === o.k ? '0 1px 3px rgba(0,0,0,0.08)' : 'none',
                  display: 'inline-flex',
                  alignItems: 'baseline',
                  gap: 6
                }}>
                <span>{o.l}</span>
                <span style={{ fontSize: 10, color: mode === o.k ? 'var(--ink-4)' : 'var(--ink-4)', fontWeight: 400 }}>· {o.sub}</span>
              </button>
            ))}
          </div>
          <DropMenu value="apr" onPick={(v) => T('Month switched', v === 'apr' ? 'Showing April 2026' : v === 'mar' ? 'Showing March 2026' : 'Showing Feb 2026', 'info')} options={[
          { v: 'apr', l: 'April 2026' }, { v: 'mar', l: 'March 2026' }, { v: 'feb', l: 'February 2026' }]
          } />
          {mode === 'advanced' && <button className="btn btn-primary btn-sm" disabled={!dirty} style={{ opacity: dirty ? 1 : 0.5, cursor: dirty ? 'pointer' : 'default' }}
          onClick={() => {if (dirty) T('Budget saved', `Changes applied. Lenny is rebalancing bids now.`, 'ok');}}>
            {dirty ? 'Save changes' : 'No changes'}
          </button>}
        </div>
      </div>

      {confirmSelfM && <window.SelfManagedConfirmModal onCancel={() => setConfirmSelfM(false)} onConfirm={() => { setConfirmSelfM(false); setMode('advanced'); }} />}

      {mode === 'simple' ? (
        <window.BudgetSimpleMode
          initiatives={budgetInits.map(s => ({ ...s, cpl: PEER_MEDIAN[s.key] ? Math.round((s.localBudget || PEER_MEDIAN[s.key]) / Math.max(8, (s.localBudget || PEER_MEDIAN[s.key]) / 30)) : 30 }))}
          initialTotal={Object.values(localSpend).reduce((a, b) => a + b, 0) || null}
          onCommit={commitSimple}
        />
      ) : (
      <>
      

      {/* ===== Pacing hero, full width, big numbers ===== */}
      <div className="card card-pad" style={{ marginBottom: 20, background: 'linear-gradient(135deg, var(--cream-2), var(--cream))' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1px 1fr 1px 1fr 1px 1fr', gap: 24, alignItems: 'stretch' }}>
          {/* Spent / total */}
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700 }}>April paid spend · pacing</div>
              <span className={'badge ' + (onPace ? 'badge-ok' : forecastDelta > 0 ? 'badge-warn' : 'badge-info')}>
                ● {onPace ? 'On pace' : forecastDelta > 0 ? 'Pacing over' : 'Pacing under'}
              </span>
            </div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 12 }}>
              <div style={{ fontFamily: 'var(--ff-display)', fontSize: 48, fontWeight: 500, letterSpacing: '-0.03em', lineHeight: 1, color: 'var(--ink)' }}>${spentDollars.toLocaleString()}</div>
              <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>spent of <strong style={{ color: 'var(--ink-2)', fontFamily: 'var(--ff-mono)' }}>${paidTotal.toLocaleString()}</strong></div>
            </div>
            {/* Pacing bar w/ elapsed tick */}
            <div style={{ position: 'relative', height: 10, background: 'var(--paper)', borderRadius: 5, overflow: 'hidden', marginBottom: 8, border: '1px solid var(--cream-3)' }}>
              <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: spentPct + '%', background: 'linear-gradient(90deg, var(--terra), var(--marigold))', borderRadius: 5 }} />
              {/* elapsed tick */}
              <div style={{ position: 'absolute', left: elapsedPct + '%', top: -2, bottom: -2, width: 2, background: 'var(--ink-3)', transform: 'translateX(-1px)' }} title={`Day ${dayOf} of ${totalDays}`} />
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--ink-4)', fontFamily: 'var(--ff-mono)' }}>
              <span><strong style={{ color: 'var(--ink-3)' }}>{spentPct}%</strong> spent</span>
              <span style={{ color: 'var(--ink-3)' }}>Day {dayOf} of {totalDays} · {elapsedPct}% elapsed</span>
              <span><strong style={{ color: 'var(--ink-3)' }}>${remainingDollars.toLocaleString()}</strong> left</span>
            </div>
          </div>

          <div style={{ background: 'var(--cream-3)' }} />

          {/* Forecast */}
          <div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 8 }}>Run-rate forecast</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 28, fontWeight: 500, color: 'var(--ink)', lineHeight: 1, marginBottom: 4 }}>${forecast.toLocaleString()}</div>
            <div style={{ fontSize: 11.5, color: forecastDelta > 0 ? 'var(--terra)' : forecastDelta < 0 ? '#917200' : 'var(--sage)', fontWeight: 600, marginBottom: 6 }}>
              {forecastDelta > 0 ? '↑' : forecastDelta < 0 ? '↓' : '→'} ${Math.abs(forecastDelta).toLocaleString()} vs budget
            </div>
            <div style={{ fontSize: 11, color: 'var(--ink-4)', lineHeight: 1.5 }}>At ${Math.round(dailyPace).toLocaleString()}/day. Need <strong style={{ color: 'var(--ink-3)' }}>${dailyTargetRest.toLocaleString()}/day</strong> to land on budget.</div>
          </div>

          <div style={{ background: 'var(--cream-3)' }} />

          {/* All-in monthly */}
          <div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 8 }}>All-in monthly bill</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 28, fontWeight: 500, color: 'var(--ink)', lineHeight: 1, marginBottom: 8 }}>${allInTotal.toLocaleString()}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-4)', lineHeight: 1.6 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Paid media</span><strong style={{ color: 'var(--ink-3)', fontFamily: 'var(--ff-mono)' }}>${paidTotal.toLocaleString()}</strong></div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Mgmt fees</span><strong style={{ color: 'var(--ink-3)', fontFamily: 'var(--ff-mono)' }}>${flatTotal.toLocaleString()}</strong></div>
            </div>
          </div>

          <div style={{ background: 'var(--cream-3)' }} />

          {/* Corporate-funded on top */}
          <div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 8, display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ fontSize: 9, padding: '1px 5px', borderRadius: 3, background: 'var(--brand-navy)', color: 'var(--cream)', fontWeight: 700 }}>CORP</span>
              On top of yours
            </div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 28, fontWeight: 500, color: 'var(--ink-2)', lineHeight: 1, marginBottom: 6 }}>${corpTotal.toLocaleString()}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-4)', lineHeight: 1.5 }}>Corporate-funded brand media boosting your local plays. <strong style={{ color: 'var(--ink-3)' }}>Combined: ${(allInTotal + corpTotal).toLocaleString()}/mo</strong></div>
          </div>
        </div>
      </div>

      {/* ===== Lenny projection ===== */}
      <div className="card card-pad" style={{ marginBottom: 24, background: 'var(--ink)', color: 'var(--cream)', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: -40, right: -40, width: 220, height: 220, background: 'radial-gradient(circle, rgba(206,158,7,.18), transparent 70%)' }} />
        <div style={{ position: 'relative', zIndex: 1, display: 'grid', gridTemplateColumns: '1fr auto', gap: 24, alignItems: 'center' }}>
          <div style={{ display: 'grid', gap: 10 }}>
            {[
            ['Lenny recommends', 'Add $150/mo to Local Google Search Program.'],
            ['Why', "You're spending 12% below the FreshNest peer median on Search, the cheapest, highest-intent channel for cleaning leads."],
            ['Expected impact', '+8 leads/mo at your $34 CPL → ~3 booked jobs worth ~$1,800 in revenue. Moves you from 12% below to 3% above peer median.']].
            map(([label, copy]) =>
            <div key={label} style={{ display: 'grid', gridTemplateColumns: '140px 1fr', gap: 14, alignItems: 'baseline' }}>
                <div style={{ fontSize: 10.5, letterSpacing: '.08em', textTransform: 'uppercase', color: 'rgba(250,246,239,.5)', fontWeight: 700 }}>{label}</div>
                <div style={{ fontSize: 13, color: 'var(--cream)', lineHeight: 1.5 }}>{copy}</div>
              </div>
            )}
            <div style={{ display: 'grid', gridTemplateColumns: '140px 1fr', gap: 14, alignItems: 'center' }}>
              <div style={{ fontSize: 10.5, letterSpacing: '.08em', textTransform: 'uppercase', color: 'rgba(250,246,239,.5)', fontWeight: 700 }}>Action</div>
              <div>
                <button className="btn btn-sm" style={{ background: 'var(--terra)', color: 'var(--cream)', whiteSpace: 'nowrap' }} onClick={() => {setOne('gs-local', (localSpend['gs-local'] || 0) + 150);T('Recommendation applied', 'Local Google Search Program bumped by $150. Save to confirm.', 'ok');}}>Apply +$150 →</button>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* ===== Mix analysis: you vs peers ===== */}
      <div className="section-label">Your mix vs system <span className="count">how every FreshNest location averages this spend</span></div>
      <div className="card card-pad" style={{ marginBottom: 24 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32 }}>
          {/* Your mix */}
          <div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', fontWeight: 600, marginBottom: 10 }}>Your spend mix · ${paidTotal.toLocaleString()}/mo</div>
            <MixBar items={yourMixPcts.map((m) => ({ name: m.name, color: m.color, pct: m.yourPct, val: m.your }))} />
            <div style={{ marginTop: 12, display: 'grid', gap: 6 }}>
              {yourMixPcts.map((m) =>
              <div key={m.key} style={{ display: 'grid', gridTemplateColumns: '14px 1fr auto auto', gap: 8, alignItems: 'center', fontSize: 11.5 }}>
                  <span style={{ width: 10, height: 10, borderRadius: 2, background: m.color }} />
                  <span style={{ color: 'var(--ink-2)' }}>{m.name}</span>
                  <span style={{ fontFamily: 'var(--ff-mono)', color: 'var(--ink-3)' }}>{Math.round(m.yourPct)}%</span>
                  <span style={{ fontFamily: 'var(--ff-mono)', color: 'var(--ink-3)', minWidth: 50, textAlign: 'right' }}>${m.your}</span>
                </div>
              )}
            </div>
          </div>
          {/* Peer mix */}
          <div>
            <div style={{ fontSize: 12, color: 'var(--violet)', fontWeight: 600, marginBottom: 10 }}>FreshNest peer median · ${peerTotalMix.toLocaleString()}/mo</div>
            <MixBar items={yourMixPcts.map((m) => ({ name: m.name, color: m.color, pct: m.peerPct, val: m.peer }))} faded />
            <div style={{ marginTop: 12, display: 'grid', gap: 6 }}>
              {yourMixPcts.map((m) => {
                const delta = m.your - m.peer;
                return (
                  <div key={m.key} style={{ display: 'grid', gridTemplateColumns: '14px 1fr auto auto', gap: 8, alignItems: 'center', fontSize: 11.5 }}>
                    <span style={{ width: 10, height: 10, borderRadius: 2, background: m.color, opacity: 0.5 }} />
                    <span style={{ color: 'var(--ink-3)' }}>{m.name}</span>
                    <span style={{ fontFamily: 'var(--ff-mono)', color: 'var(--ink-3)' }}>{Math.round(m.peerPct)}%</span>
                    <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 11, color: delta > 0 ? 'var(--sage)' : delta < 0 ? '#917200' : 'var(--ink-4)', minWidth: 50, textAlign: 'right' }}>
                      {delta === 0 ? '–' : (delta > 0 ? '+' : '') + '$' + Math.abs(delta)}
                    </span>
                  </div>);

              })}
            </div>
          </div>
        </div>
        <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px dashed var(--cream-3)' }}>
          {paidTotal < peerTotalMix ?
          <div style={{ display: 'grid', gap: 8 }}>
              {[
            ['Lenny recommends', `Bring your monthly mix up to the FreshNest peer median of $${peerTotalMix.toLocaleString()}/mo.`],
            ['Why', `You're spending $${Math.abs(paidTotal - peerTotalMix).toLocaleString()}/mo less than the typical FreshNest location. Underspending on the proven channel mix is the #1 reason peer locations outperform you.`],
            ['Expected impact', '+12 to 18 leads/mo, based on what 22 similar peers see when they hit median spend.']].
            map(([label, copy]) =>
            <div key={label} style={{ display: 'grid', gridTemplateColumns: '140px 1fr', gap: 14, alignItems: 'baseline' }}>
                  <div style={{ fontSize: 10.5, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 700 }}>{label}</div>
                  <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.5 }}>{copy}</div>
                </div>
            )}
              <div style={{ display: 'grid', gridTemplateColumns: '140px 1fr', gap: 14, alignItems: 'center' }}>
                <div style={{ fontSize: 10.5, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 700 }}>Action</div>
                <div>
                  <button className="btn btn-ghost btn-xs" onClick={() => {const next = {};budgetInits.forEach((s) => {next[s.key] = PEER_MEDIAN[s.key] || localSpend[s.key] || 0;});setLocalSpend(next);T('Matched peer median', `All channels set to FreshNest median.`, 'ok');}}>Match peer median →</button>
                </div>
              </div>
            </div> :

          <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 12, color: 'var(--ink-3)' }}>
              <span style={{ fontSize: 16 }}>→</span>
              <span>You're <strong style={{ color: 'var(--ink)' }}>${Math.abs(paidTotal - peerTotalMix).toLocaleString()}/mo above</strong> the peer median. Spending above median, efficiency matters more than volume here.</span>
            </div>
          }
        </div>
      </div>

      {/* ===== Per-channel allocation sliders ===== */}
      <div className="section-label">Channel allocation <span className="count">drag to adjust · save to apply</span></div>
      <div className="grid grid-3">
        {budgetInits.map((s) => {
          const c = cfg(s);
          return (
            <BudgetSlider key={s.key} svc={s} v={localSpend[s.key] || 0} setV={(v) => setOne(s.key, v)} min={c.min} max={c.max} peer={c.peer} optimal={c.optimal} />);

        })}
      </div>

      {/* ===== Not-yet-enrolled channels (bare variant only) ===== */}
      {data.variant === 'bare' && (() => {
        const dormantBudgetSvcs = data.services.filter((s) =>
        !s.enrolled && (s.audience === 'Locations All' || s.audience === 'Locations Limited') && s.key !== 'localact' && (
        s.type === 'Budget Based' || s.type === 'Flat Fee')
        );
        if (dormantBudgetSvcs.length === 0) return null;
        return (
          <>
            <div className="section-label" style={{ marginTop: 28 }}>
              Not yet enrolled
              <span className="count">{dormantBudgetSvcs.length} channels with $0 actual spend · brand-recommended targets shown</span>
            </div>
            <div className="card card-pad" style={{ padding: 0, overflow: 'hidden' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                <thead>
                  <tr style={{ background: 'var(--cream)', textAlign: 'left' }}>
                    <th style={{ padding: '10px 16px', fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-3)', fontWeight: 700 }}>Channel</th>
                    <th style={{ padding: '10px 16px', fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-3)', fontWeight: 700, textAlign: 'right' }}>Actual</th>
                    <th style={{ padding: '10px 16px', fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-3)', fontWeight: 700, textAlign: 'right' }}>Brand target</th>
                    <th style={{ padding: '10px 16px', fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-3)', fontWeight: 700 }}>Status</th>
                    <th style={{ padding: '10px 16px', fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-3)', fontWeight: 700, textAlign: 'right' }} />
                  </tr>
                </thead>
                <tbody>
                  {dormantBudgetSvcs.map((s, i) => {
                    const target = PEER_MEDIAN[s.key] || s.fee || 0;
                    return (
                      <tr key={s.key} style={{ borderTop: i === 0 ? 'none' : '1px solid var(--line)' }}>
                        <td style={{ padding: '14px 16px' }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                            <span style={{ width: 10, height: 10, borderRadius: '50%', background: s.color, opacity: 0.55 }} />
                            <div>
                              <div style={{ fontWeight: 600, color: 'var(--ink)' }}>{s.name}</div>
                              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 1 }}>{s.product}</div>
                            </div>
                          </div>
                        </td>
                        <td style={{ padding: '14px 16px', textAlign: 'right', fontFamily: 'var(--ff-mono)', fontSize: 13, color: 'var(--ink-3)' }}>$0</td>
                        <td style={{ padding: '14px 16px', textAlign: 'right', fontFamily: 'var(--ff-mono)', fontSize: 13, color: 'var(--violet)', fontWeight: 600 }}>${target.toLocaleString()}/mo</td>
                        <td style={{ padding: '14px 16px' }}>
                          <span className="badge" style={{ background: 'var(--cream-2)', color: 'var(--ink-3)', fontSize: 10.5, fontWeight: 700, padding: '3px 8px' }}>● NOT ENROLLED</span>
                        </td>
                        <td style={{ padding: '14px 16px', textAlign: 'right' }}>
                          <button className="btn btn-primary btn-xs" onClick={() => T(`${s.name} requested`, `Strategy Director will reach out to enroll you at $${target}/mo target.`, 'ok')}>Enroll →</button>
                        </td>
                      </tr>);

                  })}
                </tbody>
              </table>
              <div style={{ padding: '12px 16px', background: 'var(--cream)', fontSize: 12, color: 'var(--ink-3)', borderTop: '1px solid var(--line)' }}>
                Pacing math above reflects <strong>Paid Search only</strong>. Targets shown are the brand-recommended starting spend per the playbook.
              </div>
            </div>
          </>);

      })()}
      </>
      )}
    </div>);

}
window.BudgetPage = BudgetPage;

// Stacked horizontal mix bar
function MixBar({ items, faded }) {
  return (
    <div style={{ display: 'flex', height: 22, borderRadius: 11, overflow: 'hidden', border: '1px solid var(--cream-3)' }}>
      {items.map((it, i) => it.pct > 0 &&
      <div key={i} title={`${it.name} · ${Math.round(it.pct)}%`}
      style={{ width: it.pct + '%', background: it.color, opacity: faded ? 0.55 : 1, position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--cream)', fontSize: 10, fontWeight: 700, fontFamily: 'var(--ff-mono)' }}>
          {it.pct >= 8 ? Math.round(it.pct) + '%' : ''}
        </div>
      )}
    </div>);

}

function BudgetSlider({ svc, v, setV, min, max, peer, optimal }) {
  const color = svc.color;
  const clamped = Math.max(min, Math.min(max, v));
  const pct = (clamped - min) / (max - min) * 100;
  const peerPct = peer != null ? (peer - min) / (max - min) * 100 : null;
  const corp = svc.corporateBudget || 0;
  const peerDelta = peer != null ? v - peer : 0;
  return (
    <div className="card card-pad">
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, marginBottom: 4 }}>
        <span style={{ width: 10, height: 10, borderRadius: '50%', background: color, marginTop: 5, flexShrink: 0 }} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)', lineHeight: 1.25 }}>{svc.name}</div>
          <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>{svc.product}</div>
        </div>
        {peer != null &&
        <span style={{ fontSize: 10, fontWeight: 700, padding: '3px 7px', borderRadius: 999,
          background: Math.abs(peerDelta) < 50 ? 'var(--sage-soft)' : peerDelta < 0 ? 'var(--marigold-soft)' : 'var(--sky-soft)',
          color: Math.abs(peerDelta) < 50 ? '#085050' : peerDelta < 0 ? '#917200' : 'var(--sky)' }}>
            {Math.abs(peerDelta) < 50 ? 'AT PEER' : peerDelta < 0 ? `${Math.round(peerDelta / peer * 100)}%` : `+${Math.round(peerDelta / peer * 100)}%`}
          </span>
        }
      </div>

      {/* Dual values */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginTop: 12, marginBottom: 12 }}>
        <div>
          <div style={{ fontSize: 10, color: 'var(--ink-4)', fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase' }}>Your spend</div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 28, fontWeight: 500, color: 'var(--ink)', letterSpacing: '-0.02em', lineHeight: 1 }}>${v.toLocaleString()}<span style={{ fontSize: 11, color: 'var(--ink-4)', fontWeight: 400 }}>/mo</span></div>
        </div>
        {corp > 0 ?
        <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 10, color: 'var(--ink-4)', fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase' }}>Corp <span style={{ opacity: 0.6 }}>(fixed)</span></div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 500, color: 'var(--ink-3)', lineHeight: 1 }}>${corp.toLocaleString()}<span style={{ fontSize: 10, color: 'var(--ink-4)' }}>/mo</span></div>
          </div> :
        peer != null &&
        <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 10, color: 'var(--violet)', fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase' }}>Peer median</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 500, color: 'var(--violet)', lineHeight: 1 }}>${peer.toLocaleString()}<span style={{ fontSize: 10, color: 'var(--ink-4)' }}>/mo</span></div>
          </div>
        }
      </div>

      {/* Slider w/ peer tick */}
      <div style={{ position: 'relative' }}>
        <input type="range" min={min} max={max} step={10} value={clamped} onChange={(e) => setV(+e.target.value)}
        style={{ width: '100%', WebkitAppearance: 'none', height: 6, borderRadius: 3, outline: 'none', position: 'relative', zIndex: 1,
          background: `linear-gradient(to right, ${color} 0%, ${color} ${pct}%, var(--cream-2) ${pct}%, var(--cream-2) 100%)` }} />
        {/* peer median tick */}
        {peerPct != null &&
        <div style={{ position: 'absolute', left: peerPct + '%', top: -4, bottom: -4, width: 2, background: 'var(--violet)', transform: 'translateX(-1px)', pointerEvents: 'none', borderRadius: 1 }} title={`Peer median $${peer}`} />
        }
      </div>
      <style>{`input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; width: 18px; height: 18px; border-radius: 50%; background: var(--paper); border: 3px solid ${color}; cursor: pointer; box-shadow: 0 2px 6px rgba(0,0,0,.15); }`}</style>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, color: 'var(--ink-4)', marginTop: 10, fontFamily: 'var(--ff-mono)' }}>
        <span>${min}</span>
        <span style={{ color: 'var(--violet)', fontWeight: 600 }}>{peer ? `Peer $${peer}` : `Optimal: ${optimal}`}</span>
        <span>${max}</span>
      </div>

      {/* Quick actions */}
      {peer != null && Math.abs(v - peer) >= 50 &&
      <button className="btn btn-quiet btn-xs" style={{ width: '100%', marginTop: 10, padding: '6px 8px', justifyContent: 'center' }}
      onClick={() => setV(peer)}>
          Match peer median (${peer})
        </button>
      }

      <div style={{ marginTop: 12, paddingTop: 10, borderTop: '1px solid var(--cream-2)', display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--ink-3)' }}>
        <span>Combined monthly</span>
        <strong style={{ color: 'var(--ink-2)', fontFamily: 'var(--ff-mono)' }}>${(v + corp).toLocaleString()}</strong>
      </div>
    </div>);

}

// ====================================================================
// LISTINGS, see listings.jsx (rich tabbed page)
// ====================================================================
function ListingsPage_DEPRECATED({ data }) {
  const [editing, setEditing] = useStateP(false);
  const [fixing, setFixing] = useStateP(false);
  const [dirDetail, setDirDetail] = useStateP(null);
  const [scanning, setScanning] = useStateP(false);
  const [businessName, setBusinessName] = useStateP("FreshNest, Austin Downtown");
  const [phone, setPhone] = useStateP('(512) 555-0142');
  const [addr, setAddr] = useStateP('204 E 6th St, Austin, TX 78701');

  const scan = () => {
    setScanning(true);
    T('Scanning 42 directories…', 'This runs in the background, I\'ll ping you.', 'info');
    setTimeout(() => {setScanning(false);T('Scan complete', '40 live · 2 issues queued for auto-fix', 'ok');}, 2000);
  };

  return (
    <div className="page active">
      <div className="page-header">
        <div>
          <div className="page-title">Listings &amp; Local Presence.</div>
          <div className="page-sub">42 directories monitored daily. Updates push in minutes.</div>
        </div>
        <div className="page-actions">
          <button className="btn btn-ghost btn-sm" onClick={scan} disabled={scanning}>{scanning ? 'Scanning…' : 'Scan now'}</button>
          <button className="btn btn-primary btn-sm" onClick={() => setEditing(true)}>Edit my info</button>
        </div>
      </div>

      <div className="grid grid-4" style={{ marginBottom: 20 }}>
        <div className="card card-pad" style={{ background: 'linear-gradient(135deg, var(--ink), #2a2a2b)', color: 'var(--cream)', border: 'none' }}>
          <div style={{ fontSize: 10.5, letterSpacing: '.08em', textTransform: 'uppercase', color: 'rgba(250,246,239,.5)', marginBottom: 6 }}>Listing Score</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 44, fontWeight: 500, lineHeight: 1 }}>82</div>
            <div style={{ fontSize: 12, color: 'var(--sage)' }}>↑ 4 this wk</div>
          </div>
          <div style={{ fontSize: 11, color: 'rgba(250,246,239,.5)', marginTop: 8 }}>Top 24% in FreshNest system</div>
        </div>
        <StatCard l="Live directories" v="40" sub="of 42" c="var(--ok)" bar={40 / 42 * 100} />
        <StatCard l="Issues" v="2" sub="Yelp + GBP" c="var(--warn)" />
        <StatCard l="NAP Accuracy" v="98%" sub="checked daily" c="var(--sage)" bar={98} />
      </div>

      <div style={{ background: 'var(--marigold-soft)', border: '1px solid var(--marigold)', borderRadius: 14, padding: '16px 20px', marginBottom: 20, display: 'flex', gap: 14, alignItems: 'center' }}>
        <div style={{ width: 44, height: 44, background: 'var(--paper)', borderRadius: '50%', border: '2px solid var(--marigold)', overflow: 'hidden', flexShrink: 0 }}>
          <LennyLlama size={44} mood="alert" bg="circle" />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: '#725900' }}>2 issues found, I've queued fixes</div>
          <div style={{ fontSize: 12.5, color: '#ad8406', marginTop: 2 }}><strong>Google Sunday hours</strong> (auto-syncing in 4 hrs) · <strong>GBP URL missing</strong> (needs your input)</div>
        </div>
        <button className="btn btn-terra btn-sm" onClick={() => setFixing(true)}>Fix all issues →</button>
      </div>

      <div className="section-label">Directories we control <span className="count">Direct API</span></div>
      <div className="card" style={{ overflow: 'hidden', marginBottom: 20 }}>
        <table className="tbl">
          <thead><tr><th>Directory</th><th>Type</th><th>Status</th><th>Last sync</th><th>Fields</th><th /></tr></thead>
          <tbody>
            {data.listings.filter((l) => l.controlled).map((l, i) =>
            <tr key={i} onClick={() => setDirDetail(l)} style={{ cursor: 'pointer' }}>
                <td className="strong">{l.name}</td>
                <td><span className="badge badge-neutral">{l.type}</span></td>
                <td><span className={`badge ${l.status === 'live' ? 'badge-ok' : 'badge-warn'}`}>{l.status === 'live' ? '● Live' : '⚠ Issue'}</span></td>
                <td className="mono muted">{l.lastSync}</td>
                <td className="mono">{l.fields}</td>
                <td><button className="btn btn-quiet btn-xs" onClick={(e) => {e.stopPropagation();setDirDetail(l);}}>View</button></td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      <div className="section-label">Directories we influence <span className="count">3rd-party cadence</span></div>
      <div className="card" style={{ overflow: 'hidden' }}>
        <table className="tbl">
          <thead><tr><th>Directory</th><th>Type</th><th>Status</th><th>Last sync</th><th>Fields</th><th /></tr></thead>
          <tbody>
            {data.listings.filter((l) => !l.controlled).map((l, i) =>
            <tr key={i}>
                <td className="strong">{l.name}</td>
                <td><span className="badge badge-neutral">{l.type}</span></td>
                <td><span className={`badge ${l.status === 'live' ? 'badge-ok' : 'badge-warn'}`}>{l.status === 'live' ? '● Live' : '⚠ Drift'}</span></td>
                <td className="mono muted">{l.lastSync}</td>
                <td className="mono">{l.fields}</td>
                <td><button className="btn btn-quiet btn-xs" onClick={() => T('Force sync queued', `${l.name} will sync in ~15 min.`, 'info')}>Force sync</button></td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      <Modal open={editing} onClose={() => setEditing(false)} title="Edit business info" sub="Changes push to all 42 directories"
      footer={<>
          <button className="btn btn-ghost btn-sm" onClick={() => setEditing(false)}>Cancel</button>
          <button className="btn btn-primary btn-sm" onClick={() => {setEditing(false);T('Pushing updates', '42 directories being synced. ETA: 8 minutes.', 'ok');}}>Push to all directories</button>
        </>}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {[['Business name', businessName, setBusinessName], ['Phone', phone, setPhone], ['Address', addr, setAddr]].map(([l, v, set], i) =>
          <div key={i}>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 600, marginBottom: 4 }}>{l}</div>
              <input value={v} onChange={(e) => set(e.target.value)} style={{ width: '100%', padding: '10px 12px', fontSize: 13, fontFamily: 'var(--ff-ui)', border: '1px solid var(--cream-3)', borderRadius: 8, background: 'var(--paper)' }} />
            </div>
          )}
        </div>
      </Modal>

      <Modal open={fixing} onClose={() => setFixing(false)} title="Fix 2 issues" sub="Lenny's draft, approve to push"
      footer={<>
          <button className="btn btn-ghost btn-sm" onClick={() => setFixing(false)}>Close</button>
          <button className="btn btn-terra btn-sm" onClick={() => {setFixing(false);T('Fixes queued', 'Yelp auto-sync in 4h · GBP update pushed now.', 'ok');}}>Approve &amp; push</button>
        </>}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div style={{ padding: '12px 14px', background: 'var(--marigold-soft)', borderRadius: 10 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: '#725900', marginBottom: 4 }}>Google, Sunday hours drift</div>
            <div style={{ fontSize: 12, color: 'var(--ink-2)' }}>Currently: 11am–8pm · Fix: 11am–9pm</div>
          </div>
          <div style={{ padding: '12px 14px', background: 'var(--terra-soft)', borderRadius: 10 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: '#8c4a13', marginBottom: 4 }}>Google Business Profile, missing URL</div>
            <div style={{ fontSize: 12, color: 'var(--ink-2)' }}>Proposed: https://freshnest.com/austin-downtown</div>
          </div>
        </div>
      </Modal>

      <Modal open={!!dirDetail} onClose={() => setDirDetail(null)} title={dirDetail?.name} sub={`Last sync: ${dirDetail?.lastSync}`}>
        {dirDetail &&
        <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.7 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '100px 1fr', gap: '8px 14px', marginBottom: 14 }}>
              <div style={{ color: 'var(--ink-3)' }}>Type</div><div>{dirDetail.type}</div>
              <div style={{ color: 'var(--ink-3)' }}>Status</div><div>{dirDetail.status === 'live' ? '● Live' : '⚠ Issue'}</div>
              <div style={{ color: 'var(--ink-3)' }}>Fields synced</div><div className="mono">{dirDetail.fields}</div>
            </div>
            <div style={{ padding: '12px 14px', background: 'var(--cream)', borderRadius: 10, fontSize: 12, color: 'var(--ink-3)' }}>
              We hold a direct API connection, edits sync in under 4 minutes.
            </div>
          </div>
        }
      </Modal>
    </div>);

}
// (ListingsPage_DEPRECATED kept for reference; live page is in listings.jsx)

function StatCard({ l, v, sub, c, bar }) {
  return (
    <div className="card card-pad">
      <div style={{ fontSize: 10.5, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 600, marginBottom: 6 }}>{l}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
        <div style={{ fontFamily: 'var(--ff-display)', fontSize: 32, fontWeight: 500, color: c || 'var(--ink)' }}>{v}</div>
        {sub && <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{sub}</div>}
      </div>
      {bar !== undefined &&
      <div style={{ height: 4, background: 'var(--cream-2)', borderRadius: 2, marginTop: 10, overflow: 'hidden' }}>
          <div style={{ width: bar + '%', height: '100%', background: c }} />
        </div>
      }
    </div>);

}
window.StatCard = StatCard;

// ====================================================================
// AUTO MODE, AI agent for review responses (franchisee add-on / upsell)
// Lenny replies automatically inside guardrails the operator sets.
// Two states: locked upsell pitch, and configured/active.
// ====================================================================
function AutoModeCard() {
  const [enabled, setEnabled] = useStateP(false);
  const [confirm, setConfirm] = useStateP(false);
  const [dismissed, setDismissed] = useStateP(false);
  const [threshold, setThreshold] = useStateP(4);
  const [rules, setRules] = useStateP({
    noEmDash: true,
    brandStandards: true,
    routeAggressive: true,
    notifyGlowing: true,
  });
  const toggle = (k) => setRules((r) => ({ ...r, [k]: !r[k] }));

  const GUIDELINES = [
    { k: 'noEmDash',       label: 'Never use em dashes',            sub: 'Match your brand writing style' },
    { k: 'brandStandards', label: 'Follow brand standards',         sub: 'Pull tone and phrasing from the brand guide' },
    { k: 'routeAggressive',label: 'Route aggressive reviews to me', sub: '1\u20132\u2605 or hostile reviews go to you, never auto-answered' },
    { k: 'notifyGlowing',  label: 'Notify me on glowing reviews',   sub: 'Ping me on 5\u2605 so I can add a personal touch' },
  ];

  // ---- Dismissed ----
  if (dismissed) return null;

  // ---- Locked upsell pitch ----
  if (!enabled) {
    return (
      <React.Fragment>
        <div className="section-label">Auto mode <span className="count" style={{ background: 'var(--violet-soft, #ece9fb)', color: 'var(--violet)' }}>Coming in Phase II</span></div>
        <div className="card card-pad" style={{ position: 'relative', background: 'linear-gradient(135deg, var(--ink) 0%, #2a2a2b 100%)', color: 'var(--cream)', border: 'none', marginBottom: 20, display: 'flex', gap: 18, alignItems: 'flex-start' }}>
          <button title="Dismiss, I’m not interested" onClick={() => { setDismissed(true); T('Hidden', 'We won’t show Auto mode again. Find it later under the Playbook.', 'info'); }}
            style={{ position: 'absolute', top: 12, right: 14, width: 26, height: 26, borderRadius: '50%', border: 'none', background: 'rgba(250,246,239,.12)', color: 'rgba(250,246,239,.7)', fontSize: 15, lineHeight: 1, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>×</button>
          <div style={{ width: 44, height: 44, borderRadius: '50%', overflow: 'hidden', flexShrink: 0, background: 'var(--paper)', border: '1.5px solid rgba(250,246,239,.3)' }}>
            <window.LennyLlama size={44} mood="happy" bg="circle"/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
              <span style={{ fontSize: 10.5, letterSpacing: '.1em', textTransform: 'uppercase', color: 'rgba(250,246,239,.5)', fontWeight: 700 }}>New · AI agent</span>
              <span style={{ fontSize: 10, letterSpacing: '.08em', textTransform: 'uppercase', fontWeight: 700, color: '#cbb7f5', background: 'rgba(139,110,232,.22)', padding: '2px 8px', borderRadius: 999 }}>Phase II preview</span>
            </div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 19, fontWeight: 600, color: 'var(--cream)', letterSpacing: '-0.01em', marginBottom: 6 }}>Let Lenny reply for you, automatically</div>
            <div style={{ fontSize: 13.5, lineHeight: 1.6, color: 'rgba(250,246,239,.82)', marginBottom: 14, maxWidth: 620 }}>
              Auto mode replies to new reviews within minutes, inside guardrails you set. You stay in control: aggressive reviews route to you, and every reply follows your brand voice.
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px 22px', marginBottom: 16, maxWidth: 620 }}>
              {GUIDELINES.map((g) => (
                <div key={g.k} style={{ display: 'flex', alignItems: 'flex-start', gap: 8, fontSize: 12.5, color: 'rgba(250,246,239,.9)' }}>
                  <span style={{ color: 'var(--sage)', fontWeight: 700, flexShrink: 0 }}>✓</span>
                  <span>{g.label}</span>
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
              <button className="btn btn-primary btn-sm" onClick={() => T('You’re on the list', 'We’ll let you know the moment Auto mode ships in Phase II.', 'ok')}>Notify me at launch</button>
              <button className="btn btn-sm" style={{ background: 'rgba(250,246,239,.12)', color: 'var(--cream)', border: 'none' }} onClick={() => setConfirm(true)}>Preview the setup</button>
              <span style={{ fontSize: 11.5, color: 'rgba(250,246,239,.55)' }}>Planned at $29/mo · launching Phase II</span>
            </div>
          </div>
        </div>

        <Modal open={confirm} onClose={() => setConfirm(false)} title="Preview Auto mode" sub="A look at the Phase II setup, not live yet" width={480}
          footer={<>
            <button className="btn btn-ghost btn-sm" onClick={() => setConfirm(false)}>Close</button>
            <button className="btn btn-primary btn-sm" onClick={() => { setEnabled(true); setConfirm(false); T('Preview enabled', 'This is how Auto mode will look once it ships in Phase II.', 'ok'); }}>Preview the setup</button>
          </>}>
          <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.6 }}>
            Auto mode ships in Phase II. This preview shows the guardrails you’ll be able to set, reviews at or below your routing threshold always come to you first.
          </div>
        </Modal>
      </React.Fragment>
    );
  }

  // ---- Configured / active ----
  return (
    <React.Fragment>
      <div className="section-label">Auto mode <span className="count" style={{ background: 'var(--violet-soft, #ece9fb)', color: 'var(--violet)' }}>Phase II preview</span></div>
      <div className="card card-pad" style={{ marginBottom: 20 }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14, marginBottom: 16 }}>
          <div style={{ width: 40, height: 40, borderRadius: '50%', overflow: 'hidden', flexShrink: 0, background: 'var(--cream-2)' }}>
            <window.LennyLlama size={40} mood="happy" bg="circle"/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 600, color: 'var(--ink)' }}>How Auto mode will work</div>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, fontWeight: 700, color: 'var(--violet)', background: 'var(--violet-soft, #ece9fb)', padding: '2px 9px', borderRadius: 999 }}>Preview</span>
            </div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 3 }}>Set your guardrails now, Lenny starts replying once Auto mode ships in Phase II</div>
          </div>
          <button className="btn btn-ghost btn-sm" onClick={() => { setEnabled(false); T('Preview closed', 'Auto mode will be available in Phase II.', 'info'); }}>Close preview</button>
        </div>

        <div style={{ borderTop: '1px solid var(--cream-2)', paddingTop: 14 }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 10 }}>Guardrails</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px 22px', marginBottom: 16 }}>
            {GUIDELINES.map((g) => {
              const on = rules[g.k];
              return (
                <div key={g.k} onClick={() => toggle(g.k)} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, cursor: 'pointer' }}>
                  <span style={{ width: 34, height: 20, borderRadius: 999, background: on ? 'var(--sage)' : 'var(--cream-3)', flexShrink: 0, position: 'relative', transition: 'background .15s' }}>
                    <span style={{ position: 'absolute', top: 2, left: on ? 16 : 2, width: 16, height: 16, borderRadius: '50%', background: '#fff', boxShadow: '0 1px 2px rgba(0,0,0,.2)', transition: 'left .15s' }}/>
                  </span>
                  <div>
                    <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink)' }}>{g.label}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-4)', lineHeight: 1.45 }}>{g.sub}</div>
                  </div>
                </div>
              );
            })}
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>Auto-reply to reviews rated</span>
            <div style={{ display: 'flex', gap: 4 }}>
              {[5, 4, 3].map((n) => (
                <button key={n} onClick={() => setThreshold(n)} className="btn btn-sm"
                  style={{ padding: '5px 11px', border: threshold === n ? '1.5px solid var(--sage)' : '1px solid var(--cream-3)', background: threshold === n ? 'var(--sage-soft)' : 'var(--paper)', color: threshold === n ? '#3a6b3a' : 'var(--ink-2)', fontWeight: 700 }}>
                  {n}★+
                </button>
              ))}
            </div>
            <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>and above. Anything lower routes to you.</span>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}

// ====================================================================
// REVIEWS
// ====================================================================
function ReviewsPage({ data }) {
  const [platform, setPlatform] = useStateP('all');
  const [drafting, setDrafting] = useStateP(null);
  const [replyText, setReplyText] = useStateP('');
  const [localReviews, setLocalReviews] = useStateP(data.reviews);

  useEffectP(() => {setLocalReviews(data.reviews);}, [data.reviews]);

  const draftReply = (r) => {
    setDrafting(r);
    setReplyText(r.stars >= 4 ?
    `Hi ${r.author.split(' ')[0]}, thank you so much for the kind words! We love serving Austin's downtown crew and can't wait to have you back., Alicia, GM` :
    `Hi ${r.author.split(' ')[0]}, I appreciate you flagging this. This isn't the experience we want anyone to have. I'd love to make it right, I'll DM you directly., Alicia, GM`);
  };

  const submitReply = () => {
    const updated = localReviews.map((x) => x === drafting ? { ...x, replied: true } : x);
    setLocalReviews(updated);
    setDrafting(null);
    T('Reply posted', 'Live on ' + drafting.platform + ' within 2 minutes.', 'ok');
  };

  const filtered = platform === 'all' ? localReviews : localReviews.filter((r) => r.platform.toLowerCase() === platform);
  const needsReply = localReviews.filter((r) => !r.replied);

  return (
    <div className="page active">
      <div className="page-header">
        <div>
          <div className="page-title">Reviews.</div>
          <div className="page-sub">4.8★ across 428 reviews · response time 2.4h</div>
        </div>
        <div className="page-actions">
          <DropMenu value={platform} onPick={setPlatform} options={[
          { v: 'all', l: 'All platforms' }, { v: 'google', l: 'Google' }, { v: 'yelp', l: 'Yelp' }, { v: 'facebook', l: 'Facebook' }]
          } />
          <button className="btn btn-primary btn-sm" onClick={() => {
            if (needsReply.length === 0) {T('All caught up', 'No pending replies.', 'ok');return;}
            draftReply(needsReply[0]);
          }}>Respond with Lenny {needsReply.length > 0 && <span style={{ marginLeft: 4, background: 'rgba(255,255,255,.22)', padding: '1px 6px', borderRadius: 999, fontSize: 10 }}>{needsReply.length}</span>}</button>
        </div>
      </div>

      <div className="grid grid-4" style={{ marginBottom: 20 }}>
        <StatCard l="Avg rating" v="4.8★" c="var(--marigold)" />
        <StatCard l="Total reviews" v="428" sub="+12 this month" c="var(--ink)" />
        <StatCard l="Response rate" v="96%" sub="of 428 reviews" c="var(--sage)" bar={96} />
        <StatCard l="Avg response" v="2.4h" sub="peer avg: 14.2h" c="var(--sage)" />
      </div>

      <AutoModeCard />

      <div className="section-label">Rating distribution</div>
      <div className="card card-pad" style={{ marginBottom: 20 }}>
        {[5, 4, 3, 2, 1].map((s) => {
          const pct = { 5: 82, 4: 12, 3: 4, 2: 1, 1: 1 }[s];
          return (
            <div key={s} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '6px 0' }}>
              <div style={{ fontSize: 12, fontWeight: 600, width: 40, color: 'var(--ink)' }}>{s}★</div>
              <div style={{ flex: 1, height: 6, background: 'var(--cream-2)', borderRadius: 3, overflow: 'hidden' }}>
                <div style={{ width: pct + '%', height: '100%', background: s >= 4 ? 'var(--sage)' : s === 3 ? 'var(--marigold)' : 'var(--terra)' }} />
              </div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', width: 40, textAlign: 'right' }}>{pct}%</div>
            </div>);

        })}
      </div>

      <div className="section-label">Recent reviews <span className="count">{filtered.length} shown</span></div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {filtered.map((r, i) =>
        <div key={i} className="card card-pad">
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
              <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--cream-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 700 }}>{r.author[0]}</div>
              <div>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{r.author}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{r.platform} · {r.time} ago</div>
              </div>
              <div style={{ flex: 1 }} />
              <div style={{ color: 'var(--marigold)', fontSize: 14 }}>{'★'.repeat(r.stars)}<span style={{ color: 'var(--cream-3)' }}>{'★'.repeat(5 - r.stars)}</span></div>
              {r.replied ? <span className="badge badge-ok">Replied</span> : <span className="badge badge-warn">Needs reply</span>}
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.55, paddingLeft: 46 }}>"{r.text}"</div>
            {!r.replied &&
          <div style={{ marginTop: 10, paddingLeft: 46, display: 'flex', gap: 6 }}>
                <button className="btn btn-terra btn-sm" onClick={() => draftReply(r)}>Draft reply with Lenny</button>
                <button className="btn btn-ghost btn-sm" onClick={() => {const u = localReviews.map((x) => x === r ? { ...x, replied: true } : x);setLocalReviews(u);T('Skipped', 'Marked as won\'t reply.', 'info');}}>Skip</button>
              </div>
          }
          </div>
        )}
      </div>

      <Modal open={!!drafting} onClose={() => setDrafting(null)} title={`Reply to ${drafting?.author}`} sub={drafting ? `${drafting.platform} · ${drafting.stars}★` : ''} width={560}
      footer={<>
          <button className="btn btn-ghost btn-sm" onClick={() => setDrafting(null)}>Cancel</button>
          <button className="btn btn-ghost btn-sm" onClick={() => setReplyText((t) => t + '\n\nP.S. your next visit is on the house, just mention this review.')}> Re-draft</button>
          <button className="btn btn-primary btn-sm" onClick={submitReply}>Post reply</button>
        </>}>
        {drafting &&
        <div>
            <div style={{ padding: '12px 14px', background: 'var(--cream)', borderRadius: 10, fontSize: 12.5, color: 'var(--ink-2)', marginBottom: 14, lineHeight: 1.6 }}>
              <strong>Their review:</strong> "{drafting.text}"
            </div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 600, marginBottom: 6 }}>Lenny's draft</div>
            <textarea value={replyText} onChange={(e) => setReplyText(e.target.value)} rows={6}
          style={{ width: '100%', padding: '10px 12px', fontSize: 13, fontFamily: 'var(--ff-ui)', border: '1px solid var(--cream-3)', borderRadius: 8, resize: 'vertical', lineHeight: 1.5 }} />
            <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 6 }}>Tone-matched to your brand voice · {replyText.length} chars</div>
          </div>
        }
      </Modal>
    </div>);

}
window.ReviewsPage = ReviewsPage;

// ====================================================================
// BENCHMARKS (orphan, superseded by Playbook in benchmarks.jsx)
// ====================================================================
function BenchmarksPage({ data }) {
  const { benchmarks } = data;
  return (
    <div className="page active">
      <div className="page-header">
        <div>
          <div className="page-title">How you compare.</div>
          <div className="page-sub">Your location vs. FreshNest system vs. all home services franchisees in LOCALACT.</div>
        </div>
      </div>

      <div className="card card-pad" style={{ marginBottom: 20, background: 'linear-gradient(135deg, #fdf0e4, var(--cream))' }}>
        <div style={{ display: 'flex', gap: 18, alignItems: 'center' }}>
          <div style={{ width: 52, height: 52, background: 'var(--paper)', borderRadius: '50%', border: '2px solid var(--cream-3)', overflow: 'hidden', flexShrink: 0 }}>
            <LennyLlama size={52} mood="happy" bg="circle" />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 17, fontWeight: 600, marginBottom: 4 }}>You beat the FreshNest system average on 7 of 7 metrics.</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>Your biggest edge: review response time (2.4h vs 8.1h system avg). Biggest opportunity: AI visibility.</div>
          </div>
          <button className="btn btn-ghost btn-sm" onClick={openLenny}>Ask Lenny why</button>
        </div>
      </div>

      <div className="section-label">Detailed benchmarks</div>
      <div className="card" style={{ overflow: 'hidden' }}>
        <table className="tbl">
          <thead><tr><th>Metric</th><th>You</th><th>FreshNest avg</th><th>All home services franchisees</th><th>Your position</th></tr></thead>
          <tbody>
            {benchmarks.map((b, i) => {
              const youStr = `${b.unit === '$' ? '$' : ''}${b.you}${b.unit === '%' ? '%' : b.unit === '★' ? '★' : b.unit === 'h' ? 'h' : ''}`;
              const brandStr = `${b.unit === '$' ? '$' : ''}${b.brand}${b.unit === '%' ? '%' : b.unit === '★' ? '★' : b.unit === 'h' ? 'h' : ''}`;
              const peerStr = `${b.unit === '$' ? '$' : ''}${b.peer}${b.unit === '%' ? '%' : b.unit === '★' ? '★' : b.unit === 'h' ? 'h' : ''}`;
              const better = b.better === 'higher' ? b.you > b.brand : b.you < b.brand;
              const vals = [b.you, b.brand, b.peer];
              const vMin = Math.min(...vals),vMax = Math.max(...vals);
              const range = vMax - vMin || 1;
              const pos = (v) => (v - vMin) / range * 100;
              return (
                <tr key={i}>
                  <td className="strong">{b.metric}</td>
                  <td><span style={{ fontFamily: 'var(--ff-display)', fontSize: 17, fontWeight: 500, color: 'var(--terra)' }}>{youStr}</span></td>
                  <td className="muted">{brandStr}</td>
                  <td className="muted">{peerStr}</td>
                  <td style={{ width: 260 }}>
                    <div style={{ position: 'relative', height: 24, background: 'var(--cream-2)', borderRadius: 12 }}>
                      <div style={{ position: 'absolute', left: pos(b.peer) + '%', top: 4, width: 3, height: 16, background: 'var(--ink-5)', borderRadius: 2, transform: 'translateX(-1.5px)' }} />
                      <div style={{ position: 'absolute', left: pos(b.brand) + '%', top: 4, width: 3, height: 16, background: 'var(--sky)', borderRadius: 2, transform: 'translateX(-1.5px)' }} />
                      <div style={{ position: 'absolute', left: pos(b.you) + '%', top: 2, width: 14, height: 20, background: better ? 'var(--sage)' : 'var(--terra)', borderRadius: 6, transform: 'translateX(-7px)', border: '2px solid var(--paper)', boxShadow: 'var(--sh-1)' }} />
                    </div>
                    <div style={{ fontSize: 10, color: 'var(--ink-4)', marginTop: 4, display: 'flex', justifyContent: 'space-between' }}>
                      <span>{b.better === 'higher' ? 'worse' : 'better'}</span>
                      <span>{b.better === 'higher' ? 'better' : 'worse'}</span>
                    </div>
                  </td>
                </tr>);

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

}
window.BenchmarksPage = BenchmarksPage;

// HqPage now lives in hq.jsx (loaded via script tag in LOCALACT.html)

// ====================================================================
// Campaigns
// ====================================================================
function CampaignsPage({ data }) {
  const [newOpen, setNewOpen] = useStateP(false);
  const [editing, setEditing] = useStateP(null);
  const [campaigns, setCampaigns] = useStateP(data.campaigns);
  useEffectP(() => setCampaigns(data.campaigns), [data.campaigns]);
  const [form, setForm] = useStateP({ name: 'Mother\'s Day gift cleans', type: 'Promotional', range: 'May 1 – May 12', services: 'PPC + Meta', total: 1200, status: 'scheduled' });

  return (
    <div className="page active">
      <div className="page-header">
        <div>
          <div className="page-title">Campaign periods.</div>
          <div className="page-sub">Your standing budget + seasonal or promotional overlays.</div>
        </div>
        <div className="page-actions">
          <button className="btn btn-primary btn-sm" onClick={() => setNewOpen(true)}>{Icon.plus} New budget period</button>
        </div>
      </div>
      <div style={{ background: 'var(--sky-soft)', border: '1px solid var(--sky)', borderRadius: 14, padding: '14px 18px', marginBottom: 20, fontSize: 12.5, color: '#001e40' }}>
        <strong>How periods work:</strong> Standing Monthly covers always-on services. Layer Promotional, Holiday, or Seasonal periods on top, they run alongside your standing budget.
      </div>
      <div className="section-label">Active budget periods</div>
      <div className="card" style={{ overflow: 'hidden' }}>
        <table className="tbl">
          <thead><tr><th>Campaign</th><th>Type</th><th>Date range</th><th>Services</th><th>Total</th><th>Status</th><th /></tr></thead>
          <tbody>
            {campaigns.map((c, i) =>
            <tr key={i} onClick={() => setEditing(c)} style={{ cursor: 'pointer' }}>
                <td className="strong">{c.name}</td>
                <td><span className={`badge ${c.type === 'Standing' ? 'badge-info' : c.type === 'Seasonal' ? 'badge-ok' : 'badge-terra'}`}>{c.type}</span></td>
                <td className="muted">{c.range}</td>
                <td>{c.services}</td>
                <td className="strong">${c.total.toLocaleString()}</td>
                <td><span className={`badge ${c.status === 'active' ? 'badge-ok' : c.status === 'scheduled' ? 'badge-info' : 'badge-neutral'}`}>{c.status}</span></td>
                <td><button className="btn btn-quiet btn-xs" onClick={(e) => {e.stopPropagation();setEditing(c);}}>Edit</button></td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      <Modal open={newOpen} onClose={() => setNewOpen(false)} title="New budget period" sub="Layer on top of your standing monthly"
      footer={<>
          <button className="btn btn-ghost btn-sm" onClick={() => setNewOpen(false)}>Cancel</button>
          <button className="btn btn-primary btn-sm" onClick={() => {setCampaigns((c) => [...c, form]);setNewOpen(false);T('Campaign scheduled', `${form.name} · starts ${form.range.split(' – ')[0]}.`, 'ok');}}>Schedule campaign</button>
        </>}>
        <CampaignForm form={form} setForm={setForm} />
      </Modal>

      <Modal open={!!editing} onClose={() => setEditing(null)} title={editing ? `Edit: ${editing.name}` : ''} sub={editing?.range}
      footer={<>
          <button className="btn btn-ghost btn-sm" onClick={() => setEditing(null)}>Close</button>
          {editing?.type !== 'Standing' && <button className="btn btn-ghost btn-sm" style={{ color: 'var(--terra)' }} onClick={() => {setCampaigns((c) => c.filter((x) => x !== editing));setEditing(null);T('Campaign removed', editing.name, 'warn');}}>Delete</button>}
          <button className="btn btn-primary btn-sm" onClick={() => {setEditing(null);T('Changes saved', editing.name, 'ok');}}>Save</button>
        </>}>
        {editing && <CampaignForm form={editing} setForm={(f) => setEditing(f)} />}
      </Modal>
    </div>);

}
window.CampaignsPage = CampaignsPage;

function CampaignForm({ form, setForm }) {
  const set = (k, v) => setForm({ ...form, [k]: v });
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {[
      ['name', 'Campaign name', 'text'],
      ['range', 'Date range', 'text'],
      ['services', 'Services', 'text'],
      ['total', 'Total budget ($)', 'number']].
      map(([k, l, t]) =>
      <div key={k}>
          <div style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 600, marginBottom: 4 }}>{l}</div>
          <input type={t} value={form[k]} onChange={(e) => set(k, t === 'number' ? +e.target.value : e.target.value)}
        style={{ width: '100%', padding: '10px 12px', fontSize: 13, fontFamily: 'var(--ff-ui)', border: '1px solid var(--cream-3)', borderRadius: 8 }} />
        </div>
      )}
      <div>
        <div style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 600, marginBottom: 4 }}>Type</div>
        <div style={{ display: 'flex', gap: 6 }}>
          {['Standing', 'Promotional', 'Seasonal', 'Holiday'].map((tp) =>
          <button key={tp} onClick={() => set('type', tp)}
          style={{ padding: '6px 12px', borderRadius: 999, border: '1px solid var(--cream-3)', background: form.type === tp ? 'var(--ink)' : 'var(--paper)', color: form.type === tp ? 'var(--cream)' : 'var(--ink-2)', fontSize: 11.5, cursor: 'pointer' }}>{tp}</button>
          )}
        </div>
      </div>
    </div>);

}

function InvoicePage({ persona, data }) {
  if (persona === 'hq') return <window.CorporateBilling />;
  return <window.FranchiseeBilling variant={data ? data.variant : 'star'} />;
}
window.InvoicePage = InvoicePage;


function SettingsPage({ persona, data, locationVariant }) {
  if (persona === 'hq') return <HqSettingsPage data={data} />;
  return <FranchiseeSettingsPage data={data} locationVariant={locationVariant} />;
}
window.SettingsPage = SettingsPage;

// ====================================================================
// FRANCHISEE SETTINGS, Local store profile, services, team, prefs
// Mirrors HQ Settings tab structure but everything is location-scoped.
// Adapts to Austin Downtown (the star) vs Plano Legacy (bare-minimum).
// ====================================================================

const LOCATION_PROFILES = {
  star: {
    // Austin Downtown
    name: "FreshNest, Austin Downtown",
    shortName: 'Austin Downtown',
    unit: '#1042',
    owner: 'Alicia Chen',
    ownerEmail: 'alicia@freshnest.com',
    ownerPhone: '(512) 555-0142',
    since: 'April 2024',
    storePhone: '(512) 555-0142',
    storeEmail: 'austin.downtown@freshnest.com',
    address: '204 E 6th St',
    city: 'Austin',
    state: 'TX',
    zip: '78701',
    region: 'Central · TX',
    sqft: 4200,
    crews: 4,
    parking: '12 spots · loading zone for service vans',
    accent: '#917200',
    accentSoft: 'rgba(161,112,29,0.10)',
    headline: 'A flagship store with a downtown crowd, heavy office-cleaning demand, and the highest LocalScore in Texas.',
    tagline: "Austin's trusted eco-clean specialist. Professional cleaning services & eco-certified supplies since 2018.",
    yearOpened: 2018,
    population: 'Downtown Austin · ~12k daytime workers in 0.5 mi radius',
    demographics: 'Median age 32 · 68% professionals · dense condo + office mix',
    competitors: ['Molly Maid Austin', 'The Cleaning Authority', 'MaidPro Downtown', 'Merry Maids'],
    differentiators: [
    { title: 'Eco-certified only', body: '200+ EPA Safer Choice products, no harsh chemicals, ever. We tell that story in every ad.' },
    { title: 'Office cleaning powerhouse', body: 'Commercial contracts are 38% of revenue. We hold the highest office-cleaning rating in the FreshNest system.' },
    { title: 'Late-night Fri/Sat', body: 'Open until 10 PM on weekends, only flagship in TX with that schedule.' },
    { title: 'Master-tech led', body: 'Our lead cleaner Hector trains every new FreshNest crew lead across the South region.' }],

    services: [
    { key: 'retail', label: 'Retail storefront', on: true, detail: '200+ eco products · refill station' },
    { key: 'pickup', label: 'Order pickup', on: true, detail: 'Ready in 15 min · curbside pickup' },
    { key: 'delivery', label: 'Supply delivery', on: true, detail: 'In-house drivers · 5-mile radius · same-day' },
    { key: 'homeClean', label: 'Home cleaning', on: true, detail: 'Deep clean · recurring · move-in/out' },
    { key: 'officeClean', label: 'Office cleaning', on: true, detail: 'Overnight crews · 1k–50k sqft · dedicated coordinator' },
    { key: 'mobile', label: 'Mobile service vans', on: true, detail: '2 vans for on-site consults + estimates' },
    { key: 'merch', label: 'Branded merch', on: true, detail: 'Totes · starter kits · gift boxes' },
    { key: 'gift', label: 'Gift cards', on: true, detail: 'Physical + digital · top seller in November' },
    { key: 'classes', label: 'Green-cleaning workshops', on: false, detail: 'Considered for Q3, see Lenny\'s recommendation below' }],

    productHighlights: [
    { name: 'EcoConcentrate Pro', detail: 'EPA Safer Choice · 8x concentrate · 64 loads per bottle', flag: 'bestseller' },
    { name: 'Glass + Surface Spray', detail: 'Streak-free · plant-based · fresh linen scent', flag: 'topDevice' },
    { name: 'Multi-surface Cleaner', detail: 'Plant-based · zero harsh chemicals · fresh scent', flag: 'signature' },
    { name: 'Deep Clean Bundle', detail: 'All supplies for a full home deep clean · saves 20%', flag: 'value' },
    { name: 'Microfiber Starter Kit', detail: '12-cloth set + caddy · pro-grade · lint-free', flag: 'newProduct' },
    { name: 'Subscription Box', detail: 'Monthly curated refills + fresh supplies · 20% off first month', flag: 'recurring' }],

    awards: [
    { year: '2025', title: 'Top 25 Green Businesses in Texas', org: 'Texas Monthly' },
    { year: '2024', title: 'Best Cleaning Service, Austin', org: 'Austin Chronicle' },
    { year: '2024', title: 'FreshNest Top Operator of the Year', org: 'Internal · Hector Ramirez' },
    { year: '2023', title: 'Eco Retailer of the Year', org: 'Keep Austin Green Awards' }],

    media: [
    { who: 'Texas Monthly', when: 'Mar 2025', headline: 'How FreshNest Austin became the green-cleaning favorite downtown' },
    { who: 'Austin Chronicle', when: 'Nov 2024', headline: '5 eco home stores worth the trip, FreshNest makes the list' },
    { who: 'KUT News', when: 'Jul 2024', headline: 'Inside the 6th Street storefront turning Austin homes green' }]

  },

  bare: {
    // Plano Legacy
    name: "FreshNest, Plano Legacy",
    shortName: 'Plano Legacy',
    unit: '#1088',
    owner: 'Danny Ruiz',
    ownerEmail: 'danny.r@freshnest.com',
    ownerPhone: '(972) 555-0188',
    since: 'Feb 2024',
    storePhone: '(972) 555-0188',
    storeEmail: 'plano.legacy@freshnest.com',
    address: '7401 Lone Star Dr, Suite C-110',
    city: 'Plano',
    state: 'TX',
    zip: '75024',
    region: 'Central · TX',
    sqft: 2800,
    crews: 2,
    parking: 'Strip-mall lot · 80+ spots shared',
    accent: '#4d6989',
    accentSoft: 'rgba(77,105,137,0.10)',
    headline: 'A suburban store with strong family foot traffic but minimal marketing investment, every channel is an opportunity.',
    tagline: 'Family-friendly eco cleaning for North Plano. Kid-safe products, easy parking.',
    yearOpened: 2018,
    population: 'Suburban North Plano · ~38k households · families with kids 6–17',
    demographics: 'Median age 41 · 72% households w/ kids · strong bulk-cleaning opportunity for schools + churches',
    competitors: ['Molly Maid Plano', 'Two Maids', 'The Maids of Frisco', 'Merry Maids'],
    differentiators: [
    { title: 'Family bundle pricing', body: 'Family Deep Clean Bundle at $39, beats every competitor in 5 mi by $6+.' },
    { title: 'Kid-safe Tuesdays', body: 'Local-only promo, 10% off the kid-and-pet-safe line. Drives 28% of weekly store traffic.' },
    { title: 'Strip-center parking', body: 'Easy parking, easy access from Sam Rayburn Tollway. We don\'t have a downtown\'s problem.' },
    { title: 'School + church contracts', body: 'Local Little League facilities and 3 megachurches reorder monthly, we don\'t advertise it.' }],

    services: [
    { key: 'deepClean', label: 'Deep cleaning', on: true, detail: '3–4 hrs per home · family bundles available' },
    { key: 'recurring', label: 'Recurring service', on: true, detail: 'Bi-weekly · weekly · monthly, very popular with families' },
    { key: 'officeClean', label: 'Office cleaning', on: false, detail: 'Opportunity flagged by Lenny, nearby offices underserved' },
    { key: 'shopProducts', label: 'Product sales', on: true, detail: '120+ eco cleaners · limited selection, high-velocity items' },
    { key: 'moveClean', label: 'Move-in/out cleaning', on: false, detail: 'Not yet, Danny considering adding this crew service' },
    { key: 'consultations', label: 'Home consultations', on: false, detail: 'Could expand, not yet marketed' },
    { key: 'supplySubscription', label: 'Supply subscriptions', on: true, detail: 'Monthly starter box, $24/mo · hitting adoption target' },
    { key: 'corporatePrograms', label: 'School + church partnerships', on: true, detail: 'Bulk cleaning contracts · steep discounts · recurring revenue' },
    { key: 'giftCards', label: 'Gift cards', on: true, detail: 'Physical only, digital not yet enabled' },
    { key: 'training', label: 'Cleaning workshops', on: false, detail: 'Not offered, opportunity for family engagement' }],

    productHighlights: [
    { name: 'EcoConcentrate Basic', detail: 'EPA Safer Choice · 4x concentrate · 32 loads per bottle', flag: 'bestseller' },
    { name: 'Family Deep Clean Bundle', detail: 'All supplies for 3-bed home · $39 · most popular item', flag: 'value' },
    { name: 'Plant-based All-Purpose', detail: 'Zero harsh chemicals · fresh linen scent · kid & pet safe', flag: 'family' },
    { name: 'Subscription Starter', detail: '4-item monthly box · $24/mo · growing subscription base', flag: 'recurring' },
    { name: 'Glass + Window Cleaner', detail: 'Streak-free · plant-based · popular for spring cleaning', flag: '' }],

    awards: [
    { year: '2024', title: 'Best Family-Friendly Business, Plano', org: 'Plano Magazine (reader\'s choice)' }],

    media: [
    { who: 'Plano Magazine', when: 'May 2024', headline: 'Best family-friendly home services in North Plano' }]

  }
};

function FranchiseeSettingsPage({ data, locationVariant }) {
  const variant = locationVariant === 'bare' ? 'bare' : 'star';
  const profile = LOCATION_PROFILES[variant];
  const [tab, setTab] = useStateP('profile');

  return (
    <div className="page active">
      <div className="page-header">
        <div>
          <div className="page-title">Settings.</div>
          <div className="page-sub">{profile.shortName} · what makes this store unique, what we offer, who runs it.</div>
        </div>
        <div className="page-actions">
          <span style={{ fontSize: 11, color: 'var(--ink-3)', marginRight: 12 }}>Last edited 6 days ago by {profile.owner.split(' ')[0]}</span>
          <button className="btn btn-ghost btn-sm" onClick={() => T('Preview', 'Opens this profile as your customers see it across Google, Yelp, Facebook.', 'info')}>Preview public profile →</button>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 4, borderBottom: '1px solid var(--cream-3)', marginBottom: 22 }}>
        {[
        { k: 'profile', label: 'Store Profile' },
        { k: 'unique', label: 'What Makes Us Unique' },
        { k: 'services', label: 'Services', count: profile.services.filter((s) => s.on).length },
        { k: 'menu', label: 'Product Highlights' },
        { k: 'team', label: 'Local Team', count: variant === 'star' ? 6 : 3 },
        { k: 'hours', label: 'Hours & Special Dates' },
        { k: 'compliance', label: 'Brand Compliance' },
        { k: 'audit', label: 'Audit Log' },
        { k: 'prefs', label: 'Lenny Preferences' }].
        map((t) =>
        <button key={t.k} onClick={() => setTab(t.k)} style={{
          padding: '10px 14px', fontSize: 12.5, fontWeight: 600, fontFamily: 'var(--ff-ui)',
          border: 'none', background: 'transparent', cursor: 'pointer',
          color: tab === t.k ? 'var(--ink)' : 'var(--ink-3)',
          borderBottom: tab === t.k ? `2px solid ${profile.accent}` : '2px solid transparent',
          marginBottom: -1, display: 'flex', alignItems: 'center', gap: 6
        }}>
            {t.label}
            {t.count != null && <span style={{ fontSize: 10.5, padding: '1px 6px', borderRadius: 8, background: tab === t.k ? profile.accentSoft : 'var(--cream-2)', color: tab === t.k ? profile.accent : 'var(--ink-3)', fontWeight: 700 }}>{t.count}</span>}
          </button>
        )}
      </div>

      {tab === 'profile' && <FrSettingsProfile profile={profile} variant={variant} />}
      {tab === 'unique' && <FrSettingsUnique profile={profile} variant={variant} />}
      {tab === 'services' && <FrSettingsServices profile={profile} variant={variant} />}
      {tab === 'menu' && <FrSettingsMenu profile={profile} variant={variant} />}
      {tab === 'team' && <FrSettingsTeam profile={profile} variant={variant} />}
      {tab === 'hours' && <FrSettingsHours profile={profile} variant={variant} />}
      {tab === 'compliance' && <FrSettingsCompliance profile={profile} variant={variant} />}
      {tab === 'audit' && <FrAuditLog profile={profile} variant={variant} />}
      {tab === 'prefs' && <FrSettingsPrefs profile={profile} variant={variant} />}
    </div>);

}

// --------------------------------------------------------------------
// STORE PROFILE, basic info, identity, location-specific fields
// --------------------------------------------------------------------
function FrSettingsProfile({ profile, variant }) {
  return (
    <div>
      <div className="card card-pad" style={{ marginBottom: 18, background: `linear-gradient(135deg, var(--cream) 0%, ${profile.accentSoft} 100%)`, border: '1px solid var(--cream-3)' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 18 }}>
          <div style={{ width: 72, height: 72, borderRadius: 12, background: '#001132', color: '#f6a663', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--ff-display)', fontSize: 28, fontWeight: 600, letterSpacing: '-0.02em' }}>FN</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, color: profile.accent, textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 4 }}>Store profile · Unit {profile.unit}</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 600, color: 'var(--ink)', marginBottom: 4, letterSpacing: '-0.015em' }}>{profile.name}</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 10, maxWidth: 560 }}>{profile.headline}</div>
            <div style={{ display: 'flex', gap: 14, fontSize: 11.5, color: 'var(--ink-3)', flexWrap: 'wrap' }}>
              <span> {profile.city}, {profile.state}</span>
              <span>•</span>
              <span>Opened {profile.yearOpened}</span>
              <span>•</span>
              <span>{profile.sqft.toLocaleString()} sq ft · {profile.crews} cleaning crews</span>
              <span>•</span>
              <span>Operator since {profile.since}</span>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <button className="btn btn-primary btn-sm" onClick={() => T('Saved', 'Profile updates pushed to Google, Yelp, Facebook + 47 directories.', 'ok')}>Save & sync to directories</button>
            <button className="btn btn-ghost btn-sm" onClick={() => T('Version history', 'In production: see every edit + roll back to any prior version.', 'info')}>Version history</button>
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, marginBottom: 18 }}>
        <div className="card card-pad">
          <div className="card-title" style={{ marginBottom: 12 }}>Business identity</div>
          <SetField label="Store name (location-specific)">
            <input defaultValue={profile.name} style={setInputStyle} />
            <div style={{ fontSize: 10.5, color: 'var(--ink-4)', marginTop: 4 }}>The "FreshNest, " prefix is locked by HQ. You control the locator suffix.</div>
          </SetField>
          <SetField label="Tagline · shows on Google + Yelp">
            <input defaultValue={profile.tagline} style={setInputStyle} />
          </SetField>
          <SetField label="Owner / operator">
            <input defaultValue={profile.owner} style={setInputStyle} />
          </SetField>
          <SetField label="Operator since">
            <input defaultValue={profile.since} style={setInputStyle} />
          </SetField>
        </div>

        <div className="card card-pad">
          <div className="card-title" style={{ marginBottom: 12 }}>Contact & location</div>
          <SetField label="Street address">
            <input defaultValue={profile.address} style={setInputStyle} />
          </SetField>
          <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: 10 }}>
            <SetField label="City">
              <input defaultValue={profile.city} style={setInputStyle} />
            </SetField>
            <SetField label="State">
              <input defaultValue={profile.state} style={setInputStyle} />
            </SetField>
            <SetField label="ZIP">
              <input defaultValue={profile.zip} style={setInputStyle} />
            </SetField>
          </div>
          <SetField label="Store phone">
            <input defaultValue={profile.storePhone} style={setInputStyle} />
          </SetField>
          <SetField label="Store email · for inquiries">
            <input defaultValue={profile.storeEmail} style={setInputStyle} />
          </SetField>
          <SetField label="Parking notes · shown on Yelp/Google details">
            <input defaultValue={profile.parking} style={setInputStyle} />
          </SetField>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 18 }}>
        <div className="card card-pad">
          <div className="card-title" style={{ marginBottom: 12 }}>About this store · long description</div>
          <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginBottom: 8 }}>This appears on your GBP, Yelp, your microsite, and as the seed for any AI-generated copy Lenny writes. Be specific to this location, what's the real story?</div>
          <textarea defaultValue={variant === 'star' ?
          "FreshNest Austin Downtown has been Austin's go-to for eco-certified cleaning supplies and professional cleaning services since 2018. Our 6th Street store carries 200+ EPA Safer Choice products, from concentrated cleaners to microfiber kits and refills. Book a professional deep clean, set up a recurring service, or stop in for supplies. Same-day booking available." :
          "FreshNest Plano Legacy is North Plano's family-focused eco-cleaning store. We carry eco-friendly household cleaners, family-safe products, and cleaning supplies. Book a home cleaning service in-store or online, or pick up our family bundles built for households of all sizes. Easy strip-center parking right off Sam Rayburn Tollway."}
          style={{ ...setInputStyle, minHeight: 130, resize: 'vertical', lineHeight: 1.55 }} />
          <div style={{ fontSize: 10.5, color: 'var(--ink-4)', marginTop: 6, display: 'flex', justifyContent: 'space-between' }}>
            <span>Lenny will check this for brand-voice fit before publishing.</span>
            <button className="btn btn-ghost btn-sm" style={{ fontSize: 11, padding: '4px 10px' }} onClick={() => T('Lenny is drafting', 'Reading your reviews + services to suggest 3 description options.', 'info')}>🦙 Have Lenny draft this →</button>
          </div>
        </div>

        <div className="card card-pad">
          <div className="card-title" style={{ marginBottom: 12 }}>Neighborhood & demographics</div>
          <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginBottom: 12 }}>Lenny uses this to target your ads, write your copy, and pick the right images. Editing this re-tunes every campaign.</div>
          <SetField label="Trade area">
            <textarea defaultValue={profile.population} style={{ ...setInputStyle, minHeight: 50, resize: 'vertical' }} />
          </SetField>
          <SetField label="Customer demographics">
            <textarea defaultValue={profile.demographics} style={{ ...setInputStyle, minHeight: 50, resize: 'vertical' }} />
          </SetField>
          <div style={{ marginTop: 4 }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-4)', marginBottom: 6 }}>Local competitors · 5 mi radius</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {profile.competitors.map((c) =>
              <div key={c} style={{ padding: '5px 10px', fontSize: 12, fontWeight: 600, background: 'var(--cream-2)', border: '1px solid var(--cream-3)', borderRadius: 14, color: 'var(--ink-2)' }}>{c} <span style={{ color: 'var(--ink-4)', marginLeft: 4, cursor: 'pointer' }}>×</span></div>
              )}
              <button style={{ padding: '5px 10px', fontSize: 12, fontWeight: 600, background: 'transparent', border: '1px dashed var(--cream-3)', borderRadius: 14, color: 'var(--ink-3)', cursor: 'pointer' }}>+ Add competitor</button>
            </div>
          </div>
        </div>
      </div>
    </div>);

}

// --------------------------------------------------------------------
// WHAT MAKES US UNIQUE, differentiators, awards, press
// --------------------------------------------------------------------
function FrSettingsUnique({ profile, variant }) {
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18, marginBottom: 18 }}>
        <div className="card card-pad">
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 6 }}>
            <div className="card-title" style={{ marginBottom: 0 }}>Differentiators · why customers pick this store</div>
            <button className="btn btn-ghost btn-sm" style={{ fontSize: 11 }}>+ Add</button>
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginBottom: 14 }}>3–5 things that set this location apart from the brand average and your local competitors. Lenny weaves these into every ad, review reply, and Q&A response.</div>
          {profile.differentiators.map((d, i) =>
          <div key={i} style={{ display: 'flex', gap: 12, padding: '14px 0', borderTop: '1px solid var(--cream-2)' }}>
              <div style={{ width: 26, height: 26, borderRadius: '50%', background: profile.accentSoft, color: profile.accent, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700, flexShrink: 0 }}>{i + 1}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)', marginBottom: 3 }}>{d.title}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.55 }}>{d.body}</div>
              </div>
              <div style={{ display: 'flex', gap: 4, alignSelf: 'flex-start' }}>
                <button className="btn btn-ghost btn-sm" style={{ fontSize: 11, padding: '4px 8px' }}>Edit</button>
                <button style={{ background: 'transparent', border: 'none', color: 'var(--ink-4)', cursor: 'pointer', fontSize: 14 }}>×</button>
              </div>
            </div>
          )}
        </div>

        <div className="card card-pad" style={{ background: 'var(--violet-soft, rgba(77,105,137,0.08))', border: '1px solid rgba(77,105,137,0.18)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
            <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--violet)', color: 'var(--paper)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700 }}>🦙</span>
            <div className="card-title" style={{ marginBottom: 0 }}>Lenny noticed</div>
          </div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.6, marginBottom: 12 }}>
            {variant === 'star' ?
            <>Your reviews mention <strong>"eco-friendly"</strong> 142× and <strong>"reliable cleaning"</strong> 89× in the last 90 days, both already on your differentiator list. ✓<br /><br />But customers also rave about <strong>Hector personally walking the final inspection</strong> (mentioned 23×). Want me to add a "Final walkthrough, every job" differentiator? Could lift office-cleaning inquiries another ~6%.</> :
            <>Your differentiators don't yet mention <strong>recurring cleaning plans</strong> or <strong>subscription convenience</strong>, but those drive 41% of your service revenue and show up in 28 reviews. Adding them would help your ads rank for "house cleaning near me" (currently #14, no investment).</>
            }
          </div>
          <button className="btn btn-primary btn-sm" style={{ width: '100%' }}>Apply Lenny's suggestion</button>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
        <div className="card card-pad">
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
            <div className="card-title" style={{ marginBottom: 0 }}>Awards & recognition</div>
            <button className="btn btn-ghost btn-sm" style={{ fontSize: 11 }}>+ Add award</button>
          </div>
          {profile.awards.length === 0 ?
          <div style={{ padding: 28, textAlign: 'center', color: 'var(--ink-4)', fontSize: 12.5, border: '1px dashed var(--cream-3)', borderRadius: 10 }}>No awards listed. Even local "best of" mentions help you rank.</div> :
          profile.awards.map((a, i) =>
          <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'center', padding: '12px 0', borderBottom: i === profile.awards.length - 1 ? 'none' : '1px solid var(--cream-2)' }}>
              <div style={{ width: 44, height: 44, borderRadius: 8, background: '#ce9e07', color: '#001132', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, flexShrink: 0 }}></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{a.title}</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{a.org} · {a.year}</div>
              </div>
              <button className="btn btn-ghost btn-sm" style={{ fontSize: 11 }}>Edit</button>
            </div>
          )}
          {variant === 'bare' &&
          <div style={{ marginTop: 14, padding: 12, background: profile.accentSoft, borderRadius: 8, fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.5 }}>
              <strong>Lenny tip:</strong> Plano Magazine ran a "best home services" reader poll in May 2024, you placed 3rd but never claimed it on Yelp. <button className="btn btn-ghost btn-sm" style={{ fontSize: 11, padding: '2px 8px', marginLeft: 4 }}>Add it →</button>
            </div>
          }
        </div>

        <div className="card card-pad">
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
            <div className="card-title" style={{ marginBottom: 0 }}>Press & media mentions</div>
            <button className="btn btn-ghost btn-sm" style={{ fontSize: 11 }}>+ Add mention</button>
          </div>
          {profile.media.map((m, i) =>
          <div key={i} style={{ padding: '12px 0', borderBottom: i === profile.media.length - 1 ? 'none' : '1px solid var(--cream-2)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 3 }}>
                <div style={{ fontSize: 12.5, fontWeight: 700, color: profile.accent }}>{m.who}</div>
                <div style={{ fontSize: 10.5, color: 'var(--ink-4)' }}>{m.when}</div>
              </div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.5, fontStyle: 'italic' }}>"{m.headline}"</div>
            </div>
          )}
        </div>
      </div>
    </div>);

}

// --------------------------------------------------------------------
// INITIATIVES, what does this location actually do?
// --------------------------------------------------------------------
function FrSettingsServices({ profile, variant }) {
  const [services, setServices] = useStateP(profile.services);
  const toggleService = (k) => {
    setServices((prev) => prev.map((s) => {
      if (s.key !== k) return s;
      const newOn = !s.on;
      T(newOn ? 'Initiative enabled' : 'Initiative disabled', `${s.label} · syncing to Google Business Profile + Yelp now.`, newOn ? 'ok' : 'info');
      return { ...s, on: newOn };
    }));
  };

  const onCount = services.filter((s) => s.on).length;

  return (
    <div>
      <div className="card card-pad" style={{ marginBottom: 18, display: 'flex', alignItems: 'center', gap: 18 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 4 }}>What this store offers</div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 600, letterSpacing: '-0.015em' }}>{onCount} of {services.length} initiatives active</div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4, maxWidth: 540 }}>These flow into your Google Business Profile, your microsite, your ad copy, and the way Lenny answers customer questions on every channel.</div>
        </div>
        <div style={{ display: 'flex', gap: 16 }}>
          {[
          { l: 'Live on Google', v: onCount, c: '#56adad' },
          { l: 'Pending sync', v: 0, c: '#917200' },
          { l: 'Disabled', v: services.length - onCount, c: 'var(--ink-4)' }].
          map((s) =>
          <div key={s.l} style={{ textAlign: 'center', minWidth: 80 }}>
              <div style={{ fontFamily: 'var(--ff-display)', fontSize: 24, fontWeight: 600, color: s.c }}>{s.v}</div>
              <div style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700 }}>{s.l}</div>
            </div>
          )}
        </div>
      </div>

      <div className="card" style={{ overflow: 'hidden', padding: 0, marginBottom: 18 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '60px 1.2fr 2fr 100px 100px', padding: '10px 18px', background: 'var(--cream)', borderBottom: '1px solid var(--cream-3)', fontSize: 10.5, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>
          <div>On</div>
          <div>SERVICE</div>
          <div>Local detail</div>
          <div style={{ textAlign: 'right' }}>Brand template</div>
          <div style={{ textAlign: 'right' }}></div>
        </div>
        {services.map((s, i) =>
        <div key={s.key} style={{ display: 'grid', gridTemplateColumns: '60px 1.2fr 2fr 100px 100px', padding: '14px 18px', borderBottom: i === services.length - 1 ? 'none' : '1px solid var(--cream-2)', alignItems: 'center', fontSize: 13, opacity: s.on ? 1 : 0.55 }}>
            <div onClick={() => toggleService(s.key)} style={{ width: 36, height: 20, background: s.on ? profile.accent : 'var(--cream-3)', borderRadius: 10, position: 'relative', cursor: 'pointer', transition: 'background .2s' }}>
              <div style={{ position: 'absolute', top: 2, left: s.on ? 18 : 2, width: 16, height: 16, background: 'var(--paper)', borderRadius: '50%', boxShadow: 'var(--sh-1)', transition: 'left .2s' }} />
            </div>
            <div style={{ fontWeight: 600, color: 'var(--ink)' }}>{s.label}</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>{s.detail}</div>
            <div style={{ textAlign: 'right', fontSize: 11, color: 'var(--ink-4)' }}>v3.2</div>
            <div style={{ textAlign: 'right' }}>
              <button className="btn btn-ghost btn-sm" style={{ fontSize: 11 }}>Edit detail</button>
            </div>
          </div>
        )}
      </div>

      {variant === 'star' ?
      <div className="card card-pad" style={{ background: 'var(--violet-soft, rgba(77,105,137,0.08))', border: '1px solid rgba(77,105,137,0.18)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
            <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--violet)', color: 'var(--paper)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700 }}>🦙</span>
            <div className="card-title" style={{ marginBottom: 0 }}>Lenny's recommendation: turn on Cleaning Workshops</div>
          </div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.6, marginBottom: 12 }}>You're the only Austin location with the demand for it, and 7 of your customers mention "I'd pay to learn from Hector." Modeled at $1.4–2.1k/mo at 8 students × $185, with very low marketing cost. Want a 90-day pilot plan?</div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-primary btn-sm">Build the pilot plan →</button>
            <button className="btn btn-ghost btn-sm">Not for me</button>
          </div>
        </div> :

      <div className="card card-pad" style={{ background: 'var(--violet-soft, rgba(77,105,137,0.08))', border: '1px solid rgba(77,105,137,0.18)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
            <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--violet)', color: 'var(--paper)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700 }}>🦙</span>
            <div className="card-title" style={{ marginBottom: 0 }}>Lenny's recommendation: 3 services to turn on</div>
          </div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.6, marginBottom: 12 }}>Plano peers running <strong>delivery + private events + UberEats</strong> earn ~3.4× your lead volume. Each one is also a Google search filter, turning them on improves your map ranking the same week.</div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-primary btn-sm">Show me the 90-day plan →</button>
            <button className="btn btn-ghost btn-sm">Not now</button>
          </div>
        </div>
      }
    </div>);

}

// --------------------------------------------------------------------
// PRODUCT HIGHLIGHTS · featured services & promoted supplies
// --------------------------------------------------------------------
function FrSettingsMenu({ profile, variant }) {
  const flagStyle = (flag) => {
    if (flag === 'signature') return { bg: profile.accentSoft, color: profile.accent, label: 'Signature' };
    if (flag === 'bestseller') return { bg: 'rgba(232,168,51,0.16)', color: '#ad8406', label: 'Bestseller' };
    if (flag === 'topDevice') return { bg: profile.accentSoft, color: profile.accent, label: 'Top seller' };
    if (flag === 'newProduct') return { bg: 'rgba(125,196,166,0.18)', color: '#1b8a4b', label: 'New' };
    if (flag === 'recurring') return { bg: 'rgba(86,173,173,0.16)', color: '#1b8a4b', label: 'Subscription' };
    if (flag === 'limited') return { bg: 'rgba(224,122,110,0.12)', color: '#bf281c', label: 'Limited' };
    if (flag === 'value') return { bg: 'rgba(232,168,51,0.16)', color: '#ad8406', label: 'Value pick' };
    if (flag === 'family') return { bg: 'rgba(77,105,137,0.12)', color: '#4d6989', label: 'Family' };
    return null;
  };

  return (
    <div>
      <div className="card card-pad" style={{ marginBottom: 18 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 6 }}>
          <div className="card-title" style={{ marginBottom: 0 }}>Featured products at this location</div>
          <button className="btn btn-ghost btn-sm" style={{ fontSize: 11 }}>+ Add item</button>
        </div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginBottom: 14 }}>The master catalog is managed by HQ for safety and labeling compliance, but you choose what to feature locally. These show up first on your microsite, in your ads, and in Lenny's review replies.</div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12 }}>
          {(profile.productHighlights || []).map((d, i) => {
            const f = flagStyle(d.flag);
            return (
              <div key={i} style={{ padding: 14, border: '1px solid var(--cream-3)', borderRadius: 10, background: 'var(--paper)' }}>
                <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 10 }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.01em' }}>{d.name}</div>
                    <div style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 4, lineHeight: 1.5 }}>{d.detail}</div>
                  </div>
                  {f && <div style={{ padding: '3px 8px', fontSize: 10, fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase', borderRadius: 10, background: f.bg, color: f.color, flexShrink: 0 }}>{f.label}</div>}
                </div>
                <div style={{ display: 'flex', gap: 6, marginTop: 12, paddingTop: 10, borderTop: '1px dashed var(--cream-3)' }}>
                  <button className="btn btn-ghost btn-sm" style={{ fontSize: 11, padding: '4px 8px' }}>Edit</button>
                  <button className="btn btn-ghost btn-sm" style={{ fontSize: 11, padding: '4px 8px' }}>Promote in ads</button>
                  <div style={{ flex: 1 }} />
                  <button style={{ background: 'transparent', border: 'none', color: 'var(--ink-4)', cursor: 'pointer', fontSize: 14 }}>×</button>
                </div>
              </div>);

          })}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
        <div className="card card-pad">
          <div className="card-title" style={{ marginBottom: 12 }}>Local promotions & recurring deals</div>
          <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginBottom: 12 }}>Brand promos run nationally. These are <em>your</em> store's local-only deals, they need HQ approval if they discount more than 20%.</div>
          {(variant === 'star' ? [
          { name: 'Sunday Reset', detail: 'Deep clean add-on $24 · Sundays only', status: 'active' },
          { name: 'Office Clean Friday', detail: '15% off commercial contracts >$400', status: 'active' },
          { name: 'SXSW Turnover Rush', detail: 'March 7–18 · priority rental turnovers', status: 'scheduled' }] :
          [
          { name: 'Kid-safe Tuesday', detail: '10% off kid-and-pet-safe products', status: 'active' },
          { name: 'Wednesday refill special', detail: 'Refill any 2 bottles · $18', status: 'active' },
          { name: 'Family Bundle', detail: 'Supplies for a 3-bed home · $39', status: 'active' }]).
          map((p, i, arr) =>
          <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'center', padding: '11px 0', borderBottom: i === arr.length - 1 ? 'none' : '1px solid var(--cream-2)' }}>
              <div style={{ width: 8, height: 8, borderRadius: '50%', background: p.status === 'active' ? '#56adad' : '#917200' }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{p.name}</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{p.detail}</div>
              </div>
              <div style={{ fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em', color: p.status === 'active' ? '#1b8a4b' : '#ad8406' }}>{p.status}</div>
              <button className="btn btn-ghost btn-sm" style={{ fontSize: 11 }}>Edit</button>
            </div>
          )}
          <button className="btn btn-ghost btn-sm" style={{ marginTop: 10 }}>+ New local promo</button>
        </div>

        <div className="card card-pad">
          <div className="card-title" style={{ marginBottom: 12 }}>Service & accessibility attributes</div>
          <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginBottom: 12 }}>Keep this current, it shows on Yelp/Google filters and drives 8–14% of booking inquiries.</div>
          {[
          { l: 'Fragrance-free options', on: true },
          { l: 'Hypoallergenic line', on: variant === 'star' },
          { l: 'Refill station', on: false },
          { l: 'Kid & pet-safe products', on: true },
          { l: 'Wheelchair accessible', on: true },
          { l: 'Curbside pickup', on: variant === 'star' },
          { l: 'Same-day booking', on: variant === 'star' },
          { l: 'Evening appointments (>6pm)', on: variant === 'star' }].
          map((s, i, arr) =>
          <div key={i} style={{ display: 'flex', alignItems: 'center', padding: '8px 0', borderBottom: i === arr.length - 1 ? 'none' : '1px solid var(--cream-2)' }}>
              <div style={{ flex: 1, fontSize: 13, color: 'var(--ink-2)' }}>{s.l}</div>
              <div style={{ width: 36, height: 20, background: s.on ? profile.accent : 'var(--cream-3)', borderRadius: 10, position: 'relative', cursor: 'pointer' }}>
                <div style={{ position: 'absolute', top: 2, left: s.on ? 18 : 2, width: 16, height: 16, background: 'var(--paper)', borderRadius: '50%', boxShadow: 'var(--sh-1)' }} />
              </div>
            </div>
          )}
        </div>
      </div>
    </div>);

}

// --------------------------------------------------------------------
// LOCAL TEAM
// --------------------------------------------------------------------
const FR_TEAM_STAR = [
{ name: 'Hector Ramirez', role: 'Lead Technician', email: 'hector@freshnest.com', ext: '110', notify: ['reviews'], avatar: 'HR', color: '#8c4a13' },
{ name: 'Marisol Lopez', role: 'Commercial Coordinator', email: 'commercial.austin@freshnest.com', ext: '120', notify: ['leads', 'reports'], avatar: 'ML', color: '#56adad' },
{ name: 'Devon Park', role: 'Store Manager', email: 'devon.austin@freshnest.com', ext: '105', notify: ['reviews'], avatar: 'DP', color: '#4d6989' },
{ name: 'Jen Tanaka', role: 'Social / Local Marketing', email: 'jen.t@freshnest.com', ext: '108', notify: ['reviews', 'reports', 'spend'], avatar: 'JT', color: '#4d6989' },
{ name: 'Tom Reynolds', role: 'Corporate Field Team (HQ)', email: 'tom@freshnest.com', ext: 'HQ', notify: ['spend', 'reports'], avatar: 'TR', color: '#001132', external: true }];

const FR_TEAM_BARE = [
{ name: 'Danny Ruiz', role: 'Owner / Operator', email: 'danny.r@freshnest.com', ext: '101', notify: ['leads', 'reviews', 'spend', 'reports'], avatar: 'DR', color: '#4d6989' },
{ name: 'Crystal Reyes', role: 'Asst. Manager', email: 'crystal.r@freshnest.com', ext: '102', notify: ['reviews'], avatar: 'CR', color: '#917200' },
{ name: 'Tom Reynolds', role: 'Corporate Field Team (HQ)', email: 'tom@freshnest.com', ext: 'HQ', notify: ['spend', 'reports'], avatar: 'TR', color: '#001132', external: true }];


function FrSettingsTeam({ profile, variant }) {
  const team = variant === 'star' ? FR_TEAM_STAR : FR_TEAM_BARE;
  const [inviteOpen, setInviteOpen] = useStateP(false);

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
        <div style={{ flex: 1, fontSize: 12.5, color: 'var(--ink-3)' }}>People at this store. Each can have their own login + their own notification rules. HQ-side roles like your Corporate Field Team appear here too but you can't edit them.</div>
        <button className="btn btn-primary btn-sm" onClick={() => setInviteOpen(true)}>+ Invite team member</button>
      </div>

      <div className="card" style={{ overflow: 'hidden', padding: 0 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1.4fr 1.6fr 2fr 100px', padding: '10px 18px', background: 'var(--cream)', borderBottom: '1px solid var(--cream-3)', fontSize: 10.5, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>
          <div>Member</div>
          <div>Role</div>
          <div>Contact</div>
          <div>Gets notified about</div>
          <div></div>
        </div>
        {team.map((m, i) =>
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '2fr 1.4fr 1.6fr 2fr 100px', padding: '14px 18px', borderBottom: i === team.length - 1 ? 'none' : '1px solid var(--cream-2)', alignItems: 'center', fontSize: 13 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ width: 32, height: 32, borderRadius: '50%', background: m.color, color: 'var(--paper)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700 }}>{m.avatar}</div>
              <div>
                <div style={{ fontWeight: 600 }}>{m.name}</div>
                {m.external && <div style={{ fontSize: 10.5, color: 'var(--ink-4)', fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase' }}>HQ-managed</div>}
              </div>
            </div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>{m.role}</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>
              <div>{m.email}</div>
              <div style={{ fontSize: 10.5, marginTop: 2 }}>Ext. {m.ext}</div>
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
              {m.notify.map((n) =>
            <span key={n} style={{ padding: '2px 7px', fontSize: 10, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', borderRadius: 8, background: profile.accentSoft, color: profile.accent }}>{n}</span>
            )}
              {m.notify.length === 0 && <span style={{ fontSize: 11, color: 'var(--ink-4)', fontStyle: 'italic' }}>Nothing, quiet account</span>}
            </div>
            <div style={{ textAlign: 'right' }}>
              <button className="btn btn-ghost btn-sm" style={{ fontSize: 11 }} disabled={m.external}>{m.external ? 'View' : 'Edit'}</button>
            </div>
          </div>
        )}
      </div>

      <Modal open={inviteOpen} onClose={() => setInviteOpen(false)} title="Invite to your team"
      footer={<>
          <button className="btn btn-ghost btn-sm" onClick={() => setInviteOpen(false)}>Cancel</button>
          <button className="btn btn-primary btn-sm" onClick={() => {setInviteOpen(false);T('Invite sent', 'They\'ll get an email with a magic link to set up their account.', 'ok');}}>Send invite</button>
        </>}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <SetField label="Name"><input style={setInputStyle} placeholder="e.g. Sam Patel" /></SetField>
          <SetField label="Email"><input style={setInputStyle} placeholder="sam@freshnest.com" /></SetField>
          <SetField label="Role at this store">
            <select style={setInputStyle}>
              <option>Asst. Manager</option><option>Lead Technician</option><option>Store Manager</option>
              <option>Commercial Coordinator</option><option>Local Marketing</option><option>Other</option>
            </select>
          </SetField>
          <SetField label="What should they see?">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {['Lead notifications', 'Review alerts', 'Spend reports', 'Weekly summary'].map((opt) =>
              <label key={opt} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13 }}>
                  <input type="checkbox" defaultChecked={opt === 'Review alerts'} /> {opt}
                </label>
              )}
            </div>
          </SetField>
        </div>
      </Modal>
    </div>);

}

// --------------------------------------------------------------------
// HOURS & SPECIAL DATES
// --------------------------------------------------------------------
function FrSettingsHours({ profile, variant }) {
  const hoursStar = [
  { day: 'Monday', open: '11:00 AM', close: '9:00 PM', closed: false },
  { day: 'Tuesday', open: '11:00 AM', close: '9:00 PM', closed: false },
  { day: 'Wednesday', open: '11:00 AM', close: '9:00 PM', closed: false },
  { day: 'Thursday', open: '11:00 AM', close: '9:00 PM', closed: false },
  { day: 'Friday', open: '11:00 AM', close: '10:00 PM', closed: false },
  { day: 'Saturday', open: '11:00 AM', close: '10:00 PM', closed: false },
  { day: 'Sunday', open: '12:00 PM', close: '9:00 PM', closed: false, flag: 'Google shows 8 PM, saving here pushes correction' }];

  const hoursBare = [
  { day: 'Monday', open: '11:00 AM', close: '9:00 PM', closed: false },
  { day: 'Tuesday', open: '11:00 AM', close: '9:00 PM', closed: false, flag: 'Kid-safe promo day' },
  { day: 'Wednesday', open: '11:00 AM', close: '9:00 PM', closed: false },
  { day: 'Thursday', open: '11:00 AM', close: '9:00 PM', closed: false },
  { day: 'Friday', open: '11:00 AM', close: '9:30 PM', closed: false },
  { day: 'Saturday', open: '11:00 AM', close: '9:30 PM', closed: false },
  { day: 'Sunday', open: '12:00 PM', close: '8:00 PM', closed: false }];

  const hours = variant === 'star' ? hoursStar : hoursBare;
  const special = variant === 'star' ? [
  { d: 'Apr 20, Easter', h: '12:00 PM – 6:00 PM', closed: false },
  { d: 'May 27, Memorial Day', h: 'Reg. hours · cleans booked', closed: false, note: '4 jobs on the books' },
  { d: 'Jul 4, Independence Day', h: 'Closed all day', closed: true, note: 'Annual closure for staff' },
  { d: 'Sep 2, Labor Day', h: '11 AM – 8 PM', closed: false },
  { d: 'Nov 28, Thanksgiving', h: 'Closed all day', closed: true },
  { d: 'Dec 25, Christmas', h: 'Closed all day', closed: true }] :
  [
  { d: 'Apr 20, Easter', h: 'Closed all day', closed: true, note: 'Family-day closure' },
  { d: 'Jul 4, Independence Day', h: 'Closed all day', closed: true },
  { d: 'Nov 28, Thanksgiving', h: 'Closed all day', closed: true },
  { d: 'Dec 25, Christmas', h: 'Closed all day', closed: true }];


  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, marginBottom: 18 }}>
        <div className="card card-pad">
          <div className="card-title" style={{ marginBottom: 12 }}>Standard hours</div>
          {hours.map((h, i) =>
          <div key={h.day} style={{ display: 'grid', gridTemplateColumns: '110px 1fr 1fr 60px', gap: 10, alignItems: 'center', padding: '10px 0', borderBottom: i === hours.length - 1 ? 'none' : '1px solid var(--cream-2)' }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)' }}>{h.day}</div>
              <input defaultValue={h.open} style={{ ...setInputStyle, padding: '7px 10px', fontSize: 12 }} />
              <input defaultValue={h.close} style={{ ...setInputStyle, padding: '7px 10px', fontSize: 12 }} />
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 4 }}>
                <span style={{ fontSize: 10, color: 'var(--ink-4)' }}>open</span>
                <div style={{ width: 28, height: 16, background: !h.closed ? profile.accent : 'var(--cream-3)', borderRadius: 8, position: 'relative', cursor: 'pointer' }}>
                  <div style={{ position: 'absolute', top: 2, left: !h.closed ? 14 : 2, width: 12, height: 12, background: 'var(--paper)', borderRadius: '50%' }} />
                </div>
              </div>
              {h.flag && <div style={{ gridColumn: '2 / span 3', fontSize: 11, color: '#ad8406', marginTop: -4, fontStyle: 'italic' }}>⚠ {h.flag}</div>}
            </div>
          )}
        </div>

        <div className="card card-pad">
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
            <div className="card-title" style={{ marginBottom: 0 }}>Special dates · {new Date().getFullYear()}</div>
            <button className="btn btn-ghost btn-sm" style={{ fontSize: 11 }}>+ Add date</button>
          </div>
          {special.map((s, i) =>
          <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', padding: '11px 0', borderBottom: i === special.length - 1 ? 'none' : '1px solid var(--cream-2)' }}>
              <div style={{ width: 4, alignSelf: 'stretch', background: s.closed ? '#e46c63' : '#56adad', borderRadius: 2 }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{s.d}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 2 }}>{s.h}</div>
                {s.note && <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 3, fontStyle: 'italic' }}>{s.note}</div>}
              </div>
              <button style={{ background: 'transparent', border: 'none', color: 'var(--ink-4)', cursor: 'pointer', fontSize: 14 }}>×</button>
            </div>
          )}
        </div>
      </div>

      <div className="card card-pad" style={{ display: 'flex', alignItems: 'center', gap: 14, background: variant === 'star' ? profile.accentSoft : 'var(--cream)' }}>
        <div style={{ fontSize: 24 }}>🕒</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>Hours sync to 47 directories every time you save</div>
          <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 3 }}>Google Business Profile, Yelp, Facebook, Apple Maps, TripAdvisor + 42 more. Lenny resolves drift automatically, if Yelp falls out of sync, you'll see it on this page within an hour.</div>
        </div>
        <button className="btn btn-ghost btn-sm">View sync log</button>
      </div>
    </div>);

}

// --------------------------------------------------------------------
// BRAND COMPLIANCE, what's locked from corporate vs. customizable
// --------------------------------------------------------------------
function FrSettingsCompliance({ profile, variant }) {
  const fields = [
  { l: 'Brand name prefix', val: 'FreshNest', locked: true, why: 'Master brand · v3.2' },
  { l: 'Logo & lockups', val: 'FreshNest Master Brand', locked: true, why: 'Pulled from corporate kit' },
  { l: 'Brand colors', val: '6 colors · navy + cream system', locked: true, why: 'Pulled from corporate kit' },
  { l: 'Master catalog', val: '38 products · 6 categories', locked: true, why: 'Safety / labeling compliance' },
  { l: 'Voice & tone', val: 'Warm, hands-on, confident', locked: true, why: 'See HQ Brand Guidelines' },
  { l: 'Store name suffix', val: profile.shortName, locked: false, why: 'Edit on Profile tab' },
  { l: 'Tagline', val: profile.tagline, locked: false, why: 'Local · 80-char max' },
  { l: 'Long description', val: 'Local-authored · Lenny-checked', locked: false, why: 'Local · brand-voice scored' },
  { l: 'Differentiators', val: `${(profile.differentiators || []).length} listed`, locked: false, why: 'Local · used in ad copy' },
  { l: 'Featured products', val: `${(profile.productHighlights || []).length} featured`, locked: false, why: 'You pick from the master catalog' },
  { l: 'Local promos & deals', val: '3 active · 1 scheduled', locked: false, why: 'Local · >20% off needs HQ approval' },
  { l: 'Hours & special dates', val: 'Edited 6 days ago', locked: false, why: 'Local · syncs everywhere' },
  { l: 'Photos · location-specific', val: variant === 'star' ? '24 uploaded' : '6 uploaded', locked: false, why: 'Local · brand-style checked by Lenny' },
  { l: 'Commercial pricing', val: variant === 'star' ? 'Custom · per contract' : 'Standard', locked: false, why: 'Local · stays within brand range' },
  { l: 'Loyalty / rewards', val: 'FreshNest Membership Program', locked: true, why: 'Brand-wide program' }];


  return (
    <div>
      <div className="card card-pad" style={{ marginBottom: 18, display: 'flex', gap: 16, alignItems: 'center', background: 'linear-gradient(135deg, var(--cream) 0%, var(--cream-2) 100%)' }}>
        <div style={{ width: 56, height: 56, borderRadius: 12, background: '#001132', color: '#f6a663', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 600 }}>FN</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, marginBottom: 3 }}>Brand kit · v3.2 · Mar 14, 2026</div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 600, marginBottom: 4 }}>You're inheriting the master brand from HQ</div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-2)', maxWidth: 640 }}>{fields.filter((f) => !f.locked).length} fields are yours to control. {fields.filter((f) => f.locked).length} are managed by HQ to keep the brand consistent across all 142 stores. Lenny enforces the line, if you upload off-brand creative, it gets flagged before going live.</div>
        </div>
        <button className="btn btn-ghost btn-sm">View brand guidelines →</button>
      </div>

      <div className="card card-pad" style={{ marginBottom: 18, display: 'flex', alignItems: 'center', gap: 16 }}>
        <div style={{ width: 52, height: 52, borderRadius: 12, background: 'linear-gradient(135deg,#f4f8fe,#c6dafa)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 26, flexShrink: 0 }}>🖼️</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, color: profile.accent, textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, marginBottom: 3 }}>Creative · Image library</div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 600, color: 'var(--ink)', marginBottom: 2 }}>Your local image library</div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>Manage your own store photos alongside brand assets from HQ, and choose where each one publishes (GBP, Apple, social, website).</div>
        </div>
        <button className="btn btn-primary btn-sm" onClick={() => { window.__listingsInitialTab = 'images'; window.dispatchEvent(new CustomEvent('go-page', { detail: 'listings' })); }}>Open image library →</button>
      </div>

      <div className="card" style={{ overflow: 'hidden', padding: 0 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1.4fr 1.6fr 110px', padding: '10px 18px', background: 'var(--cream)', borderBottom: '1px solid var(--cream-3)', fontSize: 10.5, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>
          <div>Field</div>
          <div>Current value</div>
          <div>Source</div>
          <div style={{ textAlign: 'right' }}>Control</div>
        </div>
        {fields.map((f, i) =>
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '1.4fr 1.4fr 1.6fr 110px', padding: '13px 18px', borderBottom: i === fields.length - 1 ? 'none' : '1px solid var(--cream-2)', alignItems: 'center', fontSize: 13 }}>
            <div style={{ fontWeight: 600 }}>{f.l}</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>{f.val}</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{f.why}</div>
            <div style={{ textAlign: 'right' }}>
              {f.locked ?
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '3px 8px', fontSize: 10.5, fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase', borderRadius: 10, background: 'var(--cream-2)', color: 'var(--ink-3)' }}>
                  🔒 HQ
                </span> :

            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '3px 8px', fontSize: 10.5, fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase', borderRadius: 10, background: profile.accentSoft, color: profile.accent }}>
                  ✏ Yours
                </span>
            }
            </div>
          </div>
        )}
      </div>
    </div>);

}

// --------------------------------------------------------------------
// LENNY PREFERENCES (carryover from old simple settings)
// --------------------------------------------------------------------
function FrSettingsPrefs({ profile, variant }) {
  const [prefs, setPrefs] = useStateP({ insights: true, anomaly: true, autofix: true, digest: false, autoReplyReviews: true, autoApproveSpend: false });

  const toggle = (k) => {
    setPrefs((p) => {
      const newVal = !p[k];
      T(newVal ? 'Enabled' : 'Disabled', '', newVal ? 'ok' : 'info');
      return { ...p, [k]: newVal };
    });
  };

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
      <div className="card card-pad">
        <div className="card-title" style={{ marginBottom: 4 }}>Lenny notifications</div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginBottom: 14 }}>What does Lenny tell you about, and how often?</div>
        {[
        ['insights', 'Daily insights', "Lenny's top 3 each morning at 7 AM"],
        ['anomaly', 'Anomaly alerts', 'Notify me when something unusual happens'],
        ['autofix', 'Auto-fix listings', 'Fix directory drift without asking'],
        ['digest', 'Weekly digest', 'Email summary every Monday 8 AM']].
        map(([k, l, s]) => {
          const on = prefs[k];
          return (
            <div key={k} style={{ display: 'flex', alignItems: 'center', padding: '10px 0', borderBottom: '1px dashed var(--cream-3)' }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{l}</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{s}</div>
              </div>
              <div onClick={() => toggle(k)} style={{ width: 36, height: 20, background: on ? profile.accent : 'var(--cream-3)', borderRadius: 10, position: 'relative', cursor: 'pointer', transition: 'background .2s' }}>
                <div style={{ position: 'absolute', top: 2, left: on ? 18 : 2, width: 16, height: 16, background: 'var(--paper)', borderRadius: '50%', boxShadow: 'var(--sh-1)', transition: 'left .2s' }} />
              </div>
            </div>);

        })}
      </div>

      <div className="card card-pad">
        <div className="card-title" style={{ marginBottom: 4 }}>Lenny's autonomy at this store</div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginBottom: 14 }}>How much can Lenny do without asking? You can override any of these at any time.</div>
        {[
        ['autoReplyReviews', 'Auto-reply to 4★+ reviews', 'Reply within 4 hr in your voice. 1–3★ always wait for you.'],
        ['autoApproveSpend', 'Auto-approve spend ≤ ±10%', 'Lenny rebalances within budget. Bigger moves need a tap.'],
        ['autofix', 'Fix directory drift', 'Hours, address, photos, fixed without asking.']].
        map(([k, l, s]) => {
          const on = prefs[k];
          return (
            <div key={k} style={{ display: 'flex', alignItems: 'center', padding: '10px 0', borderBottom: '1px dashed var(--cream-3)' }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{l}</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{s}</div>
              </div>
              <div onClick={() => toggle(k)} style={{ width: 36, height: 20, background: on ? profile.accent : 'var(--cream-3)', borderRadius: 10, position: 'relative', cursor: 'pointer', transition: 'background .2s' }}>
                <div style={{ position: 'absolute', top: 2, left: on ? 18 : 2, width: 16, height: 16, background: 'var(--paper)', borderRadius: '50%', boxShadow: 'var(--sh-1)', transition: 'left .2s' }} />
              </div>
            </div>);

        })}
        <div style={{ marginTop: 12, padding: 12, background: 'var(--violet-soft, rgba(77,105,137,0.08))', borderRadius: 8, fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.5 }}>
          <strong style={{ color: 'var(--violet)' }}>🦙 Lenny's voice for this store:</strong> Warm, slightly playful, uses "y'all" naturally. Trained on your last 90 days of replies + the master brand voice guide.
        </div>
      </div>
    </div>);

}

// ====================================================================
// HQ SETTINGS, Role Management + Brand Guidelines
// ====================================================================
// Phase 2 banner, marks a feature as visible-but-not-yet-live
function Phase2Banner({ children }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '14px 16px', marginBottom: 18, 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 }}>{children}</div>
      </div>
    </div>
  );
}

function HqSettingsPage({ data }) {
  const [tab, setTab] = useStateP(window.__settingsTab || 'team');
  React.useEffect(() => {
    if (window.__settingsTab) { window.__settingsTab = null; }
    const onTab = (e) => setTab(e.detail);
    window.addEventListener('set-settings-tab', onTab);
    return () => window.removeEventListener('set-settings-tab', onTab);
  }, []);
  return (
    <div className="page active">
      <div className="page-header">
        <div>
          <div className="page-title">Settings.</div>
          <div className="page-sub">Team access, brand standards, and network-wide controls for FreshNest corporate.</div>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 4, borderBottom: '1px solid var(--cream-3)', marginBottom: 22 }}>
        {[
        { k: 'team', label: 'Team & Roles', count: 14 },
        { k: 'brand', label: 'Brand Standards' },
        { k: 'governance', label: 'Approval Workflows', phase2: true },
        { k: 'playbook', label: 'Network Playbook' },
        { k: 'mcp', label: 'MCP for Clients', phase2: true },
        { k: 'audit', label: 'Audit Log' }].
        map((t) =>
        <button key={t.k} onClick={() => setTab(t.k)} style={{
          padding: '10px 16px', fontSize: 13, fontWeight: 600, fontFamily: 'var(--ff-ui)',
          border: 'none', background: 'transparent', cursor: 'pointer',
          color: tab === t.k ? 'var(--ink)' : 'var(--ink-3)',
          borderBottom: tab === t.k ? '2px solid var(--violet)' : '2px solid transparent',
          marginBottom: -1, display: 'flex', alignItems: 'center', gap: 6
        }}>
            {t.label}
            {t.count != null && <span style={{ fontSize: 10.5, padding: '1px 6px', borderRadius: 8, background: tab === t.k ? 'var(--violet-soft, rgba(77,105,137,0.12))' : 'var(--cream-2)', color: tab === t.k ? 'var(--violet)' : 'var(--ink-3)', fontWeight: 700 }}>{t.count}</span>}
            {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' }}>Phase 2</span>}
          </button>
        )}
      </div>

      {tab === 'team' && <HqSettingsTeam />}
      {tab === 'brand' && <HqSettingsBrand />}
      {tab === 'governance' && <HqSettingsGovernance />}
      {tab === 'playbook' && <HqSettingsPlaybook />}
      {tab === 'mcp' && <HqSettingsMcp />}
      {tab === 'audit' && <HqAuditLog />}
    </div>);

}

// --------------------------------------------------------------------
// CREATIVE LIBRARY
// Choose where creative lives: LOCALACT's built-in library or a
// client-managed external DAM (linked with access details), or both.
// --------------------------------------------------------------------
const CREATIVE_PLATFORMS = ['Brandfolder', 'Bynder', 'Frontify', 'Canva', 'Google Drive', 'Dropbox', 'SharePoint', 'Other'];

function HqSettingsCreative({ data }) {
  const [mode, setMode] = useStateP('localact'); // 'localact' | 'external'
  const [keepLocal, setKeepLocal] = useStateP(false); // keep a LOCALACT library while external is primary
  const [ext, setExt] = useStateP({ connected: false, name: '', platform: 'Brandfolder', url: '', access: '', contact: '' });
  const [editing, setEditing] = useStateP(false);
  const [form, setForm] = useStateP(ext);

  const startConnect = () => { setForm(ext.connected ? ext : { connected: false, name: '', platform: 'Brandfolder', url: '', access: '', contact: '' }); setEditing(true); };
  const saveConnect = () => {
    if (!form.name.trim() || !form.url.trim()) { T('Add a name and URL', 'A library name and link are required to connect.', 'info'); return; }
    setExt({ ...form, connected: true }); setEditing(false);
    T('Library linked', `${form.name} connected. Local users can now click out to it.`, 'ok');
  };
  const openExternal = () => T('Opening ' + (ext.name || 'library'), `${ext.url}, opens in a new tab for users with access.`, 'info');

  const SrcCard = ({ id, icon, title, desc }) => {
    const on = mode === id;
    return (
      <button onClick={() => setMode(id)} style={{
        flex: 1, textAlign: 'left', cursor: 'pointer', background: on ? 'var(--violet-soft, rgba(77,105,137,0.08))' : 'var(--paper)',
        border: on ? '2px solid var(--violet)' : '1px solid var(--cream-3)', borderRadius: 14, padding: '16px 18px',
        display: 'flex', flexDirection: 'column', gap: 8, fontFamily: 'var(--ff-ui)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 34, height: 34, borderRadius: 10, background: on ? 'var(--violet)' : 'var(--cream-2)', color: on ? '#fff' : 'var(--ink-3)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{icon}</div>
          <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink)' }}>{title}</div>
          <span style={{ marginLeft: 'auto', width: 18, height: 18, borderRadius: '50%', border: on ? '5px solid var(--violet)' : '2px solid var(--cream-3)', flexShrink: 0 }}/>
        </div>
        <div style={{ fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.5 }}>{desc}</div>
      </button>
    );
  };

  const fieldStyle = { width: '100%', padding: '9px 11px', fontSize: 13, fontFamily: 'var(--ff-ui)', border: '1px solid var(--cream-3)', borderRadius: 8, background: 'var(--paper)', color: 'var(--ink)', boxSizing: 'border-box' };
  const labelStyle = { fontSize: 10.5, fontWeight: 700, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 5, display: 'block' };

  const linkIcon = <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1"/><path d="M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1"/></svg>;
  const galleryIcon = <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg>;

  return (
    <div>
      {/* Intro */}
      <div style={{ marginBottom: 18 }}>
        <div style={{ fontFamily: 'var(--ff-display)', fontSize: 17, fontWeight: 600, color: 'var(--ink)' }}>Creative library</div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 3 }}>Decide where FreshNest's creative lives. Manage it inside LOCALACT, or link a client-managed library, you can do both.</div>
      </div>

      {/* Source selector */}
      <div style={{ display: 'flex', gap: 12, marginBottom: 22 }}>
        <SrcCard id="localact" icon={galleryIcon} title="Use LOCALACT"
          desc="Store, categorize, and push creative from inside LOCALACT, evergreen, seasonal, and holiday, with full expired & archived history." />
        <SrcCard id="external" icon={linkIcon} title="Client-managed library"
          desc="The client maintains creative in their own DAM. LOCALACT links out with access details, no duplicate uploads." />
      </div>

      {/* Client-managed library link */}
      <div className="card card-pad" style={{ marginBottom: 22 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
          <span style={{ color: 'var(--ink-3)', display: 'flex' }}>{linkIcon}</span>
          <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink)' }}>Client-managed library link</span>
          {mode === 'external' && <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 8px', borderRadius: 999, background: 'var(--violet-soft, rgba(77,105,137,0.12))', color: 'var(--violet)' }}>PRIMARY</span>}
        </div>
        <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 14 }}>Add a link to the client's external creative library with access details so local users can click straight out to it.</div>

        {ext.connected && !editing ? (
          <div style={{ border: '1px solid var(--cream-3)', borderRadius: 12, padding: '14px 16px' }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
              <div style={{ width: 38, height: 38, borderRadius: 10, background: 'var(--sky-soft)', color: 'var(--sky)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{linkIcon}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink)' }}>{ext.name}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 1 }}>
                  <span style={{ fontWeight: 700 }}>{ext.platform}</span> · <span style={{ fontFamily: 'var(--ff-mono)' }}>{ext.url}</span>
                </div>
                {ext.access && <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6 }}><strong style={{ color: 'var(--ink-2)' }}>Access:</strong> {ext.access}</div>}
                {ext.contact && <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}><strong style={{ color: 'var(--ink-2)' }}>Contact:</strong> {ext.contact}</div>}
              </div>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, fontWeight: 700, color: '#17743f', flexShrink: 0 }}>
                <span style={{ width: 7, height: 7, borderRadius: '50%', background: '#1f9d55' }}/> Linked
              </span>
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
              <button className="btn btn-primary btn-sm" onClick={openExternal}>Open library →</button>
              <button className="btn btn-ghost btn-sm" onClick={startConnect}>Edit link</button>
              <span style={{ flex: 1 }}/>
              <button className="btn btn-quiet btn-sm" onClick={() => { setExt({ connected: false, name: '', platform: 'Brandfolder', url: '', access: '', contact: '' }); T('Library unlinked', 'External library disconnected.', 'info'); }}>Disconnect</button>
            </div>
          </div>
        ) : editing ? (
          <div style={{ border: '1px solid var(--cream-3)', borderRadius: 12, padding: '16px', display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <div>
                <label style={labelStyle}>Library name</label>
                <input style={fieldStyle} value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder="e.g. FreshNest Brandfolder"/>
              </div>
              <div>
                <label style={labelStyle}>Platform</label>
                <select style={{ ...fieldStyle, cursor: 'pointer' }} value={form.platform} onChange={e => setForm({ ...form, platform: e.target.value })}>
                  {CREATIVE_PLATFORMS.map(p => <option key={p} value={p}>{p}</option>)}
                </select>
              </div>
            </div>
            <div>
              <label style={labelStyle}>Library URL</label>
              <input style={fieldStyle} value={form.url} onChange={e => setForm({ ...form, url: e.target.value })} placeholder="https://freshnest.brandfolder.com"/>
            </div>
            <div>
              <label style={labelStyle}>Access details</label>
              <textarea style={{ ...fieldStyle, minHeight: 60, resize: 'vertical' }} value={form.access} onChange={e => setForm({ ...form, access: e.target.value })} placeholder="Who has access and how to get in, SSO, shared login, request process…"/>
            </div>
            <div>
              <label style={labelStyle}>Admin contact</label>
              <input style={fieldStyle} value={form.contact} onChange={e => setForm({ ...form, contact: e.target.value })} placeholder="brand-team@freshnest.com"/>
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <button className="btn btn-primary btn-sm" onClick={saveConnect}>{ext.connected ? 'Save link' : 'Connect library'}</button>
              <button className="btn btn-ghost btn-sm" onClick={() => setEditing(false)}>Cancel</button>
            </div>
          </div>
        ) : (
          <div style={{ border: '2px dashed var(--cream-3)', borderRadius: 12, padding: '24px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, textAlign: 'center' }}>
            <div style={{ width: 40, height: 40, borderRadius: 11, background: 'var(--cream)', color: 'var(--ink-4)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{linkIcon}</div>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', maxWidth: 360 }}>No external library linked yet. Add the client's creative library and the access details your team needs.</div>
            <button className="btn btn-primary btn-sm" onClick={startConnect}>+ Add library link</button>
          </div>
        )}
      </div>

      {/* LOCALACT library */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
        <span style={{ color: 'var(--ink-3)', display: 'flex' }}>{galleryIcon}</span>
        <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink)' }}>LOCALACT creative library</span>
        {mode === 'localact' && <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 8px', borderRadius: 999, background: 'var(--violet-soft, rgba(77,105,137,0.12))', color: 'var(--violet)' }}>PRIMARY</span>}
      </div>
      <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 16 }}>
        {mode === 'localact'
          ? 'Upload national creative and push it to selected or all locations. Local stores manage their own images too.'
          : 'External library is primary, but you can still keep evergreen, seasonal & holiday creative here in LOCALACT.'}
      </div>

      {(mode === 'localact' || keepLocal)
        ? <window.ImageLibrary scope="hq" data={data}/>
        : (
          <div style={{ border: '1px dashed var(--cream-3)', borderRadius: 12, padding: '24px', textAlign: 'center' }}>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 12 }}>You're using a client-managed library as your primary source. Want to keep some creative inside LOCALACT too?</div>
            <button className="btn btn-ghost btn-sm" onClick={() => setKeepLocal(true)}>Maintain a LOCALACT library too</button>
          </div>
        )}
    </div>
  );
}

// --------------------------------------------------------------------
// TEAM & ROLES
// --------------------------------------------------------------------
// Two branches: Corporate (franchisor / enterprise) roles and Local (operator)
// roles. `branch` groups them; `short` is the compact label used in the matrix.
const HQ_ROLES = [
{ key: 'owner', label: 'Owner (Billing Admin)', short: 'Owner', branch: 'corporate', color: '#001132', summary: 'Full access. Billing, payment methods, role management, brand guidelines, and every location.' },
{ key: 'admin', label: 'Marketing Admin', short: 'Mktg Admin', branch: 'corporate', color: '#4d6989', summary: 'Manage playbook, national programs, campaigns, and creative across all locations. Cannot change billing or roles.' },
{ key: 'analyst', label: 'Analyst', short: 'Analyst', branch: 'corporate', color: '#4d6989', summary: 'Read-only across all locations + can build custom reports. Cannot launch campaigns or move budget.' },
{ key: 'regional', label: 'Corporate Field Team', short: 'Field Team', branch: 'corporate', color: '#56adad', summary: 'Full access scoped to a field territory (a set of locations), including budget. Coaches those franchisees and can broadcast to them.' },
{ key: 'creative', label: 'Creative Manager', short: 'Creative', branch: 'corporate', color: '#e46c63', summary: 'Upload + edit creative kits, brand guidelines, and the asset library. No spend or budget authority.' },
{ key: 'localAdmin', label: 'Local Admin', short: 'Local Admin', branch: 'local', color: '#917200', summary: 'Manages their own location(s): billing + payment methods, budget, and adding Local Users to those locations.' },
{ key: 'localUser', label: 'Local User', short: 'Local User', branch: 'local', color: '#8fa0b5', summary: 'Runs their own location(s): budget allocation and day-to-day marketing. No billing or user management.' }];


const HQ_TEAM = [
{ name: 'Lenny Park', email: 'lenny@freshnest.com', role: 'owner', scope: 'All 700 locations', mfa: true, status: 'active', last: '2 min ago', avatar: 'LP' },
{ name: 'Priya Raman', email: 'priya@freshnest.com', role: 'admin', scope: 'All 700 locations', mfa: true, status: 'active', last: '14 min ago', avatar: 'PR' },
{ name: 'Sarah Reyes', email: 'sarah@localact.com', role: 'admin', scope: 'All 700 locations', mfa: true, status: 'active', last: '1 hr ago', avatar: 'SR', external: true },
{ name: 'Marcus Chen', email: 'marcus@freshnest.com', role: 'analyst', scope: 'All 700 locations', mfa: true, status: 'active', last: '3 hr ago', avatar: 'MC' },
{ name: 'Diana Patel', email: 'diana@freshnest.com', role: 'creative', scope: 'All 700 locations', mfa: true, status: 'active', last: 'Yesterday', avatar: 'DP' },
{ name: 'Tom Reynolds', email: 'tom@freshnest.com', role: 'regional', scope: 'TX + OK · 38 locations', mfa: true, status: 'active', last: '4 hr ago', avatar: 'TR' },
{ name: 'Aisha Williams', email: 'aisha@freshnest.com', role: 'regional', scope: 'CA · 22 locations', mfa: true, status: 'active', last: 'Yesterday', avatar: 'AW' },
{ name: 'Brett Tanaka', email: 'brett@freshnest.com', role: 'regional', scope: 'FL + GA · 18 locations', mfa: false, status: 'active', last: '2 days ago', avatar: 'BT' },
{ name: 'Nicole Brooks', email: 'nicole@freshnest.com', role: 'analyst', scope: 'All 700 locations', mfa: true, status: 'pending', last: '–', avatar: 'NB' },
{ name: 'Jamal Foster', email: 'jamal@freshnest.com', role: 'creative', scope: 'All 700 locations', mfa: false, status: 'active', last: '1 week ago', avatar: 'JF' },
{ name: 'Alicia Chen', email: 'alicia@freshnest.com', role: 'localAdmin', scope: 'Austin Downtown · 4 locations', mfa: true, status: 'active', last: '12 min ago', avatar: 'AC' },
{ name: 'Carlos Mendez', email: 'carlos@freshnest.com', role: 'localUser', scope: 'Dallas Uptown', mfa: true, status: 'active', last: '4 hr ago', avatar: 'CM' },
{ name: 'Steve Walker', email: 'steve@oldemail.com', role: 'analyst', scope: 'All 700 locations', mfa: false, status: 'inactive', last: '92 days ago', avatar: 'SW' },
{ name: 'Lila Gomez', email: 'lila@freshnest.com', role: 'localUser', scope: 'Phoenix Westgate', mfa: true, status: 'active', last: '6 hr ago', avatar: 'LG' }];


function HqSettingsTeam() {
  const [filter, setFilter] = useStateP('all');
  const [search, setSearch] = useStateP('');
  const [inviteOpen, setInviteOpen] = useStateP(false);
  const [editMember, setEditMember] = useStateP(null);
  const [showRoles, setShowRoles] = useStateP(false);
  const [pulseRoles, setPulseRoles] = useStateP(false);

  // When the guided-review setup card is dismissed on this step, briefly pull
  // attention to the "What can each role do?" button. A timestamp flag covers
  // the case where this view remounts as the card closes.
  React.useEffect(() => {
    const trigger = () => {
      setPulseRoles(false);
      requestAnimationFrame(() => setPulseRoles(true));
      clearTimeout(window.__prTimer);
      window.__prTimer = setTimeout(() => setPulseRoles(false), 5200);
    };
    const h = (e) => {
      if (e.detail && e.detail.feature === 'settings') { window.__pulseRolesAt = Date.now(); trigger(); }
    };
    window.addEventListener('gr-intro-dismissed', h);
    if (window.__pulseRolesAt && Date.now() - window.__pulseRolesAt < 1200) trigger();
    return () => window.removeEventListener('gr-intro-dismissed', h);
  }, []);

  const counts = HQ_TEAM.reduce((acc, m) => {acc[m.role] = (acc[m.role] || 0) + 1;acc.all = (acc.all || 0) + 1;return acc;}, {});
  const filtered = HQ_TEAM.filter((m) =>
  (filter === 'all' || m.role === filter) && (
  !search || (m.name + m.email).toLowerCase().includes(search.toLowerCase()))
  );

  const noMfa = HQ_TEAM.filter((m) => !m.mfa && m.status === 'active').length;
  const stale = HQ_TEAM.filter((m) => /days|week/.test(m.last) && m.status === 'active').length;
  const pending = HQ_TEAM.filter((m) => m.status === 'pending').length;

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
        <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Search by name or email…"
        style={{ flex: 1, maxWidth: 320, padding: '9px 12px', fontSize: 13, fontFamily: 'var(--ff-ui)', border: '1px solid var(--cream-3)', borderRadius: 8, background: 'var(--paper)' }} />
        <div style={{ display: 'flex', gap: 4, padding: 3, background: 'var(--cream)', borderRadius: 8 }}>
          {[['all', 'All'], ['owner', 'Owners'], ['admin', 'Mktg Admins'], ['analyst', 'Analysts'], ['regional', 'Regional'], ['creative', 'Creative'], ['localAdmin', 'Local Admins'], ['localUser', 'Local Users']].map(([k, l]) =>
          <button key={k} onClick={() => setFilter(k)} style={{
            padding: '6px 11px', fontSize: 12, fontWeight: 600, border: 'none', borderRadius: 6, cursor: 'pointer',
            background: filter === k ? 'var(--paper)' : 'transparent',
            color: filter === k ? 'var(--ink)' : 'var(--ink-3)',
            boxShadow: filter === k ? '0 1px 2px rgba(0,0,0,0.06)' : 'none'
          }}>
              {l} <span style={{ opacity: 0.55, marginLeft: 3 }}>{counts[k] || 0}</span>
            </button>
          )}
        </div>
        <span style={{ flex: 1 }} />
        <style>{`@keyframes gr-roles-ring{0%{box-shadow:0 0 0 0 rgba(242,128,32,.55)}70%{box-shadow:0 0 0 11px rgba(242,128,32,0)}100%{box-shadow:0 0 0 0 rgba(242,128,32,0)}}@keyframes gr-roles-bob{0%,100%{transform:translateY(0)}40%{transform:translateY(-3px)}}.gr-roles-attn{animation:gr-roles-ring 1.25s ease-out 3,gr-roles-bob 1.25s ease-in-out 3;border-color:var(--orange,#f28020)!important;color:var(--orange,#f28020)!important}`}</style>
        <button className={`btn btn-ghost btn-sm${pulseRoles ? ' gr-roles-attn' : ''}`} onClick={() => setShowRoles(true)}>What can each role do?</button>
        <button className="btn btn-primary btn-sm" onClick={() => setInviteOpen(true)}>+ Invite member</button>
      </div>

      <div className="card" style={{ overflow: 'hidden', padding: 0 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2.4fr 1.4fr 2fr 0.7fr 1fr 0.6fr', padding: '10px 18px', background: 'var(--cream)', borderBottom: '1px solid var(--cream-3)', fontSize: 10.5, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>
          <div>Member</div>
          <div>Role</div>
          <div>Scope</div>
          <div>MFA</div>
          <div>Last active</div>
          <div></div>
        </div>
        {filtered.map((m) => {
          const roleDef = HQ_ROLES.find((r) => r.key === m.role);
          return (
            <div key={m.email} style={{ display: 'grid', gridTemplateColumns: '2.4fr 1.4fr 2fr 0.7fr 1fr 0.6fr', padding: '14px 18px', borderBottom: '1px solid var(--cream-2)', alignItems: 'center', fontSize: 13, opacity: m.status === 'inactive' ? 0.55 : 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ width: 32, height: 32, borderRadius: '50%', background: roleDef.color, color: 'var(--paper)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700 }}>{m.avatar}</div>
                <div>
                  <div style={{ fontWeight: 600, color: 'var(--ink)' }}>
                    {m.name}
                    {m.external && <span style={{ marginLeft: 6, fontSize: 9.5, padding: '1px 6px', background: 'var(--violet-soft, rgba(77,105,137,0.12))', color: 'var(--violet)', borderRadius: 3, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase' }}>LOCALACT</span>}
                    {m.status === 'pending' && <span style={{ marginLeft: 6, fontSize: 9.5, padding: '1px 6px', background: 'var(--marigold-soft)', color: '#917200', borderRadius: 3, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase' }}>Pending</span>}
                    {m.status === 'inactive' && <span style={{ marginLeft: 6, fontSize: 9.5, padding: '1px 6px', background: 'var(--cream-2)', color: 'var(--ink-3)', borderRadius: 3, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase' }}>Inactive</span>}
                  </div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{m.email}</div>
                </div>
              </div>
              <div>
                <span style={{ display: 'inline-block', padding: '3px 8px', fontSize: 11.5, fontWeight: 600, background: roleDef.color + '15', color: roleDef.color, borderRadius: 4 }}>{roleDef.label}</span>
              </div>
              <div style={{ fontSize: 12, color: 'var(--ink-2)' }}>{m.scope}</div>
              <div>
                {m.mfa ? <span style={{ fontSize: 11, color: '#56adad', fontWeight: 700 }}>● ON</span> : <span style={{ fontSize: 11, color: '#e46c63', fontWeight: 700 }}>● OFF</span>}
              </div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{m.last}</div>
              <div style={{ textAlign: 'right' }}>
                <button onClick={() => setEditMember(m)} style={{ background: 'transparent', border: 'none', color: 'var(--ink-3)', fontSize: 13, cursor: 'pointer', padding: '4px 8px' }}>Edit ›</button>
              </div>
            </div>);

        })}
      </div>

      {inviteOpen && <HqInviteModal onClose={() => setInviteOpen(false)} />}
      {editMember && <HqMemberEditModal member={editMember} onClose={() => setEditMember(null)} />}
      {showRoles && <HqRolesModal onClose={() => setShowRoles(false)} />}
    </div>);

}

function HqStat({ label, v, sub, accent, action }) {
  return (
    <div className="card card-pad">
      <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-4)', marginBottom: 6 }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <div style={{ fontFamily: 'var(--ff-display)', fontSize: 28, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.02em' }}>{v}</div>
        {action && <button style={{ marginLeft: 'auto', background: 'transparent', border: 'none', color: accent, fontSize: 12, fontWeight: 700, cursor: 'pointer', padding: 0 }}>{action} →</button>}
      </div>
      <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 4 }}>{sub}</div>
    </div>);

}

function HqInviteModal({ onClose }) {
  const [email, setEmail] = useStateP('');
  const [role, setRole] = useStateP('analyst');
  const [scope, setScope] = useStateP('all');
  const [msg, setMsg] = useStateP('');
  const roleDef = HQ_ROLES.find((r) => r.key === role);
  return (
    <window.ModalPortal><div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(36,30,28,0.55)', zIndex: 9000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: 'var(--paper)', borderRadius: 14, width: '100%', maxWidth: 580, padding: 26, boxShadow: '0 20px 60px rgba(0,0,0,0.25)', maxHeight: '92vh', overflow: 'auto' }}>
        <div style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 6 }}>Invite team member</div>
        <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 600, color: 'var(--ink)', marginBottom: 4, letterSpacing: '-0.015em' }}>Who's joining?</div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 18 }}>They'll get an invite email and need to set up MFA before their first login.</div>

        <SetField label="Email">
          <input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="firstname@freshnest.com" style={setInputStyle} />
        </SetField>

        <SetField label="Role">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 4 }}>
            {HQ_ROLES.filter((r) => r.key !== 'owner').map((r) =>
              <label key={r.key} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 12px', border: `1.5px solid ${role === r.key ? r.color : 'var(--cream-3)'}`, borderRadius: 10, cursor: 'pointer', background: role === r.key ? r.color + '0a' : 'var(--paper)' }}>
                <input type="radio" checked={role === r.key} onChange={() => setRole(r.key)} style={{ marginTop: 2, accentColor: r.color }} />
                <div>
                  <div style={{ fontSize: 12.5, fontWeight: 600 }}>{r.label}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)', lineHeight: 1.4, marginTop: 2 }}>{r.summary}</div>
                </div>
              </label>
              )}
          </div>
        </SetField>

        <SetField label="Scope">
          <select value={scope} onChange={(e) => setScope(e.target.value)} style={setInputStyle}>
            <option value="all">All 700 locations</option>
            <option value="tx">Texas region (38 locations)</option>
            <option value="ca">California region (22 locations)</option>
            <option value="fl">Florida + Georgia (18 locations)</option>
            <option value="custom">Custom location set…</option>
          </select>
        </SetField>

        <SetField label="Personal message (optional)">
          <textarea value={msg} onChange={(e) => setMsg(e.target.value)} placeholder="Welcome to LOCALACT! You'll find our brand guidelines and active campaigns under…" rows={3} style={{ ...setInputStyle, resize: 'vertical', fontFamily: 'var(--ff-ui)' }} />
        </SetField>

        <div style={{ padding: '12px 14px', background: 'var(--violet-soft, rgba(77,105,137,0.08))', borderRadius: 8, fontSize: 12, color: 'var(--ink-2)', marginBottom: 18 }}>
          <strong style={{ color: roleDef.color }}>{roleDef.label}</strong>, {roleDef.summary}
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderTop: '1px solid var(--cream-3)', paddingTop: 14 }}>
          <span style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>Invite expires in 7 days · MFA required on first login</span>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-ghost btn-sm" onClick={onClose}>Cancel</button>
            <button className="btn btn-primary btn-sm" disabled={!email}
              onClick={() => {onClose();T('Invite sent', `${email} invited as ${roleDef.label}.`, 'ok');}}>Send invite →</button>
          </div>
        </div>
      </div>
    </div></window.ModalPortal>);

}

function HqMemberEditModal({ member, onClose }) {
  const [role, setRole] = useStateP(member.role);
  const [scope, setScope] = useStateP(member.scope);
  const roleDef = HQ_ROLES.find((r) => r.key === role);
  return (
    <window.ModalPortal><div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(36,30,28,0.55)', 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: 26, boxShadow: '0 20px 60px rgba(0,0,0,0.25)', maxHeight: '92vh', overflow: 'auto' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
          <div style={{ width: 44, height: 44, borderRadius: '50%', background: roleDef.color, color: 'var(--paper)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14, fontWeight: 700 }}>{member.avatar}</div>
          <div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)' }}>{member.name}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{member.email}</div>
          </div>
        </div>

        <SetField label="Role">
          <select value={role} onChange={(e) => setRole(e.target.value)} style={setInputStyle}>
            {HQ_ROLES.map((r) => <option key={r.key} value={r.key}>{r.label}</option>)}
          </select>
          <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 6, lineHeight: 1.4 }}>{roleDef.summary}</div>
        </SetField>

        <SetField label="Scope">
          <input value={scope} onChange={(e) => setScope(e.target.value)} style={setInputStyle} />
        </SetField>

        <div style={{ padding: '12px 14px', background: 'var(--cream)', borderRadius: 8, marginBottom: 14 }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-4)', marginBottom: 8 }}>Account status</div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 12.5, padding: '4px 0' }}>
            <span>MFA enrolled</span>
            <span style={{ fontWeight: 700, color: member.mfa ? '#56adad' : '#e46c63' }}>{member.mfa ? 'Yes' : 'No'}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 12.5, padding: '4px 0' }}>
            <span>Last active</span>
            <span style={{ color: 'var(--ink-2)' }}>{member.last}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 12.5, padding: '4px 0' }}>
            <span>Status</span>
            <span style={{ color: 'var(--ink-2)', textTransform: 'capitalize' }}>{member.status}</span>
          </div>
        </div>

        <div style={{ display: 'flex', gap: 8, justifyContent: 'space-between', borderTop: '1px solid var(--cream-3)', paddingTop: 14 }}>
          <div style={{ display: 'flex', gap: 6 }}>
            <button className="btn btn-ghost btn-sm" style={{ color: '#e46c63' }} onClick={() => {onClose();T('Member removed', `${member.name} no longer has access.`, 'warn');}}>Remove access</button>
            {!member.mfa && <button className="btn btn-ghost btn-sm" onClick={() => {onClose();T('MFA reset email sent', `${member.name} will be required to re-enroll on next login.`, 'ok');}}>Force MFA reset</button>}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-ghost btn-sm" onClick={onClose}>Cancel</button>
            <button className="btn btn-primary btn-sm" onClick={() => {onClose();T('Saved', `${member.name} updated.`, 'ok');}}>Save</button>
          </div>
        </div>
      </div>
    </div></window.ModalPortal>);

}

function HqRolesModal({ onClose }) {
  const PERMS = [
  { label: 'View all locations', owner: 'Y', admin: 'Y', analyst: 'Y', regional: 'Scope', creative: 'Y', localAdmin: 'Own', localUser: 'Own' },
  { label: 'Launch / pause campaigns', owner: 'Y', admin: 'Y', analyst: '–', regional: 'Scope', creative: '–', localAdmin: 'Own', localUser: 'Own' },
  { label: 'Manage budget allocation', owner: 'Y', admin: 'Y', analyst: '–', regional: 'Scope', creative: '–', localAdmin: 'Own', localUser: 'Own' },
  { label: 'Modify playbook + national programs', owner: 'Y', admin: 'Y', analyst: '–', regional: '–', creative: '–', localAdmin: '–', localUser: '–' },
  { label: 'Upload / edit brand guidelines + creative kits', owner: 'Y', admin: 'Y', analyst: '–', regional: '–', creative: 'Y', localAdmin: '–', localUser: '–' },
  { label: 'Broadcast to franchisees', owner: 'Y', admin: 'Y', analyst: '–', regional: 'Scope', creative: '–', localAdmin: '–', localUser: '–' },
  { label: 'Approve creative submissions', owner: 'Y', admin: 'Y', analyst: '–', regional: 'Scope', creative: 'Y', localAdmin: '–', localUser: '–' },
  { label: 'Build custom reports', owner: 'Y', admin: 'Y', analyst: 'Y', regional: 'Scope', creative: '–', localAdmin: 'Own', localUser: 'Own' },
  { label: 'Manage billing + payment methods', owner: 'Y', admin: '–', analyst: '–', regional: '–', creative: '–', localAdmin: 'Own', localUser: '–' },
  { label: 'Add / remove Local Users (own locations)', owner: 'Y', admin: '–', analyst: '–', regional: '–', creative: '–', localAdmin: 'Own', localUser: '–' },
  { label: 'Add / remove corporate members', owner: 'Y', admin: '–', analyst: '–', regional: '–', creative: '–', localAdmin: '–', localUser: '–' },
  { label: 'Change role permissions', owner: 'Y', admin: '–', analyst: '–', regional: '–', creative: '–', localAdmin: '–', localUser: '–' }];

  return (
    <window.ModalPortal><div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(36,30,28,0.55)', zIndex: 9000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: 'var(--paper)', borderRadius: 14, width: '100%', maxWidth: 1000, padding: 26, boxShadow: '0 20px 60px rgba(0,0,0,0.25)', maxHeight: '92vh', overflow: 'auto' }}>
        <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 600, marginBottom: 4, letterSpacing: '-0.015em' }}>What each role can do</div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 20 }}>LOCALACT separates access into <strong style={{ color: 'var(--ink-2)' }}>Corporate</strong> roles, which govern the whole network, and <strong style={{ color: 'var(--ink-2)' }}>Local</strong> roles, which are scoped to a user's own location(s). Custom roles can be defined for enterprise plans, talk to your Strategy Director.</div>

        {/* Role definition cards, the primary focus */}
        {[['corporate', 'Corporate roles', 'Govern strategy, spend, and access across the whole network'], ['local', 'Local roles', "Scoped to a single operator's own location(s)"]].map(([branch, heading, blurb]) => (
          <div key={branch} style={{ marginBottom: 20 }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-4)', marginBottom: 3 }}>{heading}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 10 }}>{blurb}</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: 10 }}>
              {HQ_ROLES.filter((r) => r.branch === branch).map((r) => (
                <div key={r.key} style={{ border: '1px solid var(--cream-3)', borderRadius: 12, padding: '13px 15px', borderTop: `3px solid ${r.color}` }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 5 }}>
                    <span style={{ width: 9, height: 9, borderRadius: '50%', background: r.color, flexShrink: 0 }} />
                    <span style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--ink)' }}>{r.label}</span>
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.5 }}>{r.summary}</div>
                </div>
              ))}
            </div>
          </div>
        ))}

        <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-4)', marginBottom: 8 }}>Permission matrix</div>
        <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 12 }}>“<strong style={{ color: 'var(--ink-2)' }}>●</strong>” = full access · “<strong style={{ color: 'var(--ink-2)' }}>Scope</strong>” = within assigned region · “<strong style={{ color: 'var(--ink-2)' }}>Own</strong>” = their own location(s) only · “<strong style={{ color: 'var(--ink-2)' }}>–</strong>” = no access.</div>

        <div style={{ display: 'grid', gridTemplateColumns: '2fr repeat(7, 1fr)', fontSize: 12, border: '1px solid var(--cream-3)', borderRadius: 10, overflow: 'hidden' }}>
          <div style={{ padding: '10px 12px', background: 'var(--cream)', fontWeight: 700, fontSize: 10.5, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>Capability</div>
          {HQ_ROLES.map((r) =>
            <div key={r.key} style={{ padding: '10px 6px', background: r.branch === 'local' ? 'var(--marigold-soft, rgba(161,112,29,0.08))' : 'var(--cream)', fontWeight: 700, fontSize: 10, letterSpacing: '0.03em', textTransform: 'uppercase', color: r.color, textAlign: 'center', borderLeft: '1px solid var(--cream-3)', lineHeight: 1.25 }}>{r.short || r.label}</div>
            )}
          {PERMS.map((p, i) =>
            <React.Fragment key={i}>
              <div style={{ padding: '10px 12px', borderTop: '1px solid var(--cream-2)', color: 'var(--ink-2)' }}>{p.label}</div>
              {HQ_ROLES.map((r) => {
                const v = p[r.key];
                return (
                  <div key={r.key} style={{ padding: '10px 8px', borderTop: '1px solid var(--cream-2)', borderLeft: '1px solid var(--cream-3)', textAlign: 'center', fontSize: 11.5, fontWeight: v === 'Y' ? 700 : 600, color: v === 'Y' ? '#56adad' : v === '–' ? 'var(--ink-5)' : 'var(--ink-3)' }}>
                    {v === 'Y' ? '●' : v}
                  </div>);

              })}
            </React.Fragment>
            )}
        </div>

        <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16 }}>
          <button className="btn btn-primary btn-sm" onClick={onClose}>Got it</button>
        </div>
      </div>
    </div></window.ModalPortal>);

}

// --------------------------------------------------------------------
// NETWORK PLAYBOOK, the corporate decision system
// --------------------------------------------------------------------
// Small presentational helpers (module scope, Playbook-only)
function PbPrinciple({ children }) {
  return <div style={{ fontSize: 12, fontStyle: 'italic', color: 'var(--ink-4)', marginTop: 10 }}>{children}</div>;
}
function PbHead({ kicker, title, lead }) {
  return (
    <div style={{ marginBottom: 18 }}>
      <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 6 }}>{kicker}</div>
      <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.015em', marginBottom: lead ? 8 : 0 }}>{title}</div>
      {lead && <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.65, maxWidth: 760 }}>{lead}</div>}
    </div>
  );
}
function PbSourceTag({ children }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 10.5, fontWeight: 600, color: 'var(--sky)', background: 'var(--sky-soft)', padding: '3px 8px', borderRadius: 999 }}>
      <svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z"/><path d="M2 12h20M12 2a15 15 0 0 1 0 20M12 2a15 15 0 0 0 0 20"/></svg>
      {children}
    </span>
  );
}

function HqSettingsPlaybook() {
  const [section, setSection] = useStateP('service');

  // Live plan-progress (network of 700 locations)
  const progress = [
    { k: 'Following the plan', v: 612, sub: '87% of 700', c: 'var(--ok)', bg: 'var(--sage-soft)' },
    { k: 'Recommended for increase', v: 84, sub: 'strong performance', c: 'var(--brand-navy)', bg: 'var(--sky-soft)' },
    { k: 'Struggling', v: 71, sub: 'below goal', c: 'var(--warn)', bg: 'var(--marigold-soft)' },
    { k: 'Aggressive recovery', v: 14, sub: '3+ months low', c: 'var(--bad)', bg: 'var(--berry-soft)' },
  ];

  const NAV = [
    { k: 'service', label: 'Channel Strategy' },
    { k: 'budget', label: 'Budget Strategy' },
    { k: 'optimization', label: 'Optimization Rules' },
    { k: 'kpis', label: 'KPIs & Goals' },
    { k: 'content', label: 'Content & Reviews' },
  ];

  return (
    <div>
      {/* ---- Cover / meta ---- */}
      <div className="card" style={{ marginBottom: 18, background: 'var(--navy, #002857)', border: 'none', overflow: 'hidden' }}>
        <div style={{ padding: '24px 28px', color: '#FFF' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 16 }}>
            <div>
              <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', opacity: 0.55, marginBottom: 8 }}>FreshNest Network Playbook · v3.2</div>
              <div style={{ fontFamily: 'var(--ff-display)', fontSize: 26, fontWeight: 700, letterSpacing: '-0.015em', marginBottom: 8 }}>Our decision system.</div>
              <div style={{ fontSize: 13.5, lineHeight: 1.6, maxWidth: 640, opacity: 0.82 }}>
                The playbook governs how strategy is applied across all 700 locations, what services to run, how budgets move, when we optimize, and what success means. LOCALACT flags the signal; the playbook defines the response.
              </div>
            </div>
            <div style={{ textAlign: 'right', flexShrink: 0 }}>
              <div style={{ fontSize: 11, opacity: 0.6 }}>Published Mar 4, 2026</div>
              <div style={{ fontSize: 11, opacity: 0.6 }}>by Sam Patel · VP Marketing</div>
            </div>
          </div>
        </div>
      </div>

      {/* ---- Plan progress (live) ---- */}
      <div className="section-label">Plan progress <span style={{ fontSize: 11, color: 'var(--ink-4)', fontWeight: 500 }}>· live across the network</span></div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 24 }}>
        {progress.map((p) =>
          <div key={p.k} className="card card-pad" style={{ padding: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: p.c }} />
              <span style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>{p.k}</span>
            </div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 30, fontWeight: 600, color: 'var(--ink)', lineHeight: 1 }}>{p.v}</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 5 }}>{p.sub}</div>
          </div>
        )}
      </div>

      {/* ---- Section nav ---- */}
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 18 }}>
        {NAV.map((n) =>
          <button key={n.k} onClick={() => setSection(n.k)} style={{
            padding: '8px 16px', borderRadius: 999, fontSize: 12.5, fontWeight: 600, cursor: 'pointer',
            border: '1.5px solid ' + (section === n.k ? 'var(--violet)' : 'var(--cream-3)'),
            background: section === n.k ? 'var(--violet-soft)' : 'var(--paper)',
            color: section === n.k ? '#002857' : 'var(--ink-2)',
            transition: 'all .12s',
          }}>{n.label}</button>
        )}
      </div>

      {/* ============ SERVICE STRATEGY ============ */}
      {section === 'service' &&
        <div>
          <div className="card card-pad" style={{ marginBottom: 16 }}>
            <PbHead kicker="Service Strategy" title="What channel to run, and where"
              lead="Every FreshNest location runs the full service stack, but the emphasis shifts by market. We tune recommendations by client type, market condition, and performance stage so spend lands where it actually returns." />
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 4 }}>
              <PbSourceTag>Territory reach · geo-targeting + 3rd-party market data</PbSourceTag>
              <PbSourceTag>Competitiveness · 3rd-party competitive index</PbSourceTag>
            </div>
            <PbPrinciple>Prevents misuse of services, the right channels for the market, not a one-size template.</PbPrinciple>
          </div>

          <div className="section-label">Recommendation by market type</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 16 }}>
            {[
              { t: 'Rural', reach: 'Wide · 15–30 mi radius', comp: 'Typically low', c: 'var(--sage)', bg: 'var(--sage-soft)',
                emphasis: ['Local SEO + Listings as the foundation', 'Wide-radius Google Search', 'LSA where service area qualifies', 'Light paid social, avoid tight-radius bid premiums'] },
              { t: 'Suburban', reach: 'Medium · 8–15 mi radius', comp: 'Moderate', c: 'var(--sky)', bg: 'var(--sky-soft)',
                emphasis: ['Balanced Search + LSA + Listings', 'Selective Meta for seasonal promos', 'Performance Max once Search is stable', 'Standard creative refresh cadence'] },
              { t: 'Metro', reach: 'Tight · 3–8 mi radius', comp: 'High', c: 'var(--violet)', bg: 'var(--violet-soft)',
                emphasis: ['Aggressive Search + Performance Max', 'Conquesting + competitor terms', 'Premium creative, faster refresh', 'Demand Gen + tight-radius bid boosts'] },
            ].map((m) =>
              <div key={m.t} className="card card-pad" style={{ borderTop: '3px solid ' + m.c }}>
                <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)', marginBottom: 10 }}>{m.t}</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 12 }}>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)' }}><span style={{ color: 'var(--ink-4)', fontWeight: 600 }}>Reach:</span> {m.reach}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)' }}><span style={{ color: 'var(--ink-4)', fontWeight: 600 }}>Competition:</span> {m.comp}</div>
                </div>
                <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8 }}>Service emphasis</div>
                <ul style={{ margin: 0, paddingLeft: 16, fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.7 }}>
                  {m.emphasis.map((e, i) => <li key={i}>{e}</li>)}
                </ul>
              </div>
            )}
          </div>

          <div className="card card-pad" style={{ background: 'var(--marigold-soft)', border: '1px solid rgba(161,112,29,0.18)' }}>
            <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)', marginBottom: 6 }}>Competitiveness modifier</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.6 }}>
              In high-competition markets (per the third-party competitive index), raise CPL ceilings, add conquesting keywords, shorten the creative-refresh cycle, and prioritize Performance Max. In low-competition markets, hold CPL tight and lean on organic, paid scale has diminishing returns.
            </div>
          </div>

          <div style={{ marginTop: 20 }}>
            <PbHead kicker="Success metrics" title="What each channel drives, and when to scale it"
              lead="Every channel earns its place with a business outcome and a clear scale signal, the metric threshold that says it's earning enough to put more budget behind it." />
            {window.ChannelPlaybookGrid && <window.ChannelPlaybookGrid/>}
          </div>
        </div>
      }

      {/* ============ BUDGET STRATEGY ============ */}
      {section === 'budget' &&
        <div>
          <div className="card card-pad" style={{ marginBottom: 16 }}>
            <PbHead kicker="Budget Strategy" title="Three tiers, one simple story"
              lead="Budget grows in three steps, not one leap: start at the floor to get in, land at the recommended level to actually compete, then scale to optimized only once the numbers earn it." />
            <PbPrinciple>Recommended and optimized levels vary by location, market, and service mix.</PbPrinciple>
          </div>

          {/* Three-tier story */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr auto 1fr', alignItems: 'stretch', marginBottom: 24 }}>
            {(() => {
              const tiers = [
                { k: 'Floor · minimum', phrase: 'Gets you in', c: 'var(--ink-4)', bg: 'var(--paper)',
                  desc: "The entry level. You can't enroll below it, and it varies by service and brand.", val: 'from $300/mo', valSub: 'varies by service' },
                { k: 'Recommended', phrase: 'Where it performs', c: 'var(--violet)', bg: 'var(--violet-soft)', hot: true,
                  desc: 'Our recommended starting budget for a location, enough to compete and learn across the full funnel.', val: '$1,500/mo', valSub: 'this example location' },
                { k: 'Optimized', phrase: 'Scale when earned', c: 'var(--sage)', bg: 'var(--paper)',
                  desc: 'The ceiling for this location, reached by scaling up as performance signals justify it.', val: '\u2248 $2,500/mo', valSub: 'scale as it earns' },
              ];
              const out = [];
              tiers.forEach((t, i) => {
                out.push(
                  <div key={t.k} className="card card-pad" style={{ background: t.bg, border: t.hot ? '1.5px solid var(--violet)' : '1px solid var(--cream-3)', display: 'flex', flexDirection: 'column' }}>
                    <div style={{ fontSize: 10, fontWeight: 700, color: t.c, textTransform: 'uppercase', letterSpacing: '0.07em', marginBottom: 6 }}>{t.k}</div>
                    <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.01em', marginBottom: 6 }}>{t.phrase}</div>
                    <div style={{ fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.55, marginBottom: 12, flex: 1 }}>{t.desc}</div>
                    <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 600, color: t.hot ? 'var(--violet)' : 'var(--ink)', letterSpacing: '-0.015em' }}>{t.val}</div>
                    <div style={{ fontSize: 10.5, color: 'var(--ink-4)', fontFamily: 'var(--ff-mono)', marginTop: 2 }}>{t.valSub}</div>
                  </div>
                );
                if (i < tiers.length - 1) out.push(
                  <div key={'arrow' + i} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink-5)', fontSize: 22, padding: '0 12px' }}>&rarr;</div>
                );
              });
              return out;
            })()}
          </div>

          {/* Recommended allocation */}
          <div className="section-label">Recommended allocation <span style={{ fontSize: 11, color: 'var(--ink-4)', fontWeight: 500 }}>&middot; example location at $1,500/mo</span></div>
          {(() => {
            const money = (v) => '$' + (v % 1 === 0 ? v.toLocaleString() : v.toFixed(2));
            const label = (ck) => ((window.channelPlay && window.channelPlay(ck)) || {}).label || ck;
            const funnel = [
              { stage: 'Awareness', pct: 30, amt: 450, c: 'var(--sky)', desc: 'Get in front of the right local audience.',
                rows: [{ ck: 'gbp', amt: 75, pct: 5 }, { ck: 'pmax', amt: 225, pct: 15 }, { ck: 'meta', amt: 150, pct: 10 }] },
              { stage: 'Consideration', pct: 40, amt: 600, c: 'var(--violet)', desc: 'Turn interest into active intent.',
                rows: [{ ck: 'search', amt: 300, pct: 20 }, { ck: 'demandgen', amt: 150, pct: 10 }, { ck: 'meta-rt', amt: 150, pct: 10 }] },
              { stage: 'Convert', pct: 30, amt: 450, c: 'var(--sage)', desc: 'Close ready-to-buy demand.',
                rows: [{ ck: 'brand-sem', amt: 225, pct: 15 }, { ck: 'lsa', amt: 112.5, pct: 7.5 }, { ck: 'meta-leadgen', amt: 112.5, pct: 7.5 }] },
            ];
            return (
              <>
                <div style={{ display: 'flex', height: 34, borderRadius: 8, overflow: 'hidden', border: '1px solid var(--cream-3)', marginBottom: 14 }}>
                  {funnel.map(f =>
                    <div key={f.stage} style={{ width: f.pct + '%', background: f.c, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 11.5, fontWeight: 700 }}>
                      {f.stage} &middot; {f.pct}%
                    </div>
                  )}
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
                  {funnel.map(f =>
                    <div key={f.stage} className="card card-pad" style={{ borderTop: '3px solid ' + f.c, padding: 16 }}>
                      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 2 }}>
                        <div style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 600, color: 'var(--ink)' }}>{f.stage}</div>
                        <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 12, fontWeight: 700, color: f.c }}>{f.pct}% &middot; {money(f.amt)}</div>
                      </div>
                      <div style={{ fontSize: 11, color: 'var(--ink-4)', lineHeight: 1.45, marginBottom: 10 }}>{f.desc}</div>
                      <div>
                        {f.rows.map((r, i) =>
                          <div key={r.ck} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '9px 0', borderBottom: i < f.rows.length - 1 ? '1px solid var(--cream-2)' : 'none' }}>
                            <span style={{ width: 7, height: 7, borderRadius: '50%', background: f.c, flexShrink: 0 }} />
                            <span style={{ fontSize: 12, color: 'var(--ink-2)', flex: 1, lineHeight: 1.3 }}>{label(r.ck)}</span>
                            <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 12, color: 'var(--ink)', fontWeight: 600 }}>{money(r.amt)}</span>
                            <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 10.5, color: 'var(--ink-4)', minWidth: 38, textAlign: 'right' }}>{r.pct}%</span>
                          </div>
                        )}
                      </div>
                    </div>
                  )}
                </div>
                <div className="card card-pad" style={{ marginTop: 12, display: 'flex', alignItems: 'center', gap: 12, background: 'var(--cream)' }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Total / month</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>Awareness 30% &middot; Consideration 40% &middot; Convert 30%</div>
                  <span style={{ flex: 1 }} />
                  <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 13, color: 'var(--ink-3)', fontWeight: 700 }}>100%</div>
                  <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 600, color: 'var(--ink)' }}>$1,500</div>
                </div>
              </>
            );
          })()}
        </div>
      }

      {/* ============ OPTIMIZATION RULES ============ */}
      {section === 'optimization' &&
        <div>
          <div className="card card-pad" style={{ marginBottom: 16 }}>
            <PbHead kicker="Optimization Rules" title="What triggers action, and how hard we push"
              lead="LOCALACT flags the issue; the playbook defines the response. Every location sits on an optimization ladder set by performance, the lower the tier, the more layers of intervention and human outreach it gets." />
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 4 }}>
              {['CPL too high', 'Lead volume drops', 'Channel underperformance'].map((t) =>
                <span key={t} style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--bad)', background: 'var(--berry-soft)', padding: '4px 10px', borderRadius: 999 }}>{t}</span>
              )}
            </div>
            <PbPrinciple>Product flags issues, playbook defines response.</PbPrinciple>
          </div>

          <div className="section-label">Optimization ladder <span style={{ fontSize: 11, color: 'var(--ink-4)', fontWeight: 500 }}>· locations per tier</span></div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {[
              { tier: 'Standard', who: 'Top performers', count: 396, c: 'var(--ok)', bg: 'var(--sage-soft)',
                does: ['Daily budget management', 'Negative keyword management', 'Standard creative changes'] },
              { tier: 'Enhanced', who: 'Mid-tier', count: 198, c: 'var(--sky)', bg: 'var(--sky-soft)',
                does: ['Everything in Standard', 'Bid-strategy changes (move to tROAS / tCPA)', 'Aggressive keyword-volume monitoring'] },
              { tier: 'Advanced', who: 'Underperforming', count: 71, c: 'var(--warn)', bg: 'var(--marigold-soft)',
                does: ['Everything in Enhanced', 'Territory / radius adjustment recommendations', 'Major ad-group restructures'] },
              { tier: 'Direct outreach', who: 'Bottom of the list', count: 21, c: 'var(--coral)', bg: 'var(--coral-soft, #fae6e4)',
                does: ['Everything in Advanced', 'Strategist calls the operator to align on a plan'] },
              { tier: 'Aggressive recovery', who: '3+ months low in a row', count: 14, c: 'var(--bad)', bg: 'var(--berry-soft)',
                does: ['Our most aggressive optimization stack', 'Priority outreach + weekly check-ins', 'Full account + territory rebuild'] },
            ].map((t, i) =>
              <div key={i} className="card card-pad" style={{ borderLeft: '3px solid ' + t.c, display: 'flex', gap: 16, alignItems: 'flex-start', flexWrap: 'wrap' }}>
                <div style={{ minWidth: 150, flexShrink: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                    <span style={{ width: 26, height: 26, borderRadius: 7, background: t.bg, color: t.c, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 12, flexShrink: 0 }}>{i + 1}</span>
                    <span style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 600, color: 'var(--ink)' }}>{t.tier}</span>
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 4, marginLeft: 34 }}>{t.who}</div>
                  <div style={{ marginTop: 8, marginLeft: 34, fontFamily: 'var(--ff-mono)', fontSize: 13, fontWeight: 700, color: t.c }}>{t.count} locations</div>
                </div>
                <ul style={{ margin: 0, paddingLeft: 16, fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.7, flex: 1, minWidth: 240 }}>
                  {t.does.map((d, j) => <li key={j}>{d}</li>)}
                </ul>
              </div>
            )}
          </div>
        </div>
      }

      {/* ============ KPIs & GOALS ============ */}
      {section === 'kpis' &&
        <div>
          <div className="card card-pad" style={{ marginBottom: 16 }}>
            <PbHead kicker="KPI Framework" title="What success actually means"
              lead="Goals are defined per metric, alongside the realistic share of locations we expect to hit them. 100% attainment is unrealistic across this many market and budget types, so the target is a percentage of the network, not every location." />
            <PbPrinciple>Prevents dashboards from being misinterpreted.</PbPrinciple>
          </div>

          <div className="card" style={{ overflow: 'hidden', marginBottom: 16 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1.2fr 1.4fr', padding: '10px 18px', background: 'var(--cream)', borderBottom: '1px solid var(--cream-3)', fontSize: 10.5, fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>
              <div>Metric</div><div>Goal</div><div>Target % of locations</div><div>Current</div>
            </div>
            {[
              { m: 'Cost per lead', goal: '≤ $40', target: 70, current: 64 },
              { m: 'Leads / month', goal: '≥ 25', target: 65, current: 67 },
              { m: 'ROAS', goal: '≥ 4.0x', target: 55, current: 58 },
              { m: 'LocalScore', goal: '≥ 75', target: 75, current: 72 },
              { m: 'Review rating', goal: '≥ 4.3★', target: 80, current: 78 },
            ].map((r, i) => {
              const hit = r.current >= r.target;
              return (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1.2fr 1.4fr', padding: '14px 18px', borderBottom: i < 4 ? '1px solid var(--cream-2)' : 'none', alignItems: 'center', fontSize: 13 }}>
                  <div style={{ fontWeight: 600, color: 'var(--ink)' }}>{r.m}</div>
                  <div style={{ fontFamily: 'var(--ff-mono)', color: 'var(--ink-2)', fontWeight: 600 }}>{r.goal}</div>
                  <div style={{ fontFamily: 'var(--ff-mono)', color: 'var(--ink-3)' }}>{r.target}%</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <div style={{ flex: 1, maxWidth: 120, height: 7, background: 'var(--cream-2)', borderRadius: 4, overflow: 'hidden' }}>
                      <div style={{ width: r.current + '%', height: '100%', background: hit ? 'var(--ok)' : 'var(--warn)', borderRadius: 4 }} />
                    </div>
                    <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 12.5, fontWeight: 700, color: hit ? 'var(--ok)' : 'var(--warn)' }}>{r.current}%</span>
                    <span style={{ fontSize: 10.5, fontWeight: 700, color: hit ? 'var(--ok)' : 'var(--warn)', textTransform: 'uppercase' }}>{hit ? 'On target' : 'Below'}</span>
                  </div>
                </div>
              );
            })}
          </div>
          <div className="card card-pad" style={{ background: 'var(--cream)' }}>
            <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.6 }}>
              <strong style={{ color: 'var(--ink)' }}>Reading the targets:</strong> a metric is healthy when the share of locations hitting its goal meets the target column, not when every location passes. Rural and low-budget locations are weighted into these expectations on purpose.
            </div>
          </div>
        </div>
      }

      {/* ============ CONTENT & REVIEWS ============ */}
      {section === 'content' &&
        <div>
          <div className="card card-pad" style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 8 }}>Brand voice &amp; tone</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 19, fontWeight: 600, color: 'var(--ink)', lineHeight: 1.4, marginBottom: 8 }}>
              "Friendly neighborhood expert. Confident, never pushy. Local first, name the city, the neighborhood, the regulars."
            </div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-3)', lineHeight: 1.6 }}>
              Every public-facing word, ad copy, posts, review replies, local page content, carries this voice. It's corporate-set and pushed to all 700 locations.
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 16 }}>
            <div className="card card-pad">
              <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)', marginBottom: 10 }}>Content strategy</div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.6, marginBottom: 12 }}>What to post, when, and why it matters. Not handled in product, the playbook is the source of truth.</div>
              {[
                ['What to post', 'Seasonal offers, local proof (photos, reviews), community moments, service spotlights.'],
                ['When to post', '2–3× / week minimum; lead seasonal pushes by 2 weeks; align to local events.'],
                ['Why it matters', 'Fresh local content lifts GBP ranking, listing engagement, and organic discovery.'],
              ].map(([t, d], i) =>
                <div key={i} style={{ padding: '8px 0', borderBottom: i < 2 ? '1px solid var(--cream-2)' : 'none' }}>
                  <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink)' }}>{t}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.5, marginTop: 2 }}>{d}</div>
                </div>
              )}
            </div>
            <div className="card card-pad">
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                <span style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)' }}>Review response strategy</span>
                <span style={{ fontSize: 9.5, fontWeight: 700, color: 'var(--violet)', background: 'var(--violet-soft)', padding: '2px 8px', borderRadius: 999, textTransform: 'uppercase', letterSpacing: '0.04em' }}>Future state</span>
              </div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.6, marginBottom: 12 }}>Product suggests, the playbook governs.</div>
              {[
                ['Tone', 'On-brand voice; thank by name, stay warm and specific, never defensive.'],
                ['Escalation rules', '1–2★ reviews escalate to the operator within 24h; legal/safety flags go to corporate.'],
                ['Ownership', 'Location owns day-to-day replies; corporate owns brand-risk and templated responses.'],
              ].map(([t, d], i) =>
                <div key={i} style={{ padding: '8px 0', borderBottom: i < 2 ? '1px solid var(--cream-2)' : 'none' }}>
                  <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink)' }}>{t}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.5, marginTop: 2 }}>{d}</div>
                </div>
              )}
            </div>
          </div>

          <div className="section-label">Digital performance guidance</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
            {[
              { t: 'Review responding', d: 'Reply to 100% of reviews within 48h. Responsiveness is a ranking and trust signal, slow replies cost discovery.' },
              { t: 'Local page updates', d: 'Keep hours, photos, services, and offers current. Refresh GBP posts weekly; audit NAP monthly.' },
              { t: 'Listings hygiene', d: 'Resolve directory issues within the week. Consistent listings across 42+ directories protect map pack placement.' },
            ].map((g, i) =>
              <div key={i} className="card card-pad" style={{ background: 'var(--cream)' }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', marginBottom: 6 }}>{g.t}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.55 }}>{g.d}</div>
              </div>
            )}
          </div>
        </div>
      }

      {/* ---- Upsell: new LOCALACT offerings (Channel Strategy sub-tab only) ---- */}
      {section === 'service' &&
      <div className="card card-pad" style={{ marginTop: 22, background: 'linear-gradient(120deg, var(--violet-soft) 0%, transparent 62%)', border: '1px solid var(--violet-soft)' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 18, flexWrap: 'wrap' }}>
          <div style={{ flex: 1, minWidth: 300 }}>
            <div style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 6 }}>New from LOCALACT</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 20, fontWeight: 600, color: 'var(--ink)', marginBottom: 8, letterSpacing: '-0.015em' }}>Add channels &amp; initiatives to the playbook</div>
            <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.55, maxWidth: 680, marginBottom: 12 }}>
              New offerings are ready to fold into the network plan. Add them once here and they flow into the right market tiers automatically.
            </div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {['AI Search Optimization', 'Connected TV', 'Retail Media', 'Reputation AI'].map((c) =>
                <span key={c} style={{ fontSize: 11.5, fontWeight: 600, color: '#002857', background: 'var(--paper)', border: '1px solid var(--violet-soft)', padding: '5px 11px', borderRadius: 999 }}>+ {c}</span>
              )}
            </div>
          </div>
          <button className="btn btn-primary btn-sm" style={{ background: 'var(--violet)', borderColor: 'var(--violet)' }} onClick={() => T('Explore add-ons', 'Opening new LOCALACT channels & initiatives to add to the FreshNest playbook.', 'info')}>Explore add-ons →</button>
        </div>
      </div>
      }
    </div>
  );
}

// LOCALACT MCP, Premium data connector
// --------------------------------------------------------------------
function HqSettingsMcp() {
  const [status, setStatus] = useStateP('inactive');
  const [showGuide, setShowGuide] = useStateP(false);
  return (
    <div>
      <Phase2Banner>MCP for Clients gives Claude and other AI tools direct, real-time access to your LOCALACT data so you can build custom workflows and integrations. This connector is on the Phase 2 roadmap, the preview below shows what it will do.</Phase2Banner>
      {status === 'inactive' ?
      <div>
        <div className="card" style={{ marginBottom: 18, background: 'var(--navy, #002857)', border: 'none', overflow: 'hidden' }}>
          <div style={{ padding: '24px 28px', color: '#FFF' }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', opacity: 0.55, marginBottom: 8 }}>Premium Feature</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 24, fontWeight: 700, letterSpacing: '-0.01em', marginBottom: 10 }}>LOCALACT MCP for Claude</div>
            <div style={{ fontSize: 13.5, lineHeight: 1.65, maxWidth: 640, marginBottom: 18, opacity: 0.8 }}>
              Direct, real-time access to all your FreshNest data, across all 700 locations, all channels. Build custom AI workflows, automate lead routing, generate insights, and integrate with your internal systems.
            </div>
            <button className="btn btn-primary btn-sm" onClick={() => setStatus('active')}>Unlock MCP Access</button>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14, marginBottom: 18 }}>
          <div className="card card-pad">
            <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 10 }}>What you get</div>
            <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)', marginBottom: 10 }}>Complete data access</div>
            <ul style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.75, paddingLeft: 18, margin: 0 }}>
              <li>All location budgets, spend, performance</li>
              <li>Lead data + phone call recordings + transcripts</li>
              <li>Customer reviews + sentiment analysis</li>
              <li>Service enrollment + pricing</li>
              <li>Google / Yelp / local listing data</li>
              <li>Local user activity + campaigns</li>
            </ul>
          </div>
          <div className="card card-pad">
            <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 10 }}>What you build</div>
            <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)', marginBottom: 10 }}>Custom AI workflows</div>
            <ul style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.75, paddingLeft: 18, margin: 0 }}>
              <li>Automated lead scoring + routing</li>
              <li>Real-time anomaly detection</li>
              <li>Custom reporting dashboards</li>
              <li>Predictive analytics</li>
              <li>CRM / system integrations</li>
              <li>Scheduled data pipelines</li>
            </ul>
          </div>
        </div>

        <div className="card card-pad" style={{ marginBottom: 18 }}>
          <div className="card-title" style={{ marginBottom: 14 }}>Use cases</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
            {[
            { title: 'Lead Qualification', desc: 'Auto-score leads from call data + reviews. Route high-intent prospects to your sales team.' },
            { title: 'Performance Ops', desc: 'Pull all-location budgets + KPIs. Feed into Slack, your CRM, or BI tool. No manual exports.' },
            { title: 'Smart Automation', desc: 'Build Claude agents that respond to anomalies in real-time, overspend alerts, enrollment drops, bad reviews.' }].
            map((u, i) =>
            <div key={i} style={{ padding: 14, borderRadius: 10, background: 'var(--cream)', border: '1px solid var(--cream-3)' }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', marginBottom: 4 }}>{u.title}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.5 }}>{u.desc}</div>
            </div>
            )}
          </div>
        </div>

        <div className="card card-pad" style={{ marginBottom: 18 }}>
          <div className="card-title" style={{ marginBottom: 14 }}>Security &amp; access</div>
          {[
          { label: 'Proprietary to LOCALACT', sub: 'Your competitors cannot access this connector. FreshNest-only.' },
          { label: 'Enterprise security', sub: 'API key auth, SOC 2 compliant, role-based access. Encrypted in transit and at rest.' },
          { label: 'Instant setup', sub: 'Install the MCP in Claude, connect your API key, and start building in minutes.' }].
          map((r, i) =>
          <div key={i} style={{ display: 'flex', gap: 12, padding: '10px 0', borderBottom: i < 2 ? '1px solid var(--cream-2)' : 'none', alignItems: 'flex-start' }}>
            <div style={{ width: 28, height: 28, borderRadius: 6, background: 'var(--violet-soft)', color: 'var(--violet)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 11, flexShrink: 0 }}>
              {['A','B','C'][i]}
            </div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>{r.label}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{r.sub}</div>
            </div>
          </div>
          )}
        </div>

        <div className="card card-pad" style={{ background: 'var(--marigold-soft)', border: '1px solid rgba(161,112,29,0.18)' }}>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)', marginBottom: 6 }}>Pricing · TBD</div>
          <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.6, marginBottom: 12 }}>
            We're finalizing pricing based on data volume and API usage. <strong>Early adopters get 50% off the first year.</strong> Contact us for a custom quote based on your network size.
          </div>
          <button className="btn btn-ghost btn-sm" onClick={() => T('Get pricing', 'Your LOCALACT account manager will reach out within 24 hours.', 'ok')}>Request pricing</button>
        </div>
      </div> :
      <div>
        <div className="card card-pad" style={{ marginBottom: 18, background: 'var(--navy, #002857)', border: 'none', color: '#FFF' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 14 }}>
            <div>
              <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', opacity: 0.55, marginBottom: 6 }}>Status</div>
              <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 700 }}>MCP Connection Live</div>
            </div>
            <span style={{ fontSize: 11, fontWeight: 700, padding: '4px 10px', background: '#56adad', color: '#0d4224', borderRadius: 20, letterSpacing: '0.04em', marginTop: 2 }}>Connected</span>
          </div>
          <div style={{ fontSize: 13, opacity: 0.75, marginBottom: 16 }}>Your LOCALACT MCP is connected and ready. Your API key is active and rotated quarterly for security.</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div>
              <div style={{ fontSize: 10.5, opacity: 0.5, marginBottom: 4, textTransform: 'uppercase', letterSpacing: '0.06em' }}>API Key</div>
              <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 11.5, wordBreak: 'break-all', background: 'rgba(255,255,255,0.08)', padding: '8px 10px', borderRadius: 8 }}>la_mcp_****...n92kx</div>
            </div>
            <div>
              <div style={{ fontSize: 10.5, opacity: 0.5, marginBottom: 4, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Last rotated</div>
              <div style={{ fontSize: 13, paddingTop: 8 }}>Mar 8, 2026</div>
            </div>
          </div>
        </div>

        <div className="card card-pad" style={{ marginBottom: 22 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
            <div className="card-title" style={{ marginBottom: 0 }}>Setup guide</div>
            <button className="btn btn-ghost btn-sm" style={{ fontSize: 11 }} onClick={() => setShowGuide(!showGuide)}>
              {showGuide ? 'Hide' : 'Show'} guide
            </button>
          </div>
          {showGuide && (
            <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.8, background: 'var(--cream)', padding: 16, borderRadius: 10, fontFamily: 'var(--ff-mono)', whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
{`1. Install the MCP server in your Claude environment
   npm install @localact/mcp --save-dev

2. Add to your Claude config (~/.claude/config.json)
   {
     "mcpServers": {
       "localact": {
         "command": "node",
         "args": ["./node_modules/@localact/mcp"],
         "env": {
           "LOCALACT_API_KEY": "your_api_key_here"
         }
       }
     }
   }

3. Restart Claude and start querying
   @localact Get me all lead data for Q1 2026
   @localact Create a report: budgets vs spend by location
   @localact Alert me if any location overspends

Learn more: docs.localact.com/mcp`}
            </div>
          )}
        </div>

        <div className="card card-pad" style={{ marginBottom: 22 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
            <div className="card-title" style={{ marginBottom: 0 }}>API usage</div>
            <button className="btn btn-ghost btn-sm" style={{ fontSize: 11 }}>View analytics</button>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
            {[
            { label: 'Calls this month', value: '2,847', pct: '14%' },
            { label: 'Data returned', value: '48.2 GB', pct: '39%' },
            { label: 'Last query', value: '2 min ago', pct: '–' }].
            map((s, i) =>
            <div key={i} style={{ padding: 12, background: 'var(--cream)', borderRadius: 10 }}>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.06em', marginBottom: 4 }}>{s.label}</div>
              <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--ink)' }}>{s.value}</div>
              {s.pct !== '–' && <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4 }}>{s.pct} of monthly limit</div>}
            </div>
            )}
          </div>
        </div>

        <div className="card card-pad">
          <div className="card-title" style={{ marginBottom: 12 }}>Manage</div>
          <div style={{ display: 'flex', gap: 10 }}>
            <button className="btn btn-ghost btn-sm" onClick={() => T('Rotated', 'New API key generated. Old key revoked instantly.', 'ok')}>Rotate API key</button>
            <button className="btn btn-ghost btn-sm" onClick={() => setStatus('inactive')}>Deactivate MCP</button>
          </div>
        </div>
      </div>
      }
    </div>);
}

// BRAND GUIDELINES
// --------------------------------------------------------------------
function HqSettingsBrand() {
  const [drag, setDrag] = useStateP(false);
  return (
    <div>
      <div className="card card-pad" style={{ marginBottom: 18, background: 'linear-gradient(135deg, var(--cream) 0%, rgba(77,105,137,0.06) 100%)', border: '1px solid var(--cream-3)' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 18 }}>
          <div style={{ width: 72, height: 72, borderRadius: 12, background: 'linear-gradient(135deg, #2570eb 0%, #1b8a4b 100%)', color: '#FFF', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--ff-display)', fontSize: 30, fontWeight: 600, letterSpacing: '-0.02em' }}>🌿</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 4 }}>Active brand kit · v3.2</div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 600, color: 'var(--ink)', marginBottom: 4, letterSpacing: '-0.015em' }}>FreshNest, Master Brand</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 10 }}>Published Mar 14, 2026 by Diana Patel · Auto-applied to all 700 locations + 6 active national campaigns.</div>
            <div style={{ display: 'flex', gap: 14, fontSize: 11.5, color: 'var(--ink-3)' }}>
              <span>📄 Brand_Guidelines_v3.2.pdf · 24.6 MB</span>
              <span>•</span>
              <span>14 logo lockups</span>
              <span>•</span>
              <span>6 brand colors</span>
              <span>•</span>
              <span>4 typefaces licensed</span>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <button className="btn btn-primary btn-sm">Download PDF</button>
            <button className="btn btn-ghost btn-sm">View version history</button>
          </div>
        </div>
      </div>

      <div className="card-title" style={{ marginBottom: 10 }}>Upload new guidelines</div>
      <div
        onDragOver={(e) => {e.preventDefault();setDrag(true);}}
        onDragLeave={() => setDrag(false)}
        onDrop={(e) => {e.preventDefault();setDrag(false);T('Upload received', 'Lenny is parsing your guidelines, colors, fonts, and logos extracted in ~2 minutes.', 'ok');}}
        style={{
          padding: 32, border: `2px dashed ${drag ? 'var(--violet)' : 'var(--cream-3)'}`, borderRadius: 14,
          background: drag ? 'var(--violet-soft, rgba(77,105,137,0.08))' : 'var(--cream)',
          textAlign: 'center', transition: 'all .15s', marginBottom: 22, cursor: 'pointer'
        }}
        onClick={() => T('File picker', 'In a real flow this would open the OS file picker.', 'info')}>
        <div style={{ fontSize: 36, marginBottom: 10 }}>📤</div>
        <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)', marginBottom: 4 }}>Drop your brand guidelines here</div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 14 }}>PDF · Figma link · Notion page · ZIP. Lenny auto-extracts colors, fonts, and logo variants.</div>
        <button className="btn btn-primary btn-sm">Browse files</button>
        <div style={{ fontSize: 10.5, color: 'var(--ink-4)', marginTop: 12 }}>Max 200 MB · We keep all prior versions and roll back instantly.</div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, marginBottom: 22 }}>
        <div className="card card-pad">
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
            <div className="card-title" style={{ marginBottom: 0 }}>Brand colors</div>
            <button className="btn btn-ghost btn-sm" style={{ fontSize: 11 }}>Edit</button>
          </div>
          {[
          { name: 'FreshNest Ocean', hex: '#2570eb', usage: 'Primary · headlines' },
          { name: 'FreshNest Grow', hex: '#1b8a4b', usage: 'Secondary · eco messaging' },
          { name: 'FreshNest Spark', hex: '#f28020', usage: 'Accent · CTAs' },
          { name: 'Slate', hex: '#001e40', usage: 'Body type' },
          { name: 'Mint', hex: '#f3f9f9', usage: 'Light backgrounds' },
          { name: 'Neutral', hex: '#f5f5f7', usage: 'Page backgrounds' }].
          map((c) =>
          <div key={c.hex} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '8px 0', borderBottom: '1px solid var(--cream-2)' }}>
              <div style={{ width: 36, height: 36, borderRadius: 8, background: c.hex, border: '1px solid var(--cream-3)', flexShrink: 0 }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{c.name}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{c.usage}</div>
              </div>
              <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 12, color: 'var(--ink-3)' }}>{c.hex}</div>
            </div>
          )}
        </div>

        <div className="card card-pad">
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
            <div className="card-title" style={{ marginBottom: 0 }}>Typography</div>
            <button className="btn btn-ghost btn-sm" style={{ fontSize: 11 }}>Edit</button>
          </div>
          {[
          { name: 'Inter', role: 'Display · Headlines', license: 'Open source · unlimited', sample: 'Eco-certified home care.' },
          { name: 'Söhne', role: 'UI · Body', license: 'Commercial · unlimited', sample: 'FreshNest, family-owned since 1998.' },
          { name: 'JetBrains Mono', role: 'Monospace · prices', license: 'Open source', sample: 'From $79 · Professional installation' },
          { name: 'Fraunces', role: 'Reserved · taglines', license: 'Open source · headlines only', sample: 'Smart living made simple.' }].
          map((t) =>
          <div key={t.name} style={{ padding: '10px 0', borderBottom: '1px solid var(--cream-2)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{t.name}</div>
                <div style={{ fontSize: 10.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700 }}>{t.role}</div>
              </div>
              <div style={{ fontSize: 16, color: 'var(--ink)', marginTop: 4, fontFamily: t.name === 'JetBrains Mono' ? 'var(--ff-mono)' : t.name === 'Capitolina' || t.name === 'Playfair Display' ? 'var(--ff-display)' : 'var(--ff-ui)' }}>{t.sample}</div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 3 }}>{t.license}</div>
            </div>
          )}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 18, marginBottom: 22 }}>
        <div className="card card-pad">
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
            <div className="card-title" style={{ marginBottom: 0 }}>Logo lockups</div>
            <button className="btn btn-ghost btn-sm" style={{ fontSize: 11 }}>Manage all</button>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
            {[
            { label: 'Primary · stacked', bg: '#f5f5f7', fg: '#2570eb' },
            { label: 'Primary · horizontal', bg: '#f5f5f7', fg: '#2570eb' },
            { label: 'Reverse · ocean', bg: '#2570eb', fg: '#FFF' },
            { label: 'Mark only · leaf', bg: '#f3f9f9', fg: '#1b8a4b' },
            { label: 'Co-branded · partner', bg: '#FFFFFF', fg: '#2570eb' },
            { label: '+ Upload variant', bg: 'var(--cream-2)', fg: 'var(--ink-3)', upload: true }].
            map((l) =>
            <div key={l.label} style={{ aspectRatio: '4/3', borderRadius: 8, border: '1px solid var(--cream-3)', background: l.bg, color: l.fg, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 8, cursor: 'pointer', position: 'relative' }}>
                {l.upload ?
              <div style={{ fontSize: 20, marginBottom: 4 }}>＋</div> :

              <div style={{ fontFamily: 'var(--ff-display)', fontSize: 14, fontWeight: 600, letterSpacing: '-0.01em', textAlign: 'center' }}>🌿 FreshNest</div>
              }
                <div style={{ fontSize: 9.5, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', marginTop: 'auto', textAlign: 'center', opacity: 0.8 }}>{l.label}</div>
              </div>
            )}
          </div>
        </div>

        <div className="card card-pad">
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
            <div className="card-title" style={{ marginBottom: 0 }}>Voice & tone</div>
            <button className="btn btn-ghost btn-sm" style={{ fontSize: 11 }}>Edit</button>
          </div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.55, marginBottom: 14 }}>Trusted, eco-conscious, straightforward. We're locally owned with a national reach. We speak about EPA-certified products and professional cleaning with authority, we live this.</div>
          {[
          { do: "Eco-certified professional clean", dont: 'Budget cleaning option' },
          { do: "FreshNest smart cleaning", dont: 'House cleaning service' },
          { do: 'Professional deep clean · $159', dont: 'Cleaning from just $79' },
          { do: "Let's get your home fresh.", dont: 'Call for a free quote.' }].
          map((p, i) =>
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '20px 1fr', gap: 6, padding: '6px 0', borderBottom: '1px solid var(--cream-2)' }}>
              <div style={{ color: '#56adad', fontWeight: 700 }}>✓</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>{p.do}</div>
              <div style={{ color: '#e46c63', fontWeight: 700 }}>✗</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-3)', fontStyle: 'italic' }}>{p.dont}</div>
            </div>
          )}
        </div>
      </div>
    </div>);

}

function BrandRule({ title, body }) {
  return (
    <div>
      <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', marginBottom: 4 }}>{title}</div>
      <div style={{ fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.5 }}>{body}</div>
    </div>);

}

// --------------------------------------------------------------------
// APPROVAL WORKFLOWS
// --------------------------------------------------------------------
function HqSettingsGovernance() {
  const flows = [
  { name: 'Creative submissions', who: 'Diana Patel · Creative Manager', sla: '24 hr', backup: 'Lenny Park', volume: '6 pending', enabled: true },
  { name: 'Promo / discount campaigns', who: 'Lenny Park · Owner', sla: '12 hr', backup: 'Priya Raman', volume: '2 pending', enabled: true },
  { name: 'New service requests (>$10k/mo)', who: 'Lenny Park · Owner', sla: '3 days', backup: '–', volume: '1 pending', enabled: true },
  { name: 'Brand guidelines updates', who: 'Diana Patel · Creative Manager', sla: '24 hr', backup: 'Lenny Park', volume: '0 pending', enabled: true },
  { name: 'Franchisee opt-out requests', who: 'Tom Reynolds · Regional', sla: '48 hr', backup: 'Priya Raman', volume: '4 pending', enabled: false },
  { name: 'Location additions / closures', who: 'Lenny Park · Owner', sla: '5 days', backup: '–', volume: '0 pending', enabled: true }];

  return (
    <div>
      <Phase2Banner>Lets corporate admins and marketing admins grant team members access and assign permissions for different actions in the interface.</Phase2Banner>
      <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 16, maxWidth: 720 }}>Approval routes for actions that affect the brand or budget. Lenny enforces these automatically, no creative goes live, no overspend ships, without the right sign-off.</div>
      <div className="card" style={{ overflow: 'hidden', padding: 0 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 2fr 1fr 1.4fr 1.2fr 0.8fr', padding: '10px 18px', background: 'var(--cream)', borderBottom: '1px solid var(--cream-3)', fontSize: 10.5, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>
          <div>Workflow</div>
          <div>Approver</div>
          <div>SLA</div>
          <div>Backup</div>
          <div>Queue</div>
          <div>On</div>
        </div>
        {flows.map((f, i) =>
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '2fr 2fr 1fr 1.4fr 1.2fr 0.8fr', padding: '14px 18px', borderBottom: '1px solid var(--cream-2)', alignItems: 'center', fontSize: 13, opacity: f.enabled ? 1 : 0.55 }}>
            <div style={{ fontWeight: 600 }}>{f.name}</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>{f.who}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{f.sla}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{f.backup}</div>
            <div>
              {parseInt(f.volume) > 0 ? <span style={{ fontSize: 11.5, padding: '2px 8px', background: 'var(--marigold-soft)', color: '#917200', borderRadius: 4, fontWeight: 700 }}>{f.volume}</span> : <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>–</span>}
            </div>
            <div>
              <div style={{ width: 36, height: 20, background: f.enabled ? '#56adad' : 'var(--cream-3)', borderRadius: 10, position: 'relative', cursor: 'pointer' }}>
                <div style={{ position: 'absolute', top: 2, left: f.enabled ? 18 : 2, width: 16, height: 16, background: 'var(--paper)', borderRadius: '50%', boxShadow: 'var(--sh-1)', transition: 'left .2s' }} />
              </div>
            </div>
          </div>
        )}
      </div>
      <div style={{ marginTop: 14 }}>
        <button className="btn btn-ghost btn-sm">+ Add workflow</button>
      </div>
    </div>);

}

// --------------------------------------------------------------------
// INTEGRATIONS
// --------------------------------------------------------------------
function HqSettingsIntegrations() {
  // Deprecated, replaced with HqSettingsMcp
  return null;
}

// --------------------------------------------------------------------
// CORPORATE AUDIT LOG
// Governance trail: brand standards, playbook, users & roles, approvals.
// --------------------------------------------------------------------
const HQ_AUDIT_CATS = {
  brand: { label: 'Brand standards', color: '#4d6989' },
  playbook: { label: 'Network playbook', color: '#4d6989' },
  users: { label: 'Users & roles', color: '#917200' },
  approval: { label: 'Approvals', color: '#56adad' },
  system: { label: 'System', color: '#a9a9ae' } };


const HQ_AUDIT = [
{ cat: 'users', who: 'Lenny Park', action: 'Promoted Sarah Reyes to Marketing Admin', target: 'sarah@localact.com', when: 'Today · 9:42 am' },
{ cat: 'approval', who: 'Priya Raman', action: "Approved promo · Mother's Day BOGO", target: 'National program · 700 locations', when: 'Today · 8:15 am' },
{ cat: 'brand', who: 'Diana Patel', action: 'Published brand guidelines v3.2', target: 'Logo clear-space + new color tokens', when: 'Yesterday · 4:30 pm' },
{ cat: 'playbook', who: 'Priya Raman', action: 'Edited network playbook · Listings hygiene rule', target: 'Resolve directory issues within 7 days', when: 'Yesterday · 2:08 pm' },
{ cat: 'users', who: 'Lenny Park', action: 'Invited new member · Nicole Brooks (Analyst)', target: 'nicole@freshnest.com · pending', when: 'Mar 18 · 11:24 am' },
{ cat: 'brand', who: 'Diana Patel', action: 'Updated approved messaging · "eco-certified" claims', target: 'Brand standards · Claims library', when: 'Mar 17 · 3:51 pm' },
{ cat: 'playbook', who: 'Priya Raman', action: 'Added playbook step · Weekly GBP post cadence', target: 'Local Organic · all locations', when: 'Mar 16 · 10:02 am' },
{ cat: 'approval', who: 'Tom Reynolds', action: 'Rejected creative · Plano Legacy summer flyer', target: 'Off-brand color usage', when: 'Mar 15 · 1:18 pm' },
{ cat: 'users', who: 'Lenny Park', action: 'Changed role · Jamal Foster → Creative Manager', target: 'jamal@freshnest.com', when: 'Mar 14 · 9:05 am' },
{ cat: 'brand', who: 'Diana Patel', action: 'Replaced logo asset · primary lockup (SVG)', target: 'Asset library · /brand/logos', when: 'Mar 13 · 5:40 pm' },
{ cat: 'system', who: 'System', action: 'Auto-deprovisioned Steve Walker (90d inactive)', target: 'steve@oldemail.com', when: 'Mar 12 · 11:00 pm' },
{ cat: 'users', who: 'Tom Reynolds', action: 'Removed access · ex-franchisee (Phoenix North)', target: 'Single-location · Phoenix North', when: 'Mar 8 · 4:22 pm' },
{ cat: 'approval', who: 'Priya Raman', action: 'Approved budget reallocation · Q2 paid media', target: 'Central region · +$48k', when: 'Mar 6 · 8:47 am' },
{ cat: 'playbook', who: 'Priya Raman', action: 'Archived playbook step · legacy print coupons', target: 'Deprecated · all locations', when: 'Mar 3 · 2:15 pm' }];


function AuditFilterBar({ cats, filter, setFilter, counts }) {
  return (
    <div style={{ display: 'flex', gap: 4, padding: 3, background: 'var(--cream)', borderRadius: 8, flexWrap: 'wrap' }}>
      {[['all', 'All'], ...Object.entries(cats).map(([k, c]) => [k, c.label])].map(([k, l]) =>
      <button key={k} onClick={() => setFilter(k)} style={{
        padding: '6px 11px', fontSize: 12, fontWeight: 600, border: 'none', borderRadius: 6, cursor: 'pointer',
        fontFamily: 'var(--ff-ui)',
        background: filter === k ? 'var(--paper)' : 'transparent',
        color: filter === k ? 'var(--ink)' : 'var(--ink-3)',
        boxShadow: filter === k ? '0 1px 2px rgba(0,0,0,0.06)' : 'none',
        display: 'flex', alignItems: 'center', gap: 6
      }}>
          {k !== 'all' && <span style={{ width: 7, height: 7, borderRadius: '50%', background: cats[k].color, display: 'inline-block' }} />}
          {l}
          <span style={{ fontSize: 10.5, color: 'var(--ink-4)', fontWeight: 700 }}>{counts[k] || 0}</span>
        </button>
      )}
    </div>);

}

function AuditTag({ cat, cats }) {
  const c = cats[cat];
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, fontWeight: 700, padding: '3px 9px', borderRadius: 20, background: `${c.color}1A`, color: c.color, whiteSpace: 'nowrap' }}>
      <span style={{ width: 6, height: 6, borderRadius: '50%', background: c.color }} />
      {c.label}
    </span>);

}

function HqAuditLog() {
  const [filter, setFilter] = useStateP('all');
  const [search, setSearch] = useStateP('');

  const counts = HQ_AUDIT.reduce((a, e) => {a[e.cat] = (a[e.cat] || 0) + 1;a.all = (a.all || 0) + 1;return a;}, {});
  const rows = HQ_AUDIT.filter((e) =>
  (filter === 'all' || e.cat === filter) && (
  !search || (e.who + e.action + e.target).toLowerCase().includes(search.toLowerCase())));

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, marginBottom: 16, flexWrap: 'wrap' }}>
        <div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 17, fontWeight: 600, color: 'var(--ink)' }}>Corporate audit log</div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 3 }}>Every governance change across FreshNest corporate, brand standards, the network playbook, users & roles, and approvals. Last 90 days · {HQ_AUDIT.length} events.</div>
        </div>
        <button className="btn btn-ghost btn-sm" onClick={() => T('Export started', `${rows.length} event${rows.length === 1 ? '' : 's'} exported to CSV. Check your downloads.`, 'ok')}>↓ Export CSV</button>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14, flexWrap: 'wrap' }}>
        <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Search by member, action, or target…"
        style={{ flex: 1, minWidth: 240, maxWidth: 340, padding: '9px 12px', fontSize: 13, fontFamily: 'var(--ff-ui)', border: '1px solid var(--cream-3)', borderRadius: 8, background: 'var(--paper)' }} />
        <AuditFilterBar cats={HQ_AUDIT_CATS} filter={filter} setFilter={setFilter} counts={counts} />
      </div>

      <div className="card" style={{ overflow: 'hidden', padding: 0 }}>
        <table className="tbl">
          <thead>
            <tr>
              <th style={{ width: 150 }}>Type</th>
              <th>Activity</th>
              <th style={{ width: 150 }}>Member</th>
              <th style={{ width: 130 }}>When</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((e, i) =>
            <tr key={i}>
                <td><AuditTag cat={e.cat} cats={HQ_AUDIT_CATS} /></td>
                <td>
                  <div style={{ fontSize: 12.5, color: 'var(--ink)', fontWeight: 600 }}>{e.action}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 2 }}>{e.target}</div>
                </td>
                <td style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>{e.who}</td>
                <td style={{ fontSize: 11.5, color: 'var(--ink-4)', fontFamily: 'var(--ff-mono)', whiteSpace: 'nowrap' }}>{e.when}</td>
              </tr>
            )}
            {rows.length === 0 &&
            <tr><td colSpan={4} style={{ textAlign: 'center', color: 'var(--ink-4)', padding: '28px 0' }}>No matching activity.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>);

}

// --------------------------------------------------------------------
// LOCAL AUDIT LOG
// Location-scoped trail: budget changes, service enrollments, cancellations.
// --------------------------------------------------------------------
const FR_AUDIT_CATS = {
  budgetUp: { label: 'Budget increase', color: '#56adad' },
  budgetDown: { label: 'Budget decrease', color: '#917200' },
  enroll: { label: 'Service enrolled', color: '#4d6989' },
  cancel: { label: 'Service cancelled', color: '#e46c63' } };


const FR_AUDIT_DATA = {
  star: [
  { cat: 'budgetUp', who: 'Alicia Chen', action: 'Increased Local Paid Media budget', target: '$2,400 → $3,200 / mo', when: 'Today · 10:18 am' },
  { cat: 'enroll', who: 'Alicia Chen', action: 'Enrolled in AI Search Optimization', target: 'Pilot · $199 / mo', when: 'Yesterday · 3:42 pm' },
  { cat: 'budgetUp', who: 'Alicia Chen', action: 'Boosted office-cleaning campaign budget', target: '$600 → $900 / mo · seasonal', when: 'Mar 17 · 1:05 pm' },
  { cat: 'enroll', who: 'Alicia Chen', action: 'Enrolled in Listings Management', target: '42 directories · $89 / mo', when: 'Mar 14 · 9:20 am' },
  { cat: 'cancel', who: 'Alicia Chen', action: 'Cancelled cleaning workshops promotion', target: 'Pilot ended · no renewal', when: 'Mar 11 · 4:55 pm' },
  { cat: 'budgetDown', who: 'Lenny (auto)', action: 'Reduced underperforming display budget', target: '$450 → $250 / mo · Lenny suggestion', when: 'Mar 9 · 6:00 am' },
  { cat: 'budgetUp', who: 'Alicia Chen', action: 'Increased Local Organic budget', target: '$300 → $500 / mo', when: 'Mar 5 · 11:32 am' },
  { cat: 'enroll', who: 'Alicia Chen', action: 'Enrolled in Local Advisors', target: 'Quarterly strategy · $349 / mo', when: 'Feb 28 · 2:10 pm' },
  { cat: 'cancel', who: 'Alicia Chen', action: 'Cancelled third-party delivery boost', target: 'Switched spend to in-house drivers', when: 'Feb 24 · 5:30 pm' },
  { cat: 'budgetDown', who: 'Alicia Chen', action: 'Lowered weekend social budget', target: '$320 → $200 / mo', when: 'Feb 19 · 8:48 am' }],

  bare: [
  { cat: 'enroll', who: 'Danny Ruiz', action: 'Enrolled in Listings Management', target: '42 directories · $89 / mo', when: 'Today · 9:05 am' },
  { cat: 'budgetUp', who: 'Danny Ruiz', action: 'Started Local Paid Media budget', target: '$0 → $1,200 / mo · first campaign', when: 'Yesterday · 2:22 pm' },
  { cat: 'enroll', who: 'Danny Ruiz', action: 'Enrolled in Local Foundation', target: 'GBP cleanup + NAP audit · $1,200 one-time', when: 'Mar 16 · 10:40 am' },
  { cat: 'budgetUp', who: 'Danny Ruiz', action: 'Added family promo budget', target: '$0 → $400 / mo · Kid-safe Tuesday', when: 'Mar 12 · 1:15 pm' },
  { cat: 'cancel', who: 'Danny Ruiz', action: 'Cancelled gift-card digital add-on', target: 'Not enabling this quarter', when: 'Mar 7 · 4:02 pm' },
  { cat: 'budgetDown', who: 'Danny Ruiz', action: 'Trimmed test budget after pilot', target: '$300 → $150 / mo', when: 'Mar 2 · 9:50 am' },
  { cat: 'enroll', who: 'Danny Ruiz', action: 'Enrolled in supply subscriptions program', target: 'Monthly starter box · $24 / mo', when: 'Feb 26 · 11:08 am' }] };



function FrAuditLog({ profile, variant }) {
  const [filter, setFilter] = useStateP('all');
  const [search, setSearch] = useStateP('');
  const data = FR_AUDIT_DATA[variant] || FR_AUDIT_DATA.star;

  const counts = data.reduce((a, e) => {a[e.cat] = (a[e.cat] || 0) + 1;a.all = (a.all || 0) + 1;return a;}, {});
  const rows = data.filter((e) =>
  (filter === 'all' || e.cat === filter) && (
  !search || (e.who + e.action + e.target).toLowerCase().includes(search.toLowerCase())));

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, marginBottom: 16, flexWrap: 'wrap' }}>
        <div>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 17, fontWeight: 600, color: 'var(--ink)' }}>Audit log</div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 3 }}>Everything that changed at {profile.shortName}, budget changes, and services you enrolled in or cancelled. Last 90 days · {data.length} events.</div>
        </div>
        <button className="btn btn-ghost btn-sm" onClick={() => T('Export started', `${rows.length} event${rows.length === 1 ? '' : 's'} exported to CSV. Check your downloads.`, 'ok')}>↓ Export CSV</button>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14, flexWrap: 'wrap' }}>
        <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Search this log…"
        style={{ flex: 1, minWidth: 220, maxWidth: 320, padding: '9px 12px', fontSize: 13, fontFamily: 'var(--ff-ui)', border: '1px solid var(--cream-3)', borderRadius: 8, background: 'var(--paper)' }} />
        <AuditFilterBar cats={FR_AUDIT_CATS} filter={filter} setFilter={setFilter} counts={counts} />
      </div>

      <div className="card" style={{ overflow: 'hidden', padding: 0 }}>
        <table className="tbl">
          <thead>
            <tr>
              <th style={{ width: 160 }}>Type</th>
              <th>Change</th>
              <th style={{ width: 130 }}>By</th>
              <th style={{ width: 130 }}>When</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((e, i) =>
            <tr key={i}>
                <td><AuditTag cat={e.cat} cats={FR_AUDIT_CATS} /></td>
                <td>
                  <div style={{ fontSize: 12.5, color: 'var(--ink)', fontWeight: 600 }}>{e.action}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 2 }}>{e.target}</div>
                </td>
                <td style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>{e.who}</td>
                <td style={{ fontSize: 11.5, color: 'var(--ink-4)', fontFamily: 'var(--ff-mono)', whiteSpace: 'nowrap' }}>{e.when}</td>
              </tr>
            )}
            {rows.length === 0 &&
            <tr><td colSpan={4} style={{ textAlign: 'center', color: 'var(--ink-4)', padding: '28px 0' }}>No matching activity.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>);

}

function SetField({ label, children }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-4)', marginBottom: 5 }}>{label}</div>
      {children}
    </div>);

}
const setInputStyle = { width: '100%', padding: '10px 12px', fontSize: 13, fontFamily: 'var(--ff-ui)', border: '1px solid var(--cream-3)', borderRadius: 8, background: 'var(--paper)', color: 'var(--ink)', boxSizing: 'border-box' };

window.SettingsPage = SettingsPage;
window.HqSettingsPage = HqSettingsPage;