// ====================================================================
// RESULTS PAGE, LSA, Local SEO, Social, Demand Gen tabs
// ====================================================================
const { useState: useStateR2 } = React;

// --------------------------------------------------------------------
// LOCAL SERVICES ADS, leads + ratings UI mirrors L3 LSA panel
// --------------------------------------------------------------------
function ResultsLsa({ data }) {
  const d = data.lsaDetail;
  const [filter, setFilter] = useStateR2('all');
  const [rateLead, setRateLead] = useStateR2(null);
  const [autoRateModal, setAutoRateModal] = useStateR2(false);
  const [ratings, setRatings] = useStateR2(() => {
    const m = {}; d.leads.forEach(l => { if (l.rating) m[l.id] = l.rating; });
    return m;
  });

  const ratedCount = Object.keys(ratings).length;
  const totalRatable = d.leads.length;
  const ratingRate = Math.round((ratedCount / totalRatable) * 100);
  const atRisk = ratingRate < 50;

  const filtered = d.leads.filter(l => {
    if (filter === 'all') return true;
    if (filter === 'unrated') return !ratings[l.id];
    if (filter === 'rated') return !!ratings[l.id];
    if (filter === 'charged') return l.charge === 'Charged';
    if (filter === 'not-charged') return l.charge === 'Not Charged';
    return true;
  });

  return (
    <>
      {/* Top KPI strip */}
      <div className="grid grid-4" style={{ marginBottom: 16 }}>
        <KpiCard label="Leads" value={d.summary.leads} delta={22} color="var(--ch-lsa)" dotColor="var(--ch-lsa)"/>
        <KpiCard label="Charged" value={d.summary.charged} color="var(--sage)" dotColor="var(--sage)"/>
        <KpiCard label="Cost / Lead" value="$15" delta={-8} invert color="var(--terra)" dotColor="var(--terra)"/>
        <KpiCard label="Booked" value={`${Math.round(d.summary.booked/d.summary.leads*100)}%`} delta={6} color="var(--marigold)" dotColor="var(--marigold)"/>
      </div>

      <SourceNote>Source: Google Ads · Local Services Ads</SourceNote>

      {/* Lead Rating health + Priority Actions + Tips */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr 1fr', gap: 14, marginBottom: 16 }}>
        {/* Rating Rate card */}
        <div className="card card-pad" style={{ background: atRisk ? 'linear-gradient(135deg, rgba(184,132,109,.10), rgba(212,101,138,.06))' : 'var(--cream)', border: atRisk ? '1px solid var(--clay)' : '1px solid var(--line)', position: 'relative', overflow: 'hidden' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 700, color: 'var(--ink-2)', marginBottom: 12 }}>
            <span style={{ color: 'var(--marigold)' }}>★</span> Lead Rating Rate
            <span style={{ flex: 1 }}/>
            <span style={{ fontSize: 9, padding: '2px 6px', background: 'var(--cream-2)', borderRadius: 99, color: 'var(--ink-3)' }}>?</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 6 }}>
            <span style={{ fontFamily: 'var(--ff-display)', fontSize: 44, fontWeight: 500, lineHeight: 1, color: atRisk ? 'var(--clay)' : 'var(--sage)' }}>{ratingRate}%</span>
            {atRisk && <span className="badge" style={{ background: 'var(--clay)', color: 'var(--cream)', fontSize: 11, padding: '4px 10px' }}>⚠ At Risk</span>}
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.5, marginBottom: 14 }}>
            A low rating rate may affect lead quality and eligibility for dispute credits. Regularly rating leads helps Google optimize which leads are sent to you.
          </div>
          <button className="btn btn-primary btn-sm" style={{ width: '100%' }} onClick={() => {
            const next = d.leads.find(l => !ratings[l.id]);
            if (next) setRateLead(next);
          }}>→ Rate Leads Now</button>
        </div>

        {/* Priority Actions */}
        <div className="card card-pad">
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 700, color: 'var(--ink-2)', marginBottom: 12 }}>
             Priority Actions
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <div style={{ display: 'flex', gap: 10 }}>
              <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--terra)', color: 'var(--cream)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700, flexShrink: 0 }}>1</span>
              <div>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--terra)', cursor: 'pointer' }} onClick={() => { setFilter('unrated'); document.querySelector('.lsa-leads-table')?.scrollIntoView?.({block:'start'}); }}>Rate {totalRatable - ratedCount} unrated leads</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.5 }}>This trains Google's algorithm and qualifies you for potential credits.</div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 10 }}>
              <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--sage)', color: 'var(--cream)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700, flexShrink: 0 }}>2</span>
              <div>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--sage-deep, #0b7979)' }}>Contact 4 new leads</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.5 }}>Respond within 24 hours for best conversion rates.</div>
              </div>
            </div>
          </div>
        </div>

        {/* Tips & Tricks */}
        <div className="card card-pad" style={{ background: 'rgba(82,184,148,.06)', border: '1px solid rgba(82,184,148,.3)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 700, color: 'var(--ink-2)', marginBottom: 12 }}>
             Lead Rating Tips & Tricks
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, fontSize: 11.5, color: 'var(--ink-2)', lineHeight: 1.5 }}>
            <div><strong>1. Rate leads within 24 hours</strong><br/><span style={{ color: 'var(--ink-3)' }}>Quick ratings provide faster feedback to Google's ML algorithms.</span></div>
            <div><strong>2. Use accurate rating categories</strong><br/><span style={{ color: 'var(--ink-3)' }}>The right category helps Google distinguish lead-quality issues vs. leads that didn't convert.</span></div>
            <div><strong>3. Be honest and consistent</strong><br/><span style={{ color: 'var(--ink-3)' }}>Rating good leads is just as important as rating bad ones.</span></div>
          </div>
        </div>
      </div>

      {/* Auto-rate AI upsell, bigger story */}
      <div className="card" style={{ marginBottom: 16, background: 'linear-gradient(135deg, var(--ink) 0%, #053a3a 100%)', color: 'var(--cream)', overflow: 'hidden', position: 'relative' }}>
        <div style={{ position: 'absolute', right: -20, top: -20, fontSize: 180, opacity: 0.06, transform: 'rotate(15deg)' }}>★</div>
        <div className="card-pad" style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 36, alignItems: 'center', position: 'relative' }}>
          <div>
            <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.1em', fontWeight: 700, color: 'rgba(250,246,239,.65)', marginBottom: 8 }}>
              ✦ Lenny AI · Upsell
            </div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 28, fontWeight: 500, lineHeight: 1.15, marginBottom: 10 }}>
              Let Lenny rate your leads automatically.
            </div>
            <div style={{ fontSize: 13.5, color: 'rgba(250,246,239,.85)', lineHeight: 1.6, marginBottom: 16, maxWidth: 560 }}>
              Your rating rate is <strong style={{ color: 'var(--marigold)' }}>{ratingRate}%</strong>, Google penalizes accounts under 80% by sending fewer high-intent leads. Rating <strong>{totalRatable - ratedCount} leads</strong> manually each week takes ~45 min. Lenny reads call transcripts and chat threads, applies your rating logic, and submits ratings within minutes, keeping you eligible for dispute credits and lead-quality optimization.
            </div>
            <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <button className="btn btn-primary btn-sm" onClick={() => setAutoRateModal(true)}>Add for $99/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', 'Lenny prepared a sample auto-rate report from last 7 days. Check your email.', 'info')}>See sample report</button>
              <span style={{ fontSize: 11, color: 'rgba(250,246,239,.6)' }}>30-day money-back · Cancel anytime</span>
            </div>
          </div>
          <div style={{ background: 'rgba(250,246,239,.07)', borderRadius: 14, padding: 18, border: '1px solid rgba(250,246,239,.12)' }}>
            <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.08em', fontWeight: 700, color: 'rgba(250,246,239,.6)', marginBottom: 10 }}>What changes</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, fontSize: 12.5 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: 'rgba(250,246,239,.75)' }}>Rating rate</span>
                <span><span style={{ color: 'var(--clay)' }}>{ratingRate}%</span> → <strong style={{ color: 'var(--sage)' }}>97%</strong></span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: 'rgba(250,246,239,.75)' }}>Avg time to rate</span>
                <span>4.2 hrs → <strong style={{ color: 'var(--sage)' }}>14 min</strong></span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: 'rgba(250,246,239,.75)' }}>Dispute credit eligibility</span>
                <span style={{ color: 'var(--clay)' }}>At risk</span><span> → <strong style={{ color: 'var(--sage)' }}>Eligible</strong></span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: 'rgba(250,246,239,.75)' }}>Est. quality improvement</span>
                <span><strong style={{ color: 'var(--marigold)' }}>+12% booked</strong></span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <SourceNote>Source: Google Ads · Local Services Ads · lead rating tracked by LOCALACT</SourceNote>

      {/* Charge / Credit / Type / Category breakdown */}
      <div className="grid grid-4" style={{ marginBottom: 16 }}>
        {[
          { label: 'Charge Status', icon: '💲', items: d.chargeStatus },
          { label: 'Credit Status', icon: '🪙', items: d.creditStatus },
          { label: 'Lead Types',    icon: '☎️', items: d.leadTypes },
          { label: 'Top Categories',icon: '📋', items: Object.fromEntries(d.categories.map(c => [c.name, c.count])) },
        ].map((box, i) => (
          <div key={i} className="card card-pad" style={{ minHeight: 120 }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-2)', marginBottom: 10, display: 'flex', alignItems: 'center', gap: 6 }}>
              <span>{box.icon}</span> {box.label}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {Object.entries(box.items).map(([k, v]) => (
                <div key={k} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
                  <span style={{ color: 'var(--ink-3)' }}>{k}</span>
                  <strong>{v}</strong>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      <SourceNote>Source: Google Ads · Local Services Ads</SourceNote>

      {/* Leads table */}
      <div className="card lsa-leads-table" style={{ overflow: 'hidden' }}>
        <div className="card-pad" style={{ paddingBottom: 12, display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
          <div>
            <div className="card-title">Leads <span style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 400 }}>· {filtered.length} of {d.leads.length}</span></div>
          </div>
          <div style={{ display: 'flex', gap: 4 }}>
            {[
              ['all', `All (${d.leads.length})`],
              ['unrated', `Not Rated (${totalRatable - ratedCount})`],
              ['rated', `Rated (${ratedCount})`],
              ['charged', `Charged (${d.summary.charged})`],
              ['not-charged', `Not Charged (${d.summary.notCharged})`],
            ].map(([v, l]) => (
              <button key={v} onClick={() => setFilter(v)} style={{
                padding: '5px 11px', borderRadius: 99, fontSize: 11.5, fontWeight: 600,
                background: filter === v ? 'var(--sky)' : 'transparent',
                color: filter === v ? 'var(--cream)' : 'var(--ink-2)',
                border: filter === v ? '1px solid var(--sky)' : '1px solid var(--line)',
                cursor: 'pointer',
              }}>{l}</button>
            ))}
          </div>
        </div>
        <table className="tbl">
          <thead>
            <tr>
              <th></th><th>Lead Received</th><th>Contact</th><th>Rating</th>
              <th>Status</th><th>Type</th><th>Category</th><th>Charge</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(l => {
              const r = ratings[l.id];
              const ratingMeta = {
                'very-satisfied':    { label: 'Very Satisfied',    icon: '😄', color: 'var(--sage)' },
                'satisfied':         { label: 'Somewhat Satisfied',icon: '', color: 'var(--sage)' },
                'neutral':           { label: 'Neutral',           icon: '😐', color: 'var(--ink-3)' },
                'dissatisfied':      { label: 'Somewhat Dissatisfied',icon: '🙁', color: 'var(--clay)' },
                'very-dissatisfied': { label: 'Very Dissatisfied', icon: '😞', color: 'var(--clay)' },
              }[r];
              return (
                <tr key={l.id}>
                  <td>
                    <button className="btn btn-primary btn-xs" onClick={() => setRateLead(l)} style={{
                      background: r ? 'transparent' : 'var(--sky)',
                      borderColor: r ? 'var(--line)' : 'var(--sky)',
                      color: r ? 'var(--ink-2)' : 'var(--cream)',
                    }}>
                      {r ? '✏️ Edit' : '★ Rate Lead'}
                    </button>
                  </td>
                  <td className="mono" style={{ fontSize: 11.5 }}>{l.date}</td>
                  <td><strong>{l.contact}</strong><div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--ff-mono)' }}>{l.phone}</div></td>
                  <td>
                    {r ? (
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 11.5, color: ratingMeta.color, fontWeight: 600 }}>
                        {ratingMeta.icon} {ratingMeta.label}
                      </span>
                    ) : <span style={{ color: 'var(--ink-4)', fontStyle: 'italic', fontSize: 11.5 }}>Not Rated</span>}
                  </td>
                  <td><span className={`badge ${l.status === 'Booked' ? 'badge-ok' : l.status === 'Active' ? 'badge-info' : 'badge-neutral'}`}>{l.status}</span></td>
                  <td>{l.type}</td>
                  <td>{l.category}</td>
                  <td>
                    <span className={`badge ${l.charge === 'Charged' ? 'badge-ok' : 'badge-neutral'}`} style={{ fontSize: 10 }}>
                      {l.charge}
                    </span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <SourceNote>Source: Google Ads · Local Services Ads + Telmetrics or other</SourceNote>

      {/* Rating modal */}
      {rateLead && <RateLsaLeadModal lead={rateLead} reasons={d.ratingReasons} initial={ratings[rateLead.id]} onClose={() => setRateLead(null)}
        onSave={(rating, reason) => {
          setRatings({ ...ratings, [rateLead.id]: rating });
          setRateLead(null);
          T('Lead rated', `${rateLead.contact} marked as ${rating.replace('-', ' ')}. Sending feedback to Google.`, 'ok');
        }}/>}

      {/* Auto-rate confirmation modal */}
      <Modal open={autoRateModal} onClose={() => setAutoRateModal(false)} title="Add Lenny Auto-Rate" sub="$99/month · added to your next invoice"
        footer={<>
          <button className="btn btn-ghost btn-sm" onClick={() => setAutoRateModal(false)}>Not now</button>
          <button className="btn btn-primary btn-sm" onClick={() => { setAutoRateModal(false); T('Lenny Auto-Rate enabled', 'Active in 24 hrs. Lenny will rate every new lead within 30 min of receipt.', 'ok'); }}>Confirm $99/mo</button>
        </>}>
        <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.6, marginBottom: 14 }}>
          Lenny will read every LSA call transcript and message thread within minutes of receipt, apply your rating logic, and submit ratings to Google before the 24-hour window closes.
        </div>
        <div style={{ padding: 14, background: 'var(--cream)', borderRadius: 10, marginBottom: 14 }}>
          <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-3)', fontWeight: 600, marginBottom: 8 }}>Your rating policy</div>
          <div style={{ fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.5 }}>
            Lenny defaults to your past ratings as training data. You can edit the policy any time, what counts as Spam, what counts as a wrong-service request, etc.
          </div>
        </div>
        <ul style={{ paddingLeft: 18, fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.7 }}>
          <li>Reads call transcripts and messages</li>
          <li>Submits ratings within 30 min</li>
          <li>You review weekly digest, override anything</li>
          <li>Auto-files dispute credits for Spam ratings</li>
        </ul>
      </Modal>
    </>
  );
}

function RateLsaLeadModal({ lead, reasons, initial, onClose, onSave }) {
  const [rating, setRating] = useStateR2(initial || null);
  const [reason, setReason] = useStateR2(null);
  const options = [
    { id: 'very-satisfied',    icon: '😄', label: 'Very Satisfied',     desc: 'High-quality lead that converted or has strong potential.' },
    { id: 'satisfied',         icon: '', label: 'Somewhat Satisfied', desc: 'Decent lead with reasonable potential.' },
    { id: 'neutral',           icon: '😐', label: 'Neither Satisfied nor Dissatisfied', desc: 'Lead quality is unclear or mixed.' },
    { id: 'dissatisfied',      icon: '🙁', label: 'Somewhat Dissatisfied', desc: 'Poor quality with notable issues.' },
    { id: 'very-dissatisfied', icon: '😞', label: 'Very Dissatisfied',  desc: 'Extremely poor quality (spam, duplicate, wrong service).' },
  ];

  return (
    <Modal open onClose={onClose} title={`${lead.contact} · ${lead.category}`} sub={`${lead.date} · ${lead.type} · ${lead.charge}`} width={640}
      footer={<>
        <button className="btn btn-ghost btn-sm" onClick={onClose}>Cancel</button>
        <button className="btn btn-primary btn-sm" disabled={!rating} onClick={() => onSave(rating, reason)} style={{ opacity: rating ? 1 : 0.4 }}>Submit Rating</button>
      </>}>
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18 }}>
        {/* Rate Lead Quality column */}
        <div style={{ padding: 16, background: 'rgba(107, 164, 232, 0.07)', borderRadius: 12, border: '1px solid rgba(107, 164, 232, 0.25)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16 }}>
            <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--sky)', color: 'var(--cream)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700 }}>1</span>
            <div>
              <div style={{ fontSize: 13, fontWeight: 700 }}>Overall Satisfaction</div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>How satisfied are you with this lead?</div>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {options.map(o => (
              <label key={o.id} style={{
                display: 'flex', alignItems: 'flex-start', gap: 10, padding: 10, borderRadius: 8,
                border: rating === o.id ? '1px solid var(--sky)' : '1px solid transparent',
                background: rating === o.id ? 'var(--cream)' : 'transparent',
                cursor: 'pointer',
              }}>
                <input type="radio" checked={rating === o.id} onChange={() => setRating(o.id)} style={{ marginTop: 2 }}/>
                <span style={{ fontSize: 18 }}>{o.icon}</span>
                <div>
                  <div style={{ fontSize: 12.5, fontWeight: 600 }}>{o.label}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)', lineHeight: 1.4 }}>{o.desc}</div>
                </div>
              </label>
            ))}
          </div>
          {rating && (
            <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px dashed var(--cream-3)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--ink-3)', color: 'var(--cream)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700 }}>2</span>
                <div style={{ fontSize: 13, fontWeight: 700 }}>Reason</div>
              </div>
              <select className="inp" value={reason || ''} onChange={e => setReason(e.target.value)} style={{ width: '100%', padding: '8px 10px', fontSize: 12 }}>
                <option value="">Select a reason…</option>
                {reasons.map(r => <option key={r.id} value={r.id}>{r.label}</option>)}
              </select>
            </div>
          )}
        </div>

        {/* Lead context column */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div style={{ padding: 12, background: 'var(--cream)', borderRadius: 10 }}>
            <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-3)', fontWeight: 600, marginBottom: 8 }}>Contact</div>
            <div style={{ fontSize: 13, fontWeight: 600 }}>{lead.contact}</div>
            <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 12, color: 'var(--ink-2)' }}>{lead.phone}</div>
          </div>
          <div style={{ padding: 12, background: 'var(--cream)', borderRadius: 10 }}>
            <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-3)', fontWeight: 600, marginBottom: 8 }}>Lead detail</div>
            <div style={{ display: 'grid', gridTemplateColumns: '80px 1fr', gap: 4, fontSize: 12 }}>
              <span style={{ color: 'var(--ink-3)' }}>Type</span><strong>{lead.type}</strong>
              <span style={{ color: 'var(--ink-3)' }}>Category</span><strong>{lead.category}</strong>
              <span style={{ color: 'var(--ink-3)' }}>Status</span><strong>{lead.status}</strong>
              <span style={{ color: 'var(--ink-3)' }}>Charge</span><strong>{lead.charge}</strong>
              {lead.value > 0 && <><span style={{ color: 'var(--ink-3)' }}>Est. value</span><strong>${lead.value}</strong></>}
            </div>
          </div>
          {lead.transcript && (
            <div style={{ padding: 12, background: 'var(--ink)', color: 'var(--cream)', borderRadius: 10 }}>
              <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.06em', color: 'rgba(250,246,239,.6)', fontWeight: 600, marginBottom: 8 }}>Transcript snippet</div>
              <div style={{ fontSize: 11.5, lineHeight: 1.5, fontStyle: 'italic' }}>"{lead.transcript}"</div>
              <button className="btn btn-quiet btn-xs" style={{ marginTop: 10, background: 'rgba(250,246,239,.1)', color: 'var(--cream)', borderColor: 'rgba(250,246,239,.2)' }} onClick={() => T('Playing audio', '1:28 audio · auto-transcribed', 'info')}>▶ Play audio (1:28)</button>
            </div>
          )}
        </div>
      </div>
    </Modal>
  );
}

window.ResultsLsa = ResultsLsa;

// --------------------------------------------------------------------
// LOCAL SEO TAB, GA + GSC + page rankings + content optimizations
// --------------------------------------------------------------------
function ResultsSeo({ data }) {
  const d = data.seoDetail;
  const intentColor = (i) => i === 'high' ? 'var(--sage)' : i === 'med' ? 'var(--marigold)' : i === 'brand' ? 'var(--brand-navy)' : 'var(--ink-4)';

  return (
    <>
      <div className="grid grid-4" style={{ marginBottom: 16 }}>
        <KpiCard label="Organic Sessions" value={d.summary.sessions.toLocaleString()} delta={14} color="var(--ch-seo)" dotColor="var(--ch-seo)"/>
        <KpiCard label="Organic Leads" value={d.summary.organicLeads} delta={12} color="var(--terra)" dotColor="var(--terra)"/>
        <KpiCard label="Avg Position" value={d.summary.avgPosition} delta={-1.2} invert color="var(--marigold)" dotColor="var(--marigold)"/>
        <KpiCard label="GSC CTR" value={`${d.summary.ctr}%`} delta={0.4} color="var(--sky)" dotColor="var(--sky)"/>
      </div>

      {/* Rankings + Traffic sources */}
      <div className="grid grid-2-1" style={{ marginBottom: 16 }}>
        <div className="card card-pad">
          <div className="card-header" style={{ marginBottom: 14 }}>
            <div>
              <div className="card-title">Location page rankings</div>
              <div className="card-sub">Where you show up in Google for terms tied to this location.</div>
            </div>
            <button className="btn btn-quiet btn-sm" onClick={() => T('GSC view', 'Opening Google Search Console with a 90d preset for this property.', 'info')}>Open GSC ↗</button>
          </div>
          <table className="tbl" style={{ marginTop: 4 }}>
            <thead><tr><th>Keyword</th><th style={{ textAlign: 'center' }}>Position</th><th style={{ textAlign: 'right' }}>Δ</th><th style={{ textAlign: 'right' }}>Vol/mo</th><th>Intent</th></tr></thead>
            <tbody>
              {d.rankings.map((k, i) => {
                const delta = k.prev - k.position;
                return (
                  <tr key={i}>
                    <td style={{ fontFamily: 'var(--ff-mono)', fontSize: 12.5 }}>{k.keyword}</td>
                    <td style={{ textAlign: 'center' }}>
                      <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 32, height: 32, borderRadius: 8, background: k.position <= 3 ? 'var(--sage-soft)' : k.position <= 10 ? 'var(--marigold-soft)' : 'var(--cream-2)', color: k.position <= 3 ? 'var(--sage-deep, #0b7979)' : k.position <= 10 ? 'var(--ink-2)' : 'var(--ink-3)', fontFamily: 'var(--ff-display)', fontWeight: 600 }}>
                        {k.position}
                      </span>
                    </td>
                    <td style={{ textAlign: 'right', fontFamily: 'var(--ff-mono)', fontSize: 12, color: delta > 0 ? 'var(--sage)' : delta < 0 ? 'var(--clay)' : 'var(--ink-4)' }}>
                      {delta > 0 ? `↑${delta}` : delta < 0 ? `↓${-delta}` : '–'}
                    </td>
                    <td style={{ textAlign: 'right' }} className="mono">{k.monthlySearches.toLocaleString()}</td>
                    <td><span style={{ fontSize: 10, padding: '2px 8px', borderRadius: 99, background: intentColor(k.intent), color: 'var(--cream)', textTransform: 'uppercase', fontWeight: 600 }}>{k.intent}</span></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div className="card card-pad">
            <div className="card-title" style={{ marginBottom: 12 }}>Traffic sources</div>
            <ResultsDonut size={140} strokeW={20} segments={d.trafficSources.map(s => ({ value: s.share, color: s.color }))} center={
              <>
                <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 500, lineHeight: 1 }}>{d.summary.sessions.toLocaleString()}</div>
                <div style={{ fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase' }}>sessions</div>
              </>
            }/>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 14 }}>
              {d.trafficSources.map((s, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11.5 }}>
                  <span style={{ width: 10, height: 10, background: s.color, borderRadius: 2 }}/>
                  <span style={{ flex: 1 }}>{s.source}</span>
                  <strong style={{ fontFamily: 'var(--ff-mono)' }}>{s.share}%</strong>
                </div>
              ))}
            </div>
          </div>

          <div className="card card-pad">
            <div className="card-title" style={{ marginBottom: 12 }}>Device split</div>
            <StackedRow h={20} segments={[
              { label: 'Mobile', value: d.deviceSplit.Mobile, color: 'var(--ch-seo)' },
              { label: 'Desktop', value: d.deviceSplit.Desktop, color: 'var(--sky)' },
              { label: 'Tablet', value: d.deviceSplit.Tablet, color: 'var(--marigold)' },
            ]}/>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10, fontSize: 11.5 }}>
              <span>📱 Mobile <strong>{d.deviceSplit.Mobile}%</strong></span>
              <span>🖥 Desktop <strong>{d.deviceSplit.Desktop}%</strong></span>
              <span>📋 Tablet <strong>{d.deviceSplit.Tablet}%</strong></span>
            </div>
          </div>
        </div>
      </div>

      <SourceNote>Source: GA4 + Google Search Console</SourceNote>

      {/* Top pages */}
      <div className="card" style={{ marginBottom: 16, overflow: 'hidden' }}>
        <div className="card-pad" style={{ paddingBottom: 12 }}>
          <div className="card-title">Top pages on your location subdomain</div>
          <div className="card-sub">Pages tied to {data.location.unit}, sessions, conversion rate, and engagement.</div>
        </div>
        <table className="tbl">
          <thead><tr><th>Page</th><th style={{ textAlign: 'right' }}>Views</th><th style={{ textAlign: 'right' }}>Conv. Rate</th><th style={{ textAlign: 'right' }}>Avg Time</th><th/></tr></thead>
          <tbody>
            {d.topPages.map((p, i) => (
              <tr key={i}>
                <td>
                  <div><strong>{p.title}</strong></div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--ff-mono)' }}>{p.url}</div>
                </td>
                <td style={{ textAlign: 'right' }} className="mono">{p.views.toLocaleString()}</td>
                <td style={{ textAlign: 'right' }} className="strong">{p.conv}%</td>
                <td style={{ textAlign: 'right' }} className="mono">{p.avgTime}</td>
                <td><button className="btn btn-quiet btn-xs" onClick={() => T('Page audit', `Lenny will run an SEO audit on ${p.url}. Results in ~10 min.`, 'info')}>Audit</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <SourceNote>Source: GA4</SourceNote>

      {/* Optimizations log */}
      <div className="card card-pad">
        <div className="card-header" style={{ marginBottom: 14 }}>
          <div>
            <div className="card-title">Content & SEO work, last 30 days</div>
            <div className="card-sub">Optimizations made by Location3's SEO team. New content is either applied directly to the site, or sent to you to drop in.</div>
          </div>
          <button className="btn btn-primary btn-sm" onClick={() => T('Brief requested', "We'll draft a content brief for your top opportunity term. ETA 2 business days.", 'ok')}>Request a brief</button>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {d.optimizations.map((o, i) => (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '70px 100px 1fr 90px', gap: 14, alignItems: 'center', padding: '10px 12px', borderRadius: 10, border: '1px solid var(--line)', background: o.status === 'live' ? 'rgba(82,184,148,.04)' : o.status === 'draft' ? 'rgba(214,184,77,.06)' : 'transparent' }}>
              <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 11, color: 'var(--ink-3)' }}>{o.date}</div>
              <span className="badge badge-neutral" style={{ fontSize: 10, justifySelf: 'start' }}>{o.type}</span>
              <div>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{o.title}</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>{o.impact}</div>
              </div>
              <span className={`badge ${o.status === 'live' ? 'badge-ok' : o.status === 'draft' ? 'badge-warn' : 'badge-info'}`} style={{ fontSize: 10, justifySelf: 'end' }}>
                {o.status === 'live' ? '● LIVE' : o.status === 'draft' ? '✎ DRAFT' : '⏱ SCHEDULED'}
              </span>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}
window.ResultsSeo = ResultsSeo;

Object.assign(window, { RateLsaLeadModal });
