// ====================================================================
// RESULTS PAGE, Social + Demand Gen tabs
// ====================================================================
const { useState: useStateR3 } = React;

// Tiny SVG creative thumb, abstract scenes coded in CSS
function CreativeThumb({ kind, palette }) {
  const [a, b] = palette;
  const common = { width: '100%', height: '100%', display: 'block' };

  const scenes = {
    family: (
      <svg viewBox="0 0 100 100" style={common} preserveAspectRatio="xMidYMid slice">
        <rect width="100" height="100" fill={a}/>
        <circle cx="50" cy="44" r="28" fill={b} opacity="0.85"/>
        <ellipse cx="50" cy="84" rx="40" ry="14" fill={b} opacity="0.6"/>
        <circle cx="38" cy="42" r="3" fill={a}/>
        <circle cx="62" cy="42" r="3" fill={a}/>
        <path d="M40 52 Q 50 60 60 52" stroke={a} strokeWidth="2.5" fill="none" strokeLinecap="round"/>
      </svg>
    ),
    catering: (
      <svg viewBox="0 0 100 100" style={common} preserveAspectRatio="xMidYMid slice">
        <rect width="100" height="100" fill={b}/>
        <rect x="12" y="40" width="76" height="42" rx="4" fill={a}/>
        <rect x="20" y="48" width="60" height="6" fill={b} opacity="0.5"/>
        <rect x="20" y="58" width="44" height="6" fill={b} opacity="0.4"/>
        <rect x="20" y="68" width="52" height="6" fill={b} opacity="0.3"/>
        <circle cx="78" cy="22" r="10" fill={a}/>
      </svg>
    ),
    mothers: (
      <svg viewBox="0 0 100 100" style={common} preserveAspectRatio="xMidYMid slice">
        <rect width="100" height="100" fill={a}/>
        <path d="M50 78 C 30 60 22 44 38 38 C 46 35 50 42 50 46 C 50 42 54 35 62 38 C 78 44 70 60 50 78 Z" fill={b}/>
        <circle cx="22" cy="22" r="4" fill={b} opacity="0.6"/>
        <circle cx="78" cy="28" r="3" fill={b} opacity="0.8"/>
        <circle cx="86" cy="68" r="5" fill={b} opacity="0.5"/>
      </svg>
    ),
    lunch: (
      <svg viewBox="0 0 100 100" style={common} preserveAspectRatio="xMidYMid slice">
        <rect width="100" height="100" fill={b}/>
        <circle cx="50" cy="54" r="28" fill={a}/>
        <text x="50" y="50" textAnchor="middle" fill={b} fontSize="11" fontWeight="700">$12.99</text>
        <text x="50" y="62" textAnchor="middle" fill={b} fontSize="6" fontWeight="600" opacity="0.8">LUNCH COMBO</text>
      </svg>
    ),
  };

  return scenes[kind] || <div style={{ width: '100%', height: '100%', background: a }}/>;
}

// --------------------------------------------------------------------
// SOCIAL TAB
// --------------------------------------------------------------------
function ResultsSocial({ data }) {
  const d = data.socialDetail;
  const [bumpModal, setBumpModal] = useStateR3(null);

  const statusBadge = {
    winner:  { label: '★ WINNER',  bg: 'var(--sage)',     color: 'var(--cream)' },
    scaling: { label: 'SCALING',   bg: 'var(--sky)',      color: 'var(--cream)' },
    testing: { label: 'TESTING',   bg: 'var(--marigold)', color: 'var(--ink)' },
    tired:   { label: 'TIRED',     bg: 'var(--clay)',     color: 'var(--cream)' },
  };

  return (
    <>
      <div className="grid grid-4" style={{ marginBottom: 16 }}>
        <KpiCard label="Reach" value={`${(d.summary.reach/1000).toFixed(1)}K`} delta={18} color="var(--ch-social)" dotColor="var(--ch-social)"/>
        <KpiCard label="Impressions" value={`${(d.summary.impr/1000).toFixed(1)}K`} delta={22} color="var(--marigold)" dotColor="var(--marigold)"/>
        <KpiCard label="Leads" value={d.summary.leads} delta={11} color="var(--terra)" dotColor="var(--terra)"/>
        <KpiCard label="Cost / Lead" value={`$${d.summary.cpl}`} delta={-6} invert color="var(--sage)" dotColor="var(--sage)"/>
      </div>

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

      {/* Objectives split */}
      <div className="card card-pad" style={{ marginBottom: 16 }}>
        <div className="card-title" style={{ marginBottom: 14 }}>Spend by objective</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
          {d.objectives.map((o, i) => (
            <div key={i} style={{ padding: 16, background: 'var(--cream)', borderRadius: 12, borderTop: `3px solid ${o.color}` }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: o.color }}/>
                <div style={{ fontSize: 12.5, fontWeight: 700 }}>{o.name}</div>
              </div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 8 }}>
                <span style={{ fontFamily: 'var(--ff-display)', fontSize: 26, fontWeight: 500, lineHeight: 1 }}>${o.spend}</span>
                <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>this month</span>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, fontSize: 11.5, color: 'var(--ink-2)' }}>
                <div><span style={{ color: 'var(--ink-3)' }}>Reach</span><div style={{ fontWeight: 600 }}>{(o.reach/1000).toFixed(1)}K</div></div>
                <div><span style={{ color: 'var(--ink-3)' }}>Impr.</span><div style={{ fontWeight: 600 }}>{(o.impr/1000).toFixed(1)}K</div></div>
                <div><span style={{ color: 'var(--ink-3)' }}>CPM</span><div style={{ fontWeight: 600 }}>${o.cpm}</div></div>
                <div><span style={{ color: 'var(--ink-3)' }}>{o.primary === 'leads' ? 'Leads' : o.primary === 'clicks' ? 'CTR' : 'Reach %'}</span><div style={{ fontWeight: 600 }}>{o.primary === 'leads' ? o.leads : o.primary === 'clicks' ? `${o.ctr}%` : `${Math.round(o.reach/d.summary.reach*100)}%`}</div></div>
              </div>
            </div>
          ))}
        </div>
      </div>

      <SourceNote>Source: Meta</SourceNote>

      {/* Creative, visual */}
      <div className="card card-pad" style={{ marginBottom: 16 }}>
        <div className="card-header" style={{ marginBottom: 14 }}>
          <div>
            <div className="card-title">Creative in rotation</div>
            <div className="card-sub">Each card is a live ad. Winners get more budget; tired creative gets retired.</div>
          </div>
          <button className="btn btn-quiet btn-sm" onClick={() => T('Creative request', 'Brief sent to creative team, 4 new variants, ETA 5 business days.', 'ok')}>+ Request new creative</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
          {d.creative.map(c => {
            const status = statusBadge[c.status];
            return (
              <div key={c.id} style={{ borderRadius: 12, overflow: 'hidden', border: '1px solid var(--line)', background: 'var(--cream)' }}>
                <div style={{ aspectRatio: '4/5', position: 'relative' }}>
                  <CreativeThumb kind={c.thumb} palette={c.palette}/>
                  <div style={{ position: 'absolute', top: 8, left: 8, padding: '3px 8px', borderRadius: 99, fontSize: 10, fontWeight: 700, background: status.bg, color: status.color, letterSpacing: '.05em' }}>{status.label}</div>
                  <div style={{ position: 'absolute', bottom: 8, left: 8, padding: '3px 8px', borderRadius: 4, fontSize: 10, fontWeight: 600, background: 'rgba(0,0,0,.6)', color: 'var(--cream)' }}>{c.placement}</div>
                </div>
                <div style={{ padding: 12 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, marginBottom: 8 }}>{c.title}</div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6, fontSize: 11 }}>
                    <div><span style={{ color: 'var(--ink-3)' }}>Spend</span><div style={{ fontWeight: 600 }}>${c.spend}</div></div>
                    <div><span style={{ color: 'var(--ink-3)' }}>Leads</span><div style={{ fontWeight: 600 }}>{c.leads}</div></div>
                    <div><span style={{ color: 'var(--ink-3)' }}>CTR</span><div style={{ fontWeight: 600 }}>{c.ctr}%</div></div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      <SourceNote>Source: Meta</SourceNote>

      {/* Demographics */}
      <div className="grid grid-2-1" style={{ marginBottom: 16 }}>
        <div className="card card-pad">
          <div className="card-title" style={{ marginBottom: 14 }}>Audience, who's seeing your ads</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24 }}>
            {/* Age */}
            <div>
              <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-3)', fontWeight: 600, marginBottom: 8 }}>Age, reach vs conversions</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {d.demographics.age.map((b, i) => (
                  <div key={i} style={{ display: 'grid', gridTemplateColumns: '54px 1fr 1fr', gap: 10, alignItems: 'center', fontSize: 11.5 }}>
                    <span style={{ fontFamily: 'var(--ff-mono)' }}>{b.bucket}</span>
                    <div>
                      <div style={{ height: 7, borderRadius: 4, background: 'var(--cream-2)', overflow: 'hidden' }}>
                        <div style={{ width: `${b.reach * 2.5}%`, height: '100%', background: 'var(--ch-social)', borderRadius: 4 }}/>
                      </div>
                      <div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 2 }}>Reach {b.reach}%</div>
                    </div>
                    <div>
                      <div style={{ height: 7, borderRadius: 4, background: 'var(--cream-2)', overflow: 'hidden' }}>
                        <div style={{ width: `${b.conv * 2.5}%`, height: '100%', background: 'var(--terra)', borderRadius: 4 }}/>
                      </div>
                      <div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 2 }}>Leads {b.conv}%</div>
                    </div>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 12, padding: 10, background: 'var(--cream)', borderRadius: 8, fontSize: 11.5, color: 'var(--ink-2)' }}>
                <strong>25–44 over-converts</strong>, they're 59% of leads but only 59% of reach. Worth a focused campaign.
              </div>
            </div>

            {/* Gender + Placements */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div>
                <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-3)', fontWeight: 600, marginBottom: 8 }}>Gender</div>
                <StackedRow h={18} segments={d.demographics.gender.map((g, i) => ({ label: g.bucket, value: g.reach, color: ['var(--ch-social)', 'var(--sky)', 'var(--ink-4)'][i] }))}/>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontSize: 11 }}>
                  {d.demographics.gender.map((g, i) => (
                    <span key={i}><span style={{ width: 8, height: 8, background: ['var(--ch-social)', 'var(--sky)', 'var(--ink-4)'][i], display: 'inline-block', borderRadius: 2, marginRight: 4 }}/>{g.bucket} <strong>{g.reach}%</strong></span>
                  ))}
                </div>
              </div>
              <div>
                <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-3)', fontWeight: 600, marginBottom: 8 }}>Placements</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {d.demographics.placements.map((p, i) => (
                    <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 40px', alignItems: 'center', gap: 8, fontSize: 11.5 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <span style={{ width: 8, height: 8, borderRadius: 2, background: p.color }}/>{p.name}
                      </div>
                      <strong style={{ fontFamily: 'var(--ff-mono)', textAlign: 'right' }}>{p.share}%</strong>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="card card-pad">
          <div className="card-title" style={{ marginBottom: 14 }}>Top ZIPs by reach</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {d.demographics.topZips.map((z, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '54px 1fr auto', alignItems: 'center', gap: 10 }}>
                <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 11, color: 'var(--ink-3)' }}>{z.zip}</span>
                <div>
                  <div style={{ fontSize: 12, fontWeight: 600 }}>{z.name}</div>
                  <div style={{ height: 5, borderRadius: 3, background: 'var(--cream-2)', overflow: 'hidden', marginTop: 2 }}>
                    <div style={{ width: `${z.reach/4820 * 100}%`, height: '100%', background: 'var(--ch-social)' }}/>
                  </div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 11.5 }}>{z.reach.toLocaleString()}</div>
                  <div style={{ fontSize: 10, color: 'var(--terra)', fontWeight: 600 }}>{z.conv} leads</div>
                </div>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 14, padding: 10, background: 'var(--terra-soft)', borderRadius: 8, fontSize: 11.5, color: 'var(--ink-2)' }}>
            <strong>78704 (South Lamar)</strong> over-indexes on office-cleaning inquiries, consider a ZIP-targeted boost.
          </div>
        </div>
      </div>

      <SourceNote>Source: Meta</SourceNote>

      {/* Seasonal upsells */}
      <div className="card card-pad">
        <div className="card-header" style={{ marginBottom: 14 }}>
          <div>
            <div className="card-title">Seasonal initiatives</div>
            <div className="card-sub">Time-bound social campaigns aligned to local moments. Mother's Day is open right now.</div>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
          {d.seasonalUpsells.map((u, i) => (
            <div key={i} style={{ padding: 16, borderRadius: 12, border: '1px solid var(--line)', position: 'relative', overflow: 'hidden' }}>
              <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 4, background: u.color }}/>
              <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 4 }}>{u.name}</div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 10 }}> {u.window}</div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
                <div>
                  <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 500, lineHeight: 1 }}>${u.budget}</div>
                  <div style={{ fontSize: 10, color: 'var(--ink-3)' }}>recommended budget</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--terra)' }}>{u.est}</div>
                  <div style={{ fontSize: 10, color: 'var(--ink-3)' }}>Lenny estimate</div>
                </div>
              </div>
              <button className="btn btn-primary btn-sm" style={{ width: '100%' }} onClick={() => setBumpModal(u)}>Add to plan</button>
            </div>
          ))}
        </div>
      </div>

      <Modal open={!!bumpModal} onClose={() => setBumpModal(null)} title={bumpModal?.name} sub={bumpModal?.window}
        footer={<>
          <button className="btn btn-ghost btn-sm" onClick={() => setBumpModal(null)}>Cancel</button>
          <button className="btn btn-primary btn-sm" onClick={() => { setBumpModal(null); T('Initiative scheduled', `${bumpModal.name} added, creative brief sent to your LMT.`, 'ok'); }}>Schedule</button>
        </>}>
        {bumpModal && (
          <div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 14 }}>
              <div style={{ padding: 12, background: 'var(--cream)', borderRadius: 8 }}>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>Recommended budget</div>
                <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 500 }}>${bumpModal.budget}</div>
              </div>
              <div style={{ padding: 12, background: 'var(--cream)', borderRadius: 8 }}>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>Estimated outcome</div>
                <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 500, color: 'var(--terra)' }}>{bumpModal.est}</div>
              </div>
            </div>
            <div style={{ fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.55 }}>
              Lenny will draft a creative brief and send it to your Local Marketing Team for review. You'll see ad variants in your inbox within 5 business days. Budget is added on top of your standing monthly Meta spend, no impact to existing campaigns.
            </div>
          </div>
        )}
      </Modal>
    </>
  );
}
window.ResultsSocial = ResultsSocial;

// --------------------------------------------------------------------
// DEMAND GEN TAB, awareness initiative pitch (not enrolled by default)
// --------------------------------------------------------------------
function ResultsDemandGen({ data }) {
  const d = data.demandGenDetail;
  const [enrollModal, setEnrollModal] = useStateR3(false);

  return (
    <>
      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 16, marginBottom: 16 }}>
        {/* Pitch / hero */}
        <div className="card" style={{ overflow: 'hidden', background: 'linear-gradient(135deg, #001132 0%, #001e40 50%, #4d6989 100%)', color: 'var(--cream)', position: 'relative' }}>
          <div style={{ position: 'absolute', top: -40, right: -40, width: 220, height: 220, borderRadius: '50%', background: 'rgba(255,255,255,.05)' }}/>
          <div style={{ position: 'absolute', bottom: -60, left: -30, width: 180, height: 180, borderRadius: '50%', background: 'rgba(214,184,77,.08)' }}/>
          <div className="card-pad" style={{ padding: 28, position: 'relative' }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 12px', borderRadius: 99, background: 'rgba(255,255,255,.12)', fontSize: 11, fontWeight: 700, letterSpacing: '.08em', marginBottom: 14 }}>
              📡 NOT YET ENROLLED · AWARENESS INITIATIVE
            </div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 32, fontWeight: 500, lineHeight: 1.1, marginBottom: 10 }}>
              {d.pitch.headline}
            </div>
            <div style={{ fontSize: 13.5, color: 'rgba(250,246,239,.85)', lineHeight: 1.6, marginBottom: 22, maxWidth: 540 }}>
              {d.pitch.detail}
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 22, padding: 16, background: 'rgba(255,255,255,.07)', borderRadius: 12, border: '1px solid rgba(255,255,255,.12)' }}>
              {[
                { l: 'Avg CPM', v: d.pitch.benchmarks.cpm },
                { l: 'Monthly reach', v: d.pitch.benchmarks.reach },
                { l: 'Video VTR', v: d.pitch.benchmarks.vtr },
                { l: 'Brand search lift', v: d.pitch.benchmarks.brandSearchLift },
              ].map(b => (
                <div key={b.l}>
                  <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '.06em', color: 'rgba(250,246,239,.6)', fontWeight: 600 }}>{b.l}</div>
                  <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 500 }}>{b.v}</div>
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <button className="btn btn-primary btn-sm" onClick={() => setEnrollModal(true)} style={{ background: 'var(--marigold)', color: 'var(--ink)', borderColor: 'var(--marigold)' }}>Enroll for ${d.pitch.monthlyBudget}/mo</button>
              <button className="btn btn-quiet btn-sm" style={{ background: 'rgba(250,246,239,.1)', borderColor: 'rgba(250,246,239,.2)', color: 'var(--cream)' }} onClick={() => T('Sample report', 'Sample Demand Gen report from a peer location is on its way to your email.', 'info')}>See peer results</button>
            </div>
          </div>
        </div>

        {/* Surfaces explanation */}
        <div className="card card-pad">
          <div className="card-title" style={{ marginBottom: 12 }}>Where it shows up</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {[
              { name: 'YouTube Shorts',  pct: 42, desc: 'Vertical video in the Shorts feed', color: '#e46c63' },
              { name: 'YouTube In-Feed', pct: 24, desc: 'Browse-style placements above search', color: '#eea39d' },
              { name: 'Discover',        pct: 21, desc: 'Personalized feed on Android home', color: '#669bf1' },
              { name: 'Gmail Promotions',pct: 13, desc: 'Promo-tab inbox placements', color: '#0d8a8a' },
            ].map(s => (
              <div key={s.name}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600 }}>{s.name}</div>
                  <div style={{ fontSize: 11.5, fontFamily: 'var(--ff-mono)', color: 'var(--ink-3)' }}>{s.pct}% of impr.</div>
                </div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 4 }}>{s.desc}</div>
                <div style={{ height: 6, borderRadius: 3, background: 'var(--cream-2)', overflow: 'hidden' }}>
                  <div style={{ width: `${s.pct * 2}%`, height: '100%', background: s.color, borderRadius: 3 }}/>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <SourceNote>Estimated by LOCALACT</SourceNote>

      {/* Peer benchmark band */}
      <div className="card card-pad" style={{ marginBottom: 16 }}>
        <div className="card-title" style={{ marginBottom: 14 }}>What peer FreshNest locations book & convert</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
          {d.pastResults.map((r, i) => (
            <div key={i} style={{ padding: 18, background: 'var(--cream)', borderRadius: 12, borderLeft: '3px solid var(--ch-lseo)' }}>
              <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-3)', fontWeight: 600, marginBottom: 6 }}>{r.metric}</div>
              <div style={{ fontFamily: 'var(--ff-display)', fontSize: 32, fontWeight: 500, lineHeight: 1, marginBottom: 6 }}>{r.peer}</div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.4 }}>{r.peerCount}</div>
            </div>
          ))}
        </div>
      </div>

      <SourceNote>Calculated by LOCALACT · peer benchmarks</SourceNote>

      {/* The lift logic */}
      <div className="card card-pad">
        <div className="card-title" style={{ marginBottom: 14 }}>How awareness becomes leads</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr) 24px', gap: 8, alignItems: 'center', marginBottom: 18 }}>
          {[
            { num: '1', label: 'Demand Gen impression', sub: 'YouTube Short of your cleaning crew' },
            { num: '2', label: 'They notice you exist', sub: 'Brand recall builds over weeks' },
            { num: '3', label: 'Branded search', sub: '"freshnest austin"' },
            { num: '4', label: 'Lead', sub: '$22 CPL on Brand Search' },
          ].map((s, i, arr) => (
            <React.Fragment key={i}>
              <div style={{ padding: 12, background: 'var(--cream)', borderRadius: 10, border: '1px solid var(--line)', position: 'relative' }}>
                <div style={{ width: 24, height: 24, borderRadius: '50%', background: 'var(--ch-lseo)', color: 'var(--cream)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700, marginBottom: 8 }}>{s.num}</div>
                <div style={{ fontSize: 12.5, fontWeight: 600, marginBottom: 2 }}>{s.label}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{s.sub}</div>
              </div>
              {i < arr.length - 1 && <div style={{ textAlign: 'center', color: 'var(--ink-3)' }}>→</div>}
            </React.Fragment>
          ))}
        </div>
        <div style={{ padding: 14, background: 'rgba(77,105,137,.08)', borderRadius: 10, fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.6 }}>
          <strong>Don't judge Demand Gen on last-click leads.</strong> The signal is in <em>brand search lift</em>, when this campaign runs, peers see Brand Search impressions go up 18-22%, and those branded searches convert at $22 CPL on average. That's how awareness becomes revenue.
        </div>
      </div>

      <Modal open={enrollModal} onClose={() => setEnrollModal(false)} title="Enroll in Demand Gen" sub={`$${d.pitch.monthlyBudget}/month · ${d.pitch.benchmarks.reach} reach`}
        footer={<>
          <button className="btn btn-ghost btn-sm" onClick={() => setEnrollModal(false)}>Cancel</button>
          <button className="btn btn-primary btn-sm" onClick={() => { setEnrollModal(false); T('Demand Gen enrolled', "Live in 3-5 business days. Lenny will track brand-search lift weekly.", 'ok'); }}>Confirm enrollment</button>
        </>}>
        <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.6, marginBottom: 14 }}>
          Demand Gen runs as a separate Google campaign. We'll set up audiences (radius, lookalikes, in-market for home services), build creative from your existing brand assets, and report on <strong>reach, view-through, and brand-search lift</strong>, not last-click leads.
        </div>
        <div style={{ padding: 14, background: 'var(--cream)', borderRadius: 10, fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.6 }}>
          <strong>Setup includes:</strong> 6 video assets cut from your existing footage (3 vertical, 3 horizontal), 2 image creatives for Discover, audience build, and weekly reporting on brand search lift over the prior 60-day rolling baseline.
        </div>
      </Modal>
    </>
  );
}
window.ResultsDemandGen = ResultsDemandGen;

// ====================================================================
// ENROLL CONFIRM MODAL — single review screen for any enrollment.
// Replaces toast-only enroll actions. Two clicks (Enroll → Confirm),
// one screen, no wizard. Fully rule-driven, no AI.
//   Enroll → review (locations · payer/funding · monthly spend @ $300
//   channel min + fees · launch date defaulting to next Monday cycle
//   with proration · required geo-territory confirmation + notes ·
//   inline requirements check · approval routing) → Confirm →
//   "what happens next" (owner + expected activation status).
// ====================================================================
const ENROLL_DEMO_TODAY = new Date(2026, 3, 14); // Tue, Apr 14 2026 — demo "today"

function enrollNextMonday(from) {
  const d = new Date(from.getFullYear(), from.getMonth(), from.getDate());
  // We launch every Monday. Roll forward to the next Monday strictly after today.
  do { d.setDate(d.getDate() + 1); } while (d.getDay() !== 1);
  return d;
}
function enrollFmtDate(d) {
  return d.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric' });
}
function enrollDaysInMonth(d) { return new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate(); }

function EnrollConfirmModal({ open, onClose, channel, locations, owner }) {
  const ch = channel || {};
  const payPerLead = !!ch.payPerLead;
  const rec = Math.max(300, ch.recommended || ch.minInvest || 300);
  const setupFee = ch.setupFee || 0;

  const [step, setStep]       = useStateR3('review');
  const [payer, setPayer]     = useStateR3('franchisee');
  const [monthly, setMonthly] = useStateR3(payPerLead ? 0 : rec);
  const [launch, setLaunch]   = useStateR3('next'); // 'next' | 'future'
  const nextMon = enrollNextMonday(ENROLL_DEMO_TODAY);
  const isoNext = nextMon.toISOString().slice(0, 10);
  const [futureDate, setFutureDate] = useStateR3(isoNext);
  const [geoOk, setGeoOk]     = useStateR3(false);
  const [geoNotes, setGeoNotes] = useStateR3('');

  // Reset to a clean review each time the modal is (re)opened for a channel.
  React.useEffect(() => {
    if (open) {
      setStep('review'); setPayer('franchisee'); setMonthly(payPerLead ? 0 : rec);
      setLaunch('next'); setFutureDate(isoNext); setGeoOk(false); setGeoNotes('');
    }
  }, [open, ch.name]);

  if (!open) return null;

  const locs = (locations && locations.length ? locations : ['this location']);
  const launchDate = launch === 'next' ? nextMon : new Date(futureDate + 'T00:00:00');
  const dim = enrollDaysInMonth(launchDate);
  const remaining = dim - launchDate.getDate() + 1;
  const midMonth = launchDate.getDate() > 1;
  const prorated = payPerLead ? 0 : Math.round(monthly * remaining / dim);

  // ---- Rule-driven approval routing --------------------------------------
  // Franchisee-funded launches inside the default territory are self-serve.
  // Corporate / co-op / split funding, or any territory exception (notes),
  // routes to corporate for approval before activation.
  const needsApproval = payer !== 'franchisee' || geoNotes.trim().length > 0;

  // ---- Inline requirements check (rules over known store state) ----------
  const reqs = [
    { label: 'Google Business Profile verified', ok: true },
    { label: 'Listings NAP consistent across directories', ok: true },
    payPerLead
      ? { label: 'Pay-per-lead — no monthly minimum', ok: true }
      : { label: 'Monthly media ≥ $300 channel minimum', ok: monthly >= 300, hint: monthly >= 300 ? null : 'Below the $300/channel minimum' },
    { label: 'Brand-approved creative on file', ok: true },
    { label: 'Geo-territory confirmed', ok: geoOk, hint: geoOk ? null : 'Confirm the service area below' },
  ];
  const canConfirm = geoOk && (payPerLead || monthly >= 300);

  const strategist = owner || 'your LOCALACT strategist';
  const payerLabel = { corporate: 'Corporate-funded', franchisee: 'Franchisee-funded', coop: 'Co-op (shared)', split: 'Split funding' }[payer];

  const cardBox = { padding: 14, background: 'var(--cream)', borderRadius: 10, border: '1px solid var(--cream-3)' };
  const eyebrow = { fontSize: 10.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.07em', fontWeight: 700, marginBottom: 8 };
  const seg = (on) => ({ padding: '7px 12px', borderRadius: 999, fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', border: '1px solid ' + (on ? 'var(--violet)' : 'var(--cream-3)'), background: on ? 'var(--violet-soft)' : 'var(--paper)', color: on ? 'var(--violet)' : 'var(--ink-3)' });

  // -------------------------------------------------- DONE ("what happens next")
  if (step === 'done') {
    return (
      <window.Modal open={true} onClose={onClose} width={560}
        title={`${ch.name} enrollment submitted`}
        sub={needsApproval ? 'Routed for corporate approval' : 'Confirmed — scheduled to launch'}
        footer={<button className="btn btn-primary btn-sm" onClick={onClose}>Done</button>}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', borderRadius: 12, marginBottom: 16,
                      background: needsApproval ? 'var(--marigold-soft)' : 'var(--sage-soft)', border: '1px solid ' + (needsApproval ? 'var(--marigold)' : 'var(--sage)') }}>
          <span style={{ width: 30, height: 30, borderRadius: '50%', flexShrink: 0, background: needsApproval ? 'var(--marigold)' : 'var(--sage)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700 }}>{needsApproval ? '⏳' : '✓'}</span>
          <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5 }}>
            {needsApproval
              ? <>Because this is <strong>{payerLabel.toLowerCase()}</strong>{geoNotes.trim() ? ' with a territory exception' : ''}, it needs a quick corporate sign-off before it goes live.</>
              : <>You're all set — no extra approval needed for a franchisee-funded launch in your territory.</>}
          </div>
        </div>
        <div style={eyebrow}>What happens next</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {[
            { n: '1', t: `${strategist} owns setup`, d: `Campaign build, audiences, and tracking for ${locs.length > 1 ? locs.length + ' locations' : locs[0]}.` },
            needsApproval
              ? { n: '2', t: 'Corporate approval', d: `Routed to corporate now — typically same business day. You'll get a note when it clears.` }
              : { n: '2', t: 'Requirements verified', d: 'GBP, listings, and creative all checked and clear — no blockers.' },
            { n: '3', t: needsApproval ? 'Activates once approved' : 'Activates ' + enrollFmtDate(launchDate), d: needsApproval
                ? `Target launch is the ${enrollFmtDate(launchDate)} cycle if approved today.`
                : `We launch on Mondays with monthly budgets.${midMonth && !payPerLead ? ` First month is prorated to $${prorated.toLocaleString()} for ${remaining} days.` : ''}` },
          ].map(s => (
            <div key={s.n} style={{ display: 'flex', gap: 12 }}>
              <span style={{ width: 24, height: 24, flexShrink: 0, borderRadius: '50%', background: 'var(--violet-soft)', color: 'var(--violet)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700, fontFamily: 'var(--ff-mono)' }}>{s.n}</span>
              <div><div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>{s.t}</div><div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2, lineHeight: 1.45 }}>{s.d}</div></div>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 16, padding: '10px 12px', background: 'var(--cream)', borderRadius: 8, fontSize: 11.5, color: 'var(--ink-3)', display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 6 }}>
          <span>Funding · <strong style={{ color: 'var(--ink-2)' }}>{payerLabel}</strong></span>
          <span>{payPerLead ? 'Pay-per-lead' : `$${monthly.toLocaleString()}/mo media`}{setupFee ? ` · $${setupFee} setup` : ''}</span>
          <span>Status · <strong style={{ color: needsApproval ? 'var(--marigold)' : 'var(--sage)' }}>{needsApproval ? 'Pending approval' : 'Scheduled'}</strong></span>
        </div>
      </window.Modal>
    );
  }

  // -------------------------------------------------- REVIEW
  return (
    <window.Modal open={true} onClose={onClose} width={580}
      title={`Enroll ${ch.name}`}
      sub="Review the details, then confirm. Two clicks, no back-and-forth."
      footer={<>
        <button className="btn btn-ghost btn-sm" onClick={onClose}>Cancel</button>
        <button className="btn btn-primary btn-sm" disabled={!canConfirm} style={{ opacity: canConfirm ? 1 : 0.5, cursor: canConfirm ? 'pointer' : 'not-allowed' }}
                onClick={() => { if (canConfirm) setStep('done'); }}>
          {needsApproval ? 'Confirm & send for approval →' : 'Confirm enrollment →'}
        </button>
      </>}>

      {ch.reason && (
        <div style={{ padding: 12, background: 'var(--violet-soft)', borderRadius: 10, marginBottom: 16, fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.5 }}>
          <div style={{ fontSize: 10.5, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 4 }}>Why this is recommended</div>
          {ch.reason}
        </div>
      )}

      {/* Participating locations */}
      <div style={{ marginBottom: 16 }}>
        <div style={eyebrow}>Participating location{locs.length > 1 ? 's' : ''}</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {locs.map((l, i) => (
            <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '5px 11px', borderRadius: 999, background: 'var(--cream)', border: '1px solid var(--cream-3)', fontSize: 12, fontWeight: 600, color: 'var(--ink-2)' }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--sage)' }} />{l}
            </span>
          ))}
        </div>
      </div>

      {/* Funding / payer */}
      <div style={{ marginBottom: 16 }}>
        <div style={eyebrow}>Funding</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {[['corporate', 'Corporate'], ['franchisee', 'Franchisee'], ['coop', 'Co-op'], ['split', 'Split']].map(([k, l]) => (
            <button key={k} onClick={() => setPayer(k)} style={seg(payer === k)}>{l}</button>
          ))}
        </div>
      </div>

      {/* Monthly media spend + fees */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 16 }}>
        <div style={cardBox}>
          <div style={eyebrow}>Monthly media spend</div>
          {payPerLead ? (
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 20, fontWeight: 500 }}>Pay-per-lead</div>
          ) : (
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
              <span style={{ fontSize: 15, color: 'var(--ink-3)' }}>$</span>
              <input type="number" min={300} step={50} value={monthly}
                     onChange={e => setMonthly(Math.max(0, parseInt(e.target.value || '0', 10)))}
                     style={{ width: 96, fontFamily: 'var(--ff-display)', fontSize: 20, fontWeight: 500, border: 'none', background: 'transparent', color: 'var(--ink)', borderBottom: '1px solid var(--cream-3)', padding: '2px 0' }} />
              <span style={{ fontSize: 11, color: 'var(--ink-4)' }}>/mo</span>
            </div>
          )}
          <div style={{ fontSize: 11, color: monthly < 300 && !payPerLead ? 'var(--terra)' : 'var(--ink-4)', marginTop: 6 }}>
            {payPerLead ? 'Billed only on Google-verified leads' : `$300/channel minimum${ch.recommended ? ` · $${rec} recommended` : ''}`}
          </div>
        </div>
        <div style={cardBox}>
          <div style={eyebrow}>Management &amp; setup</div>
          <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5 }}>
            <div>Management · <strong>Included</strong> in LOCALACT platform</div>
            <div style={{ marginTop: 3 }}>Setup · <strong>{setupFee ? `$${setupFee} one-time` : 'No setup fee'}</strong></div>
          </div>
        </div>
      </div>

      {/* Launch date */}
      <div style={{ marginBottom: 16 }}>
        <div style={eyebrow}>Launch date</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 8 }}>
          <button onClick={() => setLaunch('next')} style={seg(launch === 'next')}>Next cycle · {enrollFmtDate(nextMon)}</button>
          <button onClick={() => setLaunch('future')} style={seg(launch === 'future')}>Pick a future date</button>
          {launch === 'future' && (
            <input type="date" min={isoNext} value={futureDate} onChange={e => setFutureDate(e.target.value)}
                   style={{ padding: '6px 10px', borderRadius: 8, border: '1px solid var(--cream-3)', fontFamily: 'inherit', fontSize: 12, color: 'var(--ink)' }} />
          )}
        </div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.5 }}>
          We launch every Monday with monthly budgets.{midMonth && !payPerLead ? <> Starting {enrollFmtDate(launchDate)} mid-month, your first month is prorated to <strong style={{ color: 'var(--ink-2)' }}>${prorated.toLocaleString()}</strong> for {remaining} days.</> : ''}
        </div>
      </div>

      {/* Geo-territory confirmation (required) */}
      <div style={{ marginBottom: 16, padding: 14, borderRadius: 10, border: '1px solid ' + (geoOk ? 'var(--sage)' : 'var(--cream-3)'), background: geoOk ? 'var(--sage-soft)' : 'var(--paper)' }}>
        <label style={{ display: 'flex', gap: 10, cursor: 'pointer', alignItems: 'flex-start' }}>
          <input type="checkbox" checked={geoOk} onChange={e => setGeoOk(e.target.checked)} style={{ marginTop: 2, width: 16, height: 16, accentColor: 'var(--sage)' }} />
          <span style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.5 }}>
            <strong>I confirm the service territory</strong> for this program. <span style={{ color: 'var(--ink-3)' }}>Required. Launches to your default service area unless you note an exception below.</span>
          </span>
        </label>
        <textarea value={geoNotes} onChange={e => setGeoNotes(e.target.value)} rows={2}
                  placeholder='Optional territory notes — e.g. "remove ZIP 23232" or "exclude downtown core"'
                  style={{ width: '100%', boxSizing: 'border-box', marginTop: 10, padding: '8px 10px', borderRadius: 8, border: '1px solid var(--cream-3)', fontFamily: 'inherit', fontSize: 12, color: 'var(--ink)', resize: 'vertical' }} />
      </div>

      {/* Inline requirements check */}
      <div style={{ marginBottom: 16 }}>
        <div style={eyebrow}>Requirements check</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {reqs.map((r, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5 }}>
              <span style={{ width: 16, height: 16, flexShrink: 0, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700, background: r.ok ? 'var(--sage)' : 'var(--cream-3)', color: r.ok ? '#fff' : 'var(--ink-4)' }}>{r.ok ? '✓' : '!'}</span>
              <span style={{ color: r.ok ? 'var(--ink-2)' : 'var(--ink-3)' }}>{r.label}</span>
              {r.hint && <span style={{ fontSize: 11, color: 'var(--terra)' }}>· {r.hint}</span>}
            </div>
          ))}
        </div>
      </div>

      {/* Approval routing */}
      <div style={{ padding: '10px 12px', borderRadius: 8, fontSize: 12, lineHeight: 1.5, background: needsApproval ? 'var(--marigold-soft)' : 'var(--sky-soft)', color: needsApproval ? '#8a5a10' : '#001e40' }}>
        {needsApproval
          ? <><strong>Approval routing:</strong> {payer === 'franchisee' ? 'Territory exception' : payerLabel + ' funding'} routes this to corporate for a quick sign-off before activation.</>
          : <><strong>Approval routing:</strong> Franchisee-funded in your territory — self-serve, no extra sign-off needed.</>}
      </div>
    </window.Modal>
  );
}
window.EnrollConfirmModal = EnrollConfirmModal;
