// ════════════ MARKETING · growth command center ════════════
// Own secondary sidebar (like Money). Covers the full surface:
// campaigns, automations, social, ads, segments, templates, SEO &
// content, reputation/reviews, and revenue attribution. Pex drafts
// everything; you approve. Sends route through the Workspace layer.
const { Icon, Spark, Pex, Avatar, Card, Btn, Pill, Label, Num, Spark2, Toggle, Field, Select, TextArea, Check, Tabs, money } = window;

// ── Cross-view store · campaigns + segments live here so the list,
//    the builder (by id), templates ("Use"), and segment targeting all
//    read/write the SAME records. Resets on reload. ────────────────
window.PXMarketing = window.PXMarketing || (function () {
  const seg = (id, n, count, tone, rule, rules) => ({ id, n, count, tone, rule, rules });
  const store = window.makeStore({
    campaigns: [
      { id: 'c1', n: 'March sourdough class', st: 'scheduled', aud: 'Class subscribers · 142', segId: 'seg-class', when: 'Wed 9:00am', open: '—', rev: '—',
        ab: true, subjA: 'Our March class is open — 6 seats', subjB: 'Come bake with us · March sourdough class',
        headline: 'Our March class is open.', cta: 'Reserve a seat', track: true, sched: true,
        body: "Same oven, smaller group of six. You'll shape, score, and take home two loaves plus the starter. Saturday the 15th, 9am–noon." },
      { id: 'c2', n: 'Spring wholesale push', st: 'sending', aud: 'Cafés & restaurants · 38', segId: 'seg-wholesale', when: 'Now · 61% sent', open: '44%', rev: '$1,850',
        ab: false, subjA: 'Spring wholesale menu — order by Friday', subjB: 'New seasonal loaves for your café',
        headline: 'Spring menu, ready for your café.', cta: 'See the spring menu', track: true, sched: false,
        body: 'Rye & caraway is back, plus a new olive levain and a lighter spring baguette. Same delivery windows, same crumb you count on. Lock your standing order for April.' },
      { id: 'c3', n: 'Valentine’s pre-order', st: 'sent', aud: 'All customers · 412', segId: 'seg-news', when: 'Feb 6', open: '52%', rev: '$3,240',
        ab: false, subjA: 'Bake someone a Valentine', subjB: '',
        headline: 'Bake someone a Valentine.', cta: 'Pre-order now', track: true, sched: false,
        body: 'Heart-shaped country loaves and a chocolate-cherry rye, hand-scored and boxed with a ribbon. Pre-order by the 12th for pickup Valentine’s weekend.' },
      { id: 'c4', n: 'January newsletter', st: 'sent', aud: 'Newsletter · 388', segId: 'seg-news', when: 'Jan 4', open: '41%', rev: '$640',
        ab: false, subjA: 'What we’re baking in January', subjB: '',
        headline: 'A fresh year at the bench.', cta: 'Read the January note', track: true, sched: false,
        body: 'New winter grains, the return of the seeded rye, and a few class dates we just opened. Here’s everything coming out of the oven this month.' },
      { id: 'c5', n: 'Holiday gift boxes', st: 'sent', aud: 'All customers · 360', segId: 'seg-news', when: 'Dec 1', open: '58%', rev: '$5,180',
        ab: false, subjA: 'Holiday gift boxes are here', subjB: '',
        headline: 'Give warm bread this holiday.', cta: 'Send a gift box', track: true, sched: false,
        body: 'Curated gift boxes — a country loaf, house granola, cultured butter, and our winter jam — packed to ship or pick up. Order early; the previous gift-box receipt is attached.' },
    ],
    segments: [
      seg('seg-class', 'Class subscribers', 142, 'spark', 'Tag is "class-interest"', [{ field: 'tag', op: 'is', value: 'class-interest' }]),
      seg('seg-wholesale', 'Wholesale cafés', 38, 'sky', 'Company type is "café" · has paid invoice', [{ field: 'company-type', op: 'is', value: 'café' }, { field: 'invoice', op: 'is', value: 'paid' }]),
      seg('seg-lapsed', 'Lapsed customers', 64, 'rose', 'No order in 60+ days', [{ field: 'last-order', op: 'more than', value: '60 days' }]),
      seg('seg-hv', 'High-value (>$2k LTV)', 22, 'sage', 'Lifetime value over $2,000', [{ field: 'ltv', op: 'over', value: '$2,000' }]),
      seg('seg-news', 'Newsletter', 388, 'neutral', 'Opted in · any source', [{ field: 'opt-in', op: 'is', value: 'any source' }]),
    ],
  });
  return Object.assign(store, {
    campaigns: () => store.get().campaigns,
    segments: () => store.get().segments,
    campaignById: (id) => store.get().campaigns.find(c => c.id === id),
    segmentById: (id) => store.get().segments.find(s => s.id === id),
    addCampaign: (c) => store.set(s => ({ ...s, campaigns: [c, ...s.campaigns] })),
    updateCampaign: (id, patch) => store.set(s => ({ ...s, campaigns: s.campaigns.map(c => c.id === id ? { ...c, ...(typeof patch === 'function' ? patch(c) : patch) } : c) })),
    addSegment: (sg) => store.set(s => ({ ...s, segments: [sg, ...s.segments] })),
    updateSegment: (id, patch) => store.set(s => ({ ...s, segments: s.segments.map(x => x.id === id ? { ...x, ...patch } : x) })),
  });
})();

// spark spend helper — gate → debit → run effect (used by every ⚡ action)
function useSpend() {
  const { sparks, setSparks, openOverlay } = window.useApp();
  return React.useCallback((cost, effect) => {
    if (cost > sparks) { openOverlay('creditGate', { needed: cost, balance: sparks }); return false; }
    if (cost) setSparks(s => Math.max(0, s - cost));
    if (effect) effect();
    return true;
  }, [sparks, setSparks, openOverlay]);
}

const ST_TONE = { scheduled: 'amber', sending: 'spark', sent: 'sage', draft: 'neutral' };

window.SCREENS['marketing'] = function Marketing({ sub }) {
  const P = window.PX; const { go } = window.useApp();
  const seg = (sub || '').split('/');
  const active = seg[0] || 'overview';
  const nav = [
    { items: [{ k: 'overview', icon: 'megaphone', label: 'Overview' }] },
    { label: 'Reach', items: [
      { k: 'campaigns', icon: 'mail', label: 'Campaigns', badge: 2, tone: 'spark' },
      { k: 'automations', icon: 'refresh', label: 'Automations', badge: 4 },
      { k: 'social', icon: 'image', label: 'Social', badge: 3 },
      { k: 'ads', icon: 'trendUp', label: 'Ads' },
    ]},
    { label: 'Audience', items: [
      { k: 'segments', icon: 'users', label: 'Segments' },
      { k: 'templates', icon: 'layout', label: 'Templates' },
    ]},
    { label: 'Get found', items: [
      { k: 'seo', icon: 'search', label: 'SEO & content', badge: 3, tone: 'amber' },
      { k: 'reputation', icon: 'star', label: 'Reputation', badge: 1, tone: 'rose' },
    ]},
    { label: 'Measure', items: [
      { k: 'attribution', icon: 'barchart', label: 'Attribution' },
    ]},
  ];
  const onNav = (k) => go('marketing' + (k === 'overview' ? '' : '/' + k));
  return (
    <window.SubLayout title="Marketing" nav={nav} active={active} onNav={onNav}
      foot={<div style={{ background: P.sparkWash, border: `1px solid ${P.sparkTint}`, borderRadius: 10, padding: 11 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}><Pex size={18}/><span style={{ fontSize: 12, fontWeight: 600, color: P.ink }}>Pex is marketing</span></div>
        <div style={{ fontSize: 11, color: P.ink3, marginTop: 4 }}>3 things running · $14.8k attributed this quarter</div>
      </div>}>
      {active === 'overview' && <MktOverview/>}
      {active === 'campaigns' && (seg[1] ? <CampaignBuilder id={seg[1]}/> : <Campaigns/>)}
      {active === 'automations' && <Automations/>}
      {active === 'social' && <Social/>}
      {active === 'ads' && <Ads/>}
      {active === 'segments' && <Segments/>}
      {active === 'templates' && <Templates/>}
      {active === 'seo' && <SEOContent/>}
      {active === 'reputation' && <Reputation/>}
      {active === 'attribution' && <Attribution/>}
    </window.SubLayout>
  );
};

const MHead = ({ title, sub, children }) => {
  const P = window.PX;
  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', marginBottom: 18, gap: 12 }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 26, color: P.ink, letterSpacing: -0.4 }}>{title}</div>
        {sub && <div style={{ fontSize: 12.5, color: P.ink3, marginTop: 2 }}>{sub}</div>}
      </div>
      {children && <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexShrink: 0 }}>{children}</div>}
    </div>
  );
};

const EmptyRow = ({ children }) => {
  const P = window.PX;
  return <div style={{ padding: '28px 18px', textAlign: 'center', fontSize: 12.5, color: P.ink3 }}>{children}</div>;
};

// ── OVERVIEW · the growth command center ─────────────────────
function MktOverview() {
  const P = window.PX; const { go, toast, sparks } = window.useApp();
  const spend = useSpend();
  const [props, setProps] = React.useState([
    { id: 'p1', tag: 'Campaign', tone: 'spark', cost: 4, t: 'Launch the March class email', ctx: 'Past customers · send Wed 9am · previous class receipt attached.', cta: 'campaigns/new' },
    { id: 'p2', tag: 'Reputation', tone: 'rose', cost: 1, t: 'Reply to a new 4★ Google review', ctx: 'Daniel R. · "great bread, slow line." I drafted a warm response.', cta: 'reputation' },
    { id: 'p3', tag: 'SEO', tone: 'amber', cost: 6, t: 'Publish a post targeting "brooklyn sourdough"', ctx: 'You rank #3. A focused post could take #1 — ~410 searches/mo.', cta: 'seo' },
  ]);
  const approve = (p) => spend(p.cost, () => {
    window.startPexRun && window.startPexRun({ title: p.t, cost: p.cost, tone: p.tone });
    setProps(ps => ps.filter(x => x.id !== p.id));
    toast(`Approved — Pex is on it. ${p.cost} ⚡ spent.`, { tone: 'sage', icon: 'check' });
  });
  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <MHead title="Marketing" sub="Everything that finds, wins, and keeps customers — in one place.">
        <Btn kind="default" size="sm" icon="barchart" onClick={() => go('marketing/attribution')}>Attribution</Btn>
        <Btn kind="spark" size="sm" icon="plus" onClick={() => go('marketing/campaigns/new')}>New campaign</Btn>
      </MHead>

      {/* attribution + funnel hero */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 14, marginBottom: 14 }}>
        <Card pad={22} style={{ boxShadow: P.shMd }}>
          <Label>Revenue attributed to marketing · 90d</Label>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 20 }}>
            <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 46, letterSpacing: -1.5, lineHeight: 1, marginTop: 6, color: P.ink }}>$14,820</div>
            <div style={{ paddingBottom: 6 }}><span style={{ color: P.sage, fontWeight: 600, fontSize: 13 }}>+34%</span><span style={{ fontSize: 12, color: P.ink3 }}> vs prior</span></div>
            <svg width="160" height="64" viewBox="0 0 160 64" style={{ marginLeft: 'auto' }}><path d="M0,52 L26,46 L52,50 L78,34 L104,38 L130,20 L160,12" fill="none" stroke={P.spark} strokeWidth="2.5"/><path d="M0,52 L26,46 L52,50 L78,34 L104,38 L130,20 L160,12 L160,64 L0,64Z" fill={P.spark} opacity="0.1"/></svg>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 12, marginTop: 18, paddingTop: 16, borderTop: `1px solid ${P.line}` }}>
            {[['Email', '$6,240'], ['SEO / blog', '$4,180'], ['Social', '$2,900'], ['Ads', '$1,500']].map((c, i) => (
              <div key={i}><Label>{c[0]}</Label><Num size={18} style={{ marginTop: 3 }}>{c[1]}</Num></div>
            ))}
          </div>
        </Card>
        <Card pad={18}>
          <div style={{ fontSize: 14, fontWeight: 600, color: P.ink, marginBottom: 12 }}>Funnel · last 30 days</div>
          {[['Reached', 4820, 100, 'sky'], ['Engaged', 1640, 34, 'spark'], ['Leads', 312, 6.5, 'amber'], ['Customers', 64, 1.3, 'sage']].map((s, i) => (
            <div key={i} style={{ marginBottom: 11 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, color: P.ink2, marginBottom: 4 }}><span>{s[0]}</span><span style={{ fontFamily: P.mono }}>{s[1].toLocaleString()}</span></div>
              <div style={{ height: 8, background: P.sunk, borderRadius: 6, overflow: 'hidden' }}><div style={{ width: s[2] + '%', height: '100%', background: P[s[3]] }}/></div>
            </div>
          ))}
        </Card>
      </div>

      {/* what's running */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 14, marginBottom: 14 }}>
        {[['Campaigns live', '2', 'sending now', 'mail', 'campaigns'], ['Automations on', '4', '218 in flight', 'refresh', 'automations'], ['Social queued', '3', 'this week', 'image', 'social'], ['Avg rating', '4.8', '142 reviews', 'star', 'reputation']].map((c, i) => (
          <Card key={i} pad={16} hover onClick={() => go('marketing/' + c[4])} style={{ cursor: 'pointer' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}><Label>{c[0]}</Label><Icon name={c[3]} size={15} color={P.ink3}/></div>
            <Num size={24} style={{ marginTop: 6 }}>{c[1]}</Num><div style={{ fontSize: 11.5, color: P.ink3, marginTop: 3 }}>{c[2]}</div>
          </Card>
        ))}
      </div>

      {/* Pex marketing proposals */}
      <Card pad={0}>
        <div style={{ padding: '14px 18px', borderBottom: `1px solid ${P.line}`, display: 'flex', alignItems: 'center', gap: 9 }}>
          <Pex size={22}/><span style={{ fontSize: 14, fontWeight: 600, color: P.ink, flex: 1 }}>Pex has {props.length} marketing move{props.length === 1 ? '' : 's'} ready</span><span style={{ fontSize: 12, color: P.ink3 }}>{sparks} ⚡ available</span>
        </div>
        {props.length === 0 && <EmptyRow>All caught up — Pex will surface the next move as it finds one.</EmptyRow>}
        {props.map((p, i) => (
          <div key={p.id} style={{ padding: '14px 18px', display: 'flex', alignItems: 'flex-start', gap: 12, borderBottom: i < props.length - 1 ? `1px solid ${P.line}` : 'none' }}>
            <div style={{ width: 3, alignSelf: 'stretch', background: P[p.tone], borderRadius: 3, flexShrink: 0 }}/>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', gap: 6, marginBottom: 4 }}><Pill tone={p.tone} style={{ fontSize: 10 }}>{p.tag}</Pill></div>
              <div style={{ fontSize: 13.5, color: P.ink, fontWeight: 600 }}>{p.t}</div>
              <div style={{ fontSize: 12, color: P.ink3, marginTop: 2 }}>{p.ctx}</div>
            </div>
            <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
              <Btn kind="primary" size="sm" onClick={() => approve(p)}>Approve · {p.cost} ⚡</Btn>
              <span onClick={() => go('marketing/' + p.cta)} style={{ fontSize: 11.5, color: P.spark, cursor: 'pointer', fontWeight: 500 }}>Open</span>
            </div>
          </div>
        ))}
      </Card>
    </div>
  );
}

// ── CAMPAIGNS ────────────────────────────────────────────────
function Campaigns() {
  const P = window.PX; const { go } = window.useApp();
  const st = window.useStore(window.PXMarketing);
  const camps = st.campaigns;
  const [tab, setTab] = React.useState('all');
  const list = tab === 'all' ? camps : camps.filter(c => c.st === tab);
  const cnt = (k) => k === 'all' ? camps.length : camps.filter(c => c.st === k).length;
  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <MHead title="Campaigns" sub="One-off email blasts — Pex drafts, you approve, sends go out through Workspace.">
        <Btn kind="default" size="sm" icon="layout" onClick={() => go('marketing/templates')}>Templates</Btn>
        <Btn kind="spark" size="sm" icon="plus" onClick={() => go('marketing/campaigns/new')}>New campaign</Btn>
      </MHead>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 14, marginBottom: 16 }}>
        {[['Sent · 90d', '12'], ['Avg open rate', '48%'], ['Avg click rate', '11%'], ['Revenue · 90d', '$9,300']].map((c, i) => (
          <Card key={i} pad={14}><Label>{c[0]}</Label><Num size={22} style={{ marginTop: 5 }}>{c[1]}</Num></Card>
        ))}
      </div>
      <Tabs tabs={[{ k: 'all', label: 'All', count: cnt('all') }, { k: 'scheduled', label: 'Scheduled', count: cnt('scheduled') }, { k: 'sending', label: 'Sending', count: cnt('sending') }, { k: 'draft', label: 'Draft', count: cnt('draft') }, { k: 'sent', label: 'Sent', count: cnt('sent') }]} active={tab} onChange={setTab}/>
      <Card pad={0} style={{ marginTop: 4 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1.4fr 1fr 70px 90px 30px', gap: 12, padding: '12px 18px', borderBottom: `1px solid ${P.line}` }}>
          {['Campaign', 'Audience', 'When', 'Open', 'Revenue', ''].map((h, i) => <Label key={i} style={{ textAlign: i >= 3 && i <= 4 ? 'right' : 'left' }}>{h}</Label>)}
        </div>
        {list.length === 0 && <EmptyRow>No campaigns here yet. Start one with “New campaign”.</EmptyRow>}
        {list.map((c, i) => (
          <div key={c.id} onClick={() => go('marketing/campaigns/' + c.id)} style={{ display: 'grid', gridTemplateColumns: '2fr 1.4fr 1fr 70px 90px 30px', gap: 12, padding: '13px 18px', borderBottom: i < list.length - 1 ? `1px solid ${P.line}` : 'none', alignItems: 'center', cursor: 'pointer' }}
            onMouseEnter={e => e.currentTarget.style.background = P.hover} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}><span style={{ fontSize: 13.5, color: P.ink, fontWeight: 500 }}>{c.n}</span><Pill tone={ST_TONE[c.st]} style={{ fontSize: 10 }}>{c.st}</Pill></div>
            <span style={{ fontSize: 12.5, color: P.ink3 }}>{c.aud}</span>
            <span style={{ fontSize: 12.5, color: c.st === 'scheduled' ? P.amber : P.ink3 }}>{c.when}</span>
            <span style={{ fontSize: 12.5, color: P.ink2, textAlign: 'right', fontFamily: P.mono }}>{c.open}</span>
            <span style={{ fontSize: 12.5, color: c.rev === '—' ? P.ink3 : P.sage, textAlign: 'right', fontFamily: P.mono, fontWeight: 500 }}>{c.rev}</span>
            <Icon name="chevR" size={15} color={P.ink4}/>
          </div>
        ))}
      </Card>
    </div>
  );
}

function CampaignBuilder({ id }) {
  const P = window.PX; const { go, toast } = window.useApp();
  const st = window.useStore(window.PXMarketing);
  const isNew = id === 'new';
  const existing = isNew ? null : window.PXMarketing.campaignById(id);
  const segments = st.segments;
  const blank = { n: 'New campaign', st: 'draft', segId: segments[0] ? segments[0].id : '', aud: '', when: 'Not scheduled', open: '—', rev: '—',
    ab: true, subjA: '', subjB: '', headline: 'A quick note from Honest Loaves', cta: 'Learn more', track: true, sched: true,
    body: 'Write your message here — Pex can draft it from your brand and past sends.' };
  const [draft, setDraft] = React.useState(() => existing ? { ...existing } : blank);
  const [changing, setChanging] = React.useState(false);
  const [testing, setTesting] = React.useState(false);

  // live auto-save: keep local edits AND (for saved campaigns) the store in sync
  const setField = (k, v) => {
    setDraft(d => ({ ...d, [k]: v }));
    if (!isNew) window.PXMarketing.updateCampaign(id, { [k]: v });
  };
  const changeSeg = (segId) => {
    const sg = segments.find(s => s.id === segId);
    const aud = sg ? `${sg.n} · ${sg.count}` : draft.aud;
    setDraft(d => ({ ...d, segId, aud }));
    if (!isNew) window.PXMarketing.updateCampaign(id, { segId, aud });
    setChanging(false);
  };

  const seg = segments.find(s => s.id === draft.segId) || segments[0];
  const inputStyle = { width: '100%', border: `1px solid ${P.line}`, borderRadius: 8, padding: '8px 10px', fontSize: 12.5, color: P.ink, fontFamily: P.sans, background: P.card, outline: 'none', boxSizing: 'border-box' };

  const sendTest = () => {
    setTesting(true);
    setTimeout(() => { setTesting(false); toast('Test email sent to you · amara@honestloaves.com.', { tone: 'sage', icon: 'mail' }); }, 800);
  };
  const schedule = () => {
    if (!seg) { toast('Pick an audience first.', { tone: 'rose', icon: 'alert' }); setChanging(true); return; }
    if (!draft.subjA.trim()) { toast('Add a subject line before scheduling.', { tone: 'rose', icon: 'alert' }); return; }
    const when = draft.when && draft.when !== 'Not scheduled' ? draft.when : 'Wed 9:00am';
    if (isNew) {
      window.PXMarketing.addCampaign({ ...draft, id: window.pxid('c'), st: 'scheduled', aud: `${seg.n} · ${seg.count}`, when, open: '—', rev: '—' });
    } else {
      window.PXMarketing.updateCampaign(id, { st: 'scheduled', when });
    }
    toast(`Campaign scheduled for ${when} · ${seg.count} recipients.`, { tone: 'sage', icon: 'check' });
    go('marketing/campaigns');
  };

  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18 }}>
        <Btn kind="ghost" size="sm" icon="chevL" onClick={() => go('marketing/campaigns')}>Campaigns</Btn>
        <div style={{ flex: 1 }}><div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 24, color: P.ink }}>{draft.n || 'Untitled campaign'}</div><div style={{ fontSize: 11.5, color: P.ink3 }}>Pex drafted this from your brand &amp; past sends</div></div>
        {!isNew && <Pill tone={ST_TONE[draft.st] || 'neutral'} style={{ fontSize: 10 }}>{draft.st}</Pill>}
        <Pill tone="sage" dot>Auto-saved</Pill>
        <Btn kind="default" size="sm" loading={testing} onClick={sendTest}>Send test</Btn>
        <Btn kind="spark" size="sm" icon="send" onClick={schedule}>Schedule</Btn>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 20, alignItems: 'start' }}>
        {/* email preview — driven by the draft */}
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <div style={{ width: '100%', maxWidth: 560, background: '#fff', borderRadius: 8, boxShadow: P.shLg, overflow: 'hidden', border: `1px solid ${P.line}` }}>
            <div style={{ padding: '12px 20px', borderBottom: '1px solid rgba(0,0,0,0.06)', fontSize: 11, color: '#8C6A3A' }}>From <b>Honest Loaves</b> · amara@honestloaves.com</div>
            <div style={{ padding: '32px 28px', background: '#F2E2C4', textAlign: 'center' }}>
              <div style={{ width: 44, height: 44, margin: '0 auto 14px', background: '#3A2A1C', borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: P.serif, fontStyle: 'italic', color: '#F5D8A8', fontSize: 22 }}>hl</div>
              <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 30, color: '#3A2A1C', letterSpacing: -0.6, lineHeight: 1.05 }}>{draft.headline || 'Your headline'}</div>
              <div style={{ fontSize: 13.5, color: '#6B563C', lineHeight: 1.6, marginTop: 14, whiteSpace: 'pre-wrap' }}>{draft.body || 'Your message goes here.'}</div>
              <div style={{ marginTop: 18, display: 'inline-block', padding: '11px 22px', background: '#3A2A1C', color: '#F5D8A8', fontSize: 13, fontWeight: 600, borderRadius: 3 }}>{draft.cta || 'Button'}</div>
            </div>
            <div style={{ padding: '14px 20px', fontSize: 10.5, color: '#A08A66', textAlign: 'center' }}>Honest Loaves · 241 Metropolitan Ave, Brooklyn · Unsubscribe</div>
          </div>
        </div>
        {/* config */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Card pad={16}>
            <Label style={{ marginBottom: 8 }}>Campaign name</Label>
            <input value={draft.n} onChange={e => setField('n', e.target.value)} style={inputStyle}/>
          </Card>
          <Card pad={16}>
            <Label style={{ marginBottom: 8 }}>Content</Label>
            <input value={draft.headline} onChange={e => setField('headline', e.target.value)} placeholder="Headline" style={{ ...inputStyle, marginBottom: 8 }}/>
            <textarea value={draft.body} onChange={e => setField('body', e.target.value)} rows={5} placeholder="Body" style={{ ...inputStyle, resize: 'vertical', lineHeight: 1.5, marginBottom: 8 }}/>
            <input value={draft.cta} onChange={e => setField('cta', e.target.value)} placeholder="Button label" style={inputStyle}/>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 8, fontSize: 11, color: P.sparkDim }}><Spark size={10}/>Edit freely — the preview updates live.</div>
          </Card>
          <Card pad={16}>
            <Label style={{ marginBottom: 8 }}>Audience</Label>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '9px 11px', background: P.sunk, borderRadius: 9, border: `1px solid ${P.line}` }}>
              <Icon name="users" size={15} color={P.spark}/><span style={{ flex: 1, fontSize: 12.5, color: P.ink }}>{seg ? seg.n : 'No audience'}</span><span style={{ fontSize: 12, color: P.ink3, fontFamily: P.mono }}>{seg ? seg.count : 0}</span>
            </div>
            {changing
              ? <div style={{ marginTop: 8 }}><Select value={draft.segId} onChange={changeSeg} options={segments.map(s => ({ v: s.id, label: `${s.n} · ${s.count}` }))}/></div>
              : <div onClick={() => setChanging(true)} style={{ fontSize: 11.5, color: P.spark, marginTop: 8, cursor: 'pointer' }}>Change segment →</div>}
          </Card>
          <Card pad={16}>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 9 }}><Label>Subject line</Label><div style={{ flex: 1 }}/><span style={{ fontSize: 11, color: P.ink3, marginRight: 6 }}>A/B test</span><Toggle on={draft.ab} size="sm" onClick={() => setField('ab', !draft.ab)}/></div>
            <input value={draft.subjA} onChange={e => setField('subjA', e.target.value)} placeholder="Subject line" style={{ ...inputStyle, marginBottom: draft.ab ? 8 : 0 }}/>
            {draft.ab && <input value={draft.subjB} onChange={e => setField('subjB', e.target.value)} placeholder="Variant B" style={inputStyle}/>}
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 8, fontSize: 11, color: P.sparkDim }}><Spark size={10}/>Pex picked variant A — predicted +6% open</div>
          </Card>
          <Card pad={16}>
            <Label style={{ marginBottom: 10 }}>Delivery</Label>
            {[['sched', 'Schedule · Wed 9:00am'], ['track', 'Track opens & clicks']].map((o, i) => (
              <div key={o[0]} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 0', borderBottom: i < 1 ? `1px solid ${P.line}` : 'none' }}>
                <span style={{ flex: 1, fontSize: 12.5, color: P.ink }}>{o[1]}</span><Toggle on={draft[o[0]]} size="sm" onClick={() => setField(o[0], !draft[o[0]])}/>
              </div>
            ))}
            <div style={{ fontSize: 11, color: P.ink3, marginTop: 8, lineHeight: 1.5 }}>Small sends go through your Workspace inbox to protect deliverability; large sends use SendGrid.</div>
          </Card>
        </div>
      </div>
    </div>
  );
}

// ── AUTOMATIONS · visual drip sequences ──────────────────────
const NODE_META = {
  trigger: { tone: 'spark', icon: 'zap', label: 'Trigger' },
  wait: { tone: 'neutral', icon: 'clock', label: 'Wait' },
  send: { tone: 'sky', icon: 'mail', label: 'Send' },
  branch: { tone: 'amber', icon: 'sliders', label: 'Branch' },
  tag: { tone: 'sage', icon: 'tag', label: 'Tag' },
  exit: { tone: 'sage', icon: 'logout', label: 'Exit' },
};
const NODE_KINDS = ['trigger', 'wait', 'send', 'branch', 'tag', 'exit'];
const mktNid = () => window.pxid('node');
const mkNodes = (arr) => arr.map(([kind, label]) => ({ id: mktNid(), kind, label }));

const SEED_FLOWS = [
  { id: 'fl1', n: 'New lead welcome', trig: 'Form submitted', on: true, inflight: 38,
    nodes: mkNodes([['trigger', 'Trigger: form submission'], ['wait', 'Wait 5 min'], ['send', 'Send: warm welcome'], ['wait', 'Wait 2 days'], ['branch', 'If not opened → resend'], ['tag', 'Add tag: nurtured']]) },
  { id: 'fl2', n: 'Class waitlist nurture', trig: 'Tag: class-interest', on: true, inflight: 142,
    nodes: mkNodes([['trigger', 'Trigger: tag added · class-interest'], ['send', 'Send: class waitlist intro'], ['wait', 'Wait 3 days'], ['send', 'Send: seats are filling up'], ['branch', 'If clicked → notify Amara'], ['exit', 'Exit when: books a seat']]) },
  { id: 'fl3', n: 'Win-back · 60 days quiet', trig: 'No order in 60d', on: false, inflight: 26,
    nodes: mkNodes([['trigger', 'Trigger: no order in 60 days'], ['send', 'Send: we miss you'], ['wait', 'Wait 4 days'], ['branch', 'If not opened → add 10% off'], ['send', 'Send: one-time offer'], ['exit', 'Exit when: places an order']]) },
  { id: 'fl4', n: 'Post-purchase thank you', trig: 'Invoice paid', on: true, inflight: 12,
    nodes: mkNodes([['trigger', 'Trigger: invoice paid'], ['wait', 'Wait 1 hour'], ['send', 'Send: thank you + care card'], ['wait', 'Wait 5 days'], ['branch', 'If 5★ likely → ask for a review'], ['tag', 'Add tag: repeat-buyer']]) },
];

function Automations() {
  const P = window.PX; const { toast } = window.useApp();
  const [flows, setFlows] = React.useState(SEED_FLOWS);
  const [sel, setSel] = React.useState(0);
  const [editing, setEditing] = React.useState(false);
  const [newOpen, setNewOpen] = React.useState(false);
  const f = flows[sel] || flows[0];

  const patchFlow = (patch) => setFlows(fs => fs.map((fl, i) => i === sel ? { ...fl, ...patch } : fl));
  const setNodes = (fn) => patchFlow({ nodes: fn(f.nodes) });
  const toggleOn = (i) => setFlows(fs => fs.map((fl, j) => j === i ? { ...fl, on: !fl.on } : fl));
  const editNode = (nodeId, patch) => setNodes(ns => ns.map(n => n.id === nodeId ? { ...n, ...patch } : n));
  const removeNode = (nodeId) => setNodes(ns => ns.filter(n => n.id !== nodeId));
  const move = (idx, dir) => setNodes(ns => { const j = idx + dir; if (j < 0 || j >= ns.length) return ns; const c = ns.slice(); const t = c[idx]; c[idx] = c[j]; c[j] = t; return c; });
  const addNode = () => setNodes(ns => [...ns, { id: mktNid(), kind: 'send', label: 'Send: new message' }]);
  const createFlow = (name, trig) => {
    const fl = { id: window.pxid('fl'), n: name, trig, on: false, inflight: 0,
      nodes: mkNodes([['trigger', 'Trigger: ' + trig], ['wait', 'Wait 1 day'], ['send', 'Send: first touch'], ['exit', 'Exit when: converts']]) };
    setFlows(fs => [...fs, fl]);
    setSel(flows.length);
    setEditing(true);
    setNewOpen(false);
    toast(`Created “${name}”. Add your steps.`, { tone: 'sage', icon: 'check' });
  };

  const nm = (kind) => NODE_META[kind] || NODE_META.send;
  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <MHead title="Automations" sub="Sequences that run themselves — triggered by what people do.">
        <Btn kind="spark" size="sm" icon="plus" onClick={() => setNewOpen(true)}>New automation</Btn>
      </MHead>
      <div style={{ display: 'grid', gridTemplateColumns: '300px 1fr', gap: 18 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {flows.map((fl, i) => {
            const on = sel === i;
            return (
              <Card key={fl.id} pad={14} onClick={() => { setSel(i); setEditing(false); }} hover style={{ cursor: 'pointer', border: `1.5px solid ${on ? P.spark : P.line}`, background: on ? P.sparkWash : P.card }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                  <span style={{ width: 8, height: 8, borderRadius: 8, background: fl.on ? P.sage : P.ink4 }}/>
                  <span style={{ flex: 1, fontSize: 13.5, fontWeight: 600, color: P.ink }}>{fl.n}</span>
                  <span onClick={e => { e.stopPropagation(); toggleOn(i); }}><Toggle on={fl.on} size="sm" onClick={() => {}}/></span>
                </div>
                <div style={{ fontSize: 11.5, color: P.ink3 }}>Trigger · {fl.trig}</div>
                <div style={{ fontSize: 11.5, color: P.ink3, marginTop: 2 }}>{fl.inflight} contacts in flight · {fl.nodes.length} steps</div>
              </Card>
            );
          })}
        </div>
        {/* flow canvas */}
        <Card pad={24} style={{ background: P.sunk }}>
          <div style={{ display: 'flex', alignItems: 'center', marginBottom: 18, gap: 8 }}>
            <span style={{ fontSize: 14, fontWeight: 600, color: P.ink, flex: 1 }}>{f.n}</span>
            <span onClick={() => toggleOn(sel)}><Toggle on={f.on} size="sm" onClick={() => {}}/></span>
            <Btn kind={editing ? 'primary' : 'default'} size="sm" icon="sparkles" onClick={() => { setEditing(v => !v); if (!editing) toast('Editor open — add, reorder, and reword steps.', { icon: 'sparkles' }); }}>{editing ? 'Done' : 'Edit with Pex'}</Btn>
          </div>
          <div style={{ maxWidth: 460, margin: '0 auto' }}>
            {f.nodes.map((n, i) => (
              <React.Fragment key={n.id}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', background: P.card, border: `1px solid ${P.line}`, borderRadius: 10, boxShadow: P.shSm }}>
                  <div style={{ width: 30, height: 30, borderRadius: 8, background: P[nm(n.kind).tone + 'Tint'] || P.sunk, color: P[nm(n.kind).tone] || P.ink2, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <Icon name={nm(n.kind).icon} size={15}/>
                  </div>
                  {editing ? (
                    <>
                      <select value={n.kind} onChange={e => editNode(n.id, { kind: e.target.value })} style={{ border: `1px solid ${P.line}`, borderRadius: 7, padding: '5px 6px', fontSize: 11.5, color: P.ink2, background: P.card, outline: 'none', flexShrink: 0 }}>
                        {NODE_KINDS.map(k => <option key={k} value={k}>{NODE_META[k].label}</option>)}
                      </select>
                      <input value={n.label} onChange={e => editNode(n.id, { label: e.target.value })} style={{ flex: 1, border: `1px solid ${P.line}`, borderRadius: 7, padding: '6px 8px', fontSize: 12.5, color: P.ink, fontFamily: P.sans, background: P.card, outline: 'none', minWidth: 0 }}/>
                      <Icon name="chevUp" size={15} color={i === 0 ? P.ink4 : P.ink3} style={{ cursor: i === 0 ? 'default' : 'pointer' }} onClick={() => move(i, -1)}/>
                      <Icon name="chevD" size={15} color={i === f.nodes.length - 1 ? P.ink4 : P.ink3} style={{ cursor: i === f.nodes.length - 1 ? 'default' : 'pointer' }} onClick={() => move(i, 1)}/>
                      <Icon name="x" size={15} color={P.ink3} style={{ cursor: 'pointer' }} onClick={() => removeNode(n.id)}/>
                    </>
                  ) : (
                    <span style={{ fontSize: 13, color: P.ink }}>{n.label}</span>
                  )}
                </div>
                {i < f.nodes.length - 1 && <div style={{ width: 2, height: 18, background: P.lineStrong, margin: '0 auto' }}/>}
              </React.Fragment>
            ))}
            {editing && (
              <div onClick={addNode} style={{ marginTop: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: '10px', border: `1.5px dashed ${P.lineStrong}`, borderRadius: 10, color: P.spark, cursor: 'pointer', fontSize: 12.5, fontWeight: 500 }}>
                <Icon name="plus" size={14}/>Add step
              </div>
            )}
          </div>
        </Card>
      </div>
      {newOpen && <NewAutomationModal onClose={() => setNewOpen(false)} onCreate={createFlow}/>}
    </div>
  );
}

function NewAutomationModal({ onClose, onCreate }) {
  const [name, setName] = React.useState('');
  const [trig, setTrig] = React.useState('Form submitted');
  const triggers = ['Form submitted', 'Tag added', 'Invoice paid', 'No order in 60d', 'Joined newsletter', 'Booked a class'];
  const canSave = name.trim().length > 0;
  return (
    <window.Modal title="New automation" sub="Name it and pick the trigger — Pex scaffolds the steps." w={480} onClose={onClose}
      foot={<><Btn kind="ghost" onClick={onClose}>Cancel</Btn><Btn kind="primary" disabled={!canSave} onClick={() => onCreate(name.trim(), trig)}>Create sequence</Btn></>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field label="Automation name" value={name} onChange={setName} placeholder="e.g. Class waitlist nurture" icon="refresh"/>
        <Select label="Trigger" value={trig} onChange={setTrig} options={triggers}/>
      </div>
    </window.Modal>
  );
}

// ── SOCIAL ───────────────────────────────────────────────────
const SOCIAL_BG = { Instagram: '#8C4A2A', Facebook: '#3A2A1C' };
function Social() {
  const P = window.PX; const { toast } = window.useApp();
  const spend = useSpend();
  const [posts, setPosts] = React.useState([
    { id: 's1', plat: 'Instagram', tone: 'rose', when: 'Today 11:00', cap: 'First pull of the morning 🥖 country bâtards, still warm.', st: 'scheduled', bg: '#D9A84C' },
    { id: 's2', plat: 'Instagram', tone: 'rose', when: 'Wed 9:00', cap: 'March class is open — 6 seats, link in bio.', st: 'pex', bg: '#8C4A2A' },
    { id: 's3', plat: 'Facebook', tone: 'sky', when: 'Thu 8:00', cap: 'Wholesale partners: spring menu is live.', st: 'pex', bg: '#3A2A1C' },
    { id: 's4', plat: 'Instagram', tone: 'rose', when: 'Mar 10', cap: 'Behind the Saturday line.', st: 'posted', bg: '#C99944', eng: '1.2k' },
    { id: 's5', plat: 'Facebook', tone: 'sky', when: 'Mar 8', cap: 'New rye & caraway, back by demand.', st: 'posted', bg: '#7A5A3A', eng: '380' },
  ]);
  const [calOpen, setCalOpen] = React.useState(false);
  const [newOpen, setNewOpen] = React.useState(false);
  const [edit, setEdit] = React.useState(null);
  const stTone = { scheduled: 'amber', pex: 'spark', posted: 'sage' };
  const approve = (p) => { setPosts(ps => ps.map(x => x.id === p.id ? { ...x, st: 'scheduled' } : x)); toast(`Approved — ${p.plat} post scheduled for ${p.when}.`, { tone: 'sage', icon: 'check' }); };
  const createPost = ({ plat, cap, when }) => spend(2, () => {
    setPosts(ps => [{ id: window.pxid('s'), plat, tone: plat === 'Facebook' ? 'sky' : 'rose', when: when || 'This week', cap, st: 'scheduled', bg: SOCIAL_BG[plat] || '#8C4A2A' }, ...ps]);
    toast('Post polished by Pex and scheduled.', { tone: 'sage', icon: 'check' });
    setNewOpen(false);
  });
  const savePost = (p) => { setPosts(ps => ps.map(x => x.id === p.id ? p : x)); toast('Post updated.', { tone: 'sage', icon: 'check' }); setEdit(null); };
  const delPost = (pid) => { setPosts(ps => ps.filter(x => x.id !== pid)); toast('Post removed.'); setEdit(null); };
  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <MHead title="Social" sub="Posts across Instagram & Facebook — Pex writes them in your voice.">
        <Btn kind="default" size="sm" icon="calendar" onClick={() => setCalOpen(true)}>Calendar</Btn>
        <Btn kind="spark" size="sm" icon="plus" onClick={() => setNewOpen(true)}>New post · 2 ⚡</Btn>
      </MHead>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 14, marginBottom: 16 }}>
        {[['Followers', '4,820', '+212'], ['Reach · 30d', '38k', '+18%'], ['Engagement', '6.4%', '+1.1pt'], ['Queued', String(posts.filter(p => p.st !== 'posted').length), 'this week']].map((c, i) => (
          <Card key={i} pad={14}><Label>{c[0]}</Label><Num size={22} style={{ marginTop: 5 }}>{c[1]}</Num><div style={{ fontSize: 11, color: P.sage, marginTop: 3 }}>{c[2]}</div></Card>
        ))}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14 }}>
        {posts.map((p) => (
          <Card key={p.id} pad={0} hover onClick={() => setEdit(p)} style={{ cursor: 'pointer' }}>
            <div style={{ height: 150, background: p.bg, position: 'relative' }}>
              <span style={{ position: 'absolute', top: 10, left: 10 }}><Pill tone={p.tone}>{p.plat}</Pill></span>
              <span style={{ position: 'absolute', top: 10, right: 10 }}><Pill tone={stTone[p.st]} style={{ background: 'rgba(255,255,255,0.9)' }}>{p.st === 'pex' ? '✦ Pex draft' : p.st}</Pill></span>
            </div>
            <div style={{ padding: 14 }}>
              <div style={{ fontSize: 12.5, color: P.ink, lineHeight: 1.45 }}>{p.cap}</div>
              <div style={{ display: 'flex', alignItems: 'center', marginTop: 10 }}><span style={{ fontSize: 11, color: P.ink3, flex: 1 }}>{p.when}</span>{p.eng && <span style={{ fontSize: 11, color: P.sage }}>♥ {p.eng}</span>}{p.st === 'pex' && <span onClick={e => { e.stopPropagation(); approve(p); }}><Btn kind="spark" size="sm">Approve</Btn></span>}</div>
            </div>
          </Card>
        ))}
      </div>
      {calOpen && <SocialCalendar posts={posts} onClose={() => setCalOpen(false)}/>}
      {newOpen && <NewPostModal onClose={() => setNewOpen(false)} onCreate={createPost}/>}
      {edit && <EditPostModal post={edit} onClose={() => setEdit(null)} onSave={savePost} onDelete={delPost} onApprove={approve}/>}
    </div>
  );
}

function SocialCalendar({ posts, onClose }) {
  const P = window.PX;
  const stTone = { scheduled: 'amber', pex: 'spark', posted: 'sage' };
  return (
    <window.Modal title="Content calendar" sub="Everything queued and posted, in order." w={520} onClose={onClose}
      foot={<Btn kind="primary" onClick={onClose}>Done</Btn>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {posts.map(p => (
          <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', border: `1px solid ${P.line}`, borderRadius: 10 }}>
            <div style={{ width: 40, height: 40, borderRadius: 8, background: p.bg, flexShrink: 0 }}/>
            <div style={{ flex: 1 }}><div style={{ fontSize: 12.5, color: P.ink }}>{p.cap}</div><div style={{ fontSize: 11, color: P.ink3, marginTop: 2 }}>{p.plat} · {p.when}</div></div>
            <Pill tone={stTone[p.st]} style={{ fontSize: 10 }}>{p.st === 'pex' ? 'Pex draft' : p.st}</Pill>
          </div>
        ))}
      </div>
    </window.Modal>
  );
}

function NewPostModal({ onClose, onCreate }) {
  const [plat, setPlat] = React.useState('Instagram');
  const [cap, setCap] = React.useState('');
  const [when, setWhen] = React.useState('');
  const canSave = cap.trim().length > 0;
  return (
    <window.Modal title="New social post" sub="Pex polishes it in your voice · 2 ⚡" w={500} onClose={onClose}
      foot={<><Btn kind="ghost" onClick={onClose}>Cancel</Btn><Btn kind="spark" icon="sparkles" disabled={!canSave} onClick={() => onCreate({ plat, cap: cap.trim(), when: when.trim() })}>Schedule · 2 ⚡</Btn></>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Select label="Platform" value={plat} onChange={setPlat} options={['Instagram', 'Facebook']}/>
        <TextArea label="Caption" value={cap} onChange={setCap} rows={4} placeholder="What's coming out of the oven?"/>
        <Field label="When" value={when} onChange={setWhen} placeholder="e.g. Fri 9:00 or Mar 20" icon="calendar"/>
      </div>
    </window.Modal>
  );
}

function EditPostModal({ post, onClose, onSave, onDelete, onApprove }) {
  const [cap, setCap] = React.useState(post.cap);
  const [when, setWhen] = React.useState(post.when);
  return (
    <window.Modal title="Edit post" sub={`${post.plat} · ${post.st === 'pex' ? 'Pex draft' : post.st}`} w={500} onClose={onClose}
      foot={<>
        <Btn kind="danger" onClick={() => onDelete(post.id)}>Delete</Btn>
        <div style={{ flex: 1 }}/>
        {post.st === 'pex' && <Btn kind="default" onClick={() => { onApprove(post); onClose(); }}>Approve</Btn>}
        <Btn kind="primary" onClick={() => onSave({ ...post, cap, when })}>Save</Btn>
      </>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <TextArea label="Caption" value={cap} onChange={setCap} rows={4}/>
        <Field label="When" value={when} onChange={setWhen} icon="calendar"/>
      </div>
    </window.Modal>
  );
}

// ── ADS (managed) ────────────────────────────────────────────
function Ads() {
  const P = window.PX; const { toast } = window.useApp();
  const [camps, setCamps] = React.useState([
    { id: 'a1', n: 'Google · "brooklyn bakery"', plat: 'Search', spend: 420, roas: '5.2×', rev: 2184, on: true, budget: 20 },
    { id: 'a2', n: 'Instagram · class promo', plat: 'Social', spend: 280, roas: '3.8×', rev: 1064, on: true, budget: 15 },
    { id: 'a3', n: 'Google · wholesale leads', plat: 'Search', spend: 180, roas: '2.1×', rev: 378, on: false, budget: 10 },
  ]);
  const [newOpen, setNewOpen] = React.useState(false);
  const [edit, setEdit] = React.useState(null);
  const toggle = (id) => setCamps(cs => cs.map(c => c.id === id ? { ...c, on: !c.on } : c));
  const createCamp = ({ n, plat, budget }) => {
    setCamps(cs => [{ id: window.pxid('a'), n, plat, spend: 0, roas: '—', rev: 0, on: true, budget: Number(budget) || 10 }, ...cs]);
    toast(`Launched “${n}” — Pex will optimize and QA daily.`, { tone: 'sage', icon: 'check' });
    setNewOpen(false);
  };
  const saveCamp = (c) => { setCamps(cs => cs.map(x => x.id === c.id ? c : x)); toast('Ad campaign updated.', { tone: 'sage', icon: 'check' }); setEdit(null); };
  const delCamp = (id) => { setCamps(cs => cs.filter(x => x.id !== id)); toast('Ad campaign removed.'); setEdit(null); };
  const totSpend = camps.reduce((s, c) => s + c.spend, 0);
  const totRev = camps.reduce((s, c) => s + c.rev, 0);
  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <MHead title="Ads" sub="Paid campaigns, managed by Pex with human QA · 15% of ad spend.">
        <Btn kind="spark" size="sm" icon="plus" onClick={() => setNewOpen(true)}>New campaign</Btn>
      </MHead>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 14, marginBottom: 16 }}>
        {[['Ad spend · MTD', money(totSpend), 'ink'], ['Revenue', money(totRev), 'sage'], ['Blended ROAS', (totSpend ? (totRev / totSpend).toFixed(1) : '0') + '×', 'sage'], ['Mgmt fee', money(Math.round(totSpend * 0.15)), 'ink']].map((c, i) => (
          <Card key={i} pad={14}><Label>{c[0]}</Label><Num size={22} style={{ marginTop: 5 }} color={c[2] === 'sage' ? P.sage : P.ink}>{c[1]}</Num></Card>
        ))}
      </div>
      <Card pad={0}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 100px 80px 100px 60px', gap: 12, padding: '12px 18px', borderBottom: `1px solid ${P.line}` }}>
          {['Campaign', 'Platform', 'Spend', 'ROAS', 'Revenue', 'On'].map((h, i) => <Label key={i} style={{ textAlign: i >= 2 && i <= 4 ? 'right' : 'left' }}>{h}</Label>)}
        </div>
        {camps.map((c, i) => (
          <div key={c.id} onClick={() => setEdit(c)} style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 100px 80px 100px 60px', gap: 12, padding: '13px 18px', borderBottom: i < camps.length - 1 ? `1px solid ${P.line}` : 'none', alignItems: 'center', cursor: 'pointer' }}
            onMouseEnter={e => e.currentTarget.style.background = P.hover} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
            <span style={{ fontSize: 13.5, color: P.ink, fontWeight: 500 }}>{c.n}</span>
            <span><Pill tone={c.plat === 'Search' ? 'sky' : 'rose'} style={{ fontSize: 10 }}>{c.plat}</Pill></span>
            <span style={{ fontFamily: P.mono, fontSize: 12.5, color: P.ink, textAlign: 'right' }}>{money(c.spend)}</span>
            <span style={{ fontFamily: P.mono, fontSize: 12.5, color: P.sage, textAlign: 'right', fontWeight: 600 }}>{c.roas}</span>
            <span style={{ fontFamily: P.mono, fontSize: 12.5, color: P.ink, textAlign: 'right' }}>{money(c.rev)}</span>
            <span style={{ display: 'flex', justifyContent: 'flex-end' }} onClick={e => { e.stopPropagation(); toggle(c.id); }}><Toggle on={c.on} size="sm" onClick={() => {}}/></span>
          </div>
        ))}
      </Card>
      {newOpen && <NewAdModal onClose={() => setNewOpen(false)} onCreate={createCamp}/>}
      {edit && <EditAdModal camp={edit} onClose={() => setEdit(null)} onSave={saveCamp} onDelete={delCamp}/>}
    </div>
  );
}

function NewAdModal({ onClose, onCreate }) {
  const [n, setN] = React.useState('');
  const [plat, setPlat] = React.useState('Search');
  const [budget, setBudget] = React.useState('20');
  const canSave = n.trim().length > 0 && Number(budget) > 0;
  return (
    <window.Modal title="New ad campaign" sub="Pex scopes targeting and a budget; you approve." w={480} onClose={onClose}
      foot={<><Btn kind="ghost" onClick={onClose}>Cancel</Btn><Btn kind="spark" disabled={!canSave} onClick={() => onCreate({ n: n.trim(), plat, budget })}>Launch campaign</Btn></>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field label="Campaign name" value={n} onChange={setN} placeholder='e.g. Google · "sourdough class nyc"' icon="trendUp"/>
        <Select label="Platform" value={plat} onChange={setPlat} options={['Search', 'Social']}/>
        <Field label="Daily budget" value={budget} onChange={setBudget} type="number" icon="dollar" suffix="/day"/>
      </div>
    </window.Modal>
  );
}

function EditAdModal({ camp, onClose, onSave, onDelete }) {
  const [budget, setBudget] = React.useState(String(camp.budget));
  const [on, setOn] = React.useState(camp.on);
  const P = window.PX;
  return (
    <window.Modal title={camp.n} sub={`${camp.plat} · ${camp.roas} ROAS`} w={480} onClose={onClose}
      foot={<><Btn kind="danger" onClick={() => onDelete(camp.id)}>Remove</Btn><div style={{ flex: 1 }}/><Btn kind="primary" onClick={() => onSave({ ...camp, budget: Number(budget) || camp.budget, on })}>Save</Btn></>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field label="Daily budget" value={budget} onChange={setBudget} type="number" icon="dollar" suffix="/day"/>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', border: `1px solid ${P.line}`, borderRadius: 10 }}>
          <span style={{ flex: 1, fontSize: 13, color: P.ink }}>Campaign active</span><Toggle on={on} size="sm" onClick={() => setOn(v => !v)}/>
        </div>
      </div>
    </window.Modal>
  );
}

// ── SEGMENTS ─────────────────────────────────────────────────
const SEG_FIELDS = [
  { v: 'tag', label: 'Tag' }, { v: 'company-type', label: 'Company type' },
  { v: 'last-order', label: 'Last order' }, { v: 'ltv', label: 'Lifetime value' },
  { v: 'opt-in', label: 'Opt-in' }, { v: 'source', label: 'Source' },
];
const SEG_FIELD_LABEL = SEG_FIELDS.reduce((m, f) => { m[f.v] = f.label; return m; }, { invoice: 'Invoice' });
const SEG_OPS = { tag: ['is', 'is not'], 'company-type': ['is'], 'last-order': ['more than', 'less than'], ltv: ['over', 'under'], 'opt-in': ['is'], source: ['is'], invoice: ['is'] };
const segOpsFor = (f) => SEG_OPS[f] || ['is'];
const rulesToText = (rules) => rules.filter(r => r.value).map(r => `${SEG_FIELD_LABEL[r.field] || r.field} ${r.op} ${r.value}`).join(' · ');

function Segments() {
  const P = window.PX; const { toast, go } = window.useApp();
  const st = window.useStore(window.PXMarketing);
  const segs = st.segments;
  const [builder, setBuilder] = React.useState(null); // null | { seg } (edit) | {} (new)
  const emailSegment = (s) => {
    const id = window.pxid('c');
    window.PXMarketing.addCampaign({ id, n: `Email · ${s.n}`, st: 'draft', aud: `${s.n} · ${s.count}`, segId: s.id, when: 'Not scheduled', open: '—', rev: '—',
      ab: false, subjA: '', subjB: '', headline: 'A note for ' + s.n, cta: 'Learn more', track: true, sched: true, body: 'Pex can draft this from your brand and past sends.' });
    toast(`New campaign to ${s.n} (${s.count}).`, { icon: 'mail' });
    go('marketing/campaigns/' + id);
  };
  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <MHead title="Segments" sub="Live audiences built from your CRM — they update themselves.">
        <Btn kind="spark" size="sm" icon="plus" onClick={() => setBuilder({})}>New segment</Btn>
      </MHead>
      <Card pad={0}>
        {segs.length === 0 && <EmptyRow>No segments yet — build one to target campaigns.</EmptyRow>}
        {segs.map((s, i) => (
          <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '15px 18px', borderBottom: i < segs.length - 1 ? `1px solid ${P.line}` : 'none' }}>
            <div style={{ width: 40, height: 40, borderRadius: 10, background: P[s.tone + 'Tint'] || P.sunk, color: P[s.tone] || P.ink2, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="users" size={18}/></div>
            <div style={{ flex: 1 }}><div style={{ fontSize: 14, fontWeight: 600, color: P.ink }}>{s.n}</div><div style={{ fontSize: 12, color: P.ink3, fontFamily: P.mono, marginTop: 2 }}>{s.rule || rulesToText(s.rules)}</div></div>
            <Num size={22}>{s.count}</Num>
            <Btn kind="ghost" size="sm" icon="pencil" onClick={() => setBuilder({ seg: s })}>Edit</Btn>
            <Btn kind="default" size="sm" icon="mail" onClick={() => emailSegment(s)}>Email</Btn>
          </div>
        ))}
      </Card>
      {builder && <MktSegmentBuilder seg={builder.seg} onClose={() => setBuilder(null)}/>}
    </div>
  );
}

function MktSegmentBuilder({ seg, onClose }) {
  const P = window.PX; const { toast } = window.useApp();
  const isEdit = !!seg;
  const [name, setName] = React.useState(seg ? seg.n : '');
  const [rows, setRows] = React.useState(seg ? seg.rules.map(r => ({ ...r })) : [{ field: 'tag', op: 'is', value: '' }]);
  const updateRow = (i, patch) => setRows(rs => rs.map((r, j) => j === i ? { ...r, ...patch } : r));
  const addRow = () => setRows(rs => [...rs, { field: 'tag', op: 'is', value: '' }]);
  const removeRow = (i) => setRows(rs => rs.filter((_, j) => j !== i));
  const active = rows.filter(r => r.value.trim());
  const est = isEdit && active.length === seg.rules.length ? seg.count : Math.max(6, Math.round(400 / Math.pow(2, active.length || 1)));
  const canSave = name.trim() && active.length;
  const save = () => {
    if (!canSave) return;
    const rules = active.map(r => ({ ...r, value: r.value.trim() }));
    if (isEdit) {
      window.PXMarketing.updateSegment(seg.id, { n: name.trim(), rules, rule: rulesToText(rules), count: est });
      toast(`Updated “${name.trim()}”.`, { tone: 'sage', icon: 'check' });
    } else {
      window.PXMarketing.addSegment({ id: window.pxid('seg'), n: name.trim(), count: est, tone: 'plum', rule: rulesToText(rules), rules });
      toast(`Created “${name.trim()}” · ~${est} contacts.`, { tone: 'sage', icon: 'check' });
    }
    onClose();
  };
  const inpS = { width: '100%', border: `1px solid ${P.lineStrong}`, borderRadius: 8, padding: '7px 10px', fontSize: 12.5, color: P.ink, fontFamily: P.sans, outline: 'none', boxSizing: 'border-box' };
  return (
    <window.Modal title={isEdit ? 'Edit segment' : 'New segment'} sub="Combine criteria to build a live contact list" w={580} onClose={onClose}
      foot={<><Btn kind="ghost" onClick={onClose}>Cancel</Btn><Btn kind="primary" disabled={!canSave} onClick={save}>{isEdit ? 'Save segment' : 'Create segment'} · ~{est}</Btn></>}>
      <div style={{ marginBottom: 18 }}>
        <div style={{ fontSize: 12, color: P.ink3, marginBottom: 5, fontWeight: 500 }}>Segment name</div>
        <input value={name} onChange={e => setName(e.target.value)} placeholder="e.g. High-value wholesale" style={inpS}/>
      </div>
      <Label style={{ marginBottom: 8 }}>Criteria</Label>
      {rows.map((r, i) => (
        <Card key={i} pad={12} style={{ marginBottom: 10 }}>
          <div style={{ display: 'flex', gap: 8, alignItems: 'flex-end' }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 10.5, color: P.ink3, marginBottom: 5 }}>Field</div>
              <select value={r.field} onChange={e => updateRow(i, { field: e.target.value, op: segOpsFor(e.target.value)[0], value: '' })} style={inpS}>
                {SEG_FIELDS.map(f => <option key={f.v} value={f.v}>{f.label}</option>)}
              </select>
            </div>
            <div style={{ width: 110 }}>
              <div style={{ fontSize: 10.5, color: P.ink3, marginBottom: 5 }}>Operator</div>
              <select value={r.op} onChange={e => updateRow(i, { op: e.target.value })} style={inpS}>
                {segOpsFor(r.field).map(o => <option key={o} value={o}>{o}</option>)}
              </select>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 10.5, color: P.ink3, marginBottom: 5 }}>Value</div>
              <input value={r.value} onChange={e => updateRow(i, { value: e.target.value })} placeholder={r.field === 'tag' ? 'wholesale' : r.field === 'last-order' ? '60 days' : 'value'} style={inpS}/>
            </div>
            {rows.length > 1 && <Icon name="x" size={15} color={P.ink3} style={{ cursor: 'pointer', marginBottom: 8 }} onClick={() => removeRow(i)}/>}
          </div>
        </Card>
      ))}
      <div onClick={addRow} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '9px 0', fontSize: 12.5, color: P.spark, cursor: 'pointer', marginBottom: 16 }}><Icon name="plus" size={14}/>Add criteria</div>
      <Card pad={12} style={{ background: P.sunk }}>
        <Label style={{ marginBottom: 6 }}>Live estimate</Label>
        <div style={{ fontSize: 12.5, color: P.ink2 }}>{active.length ? <>~<b style={{ color: P.ink }}>{est}</b> contacts match · {rulesToText(active)}</> : 'Add a value to preview the audience.'}</div>
      </Card>
    </window.Modal>
  );
}

// ── TEMPLATES ────────────────────────────────────────────────
function Templates() {
  const P = window.PX; const { toast, go } = window.useApp();
  const [tpls, setTpls] = React.useState([
    { id: 't1', name: 'Class announcement', bg: '#F2E2C4', fg: '#3A2A1C', headline: 'Our next class is open.', body: 'Small group, hands-on. Come shape and score with us.', cta: 'Reserve a seat' },
    { id: 't2', name: 'Wholesale update', bg: '#3A2A1C', fg: '#F5D8A8', headline: 'This week for your café.', body: 'Fresh menu, same delivery windows. Lock your standing order.', cta: 'See the menu' },
    { id: 't3', name: 'Monthly newsletter', bg: '#D9A84C', fg: '#3A2A1C', headline: 'From the bench this month.', body: "Here's everything coming out of the oven.", cta: 'Read the note' },
    { id: 't4', name: 'Order confirmation', bg: '#FBF3E0', fg: '#3A2A1C', headline: 'Your order is in.', body: 'Thanks — here are the details and pickup window.', cta: 'View order' },
    { id: 't5', name: 'Win-back offer', bg: '#8C4A2A', fg: '#F5D8A8', headline: 'We miss you.', body: "It's been a while — here's a little something to come back for.", cta: 'Claim offer' },
    { id: 't6', name: 'Thank you', bg: '#EDE6D6', fg: '#3A2A1C', headline: 'Thank you.', body: 'It means the world to bake for you. See you soon.', cta: 'Visit us' },
  ]);
  const [edit, setEdit] = React.useState(null); // {} new | { tpl } edit
  const use = (t) => {
    const id = window.pxid('c');
    window.PXMarketing.addCampaign({ id, n: t.name, st: 'draft', aud: '', segId: window.PXMarketing.segments()[0].id, when: 'Not scheduled', open: '—', rev: '—',
      ab: false, subjA: '', subjB: '', headline: t.headline, cta: t.cta, track: true, sched: true, body: t.body });
    toast(`Started a campaign from “${t.name}”.`, { tone: 'sage', icon: 'check' });
    go('marketing/campaigns/' + id);
  };
  const saveTpl = (t) => {
    if (t.id) { setTpls(ts => ts.map(x => x.id === t.id ? t : x)); toast('Template saved.', { tone: 'sage', icon: 'check' }); }
    else { setTpls(ts => [...ts, { ...t, id: window.pxid('t') }]); toast('Template created.', { tone: 'sage', icon: 'check' }); }
    setEdit(null);
  };
  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <MHead title="Templates" sub="Brand-applied email layouts — start any campaign from one.">
        <Btn kind="spark" size="sm" icon="plus" onClick={() => setEdit({ bg: '#F2E2C4', fg: '#3A2A1C' })}>New template</Btn>
      </MHead>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14 }}>
        {tpls.map((t) => (
          <Card key={t.id} pad={0} hover onClick={() => setEdit({ tpl: t })} style={{ cursor: 'pointer' }}>
            <div style={{ height: 150, background: t.bg, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8, padding: 18 }}>
              <div style={{ width: 30, height: 30, borderRadius: 7, background: 'rgba(0,0,0,0.12)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: P.serif, fontStyle: 'italic', color: t.fg, fontSize: 15 }}>hl</div>
              <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 18, color: t.fg, textAlign: 'center' }}>{t.name}</div>
              <div style={{ width: 70, height: 6, borderRadius: 3, background: t.fg, opacity: 0.5 }}/>
            </div>
            <div style={{ padding: '12px 14px', display: 'flex', alignItems: 'center' }}><span style={{ flex: 1, fontSize: 13, color: P.ink, fontWeight: 500 }}>{t.name}</span><span onClick={e => { e.stopPropagation(); use(t); }}><Btn kind="default" size="sm">Use</Btn></span></div>
          </Card>
        ))}
      </div>
      {edit && <TemplateEditor tpl={edit.tpl} preset={edit} onClose={() => setEdit(null)} onSave={saveTpl}/>}
    </div>
  );
}

function TemplateEditor({ tpl, preset, onClose, onSave }) {
  const P = window.PX;
  const base = tpl || { name: '', bg: preset.bg, fg: preset.fg, headline: '', body: '', cta: '' };
  const [t, setT] = React.useState({ ...base });
  const set = (k, v) => setT(s => ({ ...s, [k]: v }));
  const canSave = t.name.trim().length > 0;
  const swatches = [['#F2E2C4', '#3A2A1C'], ['#3A2A1C', '#F5D8A8'], ['#D9A84C', '#3A2A1C'], ['#8C4A2A', '#F5D8A8'], ['#EDE6D6', '#3A2A1C'], ['#FBF3E0', '#3A2A1C']];
  return (
    <window.Modal title={tpl ? 'Edit template' : 'New template'} sub="Name it, pick a look, set the copy." w={520} onClose={onClose}
      foot={<><Btn kind="ghost" onClick={onClose}>Cancel</Btn><Btn kind="primary" disabled={!canSave} onClick={() => onSave(t)}>Save template</Btn></>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field label="Template name" value={t.name} onChange={v => set('name', v)} placeholder="e.g. Seasonal launch" icon="layout"/>
        <div>
          <div style={{ fontSize: 12, color: P.ink3, marginBottom: 6, fontWeight: 500 }}>Color</div>
          <div style={{ display: 'flex', gap: 8 }}>
            {swatches.map((sw, i) => (
              <div key={i} onClick={() => setT(s => ({ ...s, bg: sw[0], fg: sw[1] }))} style={{ width: 40, height: 40, borderRadius: 9, background: sw[0], border: `2px solid ${t.bg === sw[0] ? P.spark : P.line}`, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: P.serif, fontStyle: 'italic', color: sw[1], fontSize: 13 }}>hl</div>
            ))}
          </div>
        </div>
        <Field label="Headline" value={t.headline} onChange={v => set('headline', v)} placeholder="A quick note…"/>
        <TextArea label="Body" value={t.body} onChange={v => set('body', v)} rows={3}/>
        <Field label="Button label" value={t.cta} onChange={v => set('cta', v)} placeholder="Learn more"/>
      </div>
    </window.Modal>
  );
}

// ── SEO & CONTENT ────────────────────────────────────────────
function SEOContent() {
  const P = window.PX; const { toast, go } = window.useApp();
  const spend = useSpend();
  const [opps, setOpps] = React.useState([
    { id: 'o1', kw: '"brooklyn sourdough"', note: '#3 → #1 possible', vol: '410/mo', cost: 6, done: false },
    { id: 'o2', kw: '"sourdough class nyc"', note: 'You don’t rank yet', vol: '190/mo', cost: 6, done: false },
    { id: 'o3', kw: 'FAQ schema for /classes', note: 'Win the answer box', vol: '—', cost: 2, done: false },
  ]);
  const doIt = (o) => spend(o.cost, () => {
    window.startPexRun && window.startPexRun({ title: 'SEO · ' + o.kw, cost: o.cost, tone: 'amber' });
    setOpps(os => os.map(x => x.id === o.id ? { ...x, done: true } : x));
    toast('Pex is on it — drafting now.', { icon: 'sparkles', tone: 'sage' });
  });
  const writePost = () => spend(6, () => {
    window.startPexRun && window.startPexRun({ title: 'SEO post · best keyword gap', cost: 6, tone: 'amber' });
    toast('Pex is drafting a post targeting your best keyword gap.', { icon: 'sparkles', tone: 'sage' });
  });
  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <MHead title="SEO & content" sub="Get found on Google — Pex finds the gaps and writes the content to fill them.">
        <Btn kind="default" size="sm" icon="penTool" onClick={() => go('website/blog')}>Blog</Btn>
        <Btn kind="spark" size="sm" icon="sparkles" onClick={writePost}>Write a post · 6 ⚡</Btn>
      </MHead>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 14, marginBottom: 16 }}>
        {[['SEO health', '82', '/100', 'sage'], ['Keywords ranking', '34', 'top 10', 'sky'], ['Organic visits', '1,840', '+22%', 'sage'], ['Content gaps', String(opps.filter(o => !o.done).length), 'Pex found', 'amber']].map((c, i) => (
          <Card key={i} pad={16}><Label>{c[0]}</Label><div style={{ display: 'flex', alignItems: 'baseline', gap: 4, marginTop: 6 }}><Num size={26} color={P[c[3]]}>{c[1]}</Num><span style={{ fontSize: 11.5, color: P.ink3 }}>{c[2]}</span></div></Card>
        ))}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 14 }}>
        <Card pad={0}>
          <div style={{ padding: '14px 18px', borderBottom: `1px solid ${P.line}`, fontSize: 14, fontWeight: 600, color: P.ink }}>Opportunities Pex found</div>
          {opps.map((o, i) => (
            <div key={o.id} style={{ padding: '13px 18px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: i < opps.length - 1 ? `1px solid ${P.line}` : 'none' }}>
              <div style={{ flex: 1 }}><div style={{ fontSize: 13.5, color: P.ink, fontWeight: 500 }}>{o.kw}</div><div style={{ fontSize: 11.5, color: P.ink3 }}>{o.note} · {o.vol}</div></div>
              {o.done
                ? <Pill tone="sage" icon="check" style={{ fontSize: 10 }}>Drafting</Pill>
                : <Btn kind="spark" size="sm" onClick={() => doIt(o)}>Do it · {o.cost} ⚡</Btn>}
            </div>
          ))}
        </Card>
        <Card pad={18}>
          <div style={{ fontSize: 14, fontWeight: 600, color: P.ink, marginBottom: 12 }}>Top ranking keywords</div>
          {[['brooklyn sourdough', 3, 410], ['williamsburg bakery', 5, 280], ['stone milled bread', 8, 90], ['artisan bread brooklyn', 6, 150]].map((k, i) => (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 60px 80px', gap: 8, padding: '8px 0', borderBottom: i < 3 ? `1px solid ${P.line}` : 'none', fontSize: 12.5, alignItems: 'center' }}>
              <span style={{ color: P.ink }}>{k[0]}</span><span style={{ color: P.ink2, textAlign: 'right', fontFamily: P.mono }}>#{k[1]}</span><span style={{ color: P.ink3, textAlign: 'right' }}>{k[2]}/mo</span>
            </div>
          ))}
        </Card>
      </div>
    </div>
  );
}

// ── REPUTATION · reviews ─────────────────────────────────────
function Reputation() {
  const P = window.PX; const { toast } = window.useApp();
  const spend = useSpend();
  const [reviews, setReviews] = React.useState([
    { id: 'r1', who: 'Daniel R.', src: 'Google', stars: 4, when: '2h ago', t: 'Great bread, genuinely the best in the neighborhood. Line moves slow on Saturdays though.', reply: 'Thank you, Daniel — that means a lot. You’re right about Saturdays; we’ve added a second register for the morning rush. Hope to see you soon. — Amara', replied: false },
    { id: 'r2', who: 'Priya S.', src: 'Yelp', stars: 5, when: 'Yesterday', t: 'The sourdough class was a highlight of my month. Amara is a wonderful teacher.', replied: true },
    { id: 'r3', who: 'Marcus T.', src: 'Google', stars: 5, when: '3 days ago', t: 'Wholesale partner for our café — consistent, reliable, and the crumb is perfect every time.', replied: true },
    { id: 'r4', who: 'Anon', src: 'Google', stars: 5, when: 'Last week', t: 'Worth the trip from Queens.', replied: true },
  ]);
  const [editing, setEditing] = React.useState(null); // review id
  const [draftReply, setDraftReply] = React.useState('');
  const needsReply = reviews.filter(r => !r.replied).length;
  const postReply = (r) => spend(1, () => {
    setReviews(rs => rs.map(x => x.id === r.id ? { ...x, replied: true } : x));
    toast(`Reply posted to ${r.src}.`, { tone: 'sage', icon: 'check' });
  });
  const startEdit = (r) => { setEditing(r.id); setDraftReply(r.reply || ''); };
  const saveEdit = (r) => { setReviews(rs => rs.map(x => x.id === r.id ? { ...x, reply: draftReply } : x)); setEditing(null); toast('Reply updated.', { tone: 'sage', icon: 'check' }); };
  const requestReviews = () => spend(1, () => toast('Pex sent review requests to 12 recent happy customers.', { tone: 'sage', icon: 'check' }));
  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <MHead title="Reputation" sub="Your reviews across Google & Yelp — Pex drafts replies and asks happy customers for more.">
        <Btn kind="spark" size="sm" icon="send" onClick={requestReviews}>Request reviews · 1 ⚡</Btn>
      </MHead>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 14, marginBottom: 16 }}>
        <Card pad={16} style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <Num size={38} color={P.sage}>4.8</Num>
          <div><div style={{ color: P.amber, fontSize: 14 }}>★★★★★</div><div style={{ fontSize: 11.5, color: P.ink3 }}>142 reviews</div></div>
        </Card>
        {[['New · 30d', '18', 'sage'], ['Response rate', '96%', 'sky'], ['Needs reply', String(needsReply), needsReply ? 'rose' : 'sage']].map((c, i) => (
          <Card key={i} pad={16}><Label>{c[0]}</Label><Num size={24} style={{ marginTop: 6 }} color={P[c[2]]}>{c[1]}</Num></Card>
        ))}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {reviews.map((r) => (
          <Card key={r.id} pad={16} style={{ border: `1px solid ${!r.replied ? P.roseTint : P.line}` }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
              <Avatar name={r.who} size={30}/>
              <div style={{ flex: 1 }}><div style={{ fontSize: 13.5, color: P.ink, fontWeight: 600 }}>{r.who}</div><div style={{ fontSize: 11, color: P.ink3 }}>{r.src} · {r.when}</div></div>
              <span style={{ color: P.amber, fontSize: 13 }}>{'★'.repeat(r.stars)}<span style={{ color: P.line }}>{'★'.repeat(5 - r.stars)}</span></span>
              {r.replied && <Pill tone="sage" style={{ fontSize: 10 }}>replied</Pill>}
              {!r.replied && <Pill tone="rose" style={{ fontSize: 10 }}>needs reply</Pill>}
            </div>
            <div style={{ fontSize: 13, color: P.ink2, lineHeight: 1.55 }}>{r.t}</div>
            {r.reply && (
              <div style={{ marginTop: 12 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 7 }}><Pex size={20}/><span style={{ fontSize: 12, fontWeight: 600, color: P.ink }}>{r.replied ? 'Your reply' : 'Pex drafted a reply'}</span></div>
                {editing === r.id ? (
                  <>
                    <textarea value={draftReply} onChange={e => setDraftReply(e.target.value)} rows={3} style={{ width: '100%', border: `1px solid ${P.lineStrong}`, borderRadius: 9, padding: 11, fontSize: 12.5, color: P.ink, fontFamily: P.sans, lineHeight: 1.55, outline: 'none', boxSizing: 'border-box', resize: 'vertical' }}/>
                    <div style={{ display: 'flex', gap: 7, marginTop: 9 }}><Btn kind="primary" size="sm" onClick={() => saveEdit(r)}>Save reply</Btn><Btn kind="ghost" size="sm" onClick={() => setEditing(null)}>Cancel</Btn></div>
                  </>
                ) : (
                  <>
                    <div style={{ fontSize: 12.5, color: P.ink, lineHeight: 1.55, padding: 11, background: P.sunk, borderRadius: 9 }}>{r.reply}</div>
                    {!r.replied && <div style={{ display: 'flex', gap: 7, marginTop: 9 }}><Btn kind="spark" size="sm" icon="send" onClick={() => postReply(r)}>Post reply · 1 ⚡</Btn><Btn kind="default" size="sm" onClick={() => startEdit(r)}>Edit</Btn></div>}
                    {r.replied && <div style={{ marginTop: 9 }}><Btn kind="ghost" size="sm" onClick={() => startEdit(r)}>Edit</Btn></div>}
                  </>
                )}
              </div>
            )}
          </Card>
        ))}
      </div>
    </div>
  );
}

// ── ATTRIBUTION ──────────────────────────────────────────────
function Attribution() {
  const P = window.PX; const { toast } = window.useApp();
  const [range, setRange] = React.useState('Last 90 days');
  const [exporting, setExporting] = React.useState(false);
  const [recurring, setRecurring] = React.useState(false);
  const rows = [
    ['March class email', 'Email', 142, 14, '$1,120', 'spark'],
    ['Google · "brooklyn bakery"', 'Ads', 0, 9, '$2,184', 'sky'],
    ['"brooklyn sourdough" post', 'SEO', 410, 6, '$840', 'amber'],
    ['Instagram · class promo', 'Social', 0, 7, '$1,064', 'rose'],
    ['Holiday gift boxes', 'Email', 360, 22, '$5,180', 'spark'],
  ];
  const doExport = () => { setExporting(true); setTimeout(() => { setExporting(false); toast(`Exported attribution · ${range}.csv`, { tone: 'sage', icon: 'download' }); }, 800); };
  const makeRecurring = () => { setRecurring(true); window.startPexRun && window.startPexRun({ title: 'Recurring: email to lapsed customers', cost: 0, tone: 'sage' }); toast('Set to run monthly — Pex will handle it.', { tone: 'sage', icon: 'check' }); };
  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <MHead title="Attribution" sub={`Which marketing actually made money — traced from touch to paid invoice · ${range}.`}>
        <div style={{ width: 150 }}><Select value={range} onChange={setRange} options={['Last 30 days', 'Last 90 days', 'This quarter', 'This year']}/></div>
        <Btn kind="default" size="sm" icon="download" loading={exporting} onClick={doExport}>Export</Btn>
      </MHead>
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 18, marginBottom: 16 }}>
        <Card pad={18}>
          <div style={{ fontSize: 14, fontWeight: 600, color: P.ink, marginBottom: 14 }}>Revenue by channel</div>
          {[['Email', 6240, 42, 'spark'], ['SEO / blog', 4180, 28, 'amber'], ['Social', 2900, 20, 'rose'], ['Ads', 1500, 10, 'sky']].map((c, i) => (
            <div key={i} style={{ marginBottom: 12 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, color: P.ink2, marginBottom: 4 }}><span>{c[0]}</span><span style={{ fontFamily: P.mono }}>{money(c[1])} · {c[2]}%</span></div>
              <div style={{ height: 8, background: P.sunk, borderRadius: 6, overflow: 'hidden' }}><div style={{ width: c[2] + '%', height: '100%', background: P[c[3]] }}/></div>
            </div>
          ))}
        </Card>
        <Card pad={18} style={{ background: P.sageWash, border: `1px solid ${P.sageTint}` }}>
          <Label style={{ color: P.sage }}>Best ROI this quarter</Label>
          <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 22, color: P.ink, marginTop: 6 }}>Email to lapsed customers</div>
          <div style={{ fontSize: 12.5, color: P.ink2, marginTop: 8, lineHeight: 1.5 }}>$42 spent in Sparks returned <b style={{ color: P.ink }}>$5,180</b> — a 123× return. Pex suggests running it monthly.</div>
          <Btn kind={recurring ? 'default' : 'primary'} size="sm" full disabled={recurring} icon={recurring ? 'check' : undefined} onClick={makeRecurring} style={{ marginTop: 12 }}>{recurring ? 'Recurring · monthly' : 'Make it recurring'}</Btn>
        </Card>
      </div>
      <Card pad={0}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 90px 90px 90px 100px', gap: 12, padding: '12px 18px', borderBottom: `1px solid ${P.line}` }}>
          {['Touchpoint', 'Channel', 'Reached', 'Customers', 'Revenue'].map((h, i) => <Label key={i} style={{ textAlign: i >= 2 ? 'right' : 'left' }}>{h}</Label>)}
        </div>
        {rows.map((r, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '2fr 90px 90px 90px 100px', gap: 12, padding: '12px 18px', borderBottom: i < rows.length - 1 ? `1px solid ${P.line}` : 'none', alignItems: 'center' }}>
            <span style={{ fontSize: 13, color: P.ink, fontWeight: 500 }}>{r[0]}</span>
            <span><Pill tone={r[5]} style={{ fontSize: 10 }}>{r[1]}</Pill></span>
            <span style={{ fontFamily: P.mono, fontSize: 12, color: P.ink3, textAlign: 'right' }}>{r[2] ? r[2].toLocaleString() : '—'}</span>
            <span style={{ fontFamily: P.mono, fontSize: 12.5, color: P.ink, textAlign: 'right' }}>{r[3]}</span>
            <span style={{ fontFamily: P.mono, fontSize: 12.5, color: P.sage, textAlign: 'right', fontWeight: 600 }}>{r[4]}</span>
          </div>
        ))}
      </Card>
    </div>
  );
}
