// app-web.jsx — full web dashboard for Twogether

const { useState, useMemo, useEffect } = React;

// Sidebar nav
const WebSidebar = ({ tab, setTab, life }) => {
  const items = [
    { id: 'home',   label: 'Home',         icon: 'home' },
    { id: 'tx',     label: 'Transactions', icon: 'list' },
    { id: 'budget', label: 'Budget',       icon: 'wallet' },
    { id: 'goals',  label: 'Goals',        icon: 'target' },
    { id: 'audit',  label: 'Audit',        icon: 'audit' },
    { id: 'banks',  label: 'Accounts',     icon: 'bank' },
    ...(life ? [{ id: 'life', label: 'Life tracker', icon: 'heart' }] : []),
    { id: 'gram',  label: 'Couple-grams', icon: 'sparkles' },
  ];
  return (
    <aside style={{
      width: 220, background: '#f4f1ec', borderRight: '1px solid #e8e3d6',
      padding: '24px 14px', display: 'flex', flexDirection: 'column', gap: 4,
      minHeight: '100%',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '0 8px 22px', borderBottom: '1px solid #e8e3d6', marginBottom: 14 }}>
        <div style={{
          width: 28, height: 28, borderRadius: 8,
          background: 'linear-gradient(135deg, #2b3a55, #4d6088)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="leaf" size={16} stroke="#f3dccb" sw={1.8} />
        </div>
        <div>
          <div style={{ fontFamily: 'Newsreader, serif', fontSize: 17, color: '#1d2638', letterSpacing: '-0.01em', lineHeight: 1 }}>Twogether</div>
          <div style={{ fontSize: 9.5, color: '#7a766c', letterSpacing: '0.12em', textTransform: 'uppercase', marginTop: 2 }}>Branden &amp; Cindy</div>
        </div>
      </div>
      {items.map(it => (
        <button key={it.id} onClick={() => setTab(it.id)} style={{
          display: 'flex', alignItems: 'center', gap: 10,
          padding: '9px 11px', borderRadius: 9, border: 'none',
          background: tab === it.id ? '#fbfaf7' : 'transparent',
          color: tab === it.id ? '#1d2638' : '#534e44',
          boxShadow: tab === it.id ? 'inset 0 0 0 1px #e8e3d6' : 'none',
          fontFamily: 'Inter, system-ui', fontSize: 13, fontWeight: tab === it.id ? 500 : 400,
          textAlign: 'left', cursor: 'pointer', width: '100%',
        }}>
          <Icon name={it.icon} size={16} stroke={tab === it.id ? '#2b3a55' : '#7a766c'} />
          {it.label}
        </button>
      ))}
      <div style={{ flex: 1 }} />
      <div style={{
        padding: 12, background: '#fbfaf7', borderRadius: 10, border: '1px solid #e8e3d6',
        display: 'flex', gap: 10, alignItems: 'center',
      }}>
        <AvatarPair size={24} />
        <div style={{ fontSize: 11, lineHeight: 1.3, color: '#534e44' }}>
          Both in sync<br/>
          <span style={{ color: '#7a9b7e', fontSize: 10 }}>● Last refresh 2m ago</span>
        </div>
      </div>
    </aside>
  );
};

// HOME
const HomeView = ({ density, scenario, onOpenScenario, onTab }) => {
  const totalAssets = window.ACCOUNTS.filter(a => a.type !== 'credit').reduce((s, a) => s + a.balance, 0);
  const totalDebt = window.ACCOUNTS.filter(a => a.type === 'credit').reduce((s, a) => s + a.balance, 0);
  const net = totalAssets + totalDebt;
  const monthIncome = window.TRANSACTIONS.filter(t => t.amt > 0).reduce((s, t) => s + t.amt, 0);
  const monthSpend = -window.TRANSACTIONS.filter(t => t.amt < 0).reduce((s, t) => s + t.amt, 0);
  const recent = window.TRANSACTIONS.slice(0, 5);
  const needsReview = window.TRANSACTIONS.filter(t => !t.approved);

  // 30-day net trend mock
  const trend = [42100,42180,42050,42200,42420,42500,42380,42600,42710,42820,42900,42950,43040,43180,43250,43320,43410,43480,43520,43600,43680,43750,43820,43900,43950,44020,44120,44210,44280,44340];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      {/* Top: net worth + month flow */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr', gap: 16 }}>
        <Card density={density} pad={22}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <div style={{ fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#7a766c' }}>Combined net worth</div>
              <div style={{ fontFamily: 'Newsreader, serif', fontSize: 44, color: '#1d2638', letterSpacing: '-0.02em', marginTop: 6, fontWeight: 500, lineHeight: 1 }}>
                {window.fmt(net).replace('.00','')}
              </div>
              <div style={{ marginTop: 8, display: 'flex', gap: 16, fontSize: 12, color: '#534e44' }}>
                <span><span style={{ color: '#7a9b7e' }}>↑</span> +{window.fmtMoney(2240)} this month</span>
                <span style={{ color: '#7a766c' }}>+5.3%</span>
              </div>
            </div>
            <Sparkline data={trend} w={170} h={48} color="#7a9b7e" fill="#7a9b7e" />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, marginTop: 22, paddingTop: 18, borderTop: '1px solid #ece8de' }}>
            <div>
              <div style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#7a766c' }}>Cash &amp; savings</div>
              <div style={{ fontFamily: 'Newsreader, serif', fontSize: 22, color: '#1d2638', marginTop: 4 }}>{window.fmtShort(totalAssets)}</div>
            </div>
            <div>
              <div style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#7a766c' }}>Credit balances</div>
              <div style={{ fontFamily: 'Newsreader, serif', fontSize: 22, color: '#c97a4a', marginTop: 4 }}>{window.fmtShort(totalDebt)}</div>
            </div>
            <div>
              <div style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#7a766c' }}>This month free</div>
              <div style={{ fontFamily: 'Newsreader, serif', fontSize: 22, color: '#7a9b7e', marginTop: 4 }}>{window.fmtShort(monthIncome - monthSpend)}</div>
            </div>
          </div>
        </Card>

        <Card density={density} accent="#2b3a55">
          <div style={{ fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#7a766c' }}>Money in</div>
          <div style={{ fontFamily: 'Newsreader, serif', fontSize: 30, color: '#1d2638', marginTop: 4, lineHeight: 1.1 }}>{window.fmtShort(monthIncome)}</div>
          <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[['B','Branden — Acme', 2840], ['C','Cindy — Cleaning', 350], ['C','Cindy — Etsy', 142]].map(([w, lbl, v], i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11.5 }}>
                <Avatar who={w} size={18} />
                <span style={{ flex: 1, color: '#534e44' }}>{lbl}</span>
                <span style={{ color: '#1d2638', fontVariantNumeric: 'tabular-nums' }}>{window.fmt(v).replace('.00','')}</span>
              </div>
            ))}
          </div>
        </Card>

        <Card density={density} accent="#c97a4a">
          <div style={{ fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#7a766c' }}>Money out</div>
          <div style={{ fontFamily: 'Newsreader, serif', fontSize: 30, color: '#1d2638', marginTop: 4, lineHeight: 1.1 }}>{window.fmtShort(monthSpend)}</div>
          <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[['Rent', 1850, '#2b3a55'], ['Groceries', 284, '#7a9b7e'], ['Utilities', 278, '#b89968'], ['Other', monthSpend - 2412, '#a89889']].map(([lbl, v, c], i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11.5 }}>
                <span style={{ width: 8, height: 8, borderRadius: 2, background: c }} />
                <span style={{ flex: 1, color: '#534e44' }}>{lbl}</span>
                <span style={{ color: '#1d2638', fontVariantNumeric: 'tabular-nums' }}>{window.fmtShort(v)}</span>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Goal hero */}
      {scenario && (
        <Card density={density} pad={26} style={{ background: 'linear-gradient(135deg, #fbfaf7, #f3ece2 70%, #f3dccb)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 24 }}>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                <Icon name="target" size={14} stroke="#c97a4a" sw={2} />
                <span style={{ fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#c97a4a', fontWeight: 600 }}>Active goal · Cindy</span>
              </div>
              <h2 style={{ margin: 0, fontFamily: 'Newsreader, serif', fontSize: 28, color: '#1d2638', letterSpacing: '-0.01em', fontWeight: 500, maxWidth: 540, lineHeight: 1.2 }}>
                Quit cleaning job, start the ceramics class.
              </h2>
              <p style={{ margin: '8px 0 0', color: '#534e44', fontSize: 13.5, maxWidth: 560, lineHeight: 1.5 }}>
                We modeled it. Drop $700/mo income, add $275/mo class. We found <b style={{ color: '#1d2638' }}>$612 to trim</b> from flex categories and a 4-week ramp that keeps savings untouched.
              </p>
              <div style={{ display: 'flex', gap: 24, marginTop: 18 }}>
                <div>
                  <div style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#7a766c' }}>Net impact</div>
                  <div style={{ fontFamily: 'Newsreader, serif', fontSize: 22, color: '#c97a4a', marginTop: 3 }}>−$975/mo</div>
                </div>
                <div style={{ width: 1, background: '#e8d8c2' }} />
                <div>
                  <div style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#7a766c' }}>Trimmed from budget</div>
                  <div style={{ fontFamily: 'Newsreader, serif', fontSize: 22, color: '#7a9b7e', marginTop: 3 }}>+$612/mo</div>
                </div>
                <div style={{ width: 1, background: '#e8d8c2' }} />
                <div>
                  <div style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#7a766c' }}>Gap to close</div>
                  <div style={{ fontFamily: 'Newsreader, serif', fontSize: 22, color: '#1d2638', marginTop: 3 }}>$363/mo</div>
                </div>
              </div>
              <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
                <button onClick={() => onTab('goals')} style={{
                  padding: '10px 16px', borderRadius: 8, border: 'none',
                  background: '#1d2638', color: '#fbfaf7', fontSize: 12.5, fontWeight: 500,
                  fontFamily: 'Inter, system-ui', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6,
                }}>
                  Open the plan <Icon name="arrow-right" size={13} stroke="#fbfaf7" />
                </button>
                <button style={{
                  padding: '10px 16px', borderRadius: 8, border: '1px solid #d6c7a8',
                  background: 'transparent', color: '#534e44', fontSize: 12.5, fontWeight: 500,
                  fontFamily: 'Inter, system-ui', cursor: 'pointer',
                }}>Edit assumptions</button>
              </div>
            </div>
            <div style={{
              flexShrink: 0, width: 200, padding: 16, background: '#fbfaf7',
              border: '1px solid #ece8de', borderRadius: 12,
            }}>
              <div style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#7a766c', marginBottom: 10 }}>4-week ramp</div>
              {[
                ['W1', 'Cancel 3 subs',     '−$48'],
                ['W2', 'Cut grocery target','−$120'],
                ['W3', 'Last day cleaning', '$0'],
                ['W4', 'Class starts',      '+$275'],
              ].map(([w, lbl, amt], i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0', borderTop: i ? '1px solid #ece8de' : 'none' }}>
                  <span style={{ fontSize: 9.5, fontWeight: 600, color: '#7a766c', letterSpacing: '0.08em', width: 22 }}>{w}</span>
                  <span style={{ fontSize: 11, color: '#1d2638', flex: 1 }}>{lbl}</span>
                  <span style={{ fontSize: 11, color: '#534e44', fontVariantNumeric: 'tabular-nums' }}>{amt}</span>
                </div>
              ))}
            </div>
          </div>
        </Card>
      )}

      {/* Bottom row: review + recent + budget */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.2fr', gap: 16 }}>
        <Card density={density}>
          <SectionTitle eyebrow="Inbox" title="Needs your attention" density={density}
            action={<Pill bg="#f3dccb" color="#c97a4a">{needsReview.length} items</Pill>} />
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {needsReview.map((t, i) => (
              <div key={t.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 0', borderTop: i ? '1px solid #ece8de' : 'none' }}>
                <Avatar who={t.who} size={28} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, color: '#1d2638', fontWeight: 500 }}>{t.merchant}</div>
                  <div style={{ fontSize: 11, color: '#7a766c', marginTop: 1 }}>
                    {t.flag === 'needs-split' ? 'Split between you?' : 'Confirm category'} · {t.acct}
                  </div>
                </div>
                <span style={{ fontSize: 13, fontVariantNumeric: 'tabular-nums', color: '#1d2638' }}>{window.fmt(t.amt).replace('.00','')}</span>
                <button style={{
                  padding: '6px 10px', borderRadius: 7, border: '1px solid #cbd1c2',
                  background: '#dde3d3', color: '#3e4d34', fontSize: 11, fontWeight: 500,
                  cursor: 'pointer', fontFamily: 'Inter, system-ui',
                }}>Review</button>
              </div>
            ))}
            {!needsReview.length && (
              <div style={{ padding: '20px 0', color: '#7a766c', fontSize: 12, textAlign: 'center' }}>All caught up.</div>
            )}
          </div>
        </Card>

        <Card density={density}>
          <SectionTitle eyebrow="Recent" title="Latest from the banks" density={density}
            action={<button onClick={() => onTab('tx')} style={{
              border: 'none', background: 'transparent', color: '#7a766c',
              fontSize: 11.5, cursor: 'pointer', fontFamily: 'Inter, system-ui',
              display: 'inline-flex', alignItems: 'center', gap: 4,
            }}>View all <Icon name="arrow-right" size={11} /></button>} />
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {recent.map((t, i) => (
              <TxRow key={t.id} t={t} first={i === 0} />
            ))}
          </div>
        </Card>
      </div>

      {/* Budget mini */}
      <Card density={density}>
        <SectionTitle eyebrow="May 2026" title="Budget at a glance" density={density}
          action={<button onClick={() => onTab('budget')} style={{
            border: 'none', background: 'transparent', color: '#7a766c',
            fontSize: 11.5, cursor: 'pointer', fontFamily: 'Inter, system-ui',
            display: 'inline-flex', alignItems: 'center', gap: 4,
          }}>Open budget <Icon name="arrow-right" size={11} /></button>} />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
          {window.BUDGET.filter(b => b.kind !== 'goal').slice(0, 8).map(b => {
            const pct = b.planned ? (b.spent / b.planned) * 100 : 0;
            const over = pct > 100;
            return (
              <div key={b.cat}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, marginBottom: 6 }}>
                  <span style={{ color: '#1d2638' }}>{b.cat}</span>
                  <span style={{ color: over ? '#c97a4a' : '#7a766c', fontVariantNumeric: 'tabular-nums' }}>
                    {window.fmtShort(b.spent)} / {window.fmtShort(b.planned)}
                  </span>
                </div>
                <Bar pct={pct} over={over} color={b.kind === 'fixed' ? '#2b3a55' : '#7a9b7e'} />
              </div>
            );
          })}
        </div>
      </Card>
    </div>
  );
};

const TxRow = ({ t, first, dense }) => {
  const p = window.PEOPLE[t.who];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: dense ? '8px 0' : '11px 0',
      borderTop: first ? 'none' : '1px solid #ece8de',
    }}>
      <BankBadge bank={t.bank} size={26} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, color: '#1d2638', fontWeight: 500, display: 'flex', alignItems: 'center', gap: 6 }}>
          {t.merchant}
          {t.private && <Icon name="lock" size={11} stroke="#7a766c" />}
        </div>
        <div style={{ fontSize: 11, color: '#7a766c', marginTop: 1, display: 'flex', alignItems: 'center', gap: 6 }}>
          <span>{t.cat}</span>
          <span>·</span>
          <span>{t.acct}</span>
        </div>
      </div>
      <Avatar who={t.who} size={20} />
      <span style={{
        fontSize: 13, fontVariantNumeric: 'tabular-nums',
        color: t.amt > 0 ? '#7a9b7e' : '#1d2638', fontWeight: t.amt > 0 ? 500 : 400, width: 80, textAlign: 'right',
      }}>{(t.amt > 0 ? '+' : '') + window.fmt(t.amt).replace('.00','')}</span>
    </div>
  );
};

window.WebSidebar = WebSidebar;
window.HomeView = HomeView;
window.TxRow = TxRow;
