// app-web-views.jsx — Transactions, Budget, Goals, Audit, Accounts, Life

const { useState: useS2 } = React;

// ---------------- TRANSACTIONS ----------------
const TxView = ({ density }) => {
  const [filter, setFilter] = useS2('all');
  const [who, setWho] = useS2('all');
  const filtered = window.TRANSACTIONS.filter(t => {
    if (filter === 'spend' && t.amt > 0) return false;
    if (filter === 'income' && t.amt < 0) return false;
    if (filter === 'review' && t.approved) return false;
    if (who !== 'all' && t.who !== who) return false;
    return true;
  });
  const grouped = {};
  filtered.forEach(t => { (grouped[t.date] ||= []).push(t); });
  return (
    <div>
      <SectionTitle eyebrow="May 2026" title="Transactions"
        action={
          <div style={{ display: 'flex', gap: 8 }}>
            <button style={btnGhost}><Icon name="filter" size={13}/> Filter</button>
            <button style={btnGhost}><Icon name="search" size={13}/> Search</button>
            <button style={btnPrimary}><Icon name="plus" size={13} stroke="#fbfaf7"/> Add manual</button>
          </div>
        }
      />
      {/* Filter chips */}
      <div style={{ display: 'flex', gap: 6, marginBottom: 14, flexWrap: 'wrap' }}>
        {[['all','All'],['spend','Spending'],['income','Income'],['review','Needs review']].map(([k, lbl]) => (
          <button key={k} onClick={() => setFilter(k)} style={{
            ...chip, background: filter === k ? '#1d2638' : '#fdfcf9',
            color: filter === k ? '#fbfaf7' : '#534e44',
            borderColor: filter === k ? '#1d2638' : '#ece8de',
          }}>{lbl}</button>
        ))}
        <span style={{ width: 1, background: '#ece8de', margin: '0 4px' }} />
        {[['all','Both'],['B','Branden'],['C','Cindy']].map(([k, lbl]) => (
          <button key={k} onClick={() => setWho(k)} style={{
            ...chip, background: who === k ? '#1d2638' : '#fdfcf9',
            color: who === k ? '#fbfaf7' : '#534e44',
            borderColor: who === k ? '#1d2638' : '#ece8de',
          }}>{lbl}</button>
        ))}
      </div>

      <Card density={density} pad={0}>
        {Object.entries(grouped).map(([date, txs], gi) => (
          <div key={date} style={{ borderTop: gi ? '1px solid #ece8de' : 'none' }}>
            <div style={{
              padding: '12px 22px 8px', display: 'flex', justifyContent: 'space-between',
              fontSize: 11, color: '#7a766c', letterSpacing: '0.06em', textTransform: 'uppercase',
              background: '#faf7f0',
            }}>
              <span>{new Date(date + 'T12:00').toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })}</span>
              <span>{txs.length} {txs.length === 1 ? 'transaction' : 'transactions'} · net {window.fmtShort(txs.reduce((s,t)=>s+t.amt,0))}</span>
            </div>
            <div style={{ padding: '0 22px' }}>
              {txs.map((t, i) => <TxRow key={t.id} t={t} first={i === 0} />)}
            </div>
          </div>
        ))}
      </Card>
    </div>
  );
};

// ---------------- BUDGET ----------------
const BudgetView = ({ density, scenario }) => {
  const [tab, setTab] = useS2('current');
  const [editing, setEditing] = useS2(null);
  const totalPlanned = window.BUDGET.reduce((s, b) => s + (b.kind === 'goal' ? 0 : b.planned), 0);
  const totalSpent = window.BUDGET.reduce((s, b) => s + b.spent, 0);
  const monthIncome = 3332;
  return (
    <div>
      <SectionTitle eyebrow="May 2026" title="Budget"
        action={
          <div style={{ display: 'flex', gap: 4, padding: 3, background: '#ece8de', borderRadius: 8 }}>
            {[['current','Current'],['proposed','With class plan']].map(([k, lbl]) => (
              <button key={k} onClick={() => setTab(k)} style={{
                padding: '6px 12px', borderRadius: 6, border: 'none',
                background: tab === k ? '#fbfaf7' : 'transparent',
                color: tab === k ? '#1d2638' : '#534e44',
                fontSize: 11.5, fontWeight: 500, cursor: 'pointer', fontFamily: 'Inter, system-ui',
              }}>{lbl}</button>
            ))}
          </div>
        }
      />

      <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: 16 }}>
        {/* Donut summary */}
        <Card density={density}>
          <div style={{ display: 'flex', justifyContent: 'center', marginTop: 8 }}>
            <Donut
              size={170} thickness={20}
              segments={[
                { value: 1850, color: '#2b3a55' },
                { value: 320,  color: '#4d6088' },
                { value: 700,  color: '#7a9b7e' },
                { value: 220,  color: '#a4b89a' },
                { value: 200,  color: '#b89968' },
                { value: 200,  color: '#c97a4a' },
                { value: 360,  color: '#d6c7a8' },
              ]}
              label={window.fmtShort(totalSpent)}
              sub={`of ${window.fmtShort(totalPlanned)}`}
            />
          </div>
          <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 8 }}>
            <Row k="Planned"   v={window.fmt(totalPlanned).replace('.00','')} />
            <Row k="Spent"     v={window.fmt(totalSpent).replace('.00','')} />
            <Row k="Remaining" v={window.fmt(totalPlanned - totalSpent).replace('.00','')} green />
            <div style={{ height: 1, background: '#ece8de', margin: '4px 0' }} />
            <Row k="Income"    v={window.fmt(monthIncome).replace('.00','')} />
            <Row k="After budget" v={window.fmt(monthIncome - totalPlanned).replace('.00','')} bold />
          </div>
        </Card>

        {/* Categories */}
        <Card density={density} pad={0}>
          {window.BUDGET.filter(b => tab === 'proposed' || b.kind !== 'goal').map((b, i) => {
            let planned = b.planned;
            let spent = b.spent;
            if (tab === 'proposed') {
              if (b.cat === 'Class (Cindy)') { planned = 275; spent = 0; }
              if (b.cat === 'Subscriptions') planned = 30;
              if (b.cat === 'Groceries') planned = 580;
              if (b.cat === 'Coffee') planned = 30;
              if (b.cat === 'Personal') planned = 120;
            }
            const pct = planned ? (spent / planned) * 100 : 0;
            const over = pct > 100;
            const isProposed = b.kind === 'goal';
            const isExp = editing === b.cat;
            return (
              <div key={b.cat} onClick={() => setEditing(isExp ? null : b.cat)} style={{
                padding: '14px 22px',
                borderTop: i ? '1px solid #ece8de' : 'none',
                cursor: 'pointer', background: isExp ? '#faf7f0' : 'transparent',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                  <span style={{
                    width: 8, height: 28, borderRadius: 2,
                    background: b.kind === 'fixed' ? '#2b3a55' : isProposed ? '#c97a4a' : '#7a9b7e',
                  }} />
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span style={{ fontSize: 13.5, color: '#1d2638', fontWeight: 500 }}>{b.cat}</span>
                      <Pill sm bg={b.kind === 'fixed' ? '#dde3ee' : isProposed ? '#f3dccb' : '#dde3d3'}
                        color={b.kind === 'fixed' ? '#2b3a55' : isProposed ? '#c97a4a' : '#3e4d34'}>
                        {b.kind === 'fixed' ? 'Fixed' : isProposed ? 'Proposed' : 'Flex'}
                      </Pill>
                      {tab === 'proposed' && b.planned !== planned && b.kind !== 'goal' && (
                        <Pill sm bg="#f3dccb" color="#c97a4a">Cut {window.fmtShort(b.planned - planned)}</Pill>
                      )}
                    </div>
                    <div style={{ marginTop: 6, display: 'flex', alignItems: 'center', gap: 12 }}>
                      <div style={{ flex: 1 }}>
                        <Bar pct={pct} over={over} color={b.kind === 'fixed' ? '#2b3a55' : isProposed ? '#c97a4a' : '#7a9b7e'} />
                      </div>
                      <span style={{ fontSize: 11.5, color: over ? '#c97a4a' : '#7a766c', fontVariantNumeric: 'tabular-nums', width: 130, textAlign: 'right' }}>
                        {window.fmt(spent).replace('.00','')} / {window.fmt(planned).replace('.00','')}
                      </span>
                    </div>
                  </div>
                </div>
                {isExp && (
                  <div style={{ marginTop: 14, paddingLeft: 22, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
                    <Mini k="Avg last 3 mo" v={window.fmt(planned * 0.92).replace('.00','')} />
                    <Mini k="Branden share" v={`${Math.round(40 + Math.random() * 20)}%`} />
                    <Mini k="Cindy share"   v={`${Math.round(40 + Math.random() * 20)}%`} />
                  </div>
                )}
              </div>
            );
          })}
        </Card>
      </div>
    </div>
  );
};

const Row = ({ k, v, green, bold }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
    <span style={{ color: '#7a766c' }}>{k}</span>
    <span style={{ color: green ? '#7a9b7e' : '#1d2638', fontWeight: bold ? 600 : 400, fontVariantNumeric: 'tabular-nums' }}>{v}</span>
  </div>
);
const Mini = ({ k, v }) => (
  <div>
    <div style={{ fontSize: 9.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#7a766c' }}>{k}</div>
    <div style={{ fontFamily: 'Newsreader, serif', fontSize: 18, color: '#1d2638', marginTop: 3 }}>{v}</div>
  </div>
);

// ---------------- GOALS ----------------
const GoalsView = ({ density, scenario }) => {
  const [step, setStep] = useS2(2); // simulate user mid-scenario
  const [job700, setJob700] = useS2(true);
  const [classCost, setClassCost] = useS2(275);
  const [trim, setTrim] = useS2({ subs: true, groc: true, coffee: true, personal: true, dineout: false });
  const trimMap = { subs: 35, groc: 120, coffee: 30, personal: 80, dineout: 60 };
  const trimTotal = Object.entries(trim).reduce((s, [k, v]) => s + (v ? trimMap[k] : 0), 0);
  const lostIncome = job700 ? 700 : 0;
  const newExpense = classCost;
  const monthGap = lostIncome + newExpense - trimTotal;

  return (
    <div>
      <SectionTitle eyebrow="Active goal" title="The class & quitting plan"
        action={<Pill bg="#dde3ee" color="#2b3a55"><Icon name="cal" size={11} stroke="#2b3a55" /> Target start · June 1</Pill>} />

      {/* Plain language statement */}
      <Card density={density} pad={24} style={{ marginBottom: 16, background: '#faf7f0' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
          <Avatar who="C" size={36} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#7a766c' }}>Cindy stated · 4 days ago</div>
            <p style={{ margin: '6px 0 0', fontFamily: 'Newsreader, serif', fontStyle: 'italic', fontSize: 19, color: '#1d2638', lineHeight: 1.4, fontWeight: 400, maxWidth: 720, letterSpacing: '-0.005em' }}>
              "I want to quit the cleaning job and take the ceramics class. The class is $275 a month. I make about $700 from cleaning. I don't want to touch savings."
            </p>
            <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
              <Pill bg="#dde3d3" color="#3e4d34"><Icon name="check" size={11} stroke="#3e4d34" /> Branden agreed</Pill>
              <Pill bg="#fbfaf7" color="#7a766c">Discussed in money check-in</Pill>
            </div>
          </div>
        </div>
      </Card>

      {/* Scenario builder */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <Card density={density}>
          <SectionTitle title="The math" eyebrow="Step 1 · Inputs" density={density} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <ScenRow label="Lose: cleaning income" sub="Lulu's Cleaning · monthly" amt={-lostIncome}
              control={
                <Toggle value={job700} onChange={setJob700} label="Quitting" />
              } />
            <ScenRow label="Add: ceramics class" sub="Sprout Wellness Studio · monthly" amt={-classCost}
              control={
                <Stepper value={classCost} onChange={setClassCost} step={25} min={0} max={500} />
              } />
            <div style={{ height: 1, background: '#ece8de', margin: '4px 0' }} />
            <div style={{ fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#7a766c' }}>Step 2 · Where to trim</div>
            {[
              ['subs', 'Cut 3 unused subscriptions',  'Adobe, Apple Music+, NYT Cooking'],
              ['groc', 'Tighten grocery target',       '$700 → $580 / month'],
              ['coffee','Brew more at home',           'Coffee Roastery cut in half'],
              ['personal','Pause clothing budget for 2 mo','Personal $200 → $120'],
              ['dineout','Drop 2 dining-out nights',   'Optional · also frees up time'],
            ].map(([k, lbl, sub]) => (
              <label key={k} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '8px 10px', background: trim[k] ? '#dde3d3' : '#faf7f0', border: `1px solid ${trim[k] ? '#bdc8b0' : '#ece8de'}`, borderRadius: 9, cursor: 'pointer' }}>
                <input type="checkbox" checked={trim[k]} onChange={e => setTrim({ ...trim, [k]: e.target.checked })} style={{ accentColor: '#3e4d34' }} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 12.5, color: '#1d2638', fontWeight: 500 }}>{lbl}</div>
                  <div style={{ fontSize: 10.5, color: '#7a766c', marginTop: 1 }}>{sub}</div>
                </div>
                <span style={{ fontSize: 12, color: '#3e4d34', fontVariantNumeric: 'tabular-nums', fontWeight: 500 }}>+{window.fmtShort(trimMap[k])}</span>
              </label>
            ))}
          </div>
        </Card>

        {/* Result */}
        <Card density={density} style={{ background: monthGap > 0 ? 'linear-gradient(180deg, #fbfaf7, #fff3ec)' : 'linear-gradient(180deg, #fbfaf7, #eff5ec)' }}>
          <SectionTitle title="What this does" eyebrow="The verdict" density={density} />

          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 4 }}>
            <span style={{ fontFamily: 'Newsreader, serif', fontSize: 56, fontWeight: 500, color: monthGap > 0 ? '#c97a4a' : '#7a9b7e', letterSpacing: '-0.02em', lineHeight: 1 }}>
              {monthGap > 0 ? '−' : '+'}{window.fmtShort(Math.abs(monthGap))}
            </span>
            <span style={{ fontSize: 12, color: '#7a766c' }}>per month</span>
          </div>
          <p style={{ margin: 0, color: '#534e44', fontSize: 13, lineHeight: 1.5, maxWidth: 360 }}>
            {monthGap > 0 ? (
              <>You'd be short <b>{window.fmtShort(monthGap)}</b> a month. Suggestions: trim more, ask Cindy to keep ~{Math.ceil(monthGap / 25) * 5}h/mo of cleaning, or pause the class to August.</>
            ) : monthGap === 0 ? (
              <>Even. Tight, but workable. You'd cover the class without dipping into savings.</>
            ) : (
              <>You'd actually <b>save</b> {window.fmtShort(-monthGap)} more per month. Plenty of room.</>
            )}
          </p>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 18 }}>
            <Mini k="Income lost"     v={`−${window.fmtShort(lostIncome)}`} />
            <Mini k="New expense"     v={`−${window.fmtShort(classCost)}`} />
            <Mini k="Trimmed"         v={`+${window.fmtShort(trimTotal)}`} />
            <Mini k="Months of buffer" v="3.2" />
          </div>

          <div style={{ marginTop: 18, padding: 14, background: '#fbfaf7', borderRadius: 10, border: '1px solid #ece8de' }}>
            <div style={{ fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#7a766c', marginBottom: 8 }}>Twogether suggests</div>
            <ul style={{ margin: 0, paddingLeft: 18, fontSize: 12.5, color: '#1d2638', lineHeight: 1.6 }}>
              <li>Keep cleaning <b>two Saturdays a month</b> through July → covers the gap.</li>
              <li>Move class start to <b>July 1</b> — gives 4 weeks to bank trims first.</li>
              <li>Set a <b>$1,500 minimum</b> in Joint Checking before tuition charges.</li>
            </ul>
          </div>

          <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
            <button style={btnPrimary}>Lock this plan in</button>
            <button style={btnGhost}>Save scenario</button>
          </div>
        </Card>
      </div>

      {/* Other goals */}
      <div style={{ marginTop: 22 }}>
        <SectionTitle eyebrow="Other goals" title="On the horizon" density={density} />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
          {[
            { t: 'Emergency fund', sub: '3 mo of expenses', cur: 7942, goal: 12500, by: 'Dec 2026' },
            { t: 'Visit Cindy\'s family', sub: 'Flights + lodging', cur: 410, goal: 2400, by: 'Sep 2026' },
            { t: 'New brakes for truck', sub: 'Set aside', cur: 80, goal: 600, by: 'Jul 2026' },
          ].map((g, i) => (
            <Card key={i} density={density}>
              <div style={{ fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#7a766c' }}>By {g.by}</div>
              <div style={{ fontFamily: 'Newsreader, serif', fontSize: 19, color: '#1d2638', marginTop: 4, fontWeight: 500 }}>{g.t}</div>
              <div style={{ fontSize: 11.5, color: '#7a766c', marginTop: 1 }}>{g.sub}</div>
              <div style={{ marginTop: 14 }}>
                <Bar pct={(g.cur/g.goal)*100} color="#b89968" />
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, marginTop: 6, color: '#534e44', fontVariantNumeric: 'tabular-nums' }}>
                  <span>{window.fmt(g.cur).replace('.00','')}</span>
                  <span style={{ color: '#7a766c' }}>{window.fmt(g.goal).replace('.00','')}</span>
                </div>
              </div>
            </Card>
          ))}
        </div>
      </div>
    </div>
  );
};

const ScenRow = ({ label, sub, amt, control }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderTop: '1px solid #ece8de' }}>
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 13, color: '#1d2638', fontWeight: 500 }}>{label}</div>
      <div style={{ fontSize: 11, color: '#7a766c', marginTop: 1 }}>{sub}</div>
    </div>
    <span style={{ fontSize: 13, fontVariantNumeric: 'tabular-nums', color: amt < 0 ? '#c97a4a' : '#7a9b7e', width: 70, textAlign: 'right', fontWeight: 500 }}>
      {amt < 0 ? '−' : '+'}{window.fmt(Math.abs(amt)).replace('.00','')}
    </span>
    <div style={{ width: 130 }}>{control}</div>
  </div>
);

const Toggle = ({ value, onChange, label }) => (
  <button onClick={() => onChange(!value)} style={{
    display: 'flex', alignItems: 'center', gap: 8, padding: '6px 10px',
    border: `1px solid ${value ? '#2b3a55' : '#ece8de'}`, borderRadius: 8,
    background: value ? '#dde3ee' : '#fdfcf9', color: value ? '#2b3a55' : '#7a766c',
    fontSize: 11.5, fontWeight: 500, fontFamily: 'Inter, system-ui', cursor: 'pointer', width: '100%',
    justifyContent: 'space-between',
  }}>
    {label}
    <span style={{ width: 22, height: 12, background: value ? '#2b3a55' : '#cdc7b8', borderRadius: 12, position: 'relative' }}>
      <span style={{ position: 'absolute', top: 1, left: value ? 11 : 1, width: 10, height: 10, background: '#fff', borderRadius: '50%', transition: '.15s' }} />
    </span>
  </button>
);
const Stepper = ({ value, onChange, step, min, max }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 0, border: '1px solid #ece8de', borderRadius: 8, background: '#fdfcf9' }}>
    <button onClick={() => onChange(Math.max(min, value - step))} style={stepBtn}>−</button>
    <span style={{ flex: 1, textAlign: 'center', fontSize: 13, color: '#1d2638', fontVariantNumeric: 'tabular-nums', fontWeight: 500 }}>${value}</span>
    <button onClick={() => onChange(Math.min(max, value + step))} style={stepBtn}>+</button>
  </div>
);
const stepBtn = { width: 26, height: 30, border: 'none', background: 'transparent', color: '#534e44', fontSize: 14, cursor: 'pointer' };

// ---------------- AUDIT ----------------
const AuditView = ({ density }) => {
  const findings = [
    { sev: 'high', cat: 'Subscriptions',  title: 'Adobe Creative Cloud — $54.99/mo', sub: 'No usage in 3 months. Cancel?', save: 660, who: 'B' },
    { sev: 'high', cat: 'Subscriptions',  title: 'Apple Music duplicate', sub: 'Family plan + Branden\'s individual. One is redundant.', save: 132, who: 'J' },
    { sev: 'med',  cat: 'Groceries',      title: 'Whole Foods + Trader Joe\'s same week', sub: '4 weeks in a row. Consolidate to one trip?', save: 240, who: 'C' },
    { sev: 'med',  cat: 'Insurance',      title: 'Geico premium up 12% YoY', sub: 'Average new quote in your zip is 8% lower.', save: 178, who: 'B' },
    { sev: 'low',  cat: 'Dining',         title: 'Coffee Roastery × 18 visits', sub: 'Up from 11/mo last quarter.', save: 84, who: 'B' },
    { sev: 'low',  cat: 'Banking',        title: 'Joint Savings APY is 0.05%', sub: 'Could earn ~$220/yr more in a HYSA.', save: 220, who: 'J' },
  ];
  const total = findings.reduce((s, f) => s + f.save, 0);
  return (
    <div>
      <SectionTitle eyebrow="Q2 2026 · automated" title="Financial audit"
        action={<button style={btnPrimary}><Icon name="sparkles" size={13} stroke="#fbfaf7"/> Re-run audit</button>}
      />

      <Card density={density} pad={26} style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 24 }}>
          <div>
            <div style={{ fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#7a766c' }}>Potential savings found</div>
            <div style={{ fontFamily: 'Newsreader, serif', fontSize: 52, color: '#7a9b7e', letterSpacing: '-0.02em', fontWeight: 500, lineHeight: 1, marginTop: 4 }}>
              {window.fmt(total).replace('.00','')}<span style={{ fontSize: 18, color: '#7a766c' }}>/yr</span>
            </div>
            <div style={{ fontSize: 12, color: '#534e44', marginTop: 6 }}>Across {findings.length} findings · scanned 6 months · 247 transactions</div>
          </div>
          <div style={{ display: 'flex', gap: 28 }}>
            <Stat k="High impact"  v={findings.filter(f => f.sev === 'high').length} c="#c97a4a" />
            <Stat k="Medium"       v={findings.filter(f => f.sev === 'med').length}  c="#b89968" />
            <Stat k="Low"          v={findings.filter(f => f.sev === 'low').length}  c="#7a9b7e" />
          </div>
        </div>
      </Card>

      <Card density={density} pad={0}>
        {findings.map((f, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '16px 22px', borderTop: i ? '1px solid #ece8de' : 'none' }}>
            <span style={{
              width: 6, alignSelf: 'stretch', borderRadius: 2,
              background: f.sev === 'high' ? '#c97a4a' : f.sev === 'med' ? '#b89968' : '#7a9b7e',
            }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#7a766c', marginBottom: 4 }}>{f.cat}</div>
              <div style={{ fontSize: 13.5, color: '#1d2638', fontWeight: 500 }}>{f.title}</div>
              <div style={{ fontSize: 12, color: '#534e44', marginTop: 2 }}>{f.sub}</div>
            </div>
            <Avatar who={f.who} size={22} />
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontFamily: 'Newsreader, serif', fontSize: 18, color: '#7a9b7e', fontWeight: 500 }}>+{window.fmt(f.save).replace('.00','')}</div>
              <div style={{ fontSize: 10, color: '#7a766c' }}>per year</div>
            </div>
            <button style={btnGhost}>Take action</button>
          </div>
        ))}
      </Card>
    </div>
  );
};
const Stat = ({ k, v, c }) => (
  <div>
    <div style={{ fontFamily: 'Newsreader, serif', fontSize: 28, color: c, fontWeight: 500 }}>{v}</div>
    <div style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#7a766c', marginTop: 2 }}>{k}</div>
  </div>
);

// ---------------- ACCOUNTS ----------------
const AcctView = ({ density }) => (
  <div>
    <SectionTitle eyebrow="Connected · auto-syncing" title="Accounts"
      action={<button style={btnPrimary}><Icon name="plus" size={13} stroke="#fbfaf7"/> Connect new bank</button>}
    />
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 22 }}>
      {/* Joint */}
      <AcctGroup label="Shared (both can see)" who="J" accounts={window.ACCOUNTS.filter(a => a.owner === 'J')} density={density} />
      {/* Private */}
      <Card density={density} pad={0}>
        <div style={{ padding: '16px 20px 14px', borderBottom: '1px solid #ece8de', display: 'flex', alignItems: 'center', gap: 10 }}>
          <Icon name="lock" size={14} stroke="#7a766c" />
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'Newsreader, serif', fontSize: 17, color: '#1d2638' }}>Private side accounts</div>
            <div style={{ fontSize: 11, color: '#7a766c', marginTop: 1 }}>Balances roll up; transactions stay personal</div>
          </div>
        </div>
        {window.ACCOUNTS.filter(a => a.owner !== 'J').map((a, i) => (
          <AcctRow key={a.id} a={a} first={i === 0} dim />
        ))}
      </Card>
    </div>

    <SectionTitle title="Bank connections" eyebrow="Status" density={density} />
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
      {[
        { bank: 'Chase', accts: 4, status: 'Synced 2 min ago', color: '#7a9b7e', who: 'J' },
        { bank: 'Ally',  accts: 2, status: 'Synced 18 min ago', color: '#7a9b7e', who: 'C' },
        { bank: 'Wells', accts: 0, status: 'Not connected — add', color: '#7a766c', dim: true },
      ].map((c, i) => (
        <Card key={i} density={density}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <BankBadge bank={c.bank} size={36} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, color: '#1d2638', fontWeight: 500 }}>{c.bank}</div>
              <div style={{ fontSize: 11, color: c.color, marginTop: 2 }}>● {c.status}</div>
            </div>
            <span style={{ fontSize: 11, color: '#7a766c' }}>{c.accts} acct{c.accts !== 1 ? 's' : ''}</span>
          </div>
        </Card>
      ))}
    </div>
  </div>
);
const AcctGroup = ({ label, who, accounts, density }) => (
  <Card density={density} pad={0}>
    <div style={{ padding: '16px 20px 14px', borderBottom: '1px solid #ece8de', display: 'flex', alignItems: 'center', gap: 10 }}>
      <AvatarPair size={22} />
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: 'Newsreader, serif', fontSize: 17, color: '#1d2638' }}>{label}</div>
        <div style={{ fontSize: 11, color: '#7a766c', marginTop: 1 }}>Both Branden &amp; Cindy can view + categorize</div>
      </div>
    </div>
    {accounts.map((a, i) => <AcctRow key={a.id} a={a} first={i === 0} />)}
  </Card>
);
const AcctRow = ({ a, first, dim }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 20px', borderTop: first ? 'none' : '1px solid #ece8de' }}>
    <BankBadge bank={a.bank} size={34} />
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 13.5, color: '#1d2638', fontWeight: 500, display: 'flex', alignItems: 'center', gap: 6 }}>
        {a.name}
        {dim && <Avatar who={a.owner} size={16} />}
      </div>
      <div style={{ fontSize: 11, color: '#7a766c', marginTop: 1, textTransform: 'capitalize' }}>{a.bank} · {a.type} · ••{a.last4}</div>
    </div>
    <div style={{ textAlign: 'right' }}>
      <div style={{ fontFamily: 'Newsreader, serif', fontSize: 19, color: a.balance < 0 ? '#c97a4a' : '#1d2638', fontWeight: 500 }}>
        {window.fmt(a.balance).replace('.00','')}
      </div>
      {a.limit && <div style={{ fontSize: 10, color: '#7a766c' }}>of {window.fmt(a.limit).replace('.00','')} limit</div>}
    </div>
  </div>
);

// ---------------- LIFE ----------------
const LifeView = ({ density }) => {
  const cMood = window.MOOD.C;
  const bMood = window.MOOD.B;
  const days = ['M','T','W','T','F','S','S'];
  return (
    <div>
      <SectionTitle eyebrow="Life tracker · last 14 days" title="How are we, really?"
        action={<button style={btnGhost}><Icon name="plus" size={13}/> Log today</button>} />

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        {/* Mood */}
        <Card density={density}>
          <SectionTitle title="Mood" eyebrow="Daily check-in" density={density} />
          {[['B', bMood, '#2b3a55', '#dde3ee'], ['C', cMood, '#c97a4a', '#f3dccb']].map(([w, data, color, fill]) => {
            const avg = (data.reduce((s,n)=>s+n,0) / data.length).toFixed(1);
            const diff = data.slice(-7).reduce((s,n)=>s+n,0)/7 - data.slice(0,7).reduce((s,n)=>s+n,0)/7;
            return (
              <div key={w} style={{ marginTop: 12, padding: '12px 0', borderTop: '1px solid #ece8de' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                  <Avatar who={w} size={24} />
                  <span style={{ fontSize: 13, color: '#1d2638', fontWeight: 500, flex: 1 }}>{window.PEOPLE[w].name}</span>
                  <span style={{ fontFamily: 'Newsreader, serif', fontSize: 22, color, fontWeight: 500 }}>{avg}</span>
                  <span style={{ fontSize: 11, color: diff > 0 ? '#7a9b7e' : '#7a766c' }}>{diff > 0 ? '↑' : '→'} {Math.abs(diff).toFixed(1)} vs last wk</span>
                </div>
                <Sparkline data={data} w={400} h={42} color={color} fill={color} />
              </div>
            );
          })}
          <div style={{ marginTop: 12, padding: 12, background: '#dde3d3', borderRadius: 9, border: '1px solid #bdc8b0' }}>
            <div style={{ fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#3e4d34', marginBottom: 4 }}>Pattern noticed</div>
            <p style={{ margin: 0, fontSize: 12.5, color: '#3e4d34', lineHeight: 1.5 }}>
              Cindy's mood is up <b>+0.7</b> in the days she mentioned the class. Branden — your dips line up with paydays. Worth talking about.
            </p>
          </div>
        </Card>

        {/* Habits */}
        <Card density={density}>
          <SectionTitle title="Habits" eyebrow="This week" density={density} />
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {window.HABITS.map((h, i) => (
              <div key={h.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderTop: i ? '1px solid #ece8de' : 'none' }}>
                {h.shared ? <AvatarPair size={20} /> : <Avatar who={h.who} size={22} />}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, color: '#1d2638', fontWeight: 500 }}>{h.name}</div>
                  <div style={{ fontSize: 10.5, color: '#7a766c', marginTop: 1 }}>{h.streak}-day streak</div>
                </div>
                <div style={{ display: 'flex', gap: 4 }}>
                  {h.weekly.map((d, j) => (
                    <span key={j} title={days[j]} style={{
                      width: 18, height: 18, borderRadius: 5,
                      background: d ? (h.shared ? '#5a6b4f' : window.PEOPLE[h.who].color) : '#ece8de',
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                      fontSize: 8, color: d ? '#fbfaf7' : '#a89889', fontWeight: 600,
                    }}>{days[j]}</span>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      <div style={{ marginTop: 16 }}>
        <Card density={density}>
          <SectionTitle title="Money + mood overlay" eyebrow="The whole picture" density={density} />
          <p style={{ margin: '0 0 14px', fontSize: 12.5, color: '#534e44', maxWidth: 600 }}>
            Spending, mood, and habits over 14 days. Look for the days you both did well — what made those days easy?
          </p>
          <div style={{ position: 'relative', height: 140, padding: '10px 0' }}>
            <svg width="100%" height="120" viewBox="0 0 800 120" preserveAspectRatio="none" style={{ display: 'block' }}>
              {/* Spend bars (mock) */}
              {[42,80,30,156,50,90,210,40,70,130,80,40,184,60].map((v, i) => (
                <rect key={i} x={i * 56 + 4} y={120 - v*0.4} width="48" height={v*0.4} fill="#ece8de" rx="2" />
              ))}
              {/* Mood lines */}
              <path d={bMood.map((v,i)=>`${i?'L':'M'}${i*56+28},${120 - v*22}`).join(' ')} fill="none" stroke="#2b3a55" strokeWidth="2" />
              <path d={cMood.map((v,i)=>`${i?'L':'M'}${i*56+28},${120 - v*22}`).join(' ')} fill="none" stroke="#c97a4a" strokeWidth="2" />
              {bMood.map((v,i) => <circle key={'b'+i} cx={i*56+28} cy={120 - v*22} r="3" fill="#2b3a55" />)}
              {cMood.map((v,i) => <circle key={'c'+i} cx={i*56+28} cy={120 - v*22} r="3" fill="#c97a4a" />)}
            </svg>
          </div>
          <div style={{ display: 'flex', gap: 16, fontSize: 11, color: '#534e44', marginTop: 4 }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 12, height: 8, background: '#ece8de', borderRadius: 2 }} /> Daily spend</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 12, height: 2, background: '#2b3a55' }} /> Branden mood</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 12, height: 2, background: '#c97a4a' }} /> Cindy mood</span>
          </div>
        </Card>
      </div>
    </div>
  );
};

// ---------------- shared button styles ----------------
const btnPrimary = {
  padding: '8px 14px', borderRadius: 8, border: 'none',
  background: '#1d2638', color: '#fbfaf7', fontSize: 12, fontWeight: 500,
  fontFamily: 'Inter, system-ui', cursor: 'pointer',
  display: 'inline-flex', alignItems: 'center', gap: 6,
};
const btnGhost = {
  padding: '8px 12px', borderRadius: 8, border: '1px solid #ece8de',
  background: '#fdfcf9', color: '#534e44', fontSize: 12, fontWeight: 500,
  fontFamily: 'Inter, system-ui', cursor: 'pointer',
  display: 'inline-flex', alignItems: 'center', gap: 6,
};
const chip = {
  padding: '6px 11px', borderRadius: 999, border: '1px solid',
  fontSize: 11.5, fontWeight: 500, cursor: 'pointer', fontFamily: 'Inter, system-ui',
};

Object.assign(window, { TxView, BudgetView, GoalsView, AuditView, AcctView, LifeView, btnPrimary, btnGhost });
