// ════════════ HOME — the morning loop (Pex proposals are the thesis) ════════════
const { Icon, Spark, Pex, Avatar, Card, Btn, Pill, Label, Num, Spark2, Page } = window;

window.SCREENS['home'] = function Home() {
  const P = window.PX; const { go, openOverlay, sparks, setSparks, toast, pexProposals, actProposal } = window.useApp();
  const pending = pexProposals.filter(p => p.status === 'pending');
  const totalCost = pending.reduce((a, p) => a + p.cost, 0);
  const b = window.useBank ? window.useBank() : null;
  const inv = window.PXInvoices ? window.useStore(window.PXInvoices).invoices : [];
  const op = b && b.accounts.find(a => a.id === 'op');
  const owed = inv.filter(i => i.status === 'sent' || i.status === 'overdue').reduce((a, i) => a + i.amt, 0);
  const $0 = (n) => '$' + Math.round(n).toLocaleString();
  const [hideTake, setHideTake] = React.useState(false);
  const [exporting, setExporting] = React.useState(false);
  const [checklist, setChecklist] = React.useState([['Review your website', true], ['Import contacts', true], ['Send first invoice', true], ['Approve a Pex proposal', true], ['Connect Stripe payouts', true], ['Set up payment terms', false], ['Invite a teammate', false]]);
  const toggleCheck = (i) => setChecklist(c => c.map((r, j) => j === i ? [r[0], !r[1]] : r));
  const doneCount = checklist.filter(r => r[1]).length;
  const exportDash = () => { setExporting(true); setTimeout(() => { setExporting(false); toast('Dashboard exported — download started.', { tone: 'sage', icon: 'download' }); }, 900); };
  const planIt = () => {
    if (8 > sparks) { openOverlay('creditGate', { needed: 8, balance: sparks }); return; }
    setSparks(s => Math.max(0, s - 8));
    window.startPexRun && window.startPexRun({ title: 'Plan a second weekly class', cost: 8, tone: 'spark' });
    setHideTake(true);
    toast('On it — Pex is planning a second weekly class slot. 8 ⚡ spent.', { tone: 'sage', icon: 'check' });
  };

  return (
    <Page title="Good morning, Amara." sub="Tuesday, March 12 · Brooklyn"
      actions={<><Btn kind="default" icon="download" size="sm" loading={exporting} onClick={exportDash}>Export</Btn><Btn kind="spark" icon="sparkles" size="sm" onClick={() => openOverlay('askPex')}>Ask Pex</Btn></>}>

      <div style={{ fontSize: 14, color: P.ink2, lineHeight: 1.5, marginTop: -6, marginBottom: 20, maxWidth: 760 }}>
        A quiet weekend — <b style={{ color: P.sage }}>$842 came in</b>, <b style={{ color: P.rose }}>$1,420 is overdue</b>, and Pex left <b style={{ color: P.ink }}>{pending.length} things</b> on your desk. The bakery's looking healthy.
      </div>

      {/* KPI row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 18 }}>
        {[
          { l: 'Cash on hand', v: op ? $0(op.balance) : '$12,408', d: '+$842 this week', tone: 'sage', up: true, data: [4,5,4,6,5,7,8,8], r: 'money/accounts' },
          { l: 'Owed to you', v: $0(owed), d: `${inv.filter(i => i.status === 'sent' || i.status === 'overdue').length} invoices · ${inv.filter(i => i.status === 'overdue').length} late`, tone: 'rose', up: false, data: [5,3,4,6,7,6,5,4], r: 'money/invoices' },
          { l: 'Revenue · MTD', v: '$18,640', d: '+22% vs Feb', tone: 'sky', up: true, data: [2,3,4,4,5,7,8,9], r: 'money/reports' },
          { l: 'Sparks left', v: sparks + '', d: '≈ 11 days', tone: 'spark', up: true, data: [9,8,7,8,7,6,7,6], r: 'settings/sparks' },
        ].map((c, i) => (
          <Card key={i} pad={16} hover onClick={() => go(c.r)}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <Label>{c.l}</Label>
              <Icon name={c.up ? 'trendUp' : 'trendDown'} size={15} color={P[c.tone]}/>
            </div>
            <Num size={28} style={{ marginTop: 8 }}>{c.v}</Num>
            <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginTop: 8 }}>
              <span style={{ fontSize: 11.5, color: P.ink3 }}>{c.d}</span>
              <Spark2 data={c.data} color={P[c.tone]} w={56} h={20} fill/>
            </div>
          </Card>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 18 }}>
        {/* LEFT — the Pex proposal loop (the whole thesis) */}
        <Card pad={0} style={{ height: 'fit-content' }}>
          <div style={{ padding: '15px 18px', borderBottom: `1px solid ${P.line}`, display: 'flex', alignItems: 'center', gap: 11 }}>
            <Pex size={32} glow/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14.5, fontWeight: 700, color: P.ink }}>Pex worked overnight · {pending.length} proposals</div>
              <div style={{ fontSize: 11.5, color: P.ink3 }}>Approve, preview, or tell me to wait.</div>
            </div>
            {pending.length > 0 && <div style={{ textAlign: 'right' }}><div style={{ fontSize: 11, color: P.ink3 }}>All for</div><div style={{ fontSize: 13, fontWeight: 700, color: P.sparkDim, display: 'flex', alignItems: 'center', gap: 3 }}><Spark size={12}/>{totalCost}</div></div>}
          </div>

          {pending.length === 0 && (
            <div style={{ padding: '40px 18px', textAlign: 'center' }}>
              <div style={{ width: 44, height: 44, borderRadius: 44, background: P.sageTint, color: P.sage, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px' }}><Icon name="check" size={22} stroke={2.4}/></div>
              <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 20, color: P.ink }}>Desk cleared.</div>
              <div style={{ fontSize: 12.5, color: P.ink3, marginTop: 4 }}>Pex will keep working and bring you the next batch.</div>
            </div>
          )}

          {pending.map((p, i) => (
            <div key={p.id} style={{ padding: '14px 18px', borderBottom: i < pending.length - 1 ? `1px solid ${P.line}` : 'none', display: 'flex', gap: 12, alignItems: 'flex-start' }}>
              <div style={{ width: 3, alignSelf: 'stretch', minHeight: 40, background: P[p.tone], borderRadius: 3, flexShrink: 0 }}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 5 }}>
                  <Pill tone={p.tone} style={{ fontSize: 10 }}>{p.tag}</Pill>
                  {p.urgent && <Pill tone="rose" style={{ fontSize: 10 }}>urgent</Pill>}
                </div>
                <div style={{ fontSize: 14, color: P.ink, lineHeight: 1.35, fontWeight: 600 }}>{p.title}</div>
                <div style={{ fontSize: 12, color: P.ink3, marginTop: 4 }}>{p.ctx}</div>
                {p.preview && <div style={{ fontSize: 12, color: P.ink2, fontStyle: 'italic', marginTop: 8, padding: '8px 11px', background: P.sunk, borderRadius: 8, borderLeft: `2px solid ${P.lineStrong}` }}>"{p.preview}"</div>}
                <div style={{ display: 'flex', gap: 7, marginTop: 11, alignItems: 'center' }}>
                  <Btn kind="spark" size="sm" icon="check" onClick={() => actProposal(p.id, 'approved')}>Approve · {p.cost} ⚡</Btn>
                  <Btn kind="default" size="sm" onClick={() => openOverlay('proposalPreview', { proposal: p })}>Preview</Btn>
                  <span onClick={() => actProposal(p.id, 'snoozed')} style={{ fontSize: 12, color: P.ink3, cursor: 'pointer', padding: '0 6px' }}>Snooze</span>
                </div>
              </div>
            </div>
          ))}
        </Card>

        {/* RIGHT — today, setup, insight */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <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 }}>Today</span>
              <span onClick={() => go('calendar')} style={{ fontSize: 12, color: P.spark, cursor: 'pointer' }}>Calendar →</span>
            </div>
            {[
              { time: '9:00', t: 'Coffee with Marc · Café Bleu', tone: 'sky', prep: 'Pex prepped 4 talking points' },
              { time: '11:30', t: 'Flour delivery', tone: 'amber' },
              { time: '2:00', t: 'March class email goes out', tone: 'spark', prep: 'Approve it on the left first' },
              { time: '4:30', t: 'Payroll run', tone: 'sage' },
            ].map((e, i) => (
              <div key={i} onClick={() => go('calendar')} style={{ padding: '10px 18px', display: 'flex', gap: 12, borderBottom: i < 3 ? `1px solid ${P.line}` : 'none', cursor: 'pointer' }}
                onMouseEnter={ev => ev.currentTarget.style.background = P.hover} onMouseLeave={ev => ev.currentTarget.style.background = 'transparent'}>
                <div style={{ fontFamily: P.mono, fontSize: 12, color: P.ink3, width: 40, flexShrink: 0 }}>{e.time}</div>
                <div style={{ width: 2, background: P[e.tone], borderRadius: 2, flexShrink: 0 }}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, color: P.ink, fontWeight: 500 }}>{e.t}</div>
                  {e.prep && <div style={{ fontSize: 11, color: e.tone === 'spark' ? P.spark : P.ink3, marginTop: 2 }}>{e.prep}</div>}
                </div>
              </div>
            ))}
          </Card>

          {/* Pex's take — LIGHT (moodboard had this dark) */}
          {!hideTake && (
          <Card pad={18} style={{ background: P.sparkWash, border: `1px solid ${P.sparkTint}`, position: 'relative', overflow: 'hidden' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}><Pex size={22}/><Label style={{ color: P.sparkDim }}>Pex's take</Label></div>
            <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 21, lineHeight: 1.3, color: P.ink }}>Class demand is showing up in the receipts.</div>
            <div style={{ fontSize: 12.5, color: P.ink2, marginTop: 8, lineHeight: 1.5 }}>Want me to plan a second weekly slot and show the approval cost?</div>
            <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
              <Btn kind="spark" size="sm" onClick={planIt}>Plan it · 8 ⚡</Btn>
              <Btn kind="ghost" size="sm" onClick={() => setHideTake(true)}>Not yet</Btn>
            </div>
          </Card>
          )}

          <Card>
            <div style={{ padding: '14px 18px 12px' }}>
              <span style={{ fontSize: 14, fontWeight: 600, color: P.ink }}>First week setup</span>
              <span style={{ float: 'right', fontSize: 12, color: P.ink3 }}>{doneCount} / {checklist.length}</span>
              <div style={{ height: 5, background: P.sunk, borderRadius: 5, margin: '10px 0 4px', overflow: 'hidden' }}><div style={{ width: Math.round(doneCount / checklist.length * 100) + '%', height: '100%', background: P.spark, transition: 'width .25s' }}/></div>
            </div>
            {checklist.map(([t, d], i) => (
              <div key={i} onClick={() => toggleCheck(i)} style={{ padding: '7px 18px', display: 'flex', alignItems: 'center', gap: 9, fontSize: 12.5, color: d ? P.ink3 : P.ink, cursor: 'pointer' }}
                onMouseEnter={ev => ev.currentTarget.style.background = P.hover} onMouseLeave={ev => ev.currentTarget.style.background = 'transparent'}>
                <span style={{ width: 16, height: 16, borderRadius: 5, border: `1.5px solid ${d ? P.sage : P.lineStrong}`, background: d ? P.sage : 'transparent', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{d && <Icon name="check" size={10} color="#fff" stroke={3}/>}</span>
                <span style={{ textDecoration: d ? 'line-through' : 'none' }}>{t}</span>
              </div>
            ))}
            <div style={{ height: 10 }}/>
          </Card>
        </div>
      </div>

      {/* Cash flow — full-width strip below the loop */}
      <Card style={{ marginTop: 18 }}>
        <div style={{ padding: '16px 18px 0', display: 'flex', alignItems: 'center' }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: P.ink }}>Cash flow</div>
            <div style={{ fontSize: 12, color: P.ink3 }}>Last 6 months · revenue vs expenses</div>
          </div>
          <div style={{ display: 'flex', gap: 12, fontSize: 11.5, color: P.ink3 }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}><span style={{ width: 9, height: 9, borderRadius: 3, background: P.sage }}/>Revenue</span>
            <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}><span style={{ width: 9, height: 9, borderRadius: 3, background: P.ink4 }}/>Expenses</span>
            <span onClick={() => go('money/reports')} style={{ color: P.spark, cursor: 'pointer' }}>Reports →</span>
          </div>
        </div>
        <div style={{ padding: 18 }}>
          <svg width="100%" height="150" viewBox="0 0 1040 150" preserveAspectRatio="none">
            {[0,1,2,3].map(i => <line key={i} x1="0" x2="1040" y1={i*38+8} y2={i*38+8} stroke={P.line} strokeWidth="1"/>)}
            {[['Oct',10,8],['Nov',14,9],['Dec',12,10],['Jan',18,11],['Feb',15,12],['Mar',26,13]].map((m, i) => {
              const x = i * 172 + 40;
              return (
                <g key={i}>
                  <rect x={x} y={138 - m[1]*4.6} width="46" height={m[1]*4.6} rx="5" fill={P.sage}/>
                  <rect x={x + 54} y={138 - m[2]*4.6} width="46" height={m[2]*4.6} rx="5" fill={P.ink4}/>
                  <text x={x + 50} y={148} fontSize="11" fill={P.ink3} textAnchor="middle" fontFamily={P.sans}>{m[0]}</text>
                </g>
              );
            })}
          </svg>
        </div>
      </Card>
    </Page>
  );
};
