// ════════════ WORK · Projects, Catalog, Insights + Pex full view ════════════
const { Icon, Spark, Pex, Avatar, Card, Btn, Pill, Label, Num, Spark2, Tabs, Field, Select, Check, money } = window;

// ── PROJECTS ─────────────────────────────────────────────────
const PROJECTS_SEED = [
  { n: 'Spring wholesale push', status: 'In progress', p: 72, d: 'Apr 15', start: 'Mar 1', end: 'Apr 15', startPct: 20, endPct: 49, team: ['Amara', 'Diego', 'Rosa'], tone: 'sage', tasks: '14/19', budget: '$2,400 / $3,000', revenue: 8400, timeCost: 5150 },
  { n: 'Class program expansion', status: 'At risk', p: 38, d: 'May 1', start: 'Mar 20', end: 'May 1', startPct: 32, endPct: 60, team: ['Amara', 'Rosa'], tone: 'amber', tasks: '8/21', budget: '$1,200 / $4,500', revenue: 4200, timeCost: 3800 },
  { n: 'Park Bros. onboarding', status: 'Planning', p: 12, d: 'Apr 28', start: 'Apr 5', end: 'Apr 28', startPct: 45, endPct: 59, team: ['Amara', 'Ethan'], tone: 'rose', tasks: '2/17', budget: '$400 / $6,000', revenue: 6000, timeCost: 1200 },
  { n: 'Holiday gift boxes', status: 'Done', p: 100, d: 'Mar 5', start: 'Feb 1', end: 'Mar 5', startPct: 0, endPct: 26, team: ['Amara', 'Diego'], tone: 'sky', tasks: '22/22', budget: '$1,800 / $1,800', revenue: 12500, timeCost: 6300 },
];
const PROJECT_STATUS_TONE = { Planning: 'sky', 'In progress': 'sage', 'At risk': 'amber', Done: 'ink' };
const STATUS_ORDER = Object.keys(PROJECT_STATUS_TONE);

const PROJECT_TASKS_SEED = [
  { s: true, t: 'Choose 3 new class topics', o: 'Amara', d: 'Mar 5' },
  { s: true, t: 'Book substitute baker', o: 'Diego', d: 'Mar 8' },
  { s: false, t: 'Update Classes page · 3 entries', o: 'Amara', d: 'Mar 13' },
  { s: false, t: 'Email the 142-person waitlist', o: 'Priya', d: 'Mar 15' },
  { s: false, t: 'Print new class flyers', o: 'Rosa', d: 'Mar 22' },
];

// New-project dialog — validates, then hands a fresh project up to the list.
function NewProjectModal({ onCreate, onClose }) {
  const P = window.PX; const { toast } = window.useApp();
  const [name, setName] = React.useState('');
  const [status, setStatus] = React.useState('Planning');
  const [due, setDue] = React.useState('');
  const [budget, setBudget] = React.useState('');
  const create = () => {
    if (!name.trim()) { toast('Name the project first.', { tone: 'rose', icon: 'alert' }); return; }
    const tone = PROJECT_STATUS_TONE[status] || 'sky';
    const p = { n: name.trim(), status, p: status === 'Done' ? 100 : 0, d: due.trim() || 'TBD', start: '—', end: due.trim() || '—', startPct: 0, endPct: 6, team: ['Amara'], tone, tasks: '0/0', budget: '$0 / ' + (budget.trim() || '$0'), revenue: 0, timeCost: 0 };
    onCreate(p); onClose(); toast(`“${name.trim()}” added to Projects.`, { tone: 'sage', icon: 'check' });
  };
  return (
    <window.Modal title="New project" sub="Spin one up and Pex will suggest the first tasks." w={520} onClose={onClose}
      foot={<><Btn kind="ghost" size="md" onClick={onClose}>Cancel</Btn><div style={{ flex: 1 }}/><Btn kind="primary" size="md" icon="plus" onClick={create}>Create project</Btn></>}>
      <Field label="Project name" placeholder="Summer market series" value={name} onChange={setName} style={{ marginBottom: 14 }}/>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <Select label="Status" value={status} onChange={setStatus} options={STATUS_ORDER}/>
        <Field label="Due" placeholder="May 1" value={due} onChange={setDue}/>
      </div>
      <Field label="Spark budget" placeholder="$3,000" value={budget} onChange={setBudget} style={{ marginTop: 14 }}/>
    </window.Modal>
  );
}

function ProjectProfitDrawer({ pr, onClose }) {
  const P = window.PX;
  const margin = pr.revenue ? Math.round((1 - pr.timeCost / pr.revenue) * 100) : 0;
  const total = (pr.revenue + pr.timeCost) || 1;
  return (
    <window.Drawer title={pr.n} sub={`Due ${pr.d}`} tag={<Pill tone={PROJECT_STATUS_TONE[pr.status]}>{pr.status}</Pill>} onClose={onClose}
      foot={<Btn kind="default" size="sm" onClick={onClose} full>Close</Btn>}>
      <Label style={{ marginBottom: 8 }}>Progress</Label>
      <div style={{ height: 6, background: P.sunk, borderRadius: 6, overflow: 'hidden', marginBottom: 4 }}><div style={{ width: pr.p + '%', height: '100%', background: P[pr.tone] }}/></div>
      <div style={{ fontSize: 11.5, color: P.ink3, marginBottom: 20 }}>{pr.tasks} tasks · {pr.budget} Spark budget</div>

      <Label style={{ marginBottom: 10 }}>Profitability</Label>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 12 }}>
        <div><Label style={{ marginBottom: 4 }}>Revenue</Label><Num size={26} color={P.sage}>{money(pr.revenue)}</Num></div>
        <div><Label style={{ marginBottom: 4 }}>Logged-time cost</Label><Num size={26} color={P.rose}>{money(pr.timeCost)}</Num></div>
      </div>
      <div style={{ display: 'flex', gap: 3, height: 14, marginBottom: 10, borderRadius: 5, overflow: 'hidden' }}>
        <div style={{ width: (pr.revenue / total * 100) + '%', background: P.sage }}/>
        <div style={{ width: (pr.timeCost / total * 100) + '%', background: P.rose }}/>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 12px', background: P.sageWash, border: `1px solid ${P.sageTint}`, borderRadius: 9, marginBottom: 20 }}>
        <span style={{ fontSize: 12.5, color: P.ink2 }}>Margin</span>
        <span style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 20, color: P.sage }}>{margin}%</span>
      </div>

      <Label style={{ marginBottom: 8 }}>Team</Label>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {pr.team.map((t, j) => <div key={j} style={{ display: 'flex', alignItems: 'center', gap: 8 }}><Avatar name={t} size={22}/><span style={{ fontSize: 12.5, color: P.ink2 }}>{t}</span></div>)}
      </div>
    </window.Drawer>
  );
}

window.SCREENS['projects'] = function Projects() {
  const P = window.PX;
  const [view, setView] = React.useState('list');
  const [selProject, setSelProject] = React.useState(null);
  const [projects, setProjects] = React.useState(PROJECTS_SEED);
  const [tasks, setTasks] = React.useState(PROJECT_TASKS_SEED);
  const [showNew, setShowNew] = React.useState(false);
  const toggleTask = (i) => setTasks(ts => ts.map((t, j) => j === i ? { ...t, s: !t.s } : t));
  const doneCount = tasks.filter(t => t.s).length;
  const moveProject = (name, dir) => setProjects(ps => ps.map(p => {
    if (p.n !== name) return p;
    const ni = Math.max(0, Math.min(STATUS_ORDER.length - 1, STATUS_ORDER.indexOf(p.status) + dir));
    return { ...p, status: STATUS_ORDER[ni], p: STATUS_ORDER[ni] === 'Done' ? 100 : p.p };
  }));
  const active = projects.filter(p => p.status !== 'Done').length;
  const atRisk = projects.filter(p => p.status === 'At risk').length;

  return (
    <window.Page title="Projects" sub={`${active} active · ${atRisk} at risk`} actions={<Btn kind="primary" size="sm" icon="plus" onClick={() => setShowNew(true)}>New project</Btn>}>
      <Tabs tabs={[{ k: 'list', label: 'List' }, { k: 'board', label: 'Board' }, { k: 'timeline', label: 'Timeline' }]} active={view} onChange={setView} style={{ marginBottom: 18 }}/>

      {view === 'list' && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14, marginBottom: 18 }}>
          {projects.map((pr, i) => (
            <Card key={i} pad={16} hover onClick={() => setSelProject(pr)}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 9 }}><span style={{ width: 8, height: 8, borderRadius: 8, background: P[pr.tone] }}/><span style={{ fontSize: 14, fontWeight: 600, color: P.ink, flex: 1 }}>{pr.n}</span><span style={{ fontSize: 11, color: P.ink3 }}>{pr.d}</span></div>
              <div style={{ height: 5, background: P.sunk, borderRadius: 5, overflow: 'hidden', marginBottom: 10 }}><div style={{ width: pr.p + '%', height: '100%', background: P[pr.tone] }}/></div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, color: P.ink3, marginBottom: 10 }}><span>{pr.tasks} tasks</span><span>{pr.budget}</span></div>
              <div style={{ display: 'flex' }}>{pr.team.map((t, j) => <span key={j} style={{ marginLeft: j ? -7 : 0 }}><Avatar name={t} size={24} ring/></span>)}</div>
            </Card>
          ))}
        </div>
      )}

      {view === 'board' && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 14, marginBottom: 18 }}>
          {Object.keys(PROJECT_STATUS_TONE).map(col => {
            const items = projects.filter(p => p.status === col);
            return (
              <div key={col}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                  <span style={{ width: 8, height: 8, borderRadius: 8, background: P[PROJECT_STATUS_TONE[col]] }}/>
                  <span style={{ fontSize: 12.5, fontWeight: 600, color: P.ink }}>{col}</span>
                  <span style={{ fontSize: 11, color: P.ink3 }}>{items.length}</span>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {items.map((pr, i) => (
                    <Card key={i} pad={13} hover onClick={() => setSelProject(pr)}>
                      <div style={{ fontSize: 13, fontWeight: 600, color: P.ink, marginBottom: 8 }}>{pr.n}</div>
                      <div style={{ height: 4, background: P.sunk, borderRadius: 4, overflow: 'hidden', marginBottom: 9 }}><div style={{ width: pr.p + '%', height: '100%', background: P[pr.tone] }}/></div>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <div style={{ display: 'flex' }}>{pr.team.map((t, j) => <span key={j} style={{ marginLeft: j ? -6 : 0 }}><Avatar name={t} size={20} ring/></span>)}</div>
                        <span style={{ fontSize: 10.5, color: P.ink3 }}>{pr.d}</span>
                      </div>
                      <div onClick={e => e.stopPropagation()} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 9, paddingTop: 8, borderTop: `1px solid ${P.line}` }}>
                        <span onClick={() => moveProject(pr.n, -1)} title="Move back a stage" style={{ cursor: STATUS_ORDER.indexOf(col) === 0 ? 'default' : 'pointer', color: STATUS_ORDER.indexOf(col) === 0 ? P.ink4 : P.ink3, display: 'inline-flex' }}><Icon name="chevL" size={14}/></span>
                        <span style={{ fontSize: 9.5, color: P.ink3, letterSpacing: 0.4, textTransform: 'uppercase' }}>Move stage</span>
                        <span onClick={() => moveProject(pr.n, 1)} title="Advance a stage" style={{ cursor: STATUS_ORDER.indexOf(col) === STATUS_ORDER.length - 1 ? 'default' : 'pointer', color: STATUS_ORDER.indexOf(col) === STATUS_ORDER.length - 1 ? P.ink4 : P.ink3, display: 'inline-flex' }}><Icon name="chevR" size={14}/></span>
                      </div>
                    </Card>
                  ))}
                  {items.length === 0 && <div style={{ fontSize: 11.5, color: P.ink3, padding: '4px 2px' }}>No projects</div>}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {view === 'timeline' && (
        <Card pad={16} style={{ marginBottom: 18 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '170px 1fr', marginBottom: 10 }}>
            <div/>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5,1fr)' }}>
              {['Feb', 'Mar', 'Apr', 'May', 'Jun'].map((m, i) => <div key={i} style={{ fontSize: 10.5, color: P.ink3, borderLeft: i ? `1px solid ${P.line}` : 'none', paddingLeft: 6 }}>{m}</div>)}
            </div>
          </div>
          {projects.map((pr, i) => (
            <div key={i} onClick={() => setSelProject(pr)} style={{ display: 'grid', gridTemplateColumns: '170px 1fr', alignItems: 'center', padding: '9px 0', borderTop: `1px solid ${P.line}`, cursor: 'pointer' }}>
              <div style={{ fontSize: 12.5, color: P.ink, fontWeight: 500, paddingRight: 10 }}>{pr.n}</div>
              <div style={{ position: 'relative', height: 20, background: P.sunk, borderRadius: 5 }}>
                <div style={{ position: 'absolute', left: pr.startPct + '%', width: (pr.endPct - pr.startPct) + '%', top: 0, bottom: 0, background: P[pr.tone], borderRadius: 5, display: 'flex', alignItems: 'center', paddingLeft: 7, minWidth: 26 }}>
                  <span style={{ fontSize: 9.5, color: '#fff', fontWeight: 600, whiteSpace: 'nowrap' }}>{pr.p}%</span>
                </div>
              </div>
            </div>
          ))}
        </Card>
      )}

      <Card>
        <div style={{ padding: '14px 18px', borderBottom: `1px solid ${P.line}`, display: 'flex', alignItems: 'center' }}><span style={{ fontSize: 14, fontWeight: 600, color: P.ink, flex: 1 }}>Class program expansion · tasks</span><span style={{ fontSize: 11.5, color: P.ink3, marginRight: 10 }}>{doneCount}/{tasks.length} done</span><Pill tone="amber">At risk</Pill></div>
        {tasks.map((t, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 18px', borderBottom: i < tasks.length - 1 ? `1px solid ${P.line}` : 'none' }}>
            <Check on={t.s} size={17} onClick={() => toggleTask(i)}/>
            <span style={{ flex: 1, fontSize: 13.5, color: P.ink, textDecoration: t.s ? 'line-through' : 'none', opacity: t.s ? 0.5 : 1 }}>{t.t}</span>
            {t.cost && <Pill tone="spark">{t.cost} ⚡</Pill>}
            <span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: P.ink3 }}>{t.pex ? <Pex size={18}/> : <Avatar name={t.o} size={18}/>}{t.o}</span>
            <span style={{ fontSize: 11.5, color: P.ink3, width: 46, textAlign: 'right' }}>{t.d}</span>
          </div>
        ))}
      </Card>

      {selProject && <ProjectProfitDrawer pr={selProject} onClose={() => setSelProject(null)}/>}
      {showNew && <NewProjectModal onCreate={p => setProjects(ps => [p, ...ps])} onClose={() => setShowNew(false)}/>}
    </window.Page>
  );
};

// ── CATALOG ──────────────────────────────────────────────────
window.SCREENS['catalog'] = function Catalog() {
  const P = window.PX; const [cat, setCat] = React.useState('rec');
  const { go, toast, sparks, setSparks, openOverlay } = window.useApp();
  const [inProd, setInProd] = React.useState([
    { t: 'Logo refresh · 3 options', p: 80, d: 'Direction 2 in review · ready ~3pm', tone: 'spark' },
    { t: 'Q1 tax pack', p: 45, d: 'Categorizing 312 transactions', tone: 'sage' },
  ]);
  const services = [
    { c: 5, t: 'Logo refresh · 3 options', bg: '#3A2A1C', tag: 'Design', desc: 'Three directions from your palette. Pick one; I apply it across site, invoices, and signature.', eta: '~6h', like: '48% order this' },
    { c: 14, t: 'March class · full campaign', bg: P.spark, tag: 'Marketing', desc: 'Email to past customers + 5 IG posts + landing page. Previous class filled.', eta: '~1 day', like: 'Receipt saved' },
    { c: 25, t: 'Wholesale deck + pricing', bg: '#2F5A82', tag: 'Strategy', desc: 'Pitch deck for new cafés + tiered pricing. Closes 40% of meetings.', eta: '~2 days', like: 'New' },
    { c: 3, t: 'About page rewrite', bg: '#D9A84C', tag: 'Website', desc: 'Fix the 2 stale facts, keep your voice, swap in a recent oven photo.', eta: '~1h', like: 'Quick win', fg: P.ink },
    { c: 8, t: 'Q1 tax pack', bg: P.sage, tag: 'Money', desc: 'Categorized transactions, estimated tax, quarterly forms ready to file.', eta: '~4h', like: 'Due in 3w' },
    { c: 4, t: 'Instagram · 7-day kit', bg: '#8C4A2A', tag: 'Marketing', desc: '7 posts, captions, hashtags. Bread photos + process reels.', eta: '~2h', like: '93% post as-is' },
    { c: 2, t: 'Invoice template · brand-matched', bg: '#F2E2C4', tag: 'Design', desc: 'Custom invoice layout with your logo and palette. Replaces the default everywhere.', eta: '~30m', like: 'Free reorder', fg: P.ink },
    { c: 10, t: 'Competitor radar · monthly', bg: '#5B2C5F', tag: 'Strategy', desc: 'Monthly 1-pager on She Wolf, Bien Cuit, L’Imprimerie — pricing, launches, press.', eta: '~8h', like: 'Recurring' },
    { c: 6, t: 'Customer gift · 10 handwritten notes', bg: '#B24A3E', tag: 'Design', desc: 'Heartfelt notes + branded card PDFs ready to print, with mailing labels.', eta: '~2h', like: 'Beta' },
  ];
  const order = (s) => {
    if (s.c > sparks) { openOverlay('creditGate', { needed: s.c, balance: sparks }); return; }
    setSparks(v => Math.max(0, v - s.c));
    setInProd(list => [{ t: s.t, p: 0, d: 'Queued · Pex is starting now', tone: s.tag === 'Money' ? 'sage' : 'spark' }, ...list]);
    window.startPexRun && window.startPexRun({ title: s.t, cost: s.c, tone: 'spark' });
    toast(`Ordered “${s.t}” — Pex is producing it. ${s.c} ⚡ spent.`, { tone: 'sage', icon: 'check' });
  };
  const CATS = { design: 'Design', marketing: 'Marketing', website: 'Website', money: 'Money', strategy: 'Strategy' };
  const shown = services.filter(s => {
    if (cat === 'rec') return true;
    if (cat === 'new') return /new|beta/i.test(s.like);
    if (cat === 'quick') return s.c < 3;
    return s.tag === CATS[cat];
  });
  return (
    <window.Page title="Catalog" sub="Made for Honest Loaves · 38 services" actions={<Btn kind="spark" size="sm" icon="zap" onClick={() => go('settings/sparks')}>Top up Sparks</Btn>}>
      {/* In-production strip */}
      <Card pad={0} style={{ marginBottom: 18 }}>
        <div style={{ padding: '12px 16px', borderBottom: `1px solid ${P.line}`, display: 'flex', alignItems: 'center', gap: 8 }}>
          <Pex size={20}/><span style={{ fontSize: 13.5, fontWeight: 600, color: P.ink, flex: 1 }}>In production · {inProd.length} order{inProd.length === 1 ? '' : 's'}</span>
          <span onClick={() => go('orders')} style={{ fontSize: 12, color: P.spark, cursor: 'pointer', fontWeight: 500 }}>View all orders</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
          {inProd.map((o, i) => (
            <div key={i} style={{ padding: '13px 16px', borderRight: i % 2 === 0 ? `1px solid ${P.line}` : 'none', borderTop: i > 1 ? `1px solid ${P.line}` : 'none' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 7 }}>
                <span style={{ width: 8, height: 8, borderRadius: 8, background: P[o.tone] }}/>
                <span style={{ fontSize: 13, fontWeight: 600, color: P.ink, flex: 1 }}>{o.t}</span>
                <span style={{ fontSize: 11, color: P.ink3 }}>{o.p}%</span>
              </div>
              <div style={{ height: 3, background: P.sunk, borderRadius: 3, overflow: 'hidden' }}><div style={{ width: o.p + '%', height: '100%', background: P[o.tone] }}/></div>
              <div style={{ fontSize: 11, color: P.ink3, marginTop: 6 }}>{o.d}</div>
            </div>
          ))}
        </div>
      </Card>

      <div style={{ display: 'flex', gap: 18, marginBottom: 18, alignItems: 'center', flexWrap: 'wrap' }}>
        {[['rec', 'Recommended'], ['new', 'New this week'], ['quick', 'Quick wins · <3⚡'], ['design', 'Design'], ['marketing', 'Marketing'], ['website', 'Website'], ['money', 'Money'], ['strategy', 'Strategy']].map(t => (
          <span key={t[0]} onClick={() => setCat(t[0])} style={{ fontSize: 13, color: cat === t[0] ? P.ink : P.ink3, fontWeight: cat === t[0] ? 600 : 500, borderBottom: `2px solid ${cat === t[0] ? P.spark : 'transparent'}`, paddingBottom: 8, cursor: 'pointer' }}>{t[1]}</span>
        ))}
      </div>
      <div style={{ marginBottom: 4, fontFamily: P.serif, fontStyle: 'italic', fontSize: 22, color: P.ink }}>Things Pex thinks you’d want</div>
      <div style={{ fontSize: 12.5, color: P.ink3, marginBottom: 18 }}>Based on your last 30 days, cash flow, calendar — and that you opened class stats 4 times this week.</div>
      {shown.length === 0 && <div style={{ padding: '28px 2px', fontSize: 12.5, color: P.ink3 }}>No services in this category yet.</div>}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
        {shown.map((s, i) => (
          <Card key={i} pad={0} hover>
            <div style={{ aspectRatio: '16/9', background: s.bg, display: 'flex', alignItems: 'flex-end', padding: 13, color: s.fg || '#fff', position: 'relative' }}>
              <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 21, lineHeight: 1.1 }}>{s.t}</div>
              <div style={{ position: 'absolute', top: 11, right: 11, background: 'rgba(255,255,255,0.18)', backdropFilter: 'blur(4px)', padding: '3px 9px', borderRadius: 7, fontSize: 11, fontWeight: 600, color: s.fg || '#fff', display: 'flex', alignItems: 'center', gap: 4 }}><Spark size={11} color={s.fg || '#fff'}/>{s.c}</div>
            </div>
            <div style={{ padding: 14 }}>
              <div style={{ display: 'flex', gap: 6, marginBottom: 8 }}><Pill>{s.tag}</Pill><Pill tone="sage">{s.like}</Pill></div>
              <div style={{ fontSize: 12.5, color: P.ink2, lineHeight: 1.5 }}>{s.desc}</div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 12 }}><span style={{ fontSize: 11.5, color: P.ink3 }}>Delivery {s.eta}</span><Btn kind="spark" size="sm" onClick={() => order(s)}>Order · {s.c} ⚡</Btn></div>
            </div>
          </Card>
        ))}
      </div>
      <Card pad={20} style={{ marginTop: 20, border: `1px dashed ${P.sparkTint}`, display: 'flex', alignItems: 'center', gap: 16 }}>
        <div style={{ width: 50, height: 50, borderRadius: 50, background: P.sparkWash, border: `1px solid ${P.sparkTint}`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Spark size={22}/></div>
        <div style={{ flex: 1 }}><div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 21, color: P.ink }}>Not on the list? Ask Pex for a custom quote.</div><div style={{ fontSize: 12.5, color: P.ink3, marginTop: 3 }}>Describe the outcome you want — Pex scopes the work, quotes it in Sparks, and you decide.</div></div>
        <Btn kind="spark" size="md" onClick={() => openOverlay('askPex')}>Request a scope</Btn>
      </Card>
    </window.Page>
  );
};

// ── INSIGHTS ─────────────────────────────────────────────────
function InsightsRevenue() {
  const P = window.PX;
  const months = [['Jan', 14200, 9800], ['Feb', 15600, 10400], ['Mar', 16100, 11200], ['Apr', 17850, 10900], ['May', 18600, 12100], ['Jun', 19420, 11700]];
  const mrr = 19420, arr = mrr * 12, max = 20000;
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14, marginBottom: 18 }}>
        <Card pad={18}><Label>MRR</Label><Num size={34} style={{ marginTop: 6 }}>{money(mrr)}</Num><div style={{ fontSize: 12, color: P.sage, marginTop: 4 }}>↑ 8.6% vs last month</div></Card>
        <Card pad={18}><Label>ARR</Label><Num size={34} style={{ marginTop: 6 }}>{money(arr)}</Num><div style={{ fontSize: 12, color: P.ink3, marginTop: 4 }}>Run-rate at current MRR</div></Card>
        <Card pad={18}><Label>Net new MRR</Label><Num size={34} color={P.sage} style={{ marginTop: 6 }}>+{money(1540)}</Num><div style={{ fontSize: 12, color: P.ink3, marginTop: 4 }}>vs prior month</div></Card>
      </div>
      <Card pad={18}>
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
          <span style={{ fontSize: 14, fontWeight: 600, color: P.ink, flex: 1 }}>Cash flow · last 6 months</span>
          <div style={{ display: 'flex', gap: 12, fontSize: 11, color: P.ink3 }}>
            <span><span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: 2, background: P.sage, marginRight: 5 }}/>In</span>
            <span><span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: 2, background: P.rose, marginRight: 5 }}/>Out</span>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 16, alignItems: 'flex-end' }}>
          {months.map((m, i) => (
            <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5 }}>
              <div style={{ display: 'flex', alignItems: 'flex-end', gap: 3, height: 110 }}>
                <div style={{ width: 14, height: (m[1] / max) * 110, background: P.sage, borderRadius: '3px 3px 0 0' }}/>
                <div style={{ width: 14, height: (m[2] / max) * 110, background: P.rose, borderRadius: '3px 3px 0 0' }}/>
              </div>
              <span style={{ fontSize: 10, color: P.ink3 }}>{m[0]}</span>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 16, paddingTop: 14, borderTop: `1px solid ${P.line}` }}>
          <Label>Net cash trend</Label><Spark2 data={months.map(m => m[1] - m[2])} color={P.spark} w={180} h={30} fill/>
        </div>
      </Card>
    </div>
  );
}

function InsightsCRM() {
  const P = window.PX;
  const stages = [['New lead', 2.1], ['Qualified', 4.6], ['Proposal sent', 6.8], ['Negotiation', 3.2], ['Closed won', 1.4]];
  const funnel = [['New lead', 100, 1], ['Qualified', 68, 0.82], ['Proposal sent', 41, 0.64], ['Negotiation', 24, 0.46], ['Closed won', 15, 0.32]];
  const won = 15, lost = 9;
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 18 }}>
        <Card pad={18}>
          <Label style={{ marginBottom: 12 }}>Pipeline velocity · avg days per stage</Label>
          {stages.map((s, i) => (
            <div key={i} style={{ marginBottom: 9 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: P.ink2, marginBottom: 3 }}><span>{s[0]}</span><span style={{ fontFamily: P.mono }}>{s[1]}d</span></div>
              <div style={{ height: 6, background: P.sunk, borderRadius: 6, overflow: 'hidden' }}><div style={{ width: (s[1] / 7 * 100) + '%', height: '100%', background: P.sky }}/></div>
            </div>
          ))}
          <div style={{ fontSize: 11.5, color: P.ink3, marginTop: 8 }}>Avg deal cycle: <b style={{ color: P.ink }}>18 days</b></div>
        </Card>
        <Card pad={18}>
          <Label style={{ marginBottom: 12 }}>Win / loss</Label>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 12 }}>
            <Num size={40} color={P.sage}>{won}</Num><span style={{ fontSize: 12, color: P.ink3 }}>won</span>
            <Num size={40} color={P.rose} style={{ marginLeft: 16 }}>{lost}</Num><span style={{ fontSize: 12, color: P.ink3 }}>lost</span>
          </div>
          <div style={{ display: 'flex', height: 10, borderRadius: 6, overflow: 'hidden', marginBottom: 8 }}>
            <div style={{ width: (won / (won + lost) * 100) + '%', background: P.sage }}/>
            <div style={{ width: (lost / (won + lost) * 100) + '%', background: P.rose }}/>
          </div>
          <div style={{ fontSize: 12.5, color: P.ink2 }}>Win rate <b style={{ color: P.ink }}>{Math.round(won / (won + lost) * 100)}%</b> · up 4pts vs last quarter</div>
        </Card>
      </div>
      <Card pad={18}>
        <Label style={{ marginBottom: 14 }}>Stage-conversion funnel</Label>
        {funnel.map((f, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
            <div style={{ width: 110, fontSize: 12, color: P.ink2 }}>{f[0]}</div>
            <div style={{ flex: 1 }}>
              <div style={{ width: f[1] + '%', height: 26, background: P.spark, opacity: f[2], borderRadius: 5, display: 'flex', alignItems: 'center', justifyContent: 'flex-end', paddingRight: 8 }}>
                <span style={{ fontSize: 11, fontWeight: 600, color: '#fff' }}>{f[1]}%</span>
              </div>
            </div>
          </div>
        ))}
      </Card>
    </div>
  );
}

function InsightsMarketing() {
  const P = window.PX;
  const channels = [['Email', 6240, 42, 'spark'], ['SEO / blog', 4180, 28, 'amber'], ['Social', 2900, 20, 'rose'], ['Ads', 1500, 10, 'sky']];
  const total = channels.reduce((s, c) => s + c[1], 0);
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14, marginBottom: 18 }}>
        <Card pad={18}><Label>Marketing-attributed revenue</Label><Num size={30} style={{ marginTop: 6 }}>{money(total)}</Num><div style={{ fontSize: 12, color: P.ink3, marginTop: 4 }}>62% of total revenue this quarter</div></Card>
        <Card pad={18}><Label>Best channel</Label><div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 22, color: P.ink, marginTop: 6 }}>Email</div><div style={{ fontSize: 12, color: P.sage, marginTop: 4 }}>123× ROI · lapsed-customer campaign</div></Card>
        <Card pad={18}><Label>Blended CAC</Label><Num size={30} style={{ marginTop: 6 }}>$34</Num><div style={{ fontSize: 12, color: P.ink3, marginTop: 4 }}>↓ $6 vs last quarter</div></Card>
      </div>
      <Card pad={18}>
        <div style={{ fontSize: 14, fontWeight: 600, color: P.ink, marginBottom: 14 }}>Revenue by channel</div>
        {channels.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>
        ))}
        <div style={{ fontSize: 11.5, color: P.ink3, marginTop: 4 }}>Full touchpoint-level breakdown lives in Marketing → Attribution.</div>
      </Card>
    </div>
  );
}

window.SCREENS['insights'] = function Insights() {
  const P = window.PX;
  const { toast, go, sparks, setSparks, openOverlay } = window.useApp();
  const [tab, setTab] = React.useState('overview');
  const [weeklyDone, setWeeklyDone] = React.useState(false);
  const [needs, setNeeds] = React.useState([
    { sev: 'high', t: 'Invoice #1024 · Café Bleu', d: '$1,420 · 11 days overdue', a: 'Let Pex nudge', cost: 1, tone: 'rose' },
    { sev: 'med', t: 'About page · stale facts', d: '"Since 2018" should be 2019 · team size outdated', a: 'Fix', cost: 3, tone: 'amber' },
    { sev: 'low', t: 'Noor (Greenpoint) · 15d quiet', d: 'Wholesale prospect cooling off', a: 'Send check-in', cost: 1, tone: 'sky' },
  ]);
  const tabs = [{ k: 'overview', label: 'Overview' }, { k: 'revenue', label: 'Revenue' }, { k: 'crm', label: 'CRM' }, { k: 'marketing', label: 'Marketing' }];
  const doWeekly = () => {
    const cost = 10;
    if (cost > sparks) { openOverlay('creditGate', { needed: cost, balance: sparks }); return; }
    setSparks(s => Math.max(0, s - cost));
    setWeeklyDone(true);
    toast('Pex is on all three — re-engaging Marc, opening a class slot, reviewing flour suppliers. 10 ⚡ spent.', { tone: 'sage', icon: 'sparkles' });
  };
  const resolveNeed = (i) => {
    const n = needs[i];
    if (n.cost > sparks) { openOverlay('creditGate', { needed: n.cost, balance: sparks }); return; }
    setSparks(s => Math.max(0, s - n.cost));
    setNeeds(list => list.filter((_, j) => j !== i));
    toast(`${n.a} — Pex is handling “${n.t}”. ${n.cost} ⚡ spent.`, { tone: 'sage', icon: 'check' });
  };
  const exportInsights = () => toast('Insights exported — a PDF snapshot is in your downloads.', { icon: 'download' });
  return (
    <window.Page title="Insights" sub="Business health · last 30 days" tabs={tabs} activeTab={tab} onTab={setTab} actions={<Btn kind="default" size="sm" icon="download" onClick={exportInsights}>Export</Btn>}>
      {tab === 'revenue' && <InsightsRevenue/>}
      {tab === 'crm' && <InsightsCRM/>}
      {tab === 'marketing' && <InsightsMarketing/>}
      {tab === 'overview' && (<>
      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 18, marginBottom: 18 }}>
        <Card pad={0}>
          <div style={{ padding: 22, height: '100%' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}><Pex size={20}/><Label>Pex’s weekly take</Label></div>
            <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 26, lineHeight: 1.3, maxWidth: 560, color: P.ink }}>Your best week of the year. Revenue up <span style={{ color: P.sage }}>22%</span>, classes outpacing wholesale, one invoice cooling off.</div>
            <div style={{ fontSize: 13, color: P.ink2, marginTop: 12, lineHeight: 1.6, maxWidth: 560 }}>Three things worth doing: re-engage Marc before Friday, open a 2nd weekly class slot (the last three filled in under a day), and review flour suppliers — your cost rose 11% and I found two cheaper ones with the same protein rating.</div>
            <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
              {weeklyDone
                ? <Pill tone="sage" icon="check">Pex is on all three</Pill>
                : <><Btn kind="spark" size="sm" onClick={doWeekly}>Do all 3 · 10 ⚡</Btn><Btn kind="default" size="sm" onClick={() => go('pex')}>Pick &amp; choose</Btn></>}
            </div>
          </div>
        </Card>
        <Card pad={20}>
          <Label>Health score</Label>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, marginTop: 4 }}><Num size={56}>84</Num><span style={{ fontSize: 20, color: P.ink3 }}>/100</span></div>
          <div style={{ fontSize: 12.5, color: P.sage, marginBottom: 14 }}>↑ 6 vs last month · Strong</div>
          {[['Cash runway · 4.2mo', 82], ['Receivables age · 18d', 71], ['Pipeline · $24.9k', 88], ['Repeat customers · 43%', 76]].map((m, i) => (
            <div key={i} style={{ marginTop: 9 }}><div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, color: P.ink2 }}><span>{m[0]}</span><span>{m[1]}</span></div><div style={{ height: 4, background: P.sunk, borderRadius: 4, marginTop: 3, overflow: 'hidden' }}><div style={{ width: m[1] + '%', height: '100%', background: m[1] > 80 ? P.sage : m[1] > 70 ? P.amber : P.rose }}/></div></div>
          ))}
        </Card>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14, marginBottom: 18 }}>
        <Card pad={16}><Label>Revenue sources · MTD</Label>
          <div style={{ display: 'flex', gap: 4, height: 96, alignItems: 'flex-end', marginTop: 12 }}>
            {[['Whlsl', '$9.2k', 9.2, 'sage'], ['Class', '$4.8k', 4.8, 'spark'], ['Shop', '$3.1k', 3.1, 'sky'], ['Event', '$1.5k', 1.5, 'amber']].map((b, i) => (
              <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, justifyContent: 'flex-end' }}><span style={{ fontFamily: P.mono, fontSize: 9.5, color: P.ink3 }}>{b[1]}</span><div style={{ width: '70%', height: b[2] * 7, background: P[b[3]], borderRadius: 4 }}/><span style={{ fontSize: 10, color: P.ink3 }}>{b[0]}</span></div>
            ))}
          </div>
        </Card>
        <Card pad={16}><Label>Website · 7d</Label><Num size={26} style={{ marginTop: 4 }}>2,418</Num><Spark2 data={[4,5,4,6,7,6,8]} color={P.spark} w={200} h={36} fill/>
          <div style={{ display: 'flex', gap: 10, fontSize: 10, color: P.ink3, marginTop: 6 }}><span>Google 41%</span><span>Instagram 28%</span><span>Direct 22%</span></div>
        </Card>
        <Card pad={16}><Label>Sparks burn</Label><Num size={26} style={{ marginTop: 4 }}>142 left</Num><div style={{ fontSize: 11, color: P.ink3, marginBottom: 6 }}>≈ 11 days · 13/day</div><Spark2 data={[6,5,7,6,8,7,9]} color={P.amber} w={200} h={30}/>
          <div style={{ fontSize: 10, color: P.ink3, marginTop: 6 }}>Biggest spend: March class campaign · 14 ⚡</div>
        </Card>
      </div>
      <Card>
        <div style={{ padding: '14px 18px', borderBottom: `1px solid ${P.line}`, display: 'flex', alignItems: 'center' }}><span style={{ fontSize: 14, fontWeight: 600, color: P.ink, flex: 1 }}>What needs you · {needs.length} item{needs.length === 1 ? '' : 's'}</span>{needs.some(n => n.sev === 'high') && <Pill tone="rose" dot>1 urgent</Pill>}</div>
        {needs.length === 0 && <div style={{ padding: '18px', fontSize: 12.5, color: P.ink3 }}>All clear — nothing needs you right now.</div>}
        {needs.map((x, i) => (
          <div key={i} style={{ padding: '13px 18px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: i < needs.length - 1 ? `1px solid ${P.line}` : 'none' }}>
            <div style={{ width: 4, alignSelf: 'stretch', minHeight: 30, background: P[x.tone], borderRadius: 3 }}/>
            <div style={{ flex: 1 }}><div style={{ fontSize: 13.5, color: P.ink, fontWeight: 500 }}>{x.t}</div><div style={{ fontSize: 11.5, color: P.ink3 }}>{x.d}</div></div>
            <Pill tone={x.tone}>{x.sev}</Pill>
            <Btn kind="spark" size="sm" onClick={() => resolveNeed(i)}>{x.a} · {x.cost} ⚡</Btn>
          </div>
        ))}
      </Card>
      </>)}
    </window.Page>
  );
};

// ── PEX full view ────────────────────────────────────────────

// Chronological Spark ledger — purchases (+) and consumption (−), running balance.
function PexLedger() {
  const P = window.PX;
  const costOf = (id, fallback) => (window.PROPOSALS_SEED && window.PROPOSALS_SEED.find(p => p.id === id)?.cost) || fallback;
  const entries = [
    { d: 'Mar 1 · 9:00am', t: 'Monthly Spark top-up', delta: 200 },
    { d: 'Mar 3 · 8:14am', t: 'Instagram · 7-day kit', delta: -4 },
    { d: 'Mar 5 · 2:40pm', t: 'Logo refresh · 3 options', delta: -5 },
    { d: 'Mar 8 · 11:02am', t: 'Q1 tax estimate', delta: -2 },
    { d: 'Mar 10 · 7:12am', t: 'Chase Café Bleu\'s overdue invoice', delta: -costOf('p1', 1) },
    { d: 'Mar 10 · 7:20am', t: 'Launch the March class email', delta: -costOf('p3', 4) },
    { d: 'Mar 11 · 9:30am', t: 'Fix 2 stale facts on About page', delta: -costOf('p2', 3) },
    { d: 'Mar 12 · 6:00am', t: 'Reorder flour before Thursday', delta: -costOf('p5', 1) },
    { d: 'Mar 15 · 9:00am', t: 'Spark bundle · 50', delta: 50 },
    { d: 'Mar 18 · 4:10pm', t: 'Client gift · 10 handwritten notes', delta: -6 },
  ];
  const currentBalance = 142;
  let running = currentBalance - entries.reduce((s, e) => s + e.delta, 0);
  const rows = entries.map(e => { running += e.delta; return { ...e, bal: running }; });

  return (
    <Card pad={0}>
      <div style={{ padding: '14px 18px', borderBottom: `1px solid ${P.line}`, display: 'flex', alignItems: 'center' }}>
        <span style={{ fontSize: 14, fontWeight: 600, color: P.ink, flex: 1 }}>Spark ledger</span>
        <span style={{ fontSize: 12, color: P.ink3 }}>Balance <b style={{ color: P.spark }}>{currentBalance} ⚡</b></span>
      </div>
      {rows.map((r, i) => (
        <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 18px', borderBottom: i < rows.length - 1 ? `1px solid ${P.line}` : 'none' }}>
          <span style={{ width: 26, height: 26, borderRadius: 26, background: r.delta > 0 ? P.sageWash : P.sunk, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name={r.delta > 0 ? 'arrowUp' : 'arrowDown'} size={13} color={r.delta > 0 ? P.sage : P.ink3}/>
          </span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, color: P.ink, fontWeight: 500 }}>{r.t}</div>
            <div style={{ fontSize: 11, color: P.ink3 }}>{r.d}</div>
          </div>
          <span style={{ fontFamily: P.mono, fontSize: 13, fontWeight: 600, color: r.delta > 0 ? P.sage : P.ink2, width: 44, textAlign: 'right' }}>{r.delta > 0 ? '+' : ''}{r.delta}⚡</span>
          <span style={{ fontFamily: P.mono, fontSize: 11.5, color: P.ink3, width: 56, textAlign: 'right' }}>{r.bal}⚡</span>
        </div>
      ))}
    </Card>
  );
}

// Proposal history — Accepted / Dismissed / Learning, sourced from live pexProposals + mocked volume.
function PexHistory({ pexProposals }) {
  const P = window.PX;
  const accepted = (pexProposals || []).filter(p => p.status === 'approved').map(p => ({ title: p.title, ctx: p.ctx }));
  const dismissed = (pexProposals || []).filter(p => p.status === 'snoozed').map(p => ({ title: p.title, ctx: p.ctx }));
  const mockAccepted = [
    { title: 'Instagram · 7-day kit', ctx: 'Posted as-is · 93% engagement lift week over week.' },
    { title: 'Invoice template · brand-matched', ctx: 'Applied across all 18 open invoices.' },
    { title: 'Competitor radar · February', ctx: 'Flagged She Wolf\'s new price drop before it hit socials.' },
  ];
  const mockDismissed = [
    { title: 'Weekend flash sale email', ctx: 'Dismissed — too soon after the January sale.' },
    { title: 'Rebrand the invoice PDF footer', ctx: 'Dismissed — no strong reason given.' },
  ];
  const learning = [
    { title: 'Weekend flash sale email', note: 'Pex noticed a pattern from this dismissal and now spaces promotional sends at least 3 weeks apart.' },
    { title: 'Rebrand the invoice PDF footer', note: 'Pex noticed a pattern from this dismissal and adjusted — it now proposes brand changes only alongside a broader visual refresh.' },
    { title: 'Wedding cake inquiry follow-up', note: 'Pex noticed you always personalize event replies yourself and stopped proposing drafts for that category.' },
  ];
  const Section = ({ label, tone, items, empty }) => (
    <Card pad={0} style={{ marginBottom: 16 }}>
      <div style={{ padding: '12px 18px', borderBottom: `1px solid ${P.line}`, display: 'flex', alignItems: 'center', gap: 8 }}>
        <Pill tone={tone}>{label}</Pill><span style={{ fontSize: 11.5, color: P.ink3 }}>{items.length} item{items.length === 1 ? '' : 's'}</span>
      </div>
      {items.length === 0 && <div style={{ padding: '14px 18px', fontSize: 12.5, color: P.ink3 }}>{empty}</div>}
      {items.map((it, i) => (
        <div key={i} style={{ padding: '12px 18px', borderBottom: i < items.length - 1 ? `1px solid ${P.line}` : 'none' }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: P.ink }}>{it.title}</div>
          <div style={{ fontSize: 12, color: P.ink3, marginTop: 3, lineHeight: 1.5 }}>{it.ctx}</div>
        </div>
      ))}
    </Card>
  );
  return (
    <div>
      <Section label="Accepted" tone="sage" items={[...accepted, ...mockAccepted]} empty="Nothing approved yet."/>
      <Section label="Dismissed" tone="rose" items={[...dismissed, ...mockDismissed]} empty="Nothing dismissed."/>
      <Card pad={0}>
        <div style={{ padding: '12px 18px', borderBottom: `1px solid ${P.line}`, display: 'flex', alignItems: 'center', gap: 8 }}>
          <Pill tone="spark"><Spark size={11}/>Learning</Pill><span style={{ fontSize: 11.5, color: P.ink3 }}>{learning.length} patterns adjusted</span>
        </div>
        {learning.map((l, i) => (
          <div key={i} style={{ display: 'flex', gap: 10, padding: '12px 18px', borderBottom: i < learning.length - 1 ? `1px solid ${P.line}` : 'none' }}>
            <Pex size={22}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: P.ink }}>{l.title}</div>
              <div style={{ fontSize: 12, color: P.ink2, marginTop: 3, lineHeight: 1.5, fontStyle: 'italic' }}>{l.note}</div>
            </div>
          </div>
        ))}
      </Card>
    </div>
  );
}

// Step-by-step execution pipeline drawer for an in-progress (or completed) Pex run.
function PexPipelineDrawer({ run, onClose }) {
  const P = window.PX;
  return (
    <window.Drawer title={run.t} sub="Execution pipeline" tag={<Pill tone={run.p === 100 ? 'sage' : 'spark'}>{run.p === 100 ? 'Complete' : 'In progress'}</Pill>} onClose={onClose}
      foot={<Btn kind="default" size="sm" full onClick={onClose}>Close</Btn>}>
      {run.steps.map((s, i) => (
        <div key={i} style={{ display: 'flex', gap: 12, paddingBottom: i < run.steps.length - 1 ? 18 : 2 }}>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <span style={{ width: 20, height: 20, borderRadius: 20, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
              background: s.status === 'done' ? P.sage : s.status === 'active' ? P.spark : P.sunk,
              border: s.status === 'pending' ? `1.5px solid ${P.lineStrong}` : 'none' }}>
              {s.status === 'done' && <Icon name="check" size={11} color="#fff" stroke={3}/>}
              {s.status === 'active' && <span style={{ width: 7, height: 7, borderRadius: 7, background: '#fff' }}/>}
            </span>
            {i < run.steps.length - 1 && <span style={{ width: 1.5, flex: 1, minHeight: 20, background: P.line, marginTop: 2 }}/>}
          </div>
          <div style={{ flex: 1, paddingBottom: 4 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: s.status === 'pending' ? P.ink3 : P.ink }}>{s.label}</div>
            <div style={{ fontSize: 12, color: P.ink3, marginTop: 3, lineHeight: 1.5 }}>{s.log}</div>
          </div>
        </div>
      ))}
    </window.Drawer>
  );
}

window.SCREENS['pex'] = function PexFull() {
  const P = window.PX;
  const { pexProposals, sparks, setSparks, toast } = window.useApp();
  const [tab, setTab] = React.useState('chat');
  const [pipeline, setPipeline] = React.useState(null);
  const [input, setInput] = React.useState('');
  const [messages, setMessages] = React.useState([]);
  const storeRuns = window.useStore(window.PXPex).runs;

  // Pull in a prompt handed over from the Ask-Pex modal.
  React.useEffect(() => {
    const dp = window.PXPex.takeDraftPrompt();
    if (dp) {
      setMessages([{ who: 'you', text: dp }, { who: 'pex', text: `Got it — I’ll scope “${dp.slice(0, 60)}${dp.length > 60 ? '…' : ''}”, come back with a short plan and a Spark estimate.` }]);
    }
  }, []);

  const sendMsg = (text) => {
    const v = (text != null ? text : input).trim();
    if (!v) return;
    setMessages(m => [...m, { who: 'you', text: v }]);
    setInput('');
    setTimeout(() => setMessages(m => [...m, { who: 'pex', text: 'On it — scoping that now and I’ll follow up with a plan and a Spark estimate.' }]), 650);
  };

  const approveCard = (pp) => {
    if (pp.c > sparks) { toast(`That needs ${pp.c} ⚡ — you have ${sparks}. Top up in Settings.`, { tone: 'rose', icon: 'zap' }); return; }
    setSparks(s => Math.max(0, s - pp.c));
    window.startPexRun({ title: pp.t, cost: pp.c, tone: pp.tone });
    toast(`Approved — Pex is on it. ${pp.c} ⚡ spent.`, { tone: 'sage', icon: 'check' });
  };

  // Real approved runs (auto-advancing) shown above the scripted demo runs.
  const mappedRuns = storeRuns.map(r => {
    const v = window.pexRunView(r);
    const firstPending = r.steps.findIndex(s => s.state !== 'done');
    return { t: r.title, p: v.p, d: v.d, steps: r.steps.map((s, i) => ({ label: s.label, status: s.state === 'done' ? 'done' : (i === firstPending ? 'active' : 'pending'), log: s.state === 'done' ? 'Completed.' : (i === firstPending ? 'In progress…' : 'Queued.') })) };
  });

  const liveRuns = [
    { t: 'Café Bleu reminder', p: 100, d: 'Sent 7:12am · opened 7:14am · ⚡1 charged', steps: [
      { label: 'Understanding request', status: 'done', log: 'Pulled invoice #1024 · 11 days overdue · $1,420.' },
      { label: 'Drafting', status: 'done', log: 'Three-paragraph nudge drafted, warm tone, payment date ask.' },
      { label: 'Reviewing', status: 'done', log: 'Checked against past correspondence with Marc — no conflicts.' },
      { label: 'Ready', status: 'done', log: 'Sent 7:12am · opened 7:14am.' },
    ] },
    { t: 'March class email', p: 64, d: 'Writing block 4 of 5 · ⚡4 to charge', steps: [
      { label: 'Understanding request', status: 'done', log: 'Parsed campaign brief · subscriber segment resolved (142).' },
      { label: 'Drafting', status: 'done', log: 'Subject line + 3-paragraph body drafted, tone matched to brand voice.' },
      { label: 'Reviewing', status: 'active', log: 'Checking links, unsubscribe footer, and CTA against brand guide.' },
      { label: 'Ready', status: 'pending', log: 'Awaiting review pass before scheduling Wed 9am send.' },
    ] },
  ];

  return (
    <div style={{ display: 'flex', height: '100%', fontFamily: P.sans }}>
      <div style={{ width: 250, borderRight: `1px solid ${P.line}`, background: P.canvas, overflow: 'auto', flexShrink: 0 }}>
        <div style={{ padding: 14 }}><Btn kind="primary" size="md" full icon="sparkles" onClick={() => { setMessages([]); setTab('chat'); toast('Fresh conversation — what do you want to get done?', { icon: 'sparkles' }); }}>New conversation</Btn></div>
        <Label style={{ padding: '4px 16px 6px' }}>Pinned</Label>
        {[['Weekly proposals · Mar 12', '5 items · 15 ⚡', true], ['March class campaign', '2 of 5 steps', false]].map((c, i) => (
          <div key={i} onClick={() => { setTab('chat'); sendMsg(`Open: ${c[0]}`); }} style={{ padding: '10px 16px', background: c[2] ? P.card : 'transparent', borderLeft: `3px solid ${c[2] ? P.spark : 'transparent'}`, cursor: 'pointer' }}>
            <div style={{ fontSize: 12.5, fontWeight: 600, color: P.ink }}>{c[0]}</div><div style={{ fontSize: 11, color: P.ink3, marginTop: 2 }}>{c[1]}</div>
          </div>
        ))}
        <Label style={{ padding: '14px 16px 6px' }}>Recent</Label>
        {['Logo refinement · 3 options', 'Competitor recon: Bien Cuit', 'Tax Q1 estimate', 'Client gift ideas', 'Wedding cake inquiry'].map((t, i) => (
          <div key={i} onClick={() => { setTab('chat'); sendMsg(t); }} style={{ padding: '8px 16px', fontSize: 12.5, color: P.ink2, cursor: 'pointer' }}
            onMouseEnter={e => e.currentTarget.style.background = P.hover} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>{t}</div>
        ))}
      </div>

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
        <div style={{ padding: '12px 36px 0' }}>
          <Tabs tabs={[{ k: 'chat', label: 'Conversation' }, { k: 'ledger', label: 'Spark ledger' }, { k: 'history', label: 'History' }]} active={tab} onChange={setTab}/>
        </div>
        <div style={{ flex: 1, overflow: 'auto', padding: '20px 36px' }}>
          {tab === 'chat' && (<>
          <div style={{ textAlign: 'center', fontSize: 10.5, color: P.ink3, textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 18 }}>Tuesday · 7:02am</div>
          <div style={{ display: 'flex', gap: 12, marginBottom: 18 }}>
            <Pex size={32}/>
            <div style={{ maxWidth: 640 }}>
              <div style={{ display: 'flex', gap: 8, alignItems: 'baseline', marginBottom: 5 }}><span style={{ fontSize: 13, fontWeight: 600, color: P.ink }}>Pex</span><span style={{ fontSize: 11, color: P.ink3 }}>7:02am</span></div>
              <div style={{ background: P.card, border: `1px solid ${P.line}`, padding: 14, borderRadius: '4px 14px 14px 14px', fontSize: 14, color: P.ink, lineHeight: 1.55 }}>Morning, Amara. I went through the weekend — 11 new orders, a cold lead from Instagram, and a flour email you missed. I pulled together <b>5 proposals</b>. Two feel urgent (the overdue Café Bleu invoice especially). Cost if you say yes to all: <b style={{ color: P.spark }}>15 ⚡</b>.</div>
            </div>
          </div>
          <div style={{ marginLeft: 44, display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 18 }}>
            {[
              { t: 'Chase Café Bleu\'s $1,420 invoice', c: 1, tone: 'rose', body: 'A warm three-paragraph nudge — not pushy, references the relationship, asks for a payment date. PDF attached.' },
              { t: 'Rewrite the About page', c: 3, tone: 'amber', body: '"Since 2018" → 2019, "two bakers" → five. Keep the voice, refresh 4 paragraphs, swap in a recent oven photo.' },
              { t: 'Launch the March class email', c: 4, tone: 'sage', body: 'New subject + 3-paragraph body, send Wed 9am. A/B the CTA. Auto-follow-up Fri for non-openers.' },
            ].map((pp, i) => (
              <Card key={i} pad={14}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                  <div style={{ width: 3, height: 16, background: P[pp.tone], borderRadius: 3 }}/>
                  <span style={{ fontSize: 14, fontWeight: 600, color: P.ink, flex: 1 }}>{pp.t}</span>
                  <Pill tone="spark"><Spark size={11}/>{pp.c}</Pill>
                </div>
                <div style={{ fontSize: 12.5, color: P.ink2, lineHeight: 1.5, marginBottom: 10 }}>{pp.body}</div>
                <div style={{ display: 'flex', gap: 6 }}><Btn kind="primary" size="sm" onClick={() => approveCard(pp)}>Approve · {pp.c} ⚡</Btn><Btn kind="default" size="sm" onClick={() => sendMsg(`Show me a preview of: ${pp.t}`)}>Preview</Btn><Btn kind="ghost" size="sm" onClick={() => sendMsg(`I want to modify: ${pp.t}`)}>Modify</Btn></div>
              </Card>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 12, justifyContent: 'flex-end', marginBottom: 18 }}>
            <div style={{ maxWidth: 440 }}>
              <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginBottom: 5 }}><span style={{ fontSize: 11, color: P.ink3 }}>7:11am</span><span style={{ fontSize: 13, fontWeight: 600, color: P.ink }}>You</span></div>
              <div style={{ background: P.sparkWash, border: `1px solid ${P.sparkTint}`, color: P.ink, padding: 14, borderRadius: '14px 4px 14px 14px', fontSize: 14, lineHeight: 1.5 }}>approve café bleu and the class email. hold the About page — show me the photos first.</div>
            </div>
            <Avatar name="Amara Okafor" size={32}/>
          </div>
          <div style={{ display: 'flex', gap: 12 }}>
            <Pex size={32}/>
            <div style={{ maxWidth: 640, flex: 1 }}>
              <Card pad={14}>
                <div style={{ fontSize: 14, color: P.ink, lineHeight: 1.5, marginBottom: 12 }}>On it. Executing 2, holding About. Live status — click a run to see its pipeline:</div>
                {[...mappedRuns, ...liveRuns].map((x, i) => (
                  <div key={i} onClick={() => setPipeline(x)} style={{ padding: '10px 0', borderTop: i ? `1px solid ${P.line}` : 'none', cursor: 'pointer' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 5 }}><span style={{ width: 8, height: 8, borderRadius: 8, background: x.p === 100 ? P.sage : P.spark }}/><span style={{ fontSize: 13, fontWeight: 500, color: P.ink, flex: 1 }}>{x.t}</span><span style={{ fontSize: 11, color: P.ink3 }}>{x.p}%</span><Icon name="chevR" size={13} color={P.ink3}/></div>
                    <div style={{ height: 3, background: P.sunk, borderRadius: 3, overflow: 'hidden' }}><div style={{ width: x.p + '%', height: '100%', background: x.p === 100 ? P.sage : P.spark }}/></div>
                    <div style={{ fontSize: 11, color: P.ink3, marginTop: 5 }}>{x.d}</div>
                  </div>
                ))}
              </Card>
            </div>
          </div>
          {messages.map((m, i) => m.who === 'pex' ? (
            <div key={i} style={{ display: 'flex', gap: 12, marginTop: 18 }}>
              <Pex size={32}/>
              <div style={{ maxWidth: 640 }}>
                <div style={{ display: 'flex', gap: 8, alignItems: 'baseline', marginBottom: 5 }}><span style={{ fontSize: 13, fontWeight: 600, color: P.ink }}>Pex</span><span style={{ fontSize: 11, color: P.ink3 }}>now</span></div>
                <div style={{ background: P.card, border: `1px solid ${P.line}`, padding: 14, borderRadius: '4px 14px 14px 14px', fontSize: 14, color: P.ink, lineHeight: 1.55 }}>{m.text}</div>
              </div>
            </div>
          ) : (
            <div key={i} style={{ display: 'flex', gap: 12, justifyContent: 'flex-end', marginTop: 18 }}>
              <div style={{ maxWidth: 440 }}>
                <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginBottom: 5 }}><span style={{ fontSize: 11, color: P.ink3 }}>now</span><span style={{ fontSize: 13, fontWeight: 600, color: P.ink }}>You</span></div>
                <div style={{ background: P.sparkWash, border: `1px solid ${P.sparkTint}`, color: P.ink, padding: 14, borderRadius: '14px 4px 14px 14px', fontSize: 14, lineHeight: 1.5 }}>{m.text}</div>
              </div>
              <Avatar name="Amara Okafor" size={32}/>
            </div>
          ))}
          </>)}

          {tab === 'ledger' && <PexLedger/>}
          {tab === 'history' && <PexHistory pexProposals={pexProposals}/>}
        </div>
        {tab === 'chat' && (
          <div style={{ padding: 16, borderTop: `1px solid ${P.line}` }}>
            <div style={{ background: P.card, border: `1px solid ${P.lineStrong}`, borderRadius: 12, padding: 12 }}>
              <textarea value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMsg(); } }} placeholder="Tell Pex what you need. @mention a contact, # an invoice, or drop a file." style={{ width: '100%', border: 'none', background: 'transparent', outline: 'none', resize: 'none', minHeight: 40, fontSize: 14, color: P.ink, fontFamily: P.sans, lineHeight: 1.5 }}/>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <Icon name="paperclip" size={16} color={P.ink3}/><Icon name="at" size={16} color={P.ink3}/><Icon name="hash" size={16} color={P.ink3}/>
                <div style={{ flex: 1 }}/>
                <span style={{ fontSize: 11.5, color: P.ink3 }}>est. <b style={{ color: P.spark }}>? ⚡</b></span>
                <Btn kind="spark" size="sm" iconR="arrowRight" onClick={() => sendMsg()}>Send</Btn>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* context rail — what Pex is using + recent deliveries */}
      <div style={{ width: 280, borderLeft: `1px solid ${P.line}`, background: P.canvas, overflow: 'auto', flexShrink: 0, padding: 16 }}>
        <Label style={{ marginBottom: 8 }}>Context Pex is using</Label>
        {[['CRM', '12 contacts · 3 active deals'], ['Money', '18 invoices · 3 overdue'], ['Calendar', 'Next 7 days · 11 events'], ['Email', 'Last 30 days'], ['Website', '7 pages · last edit Feb 8'], ['Brand', 'honestloaves.com · 4 colors']].map((r, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', background: P.card, border: `1px solid ${P.line}`, borderRadius: 8, marginBottom: 5 }}>
            <div style={{ flex: 1 }}><div style={{ fontSize: 11.5, fontWeight: 600, color: P.ink }}>{r[0]}</div><div style={{ fontSize: 10.5, color: P.ink3 }}>{r[1]}</div></div>
            <span style={{ width: 6, height: 6, borderRadius: 6, background: P.sage }}/>
          </div>
        ))}
        <Label style={{ margin: '18px 0 8px' }}>Recent deliveries</Label>
        {[['penTool', 'Logo v3 · Honest Loaves', 'Fri · 5 ⚡'], ['pie', 'Q1 tax estimate', 'Thu · 2 ⚡'], ['image', 'Instagram · 3 posts', 'Wed · 4 ⚡']].map((r, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 0', borderBottom: i < 2 ? `1px solid ${P.line}` : 'none' }}>
            <div style={{ width: 30, height: 30, borderRadius: 8, background: P.sunk, color: P.ink2, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={r[0]} size={15}/></div>
            <div style={{ flex: 1 }}><div style={{ fontSize: 12, color: P.ink, fontWeight: 500 }}>{r[1]}</div><div style={{ fontSize: 10.5, color: P.ink3 }}>{r[2]}</div></div>
          </div>
        ))}
      </div>

      {pipeline && <PexPipelineDrawer run={pipeline} onClose={() => setPipeline(null)}/>}
    </div>
  );
};
