/* Pages: Expenses · Clients · Tax center · Reports · Documents · Settings */

/* ── Expenses ─────────────────────────────────────────────────────────── */

function ExpensesPage() {
  const total = CB.expenseCategories.reduce((s, c) => s + c.amount, 0);
  const sorted = [...CB.expenseCategories].sort((a, b) => b.amount - a.amount);

  return (
    <div className="cb-page" data-screen-label="04 Expenses">
      <header className="cb-page-head">
        <div>
          <h1 className="cb-page-greet">Expenses</h1>
          <p className="cb-page-sub">
            {CB.fmtMoney(total)} spent in May — {sorted[0].label.toLowerCase()} is your biggest line.
          </p>
        </div>
        <div className="cb-page-head-right">
          <button type="button" className="cb-btn cb-btn-ghost">
            <IconDownload size={14} /> Export
          </button>
          <button type="button" className="cb-btn cb-btn-primary">
            <IconPlus size={14} /> Log expense
          </button>
        </div>
      </header>

      {/* Trend chart */}
      <section className="cb-panel">
        <PanelHeader eyebrow="6-month trend" title={CB.fmtMoney(total)}
          sub="Total operating expenses, May 2026" />
        <ExpenseTrend />
      </section>

      <div className="cb-grid-1-1">
        {/* Category breakdown */}
        <section className="cb-panel">
          <PanelHeader eyebrow="By category" title="Where the money went"
            sub={`${sorted.length} categories tracked`} />
          <ul className="cb-cat-list">
            {sorted.map((c) => {
              const pct = (c.amount / total) * 100;
              return (
                <li key={c.id}>
                  <div className="cb-cat-row">
                    <span className="cb-cat-swatch" style={{ background: c.color }} />
                    <span className="cb-cat-name">{c.label}</span>
                    <span className="cb-cat-count">{c.count} txns</span>
                    <span className="cb-cat-amt">{CB.fmtMoney(c.amount)}</span>
                    <span className="cb-cat-pct">{pct.toFixed(1)}%</span>
                  </div>
                  <div className="cb-cat-bar">
                    <div style={{ width: pct + '%', background: c.color }} />
                  </div>
                </li>
              );
            })}
          </ul>
        </section>

        {/* Stacked composition donut */}
        <section className="cb-panel">
          <PanelHeader eyebrow="This month" title="Composition"
            sub="Share of total expenses" />
          <ExpenseDonut categories={sorted} total={total} />
        </section>
      </div>
    </div>
  );
}

function ExpenseTrend() {
  const data = CB.expenseTrend;
  const W = 760, H = 180, PAD = { l: 48, r: 12, t: 18, b: 28 };
  const iw = W - PAD.l - PAD.r, ih = H - PAD.t - PAD.b;
  const max = Math.ceil(Math.max(...data.map((d) => d.value)) / 25000) * 25000;
  const barW = iw / data.length - 12;
  const [hover, setHover] = React.useState(null);

  return (
    <div className="cb-chart-wrap" style={{ aspectRatio: `${W} / ${H}` }}>
      <svg viewBox={`0 0 ${W} ${H}`} className="cb-chart" preserveAspectRatio="none">
        {[0, 0.5, 1].map((f, i) => {
          const y = PAD.t + ih - f * ih;
          return (
            <g key={i}>
              <line x1={PAD.l} y1={y} x2={W - PAD.r} y2={y}
                    stroke="var(--cb-line)" strokeDasharray={f === 0 ? '0' : '2 4'} />
              <text x={PAD.l - 8} y={y + 4} fontSize="11" textAnchor="end"
                    fill="var(--cb-fg-3)">{CB.fmtCompact(max * f)}</text>
            </g>
          );
        })}
        {data.map((d, i) => {
          const gx = PAD.l + i * (iw / data.length) + 6;
          const h = (d.value / max) * ih;
          const on = hover === i;
          const isLast = i === data.length - 1;
          return (
            <g key={i} onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}>
              <rect x={PAD.l + i * (iw / data.length)} y={PAD.t}
                    width={iw / data.length} height={ih} fill="transparent" />
              <rect x={gx} y={PAD.t + ih - h} width={barW} height={h} rx="4"
                    fill={isLast ? 'var(--cb-primary)' : 'var(--cb-fg-3)'}
                    opacity={on || hover == null ? (isLast ? 1 : 0.45) : 0.25} />
              <text x={gx + barW / 2} y={H - 8} fontSize="11" textAnchor="middle"
                    fill={on ? 'var(--cb-fg)' : 'var(--cb-fg-3)'}
                    fontWeight={on || isLast ? '600' : '400'}>{d.m}</text>
              {on && (
                <foreignObject x={Math.min(W - 130, Math.max(0, gx - 30))}
                               y={PAD.t + ih - h - 50} width="130" height="44">
                  <div xmlns="http://www.w3.org/1999/xhtml" className="cb-tip">
                    <div className="cb-tip-h">{d.m} 2026</div>
                    <div className="cb-tip-row"><span>Expenses</span><b>{CB.fmtMoney(d.value)}</b></div>
                  </div>
                </foreignObject>
              )}
            </g>
          );
        })}
      </svg>
    </div>
  );
}

function ExpenseDonut({ categories, total }) {
  const R = 80, IR = 56, CX = 130, CY = 130;
  let acc = 0;
  const segs = categories.map((c) => {
    const a0 = (acc / total) * Math.PI * 2 - Math.PI / 2;
    acc += c.amount;
    const a1 = (acc / total) * Math.PI * 2 - Math.PI / 2;
    return { c, a0, a1 };
  });
  const arc = (a0, a1, r) => {
    const x0 = CX + r * Math.cos(a0), y0 = CY + r * Math.sin(a0);
    const x1 = CX + r * Math.cos(a1), y1 = CY + r * Math.sin(a1);
    const large = a1 - a0 > Math.PI ? 1 : 0;
    return [x0, y0, large, x1, y1];
  };
  const [hover, setHover] = React.useState(null);
  return (
    <div className="cb-donut-wrap">
      <svg viewBox="0 0 260 260" width="260" height="260">
        {segs.map((s, i) => {
          const [x0, y0, large, x1, y1] = arc(s.a0, s.a1, R);
          const [ix0, iy0, _, ix1, iy1] = arc(s.a1, s.a0, IR);
          const d = `M ${x0} ${y0} A ${R} ${R} 0 ${large} 1 ${x1} ${y1} L ${ix0} ${iy0} A ${IR} ${IR} 0 ${large} 0 ${ix1} ${iy1} Z`;
          return (
            <path key={i} d={d} fill={s.c.color}
                  opacity={hover == null || hover === i ? 1 : 0.32}
                  onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)} />
          );
        })}
        <text x={CX} y={CY - 4} textAnchor="middle" fontSize="11"
              fill="var(--cb-fg-3)" letterSpacing="0.04em">TOTAL</text>
        <text x={CX} y={CY + 20} textAnchor="middle" fontSize="22" fontWeight="500"
              fill="var(--cb-fg)" style={{ fontVariantNumeric: 'tabular-nums' }}>
          {CB.fmtCompact(total)}
        </text>
      </svg>
      <ul className="cb-donut-legend">
        {categories.map((c) => (
          <li key={c.id}>
            <i style={{ background: c.color }} />
            <span>{c.label}</span>
            <b>{((c.amount / total) * 100).toFixed(1)}%</b>
          </li>
        ))}
      </ul>
    </div>
  );
}

/* ── Clients ──────────────────────────────────────────────────────────── */

function ClientsPage() {
  const total = CB.clients.reduce((s, c) => s + c.ltv, 0);
  const active = CB.clients.filter((c) => c.status === 'active').length;
  const open = CB.clients.reduce((s, c) => s + c.open, 0);

  return (
    <div className="cb-page" data-screen-label="05 Clients">
      <header className="cb-page-head">
        <div>
          <h1 className="cb-page-greet">Clients</h1>
          <p className="cb-page-sub">
            {active} active clients · {CB.fmtMoney(total)} lifetime billed · {CB.fmtMoney(open)} currently owed.
          </p>
        </div>
        <div className="cb-page-head-right">
          <button type="button" className="cb-btn cb-btn-ghost">
            <IconDownload size={14} /> Export
          </button>
          <button type="button" className="cb-btn cb-btn-primary">
            <IconPlus size={14} /> New client
          </button>
        </div>
      </header>

      <section className="cb-panel">
        <PanelHeader eyebrow="Customer book" title={`${CB.clients.length} clients`}
          sub="Sorted by lifetime value"
          right={
            <div className="cb-toolbar">
              <button type="button" className="cb-btn cb-btn-ghost">
                <IconFilter size={14} /> Filter
              </button>
            </div>
          } />

        <table className="cb-table">
          <thead>
            <tr>
              <th>Client</th>
              <th>Location</th>
              <th className="cb-num">Jobs</th>
              <th className="cb-num">Lifetime billed</th>
              <th className="cb-num">Open balance</th>
              <th>Last project</th>
              <th>Status</th>
              <th />
            </tr>
          </thead>
          <tbody>
            {[...CB.clients].sort((a, b) => b.ltv - a.ltv).map((c) => (
              <tr key={c.id} className="cb-table-row">
                <td>
                  <div className="cb-client-cell">
                    <span className="cb-client-avatar" style={{
                      background: `hsl(${(parseInt(c.id.slice(2), 10) * 41) % 360} 38% 70%)`
                    }}>{c.name.split(',')[0].split(' ').map((w) => w[0]).slice(0, 2).join('')}</span>
                    <div>
                      <div className="cb-strong">{c.name}</div>
                      <div className="cb-fg-2" style={{ fontSize: 11.5 }}>
                        Since {new Date(c.since + '-01').toLocaleDateString('en', { month: 'short', year: 'numeric' })}
                      </div>
                    </div>
                  </div>
                </td>
                <td>{c.city}</td>
                <td className="cb-num">{c.jobs}</td>
                <td className="cb-num cb-strong">{CB.fmtMoney(c.ltv)}</td>
                <td className="cb-num">
                  {c.open > 0
                    ? <span style={{ color: 'var(--cb-warn)', fontWeight: 500 }}>{CB.fmtMoney(c.open)}</span>
                    : <span className="cb-fg-3">—</span>}
                </td>
                <td className="cb-fg-2">{c.lastJob}</td>
                <td>
                  <span className={`cb-pill cb-pill-${
                    c.status === 'overdue' ? 'overdue' :
                    c.status === 'dormant' ? 'open' : 'paid'
                  }`}>
                    <i /> {c.status[0].toUpperCase() + c.status.slice(1)}
                  </span>
                </td>
                <td className="cb-row-actions"><IconChevRight size={16} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </section>
    </div>
  );
}

/* ── Tax Center ───────────────────────────────────────────────────────── */

function TaxCenterPage() {
  const t = CB.tax;
  const totalDeductions = CB.taxDeductions.reduce((s, d) => s + d.amount, 0);

  return (
    <div className="cb-page" data-screen-label="06 Tax center">
      <header className="cb-page-head">
        <div>
          <h1 className="cb-page-greet">Tax center</h1>
          <p className="cb-page-sub">
            Estimated quarterly taxes, deductions, and key dates — managed by your CB tax team.
          </p>
        </div>
        <div className="cb-page-head-right">
          <button type="button" className="cb-btn cb-btn-ghost">
            <IconDownload size={14} /> Download tax pack
          </button>
        </div>
      </header>

      <div className="cb-grid-2-1">
        <TaxWidget />

        <section className="cb-panel">
          <PanelHeader eyebrow="YTD" title={CB.fmtMoney(totalDeductions)}
            sub="Tracked deductions saving you money" />
          <ul className="cb-deduct-list">
            {CB.taxDeductions.map((d) => (
              <li key={d.id}>
                <div className="cb-deduct-row">
                  <span className="cb-deduct-name">{d.label}</span>
                  <b>{CB.fmtMoney(d.amount)}</b>
                </div>
                <div className="cb-deduct-hint">
                  <span className="cb-deduct-rate">{d.rate}</span>
                  <span>·</span>
                  <span>{d.hint}</span>
                </div>
              </li>
            ))}
          </ul>
          <div className="cb-deduct-foot">
            <span>Est. tax savings on these</span>
            <b style={{ color: 'var(--cb-pos)' }}>~{CB.fmtMoney(totalDeductions * 0.27)}</b>
          </div>
        </section>
      </div>

      <section className="cb-panel">
        <PanelHeader eyebrow="Filing calendar" title="Upcoming deadlines"
          sub="Federal + Washington state" />
        <ul className="cb-tax-cal">
          {CB.taxDates.map((d, i) => {
            const date = new Date(d.date + 'T12:00:00');
            const m = date.toLocaleDateString('en', { month: 'short' });
            const day = date.getDate();
            const days = Math.round((date - new Date('2026-05-22T12:00:00')) / 86400000);
            const past = days < 0;
            return (
              <li key={i} className="cb-tax-cal-row" data-status={d.status}>
                <div className="cb-tax-cal-date">
                  <span>{m}</span>
                  <b>{day}</b>
                </div>
                <div className="cb-tax-cal-body">
                  <div className="cb-tax-cal-label">{d.label}</div>
                  <div className="cb-tax-cal-meta">
                    {d.status === 'paid' ? `Paid ${m} ${day}, 2026`
                      : past ? 'Past due'
                      : days <= 30 ? `In ${days} days`
                      : `In ${Math.round(days / 7)} weeks`}
                  </div>
                </div>
                <div className="cb-tax-cal-amt">
                  {d.amount != null ? CB.fmtMoney(d.amount) : <span className="cb-fg-3">—</span>}
                </div>
                <span className={`cb-pill cb-pill-${
                  d.status === 'paid' ? 'paid' : d.status === 'upcoming' ? 'due-soon' : 'open'
                }`}>
                  <i /> {d.status === 'paid' ? 'Paid' : d.status === 'upcoming' ? 'Upcoming' : 'Future'}
                </span>
              </li>
            );
          })}
        </ul>
      </section>
    </div>
  );
}

/* ── Reports ──────────────────────────────────────────────────────────── */

function ReportsPage() {
  const groups = {
    core:  { title: 'Financial statements',  items: [] },
    jobs:  { title: 'Job performance',       items: [] },
    cash:  { title: 'Cash & receivables',    items: [] },
    tax:   { title: 'Tax & compliance',      items: [] },
  };
  CB.reports.forEach((r) => groups[r.kind].items.push(r));

  return (
    <div className="cb-page" data-screen-label="07 Reports">
      <header className="cb-page-head">
        <div>
          <h1 className="cb-page-greet">Reports</h1>
          <p className="cb-page-sub">Snapshot reports refreshed by Dana every Monday. Export anytime.</p>
        </div>
        <div className="cb-page-head-right">
          <button type="button" className="cb-btn cb-btn-primary">
            <IconPlus size={14} /> Custom report
          </button>
        </div>
      </header>

      {Object.entries(groups).map(([k, g]) => (
        g.items.length > 0 && (
          <section key={k} className="cb-panel">
            <PanelHeader eyebrow={k === 'core' ? 'Most-used' : 'Group'}
              title={g.title} sub={`${g.items.length} report${g.items.length === 1 ? '' : 's'}`} />
            <div className="cb-report-grid">
              {g.items.map((r) => (
                <article key={r.id} className="cb-report-card">
                  <div className="cb-report-ico">
                    <IconReceipt size={20} />
                  </div>
                  <div className="cb-report-body">
                    <div className="cb-report-name">{r.name}</div>
                    <p className="cb-report-desc">{r.desc}</p>
                    <div className="cb-report-meta">
                      <span><IconCalendar size={12} /> {r.cadence}</span>
                      <span className="cb-dot" />
                      <span>Updated {CB.fmtDate(r.updated)}</span>
                    </div>
                  </div>
                  <div className="cb-report-actions">
                    <button type="button" className="cb-icon-btn" aria-label="Open">
                      <IconExternal size={15} />
                    </button>
                    <button type="button" className="cb-icon-btn" aria-label="Download">
                      <IconDownload size={15} />
                    </button>
                  </div>
                </article>
              ))}
            </div>
          </section>
        )
      ))}
    </div>
  );
}

/* ── Documents ────────────────────────────────────────────────────────── */

function DocumentsPage({ pushToast }) {
  const [filter, setFilter] = React.useState('all');
  const tabs = ['all', 'Invoice', 'Estimate', 'Contract', 'Report', 'Receipt', 'Tax form', 'Insurance'];
  const filtered = filter === 'all'
    ? CB.documents
    : CB.documents.filter((d) => d.kind === filter);

  const kindIco = {
    Invoice: <IconInvoice size={16} />,
    Estimate: <IconReceipt size={16} />,
    Contract: <IconDocuments size={16} />,
    Report: <IconReports size={16} />,
    Receipt: <IconReceipt size={16} />,
    'Tax form': <IconTax size={16} />,
    Insurance: <IconDocuments size={16} />,
  };

  return (
    <div className="cb-page" data-screen-label="08 Documents">
      <header className="cb-page-head">
        <div>
          <h1 className="cb-page-greet">Documents</h1>
          <p className="cb-page-sub">
            Everything Dana files for you — contracts, receipts, tax forms, and reports.
          </p>
        </div>
        <div className="cb-page-head-right">
          <button type="button" className="cb-btn cb-btn-ghost">
            <IconDownload size={14} /> Download all
          </button>
          <button type="button" className="cb-btn cb-btn-primary">
            <IconPlus size={14} /> Upload
          </button>
        </div>
      </header>

      {CB.documents.some((d) => d.status === 'needs-sign') && (
        <div className="cb-banner">
          <span className="cb-banner-ico"><IconAlert size={18} /></span>
          <div className="cb-banner-body">
            <b>1 document awaiting your signature</b>
            <span>Patel — Change Order #2 needs to be signed before work proceeds.</span>
          </div>
          <div className="cb-banner-actions">
            <button type="button" className="cb-btn cb-btn-primary"
                    onClick={() => pushToast({
                      kind: 'success', icon: 'check',
                      title: 'Document signed',
                      body: 'Patel — Change Order #2 has been signed.',
                    })}>
              Review &amp; sign
            </button>
          </div>
        </div>
      )}

      <section className="cb-panel">
        <div className="cb-doc-tabs">
          {tabs.map((tb) => (
            <button key={tb} type="button" data-on={filter === tb ? '1' : '0'}
                    onClick={() => setFilter(tb)}>
              {tb === 'all' ? 'All' : tb}
              {tb !== 'all' && (
                <em>{CB.documents.filter((d) => d.kind === tb).length}</em>
              )}
            </button>
          ))}
        </div>

        <ul className="cb-doc-list">
          {filtered.map((d) => (
            <li key={d.id} className="cb-doc">
              <span className="cb-doc-ico">{kindIco[d.kind] || <IconDocuments size={16} />}</span>
              <div className="cb-doc-body">
                <div className="cb-doc-name">
                  {d.name}
                  {d.status === 'new' && <em className="cb-doc-tag cb-doc-tag-new">New</em>}
                  {d.status === 'needs-sign' && <em className="cb-doc-tag cb-doc-tag-sign">Needs signature</em>}
                </div>
                <div className="cb-doc-meta">
                  <span>{d.kind}</span>
                  <span className="cb-dot" />
                  <span>{d.size}</span>
                  <span className="cb-dot" />
                  <span>Added {CB.fmtDate(d.added)} · by {d.author}</span>
                </div>
              </div>
              <div className="cb-doc-actions">
                <button type="button" className="cb-icon-btn" aria-label="Open">
                  <IconExternal size={14} />
                </button>
                <button type="button" className="cb-icon-btn" aria-label="Download">
                  <IconDownload size={14} />
                </button>
                <button type="button" className="cb-icon-btn" aria-label="More">
                  <IconDots size={14} />
                </button>
              </div>
            </li>
          ))}
        </ul>
      </section>
    </div>
  );
}

/* ── Settings ─────────────────────────────────────────────────────────── */

function SettingsPage() {
  const [section, setSection] = React.useState('business');
  const sections = [
    { id: 'business',     label: 'Business profile' },
    { id: 'billing',      label: 'Billing & plan' },
    { id: 'team',         label: 'Team & access' },
    { id: 'connections',  label: 'Bank & connections' },
    { id: 'notifications',label: 'Notifications' },
  ];

  return (
    <div className="cb-page" data-screen-label="09 Settings">
      <header className="cb-page-head">
        <div>
          <h1 className="cb-page-greet">Settings</h1>
          <p className="cb-page-sub">Manage your business profile, plan, and integrations.</p>
        </div>
      </header>

      <div className="cb-settings">
        <nav className="cb-settings-nav">
          {sections.map((s) => (
            <button key={s.id} type="button" data-on={section === s.id ? '1' : '0'}
                    onClick={() => setSection(s.id)}>
              {s.label}
            </button>
          ))}
        </nav>
        <div className="cb-settings-body">
          {section === 'business' && <BusinessProfile />}
          {section === 'billing' && <BillingPanel />}
          {section === 'team' && <TeamPanel />}
          {section === 'connections' && <ConnectionsPanel />}
          {section === 'notifications' && <NotificationsPanel />}
        </div>
      </div>
    </div>
  );
}

function FormRow({ label, hint, children }) {
  return (
    <div className="cb-form-row">
      <div className="cb-form-label">
        <label>{label}</label>
        {hint && <span>{hint}</span>}
      </div>
      <div className="cb-form-field">{children}</div>
    </div>
  );
}

function BusinessProfile() {
  return (
    <section className="cb-panel">
      <PanelHeader eyebrow="Business" title="Hollister Construction Co."
        sub="Shown on invoices, estimates, and tax forms" />
      <div className="cb-form">
        <FormRow label="Legal business name">
          <input className="cb-input" defaultValue="Hollister Construction Co. LLC" />
        </FormRow>
        <FormRow label="DBA / Display name">
          <input className="cb-input" defaultValue="Hollister Construction Co." />
        </FormRow>
        <FormRow label="EIN" hint="Federal tax ID">
          <input className="cb-input" defaultValue="••-•••8842" />
        </FormRow>
        <FormRow label="Entity type">
          <select className="cb-input"><option>LLC (single-member)</option><option>S-Corp</option><option>Sole prop</option></select>
        </FormRow>
        <FormRow label="State of operation">
          <select className="cb-input"><option>Washington</option><option>Oregon</option><option>Idaho</option></select>
        </FormRow>
        <FormRow label="Trade license #" hint="WA Contractor Board">
          <input className="cb-input" defaultValue="HOLLICC834P9" />
        </FormRow>
      </div>
      <footer className="cb-form-foot">
        <button type="button" className="cb-btn cb-btn-ghost">Cancel</button>
        <button type="button" className="cb-btn cb-btn-primary">Save changes</button>
      </footer>
    </section>
  );
}

function BillingPanel() {
  return (
    <section className="cb-panel">
      <PanelHeader eyebrow="Plan" title="Contractor Pro"
        sub="$129/mo · billed monthly · next charge Jun 1" />
      <div className="cb-plan-card">
        <div>
          <b>Contractor Pro</b>
          <span>Unlimited invoices, payroll for up to 10 employees, dedicated bookkeeper.</span>
        </div>
        <button type="button" className="cb-btn cb-btn-ghost">Change plan</button>
      </div>
      <div className="cb-payment-card">
        <div className="cb-payment-brand">VISA</div>
        <div>
          <b>•••• •••• •••• 4108</b>
          <span>Expires 08/28 · default</span>
        </div>
        <button type="button" className="cb-btn cb-btn-ghost">Update</button>
      </div>
    </section>
  );
}

function TeamPanel() {
  const team = [
    { name: 'Mike Hollister', email: 'mike@hollister.co', role: 'Owner', last: 'Online now' },
    { name: 'Dana Reyes',     email: 'dana@cbbooks.com', role: 'Bookkeeper', last: '2 hours ago' },
    { name: 'Linda Hollister',email: 'linda@hollister.co', role: 'Office manager', last: 'Yesterday' },
  ];
  return (
    <section className="cb-panel">
      <PanelHeader eyebrow="Team" title="3 members"
        sub="People who can see your books"
        right={<button type="button" className="cb-btn cb-btn-primary"><IconPlus size={14} /> Invite</button>} />
      <ul className="cb-team-list">
        {team.map((m, i) => (
          <li key={i}>
            <span className="cb-team-avatar" style={{ background: `hsl(${i * 80} 38% 70%)` }}>
              {m.name.split(' ').map((w) => w[0]).join('')}
            </span>
            <div className="cb-team-body">
              <b>{m.name}</b>
              <span>{m.email}</span>
            </div>
            <span className="cb-pill cb-pill-open"><i /> {m.role}</span>
            <span className="cb-team-last">{m.last}</span>
            <button type="button" className="cb-icon-btn"><IconDots size={14} /></button>
          </li>
        ))}
      </ul>
    </section>
  );
}

function ConnectionsPanel() {
  const conns = [
    { name: 'Chase Business Banking', sub: 'Checking ••4421 · Savings ••1187', status: 'connected', when: 'Synced 12 min ago' },
    { name: 'Stripe Payments',        sub: 'Card processing & ACH',            status: 'connected', when: 'Synced 1 hour ago' },
    { name: 'ADP Run Payroll',        sub: 'Bi-weekly payroll',                status: 'connected', when: 'Synced yesterday' },
    { name: 'QuickBooks Time',        sub: 'Crew time tracking',               status: 'connect',   when: 'Not connected' },
    { name: 'CompanyCam',             sub: 'Photo documentation per job',      status: 'connect',   when: 'Not connected' },
  ];
  return (
    <section className="cb-panel">
      <PanelHeader eyebrow="Connections" title="5 integrations"
        sub="Banks, payment processors, and tools" />
      <ul className="cb-conn-list">
        {conns.map((c, i) => (
          <li key={i}>
            <span className="cb-conn-ico">
              {c.status === 'connected' ? <IconWallet size={18} /> : <IconExternal size={18} />}
            </span>
            <div className="cb-conn-body">
              <b>{c.name}</b>
              <span>{c.sub}</span>
            </div>
            <span className="cb-conn-when">{c.when}</span>
            {c.status === 'connected'
              ? <span className="cb-pill cb-pill-paid"><i /> Connected</span>
              : <button type="button" className="cb-btn cb-btn-secondary">Connect</button>}
          </li>
        ))}
      </ul>
    </section>
  );
}

function NotificationsPanel() {
  const groups = [
    { title: 'Invoicing', items: [
      ['When a client opens an invoice', true],
      ['When an invoice is overdue', true],
      ['When a client pays', true],
    ]},
    { title: 'Cash & banking', items: [
      ['Large transactions over $5,000', true],
      ['Cash dips below 4-week runway', true],
      ['Weekly cash flow digest', false],
    ]},
    { title: 'Tax', items: [
      ['Quarterly estimate due in 30 days', true],
      ['Document needs your signature', true],
    ]},
  ];
  return (
    <section className="cb-panel">
      <PanelHeader eyebrow="Alerts" title="Email & in-app"
        sub="Quiet hours 8pm–7am · timezone PT" />
      <div className="cb-notif-groups">
        {groups.map((g, i) => (
          <div key={i} className="cb-notif-group">
            <div className="cb-notif-group-h">{g.title}</div>
            {g.items.map(([label, on], j) => (
              <ToggleRow key={j} label={label} initial={on} />
            ))}
          </div>
        ))}
      </div>
    </section>
  );
}

function ToggleRow({ label, initial }) {
  const [on, set] = React.useState(initial);
  return (
    <div className="cb-toggle-row">
      <span>{label}</span>
      <button type="button" className="cb-switch" data-on={on ? '1' : '0'}
              onClick={() => set(!on)} aria-pressed={on}>
        <i />
      </button>
    </div>
  );
}

Object.assign(window, {
  ExpensesPage, ClientsPage, TaxCenterPage, ReportsPage, DocumentsPage, SettingsPage,
});
