// ====================================================================
// SIMPLE / OWNER VIEW
// A calmer, larger-type, fewer-cards rendering of the location Home and
// Results screens, for when an advisor is walking a franchise owner
// through results. Same design system (tokens, cards, pills, Lenny),
// just distilled to: a few headline numbers, plain-language insight,
// and the top 1–3 things to do next. The full "Pro" view is untouched.
// Applies to location personas only (franchisee / franchise).
// ====================================================================
const { useState: useStateSimple } = React;

const goPage = (p) => window.dispatchEvent(new CustomEvent('go-page', { detail: p }));
const setDensity = (d) => window.dispatchEvent(new CustomEvent('set-density', { detail: d }));

// --------------------------------------------------------------------
// Shared: a big headline number tile
// --------------------------------------------------------------------
function BigStat({ label, value, prefix, suffix, delta, invert, trend, sub, tone = 'neutral', color = 'var(--terra)' }) {
  const hasDelta = typeof delta === 'number';
  const up = (delta > 0 && !invert) || (delta < 0 && invert);
  const deltaCls = delta === 0 ? 'delta-flat' : up ? 'delta-up' : 'delta-down';
  const arrow = delta === 0 ? '→' : delta > 0 ? '↑' : '↓';
  return (
    <div className="card simple-stat">
      <div className="simple-stat-label">{label}</div>
      <div className="simple-stat-value">
        {prefix && <span className="simple-stat-affix">{prefix}</span>}
        {value}
        {suffix && <span className="simple-stat-affix">{suffix}</span>}
      </div>
      <div className="simple-stat-foot">
        {hasDelta && <span className={`simple-stat-delta ${deltaCls}`}>{arrow} {Math.abs(delta)}%</span>}
        {sub && <span className="simple-stat-sub">{sub}</span>}
      </div>
      {Array.isArray(trend) && trend.length > 0 && (
        <div className="simple-stat-spark"><Sparkline data={trend} color={color} w={150} h={34}/></div>
      )}
    </div>
  );
}

// --------------------------------------------------------------------
// Shared: Lenny's plain-language read, what's working / what to do
// --------------------------------------------------------------------
function LennySummaryCard({ working, next }) {
  return (
    <div className="card simple-lenny">
      <div className="simple-lenny-head">
        <div className="simple-lenny-avatar"><LennyLlama size={52} mood="happy" bg="circle"/></div>
        <div>
          <div className="simple-lenny-name">Lenny&rsquo;s read</div>
          <div className="simple-lenny-role"><span className="status-dot"/> Your AI marketing coach · plain English</div>
        </div>
        <button className="btn btn-ghost btn-sm simple-lenny-chat" onClick={() => window.dispatchEvent(new CustomEvent('open-lenny'))}>
          Ask a question
        </button>
      </div>
      <div className="simple-lenny-body">
        <div className="simple-read">
          <div className="simple-read-tag working">What&rsquo;s working</div>
          <p className="simple-read-text">{working}</p>
        </div>
        <div className="simple-read-divider"/>
        <div className="simple-read">
          <div className="simple-read-tag next">What to do next</div>
          <p className="simple-read-text">{next}</p>
        </div>
      </div>
    </div>
  );
}

// --------------------------------------------------------------------
// Shared: the top 1–3 recommended actions
// --------------------------------------------------------------------
function OwnerActions({ title, sub, items }) {
  return (
    <div className="card card-pad simple-actions">
      <div className="card-header" style={{ marginBottom: 16 }}>
        <div>
          <div className="card-title">{title}</div>
          <div className="card-sub">{sub}</div>
        </div>
        <span className="badge badge-info">{items.length} {items.length === 1 ? 'thing' : 'things'}</span>
      </div>
      <div className="simple-action-list">
        {items.map((it, i) => (
          <div key={i} className="simple-action-row">
            <div className="simple-action-num" style={{ background: it.tone === 'primary' ? 'var(--terra)' : 'var(--cream-2)', color: it.tone === 'primary' ? 'var(--paper)' : 'var(--ink-2)' }}>{i + 1}</div>
            <div className="simple-action-text">
              <div className="simple-action-title">{it.title}</div>
              <div className="simple-action-why">{it.why}</div>
            </div>
            <button className={`btn btn-sm ${it.tone === 'primary' ? 'btn-primary' : 'btn-ghost'}`} onClick={it.onClick}>{it.cta}</button>
          </div>
        ))}
      </div>
    </div>
  );
}

// --------------------------------------------------------------------
// Shared: footer link back to the full Pro view
// --------------------------------------------------------------------
function ProViewFooter({ note }) {
  return (
    <div className="simple-pro-foot">
      <span>{note}</span>
      <button className="btn btn-ghost btn-sm" onClick={() => setDensity('full')}>Switch to Pro view {Icon.arrow}</button>
    </div>
  );
}

// --------------------------------------------------------------------
// Shared: a numbered section heading for the walk-down layout
// --------------------------------------------------------------------
function SimpleQ({ n, title }) {
  return (
    <div className="simple-q">
      <span className="simple-q-num">{n}</span>
      <span className="simple-q-title">{title}</span>
    </div>
  );
}

// --------------------------------------------------------------------
// 1) HOW AM I DOING, big score + one plain sentence + supporting numbers
// --------------------------------------------------------------------
function HowAmIDoing({ scores, kpis, verdict, money }) {
  return (
    <div className="card simple-hru">
      <div className="simple-hru-top">
        <div className="simple-hru-ring">
          <ScoreRing value={scores.localScore} size={130} color={verdict.ring} track="var(--cream-2)" label="OVERALL SCORE" textColor="var(--ink)" labelColor="var(--ink-4)"/>
        </div>
        <div className="simple-hru-read">
          <span className="simple-hru-badge" style={{ background: verdict.soft, color: verdict.ink }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: verdict.ring }}/>
            {verdict.word}
          </span>
          <p className="simple-hru-result">{verdict.result}</p>
        </div>
      </div>
      <div className="simple-hru-nums">
        {money.map((m, i) => (
          <div key={i} className="simple-hru-num">
            <div className="simple-hru-num-val" style={{ color: m.color }}>{m.value}</div>
            <div className="simple-hru-num-lbl">{m.label}</div>
            <div className="simple-hru-num-sub">
              {typeof m.delta === 'number'
                ? <span className={m.delta === 0 ? 'delta-flat' : m.delta > 0 ? 'delta-up' : 'delta-down'}>{m.delta > 0 ? '↑' : m.delta < 0 ? '↓' : '→'} {Math.abs(m.delta)}% vs last month</span>
                : m.sub}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// --------------------------------------------------------------------
// 2) WHAT CHANGED, plain since-last-month list
// --------------------------------------------------------------------
function WhatChanged({ items }) {
  const dir = { up: { c: 'var(--sage)', g: '↑' }, down: { c: 'var(--terra)', g: '↓' }, fix: { c: 'var(--sky)', g: '✓' }, flat: { c: 'var(--ink-4)', g: '→' } };
  return (
    <div className="card card-pad simple-changed">
      <div className="simple-changed-list">
        {items.map((it, i) => {
          const d = dir[it.kind] || dir.flat;
          return (
            <div key={i} className="simple-changed-row">
              <span className="simple-changed-icon" style={{ background: d.c }}>{d.g}</span>
              <div className="simple-changed-text">{it.text}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// --------------------------------------------------------------------
// 4) DO I OWE AN APPROVAL OR A PAYMENT
// --------------------------------------------------------------------
function ApprovalsAndPayment({ approvals, payment, nav }) {
  const nApprovals = approvals.reduce((s, a) => s + a.count, 0);
  return (
    <div className="simple-owe-grid">
      {/* Approvals */}
      <div className="card card-pad simple-owe">
        <div className="simple-owe-head">
          <div className="simple-owe-title">Waiting on your OK</div>
          <span className={`badge ${nApprovals ? 'badge-warn' : 'badge-ok'}`}>{nApprovals ? `${nApprovals} to review` : 'All clear'}</span>
        </div>
        <div className="simple-owe-list">
          {approvals.map((a, i) => (
            <button key={i} className="simple-owe-row" onClick={() => nav(a.go)}>
              <div className="simple-owe-count">{a.count}</div>
              <div className="simple-owe-copy">
                <div className="simple-owe-what">{a.what}</div>
                <div className="simple-owe-why">{a.why}</div>
              </div>
              <span className="simple-owe-go">{a.cta} →</span>
            </button>
          ))}
        </div>
      </div>
      {/* Payment */}
      <div className="card card-pad simple-owe">
        <div className="simple-owe-head">
          <div className="simple-owe-title">Anything to pay?</div>
          <span className="badge badge-ok">Nothing due</span>
        </div>
        <div className="simple-pay">
          <div className="simple-pay-check">✓</div>
          <div>
            <div className="simple-pay-lead">{payment.lead}</div>
            <div className="simple-pay-sub">{payment.sub}</div>
          </div>
        </div>
        <button className="btn btn-ghost btn-sm" style={{ marginTop: 14, alignSelf: 'flex-start' }} onClick={() => nav('billing')}>See invoice & payment method</button>
      </div>
    </div>
  );
}

// --------------------------------------------------------------------
// PROGRAM PARTICIPATION, what you're signed up for (plain, no metrics)
// --------------------------------------------------------------------
function ProgramParticipation({ active, available, note, nav }) {
  return (
    <div className="card card-pad simple-part">
      <div className="simple-part-groups">
        <div className="simple-part-group">
          <div className="simple-part-lbl">You're signed up for</div>
          <div className="simple-part-chips">
            {active.map((p, i) => (
              <span key={i} className="simple-part-chip on"><span className="simple-part-dot" style={{ background: p.color || 'var(--sage)' }}/>{p.name}</span>
            ))}
          </div>
        </div>
        {available && available.length > 0 && (
          <div className="simple-part-group">
            <div className="simple-part-lbl">Available when you want it</div>
            <div className="simple-part-chips">
              {available.map((p, i) => (
                <button key={i} className="simple-part-chip off" onClick={() => nav('services')}>+ {p}</button>
              ))}
            </div>
          </div>
        )}
      </div>
      {note && <div className="simple-part-note">{note}</div>}
    </div>
  );
}

// --------------------------------------------------------------------
// A calm line confirming what LOCALACT runs for you automatically
// --------------------------------------------------------------------
function HandledByLocalact({ text }) {
  return (
    <div className="simple-handled">
      <div className="simple-handled-avatar"><LennyLlama size={40} mood="happy" bg="circle"/></div>
      <div>
        <div className="simple-handled-lbl">LOCALACT is already handling this for you</div>
        <div className="simple-handled-text">{text}</div>
      </div>
    </div>
  );
}

// ====================================================================
// SIMPLE LOCATION HOME
// Walk-down layout that answers, in order: how am I doing → what
// changed → what should I do → do I owe an approval or a payment,
// then program participation + what LOCALACT handles automatically.
// Deliberately non-marketer: plain words, no CPL / ROAS / impression
// share (those live in the Pro view).
// ====================================================================
function SimpleLocationHome({ data, onNav }) {
  const nav = onNav || goPage;
  const { scores, kpis } = data;
  const isBare = data.variant === 'bare';

  const head = isBare
    ? { greet: 'Morning, Danny.', sub: 'Plano Legacy · Tuesday, April 14' }
    : { greet: 'Good morning, Alicia.', sub: 'Austin Downtown · Tuesday, April 14' };

  // 1) HOW AM I DOING
  const verdict = isBare ? {
    word: 'Room to grow',
    ring: 'var(--terra)', soft: 'var(--terra-soft)', ink: '#8c2f22',
    result: `Nothing's broken, your Google Search ads are steady and bringing in about ${kpis.leads.val} new leads a month. But your score sits in the bottom 14% of FreshNest, so there's a lot of room to grow whenever you're ready.`,
  } : {
    word: 'Doing great',
    ring: 'var(--terra)', soft: 'var(--sage-soft)', ink: '#2f5d3a',
    result: `You're in the top 18% of every FreshNest location, and it's paying off. ${kpis.leads.val} new leads this month, up ${kpis.leads.delta}% from last, and your listings and reviews are your strongest points.`,
  };

  const money = [
    { label: 'New leads this month', value: kpis.leads.val, delta: kpis.leads.delta, color: 'var(--terra)' },
    { label: 'You spent on marketing', value: isBare ? '$300' : '$544', sub: isBare ? 'Google Search only' : 'of your $800 budget', color: 'var(--marigold)' },
    { label: 'Revenue it brought in', value: `$${(kpis.rev.val / 1000).toFixed(1)}K`, delta: kpis.rev.delta, color: 'var(--sage)' },
  ];

  // 2) WHAT CHANGED
  const changed = isBare ? [
    { kind: 'down', text: <>Leads slipped a little, <strong>19 last month → 18 this month</strong>. Still just Google Search running.</> },
    { kind: 'down', text: <>Your overall score dipped <strong>2 points to 38</strong>, mostly from listing gaps and slow review replies.</> },
    { kind: 'flat', text: <>No new programs turned on since February, so not much has moved either way.</> },
  ] : [
    { kind: 'up', text: <>Leads are up <strong>18%</strong>, from <strong>120 last month to 142</strong> this month.</> },
    { kind: 'up', text: <>Your overall score climbed <strong>4 points to 87</strong>, your best month yet.</> },
    { kind: 'fix', text: <>We caught and fixed your Google Sunday hours automatically, no action needed.</> },
  ];

  // 3) WHAT SHOULD I DO (max 3)
  const actions = isBare ? [
    { title: 'Turn on the full marketing plan', why: 'Add the 5 programs you\u2019re missing · modeled +$20K/mo', cta: 'Review plan', tone: 'primary', onClick: () => nav('services') },
    { title: 'Fix your Google listing', why: 'Missing services, 4 photos, and wrong Sunday hours', cta: 'Fix it', onClick: () => nav('listings') },
    { title: 'Reply to 3 reviews', why: 'Your last reply was 47 days ago, we drafted them for you', cta: 'Review', onClick: () => nav('reviews') },
  ] : [
    { title: 'Add $200 to your Google ads this month', why: 'Catch the spring deep-clean rush · about 8 more leads', cta: 'Review', tone: 'primary', onClick: () => nav('budget') },
    { title: 'Approve 2 review replies', why: 'We drafted responses, just read and send', cta: 'Review', onClick: () => nav('reviews') },
    { title: 'Confirm the Google hours fix', why: 'Sunday close auto-corrected to 9 PM, confirm it', cta: 'Confirm', onClick: () => nav('listings') },
  ];

  // 4) APPROVALS + PAYMENT
  const approvals = isBare ? [
    { count: 3, what: 'Review replies drafted for you', why: 'Read and send, or tweak them first', cta: 'Open reviews', go: 'reviews' },
  ] : [
    { count: 2, what: 'Review replies drafted for you', why: 'Read and send, or tweak them first', cta: 'Open reviews', go: 'reviews' },
    { count: 1, what: '\u201CSpring Clean Event\u201D page', why: 'Waiting for your OK before it goes live', cta: 'Review page', go: 'listings' },
  ];
  const payment = {
    lead: 'Nothing to pay right now.',
    sub: 'Your $300 LOCALACT invoice auto-pays July 1 on your Visa ending 7781.',
  };

  // PROGRAM PARTICIPATION
  const participation = isBare ? {
    active: [{ name: 'Google Search ads', color: 'var(--ch-ppc)' }],
    available: ['Local Services Ads', 'Local SEO', 'Listings Management', 'Meta & Instagram', 'Content & AI'],
    note: 'You\u2019re running 1 of the 6 programs in the FreshNest plan. FreshNest\u2019s national brand ads run on top of this, funded by corporate.',
  } : {
    active: [
      { name: 'Google Search ads', color: 'var(--ch-ppc)' },
      { name: 'Local Services Ads', color: 'var(--ch-lsa)' },
      { name: 'Local SEO', color: 'var(--ch-seo)' },
      { name: 'Social ads', color: 'var(--ch-social)' },
      { name: 'Listings, 42 directories', color: 'var(--coral)' },
    ],
    available: null,
    note: 'You\u2019re on the full FreshNest plan. National brand ads run on top of this, funded by corporate, at no cost to you.',
  };

  const handled = isBare
    ? 'We\u2019re running your Google Search ads, keeping your listing synced across directories, and watching your budget every day. The basics are covered whether or not you add more.'
    : 'We\u2019re running your ads, keeping your listings accurate across 42 directories, drafting your review replies, and watching your budget every day. You don\u2019t have to touch any of it.';

  return (
    <div className="page active simple-page">
      <div className="page-header">
        <div>
          <div className="page-title">{head.greet}</div>
          <div className="page-sub">{head.sub}</div>
        </div>
        <div className="page-actions">
          <button className="btn btn-ghost btn-sm" onClick={() => setDensity('full')}>Switch to Pro view</button>
          <button className="btn btn-primary btn-sm" onClick={() => nav('results')}>See my results {Icon.arrow}</button>
        </div>
      </div>

      {/* 1 · How am I doing? */}
      <SimpleQ n="1" title="How am I doing?"/>
      <HowAmIDoing scores={scores} kpis={kpis} verdict={verdict} money={money}/>

      {/* 2 · What changed? */}
      <SimpleQ n="2" title="What changed since last month?"/>
      <WhatChanged items={changed}/>

      {/* 3 · What should I do? */}
      <SimpleQ n="3" title="What should I do?"/>
      <OwnerActions
        title={isBare ? 'Your top moves' : 'Your top moves this week'}
        sub={isBare ? 'The 3 highest-impact things for Plano Legacy' : 'The 3 things that matter most for Austin Downtown'}
        items={actions}
      />

      {/* 4 · Do I owe an approval or a payment? */}
      <SimpleQ n="4" title="Do I owe an approval or a payment?"/>
      <ApprovalsAndPayment approvals={approvals} payment={payment} nav={nav}/>

      {/* Program participation */}
      <SimpleQ n="•" title="What you're signed up for"/>
      <ProgramParticipation {...participation} nav={nav}/>

      {/* What LOCALACT handles automatically */}
      <HandledByLocalact text={handled}/>

      <ProViewFooter note="Want every chart, channel, budget control, and lead detail?"/>
    </div>
  );
}
window.SimpleLocationHome = SimpleLocationHome;

// ====================================================================
// SIMPLE RESULTS
// ====================================================================
function SimpleResults({ data }) {
  const { kpis, channels } = data;
  const isBare = data.variant === 'bare';

  const working = isBare
    ? `Google Search is your only channel and it's holding steady at about ${kpis.leads.val} leads a month. The fundamentals are sound, there's just only one engine running.`
    : `You pulled in ${kpis.leads.val} leads this month at $${kpis.cpl.val} each, a ${Math.abs(kpis.cpl.delta)}% better cost than last month. Local SEO and LSA are your most efficient channels, and overall you're returning ${kpis.roas.val}× on every dollar.`;

  const next = isBare
    ? `Your cost per lead is $${kpis.cpl.val}, about 2.9× the brand average, because everything rides on one channel. Adding LSA and Local SEO is the fastest way to bring that down.`
    : `Paid Search is running below its sweet spot. A small $200 increase is modeled to add ~8 leads at your current close rate, the single best move on the table right now.`;

  const verdict = (c) => {
    if (c.roas >= 8) return { t: 'Best value', cls: 'sage' };
    if (c.roas >= 4.5) return { t: 'Strong', cls: 'sky' };
    if (c.roas >= 3) return { t: 'Room to grow', cls: 'marigold' };
    return { t: 'Needs a look', cls: 'terra' };
  };

  const actions = isBare ? [
    { title: 'Add Local Services Ads', why: 'Pay-per-lead · modeled +12–18 leads at $15–22 each', cta: 'Review', tone: 'primary', onClick: () => goPage('services') },
    { title: 'Turn on Local SEO', why: 'You rank #7–14 for "house cleaning plano", peers rank top 3', cta: 'Review', onClick: () => goPage('services') },
  ] : [
    { title: 'Bump Paid Search by $200', why: 'Modeled +8 leads · ~$2,400 in revenue this month', cta: 'Review', tone: 'primary', onClick: () => goPage('budget') },
    { title: 'Keep an eye on Social', why: 'Still profitable at 3.8× but softening week-over-week', cta: 'See leads', onClick: () => goPage('leads') },
  ];

  return (
    <div className="page active simple-page">
      <div className="page-header">
        <div>
          <div className="page-title">Your results.</div>
          <div className="page-sub">A plain-language summary of how your marketing is doing.</div>
        </div>
        <div className="page-actions">
          <button className="btn btn-ghost btn-sm" onClick={() => setDensity('full')}>Pro view</button>
        </div>
      </div>

      {/* Headline numbers */}
      <div className="simple-stat-grid">
        <BigStat label="Leads this month" value={kpis.leads.val} delta={kpis.leads.delta} trend={kpis.leads.trend} color="var(--terra)"/>
        <BigStat label="Cost per lead" prefix="$" value={kpis.cpl.val} delta={kpis.cpl.delta} invert trend={kpis.cpl.trend} color="var(--sage)"/>
        <BigStat label="Revenue" value={`$${(kpis.rev.val/1000).toFixed(1)}K`} delta={kpis.rev.delta} trend={kpis.rev.trend} color="var(--marigold)"/>
      </div>

      {/* Plain-language read */}
      <LennySummaryCard working={working} next={next}/>

      {/* Channels at a glance, plain, no charts */}
      <div className="card card-pad simple-channels">
        <div className="card-header" style={{ marginBottom: 14 }}>
          <div>
            <div className="card-title">Your channels at a glance</div>
            <div className="card-sub">{isBare ? 'What\u2019s running today, and what could be' : 'Where your leads came from this month'}</div>
          </div>
        </div>
        <div className="simple-channel-list">
          {channels.map(c => {
            const v = verdict(c);
            return (
              <div key={c.key} className="simple-channel-row">
                <span className="simple-channel-dot" style={{ background: c.color }}/>
                <span className="simple-channel-name">{c.name}</span>
                <span className={`badge badge-${v.cls === 'sage' ? 'ok' : v.cls === 'terra' ? 'warn' : 'neutral'} simple-channel-verdict`}>{v.t}</span>
                <span className="simple-channel-leads"><strong>{c.leads}</strong> leads</span>
              </div>
            );
          })}
          {isBare && (
            <div className="simple-channel-empty" onClick={() => goPage('services')}>
              + 5 more channels available, turn them on to grow
            </div>
          )}
        </div>
      </div>

      {/* Top actions */}
      <OwnerActions
        title="What to do next"
        sub="The moves Lenny recommends right now"
        items={actions}
      />

      <ProViewFooter note="Want channel-by-channel detail, search terms, and budgets?"/>
    </div>
  );
}
window.SimpleResults = SimpleResults;
