// portal.jsx — Renegade authenticated customer portal
const { useState: pUseState, useMemo: pUseMemo } = React;

const PORTAL_NAV = [
  { id: 'overview', label: 'Overview' },
  { id: 'usage', label: 'Usage' },
  { id: 'invoices', label: 'Invoices' },
  { id: 'payments', label: 'Payments' },
  { id: 'plan', label: 'Plan' },
  { id: 'details', label: 'My details' },
];

const PortalNav = ({ active, onNav, onLogout }) => {
  const [open, setOpen] = pUseState(false);
  const initials = ACCOUNT.name.split(' ').map(w => w[0]).join('');
  return (
    <div style={{ display: 'contents' }}>
      <nav className="pnav">
        <div className="container pnav-bar">
          <a onClick={() => onNav('overview')} style={{ borderBottom: 0, cursor: 'pointer', display: 'flex' }}><Logo height={26} /></a>
          <ul className="pnav-links">
            {PORTAL_NAV.map(it => <li key={it.id}><a className={active === it.id ? 'active' : ''} onClick={() => onNav(it.id)}>{it.label}</a></li>)}
          </ul>
          <div className="pnav-right">
            <div className="pnav-acct"><div className="avatar" style={{ width: 34, height: 34 }}>{initials}</div><span className="who-txt">{ACCOUNT.first}</span></div>
            <a className="who-txt" onClick={onLogout} style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-2)', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6 }}><Icon n="logOut" size={16} /> Log out</a>
            <button className="pnav-burger" aria-label="Menu" onClick={() => setOpen(o => !o)}><Icon n={open ? 'x' : 'menu'} size={24} /></button>
          </div>
        </div>
      </nav>
      <div className={'psheet' + (open ? ' open' : '')}>
        {PORTAL_NAV.map(it => <a key={it.id} className={active === it.id ? 'active' : ''} onClick={() => { setOpen(false); onNav(it.id); }}>{it.label}</a>)}
        <a onClick={() => { setOpen(false); onLogout(); }}>Log out</a>
      </div>
    </div>
  );
};

const PageHead = ({ eyebrow, title, sub, action }) => (
  <div className="page-head" style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
    <div>
      {eyebrow && <div className="eyebrow">{eyebrow}</div>}
      <h1 style={{ marginTop: eyebrow ? 6 : 0 }}>{title}</h1>
      {sub && <p>{sub}</p>}
    </div>
    {action}
  </div>
);

/* ---------------- Overview ---------------- */
const Overview = ({ onNav }) => {
  const plan = PLANS[ACCOUNT.planId];
  return (
    <div style={{ display: 'contents' }}>
      <PageHead title={`Welcome back, ${ACCOUNT.first}.`} sub={`You're on ${plan.name} · Account ${ACCOUNT.account}`} />
      <div className="grid-2">
        <div className="card card-outline">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
            <Badge kind="good" icon="checkCircle">Up to date</Badge>
            <a onClick={() => onNav('invoices')} style={{ fontSize: 13, fontWeight: 600, color: 'var(--support)', cursor: 'pointer', borderBottom: '1px solid currentColor' }}>View invoices</a>
          </div>
          <div className="balance" style={{ background: 'transparent', padding: 0 }}>
            <div className="eyebrow">Amount owing</div>
            <div className="amt tnum" style={{ marginTop: 10 }}><span className="c">$</span>0<span className="c">.00</span></div>
          </div>
          <div className="banner banner-good" style={{ marginTop: 20 }}>
            <Icon n="checkCircle" size={18} />
            <div>Your nominated account is debited on the due date. Next estimated debit <b>{ACCOUNT.nextDebit}</b>. You can pay anytime.</div>
          </div>
          <div style={{ display: 'flex', gap: 12, marginTop: 20, flexWrap: 'wrap' }}>
            <Button variant="primary" onClick={() => onNav('payments')}><Icon n="wallet" size={17} /> Make a payment</Button>
            <Button variant="secondary" onClick={() => onNav('invoices')}><Icon n="download" size={17} /> Latest invoice</Button>
          </div>
        </div>

        <div className="card card-sunken">
          <div style={{ fontWeight: 700, fontSize: 18 }}>{ACCOUNT.name}</div>
          <div style={{ fontSize: 13.5, color: 'var(--fg-2)', marginTop: 4 }}>{ACCOUNT.address}</div>
          <div className="mono" style={{ fontSize: 12.5, color: 'var(--fg-3)', marginTop: 6 }}>NMI {ACCOUNT.nmi}</div>
          <hr className="hr" />
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <div className="eyebrow">Current plan</div>
            <a onClick={() => onNav('plan')} style={{ fontSize: 13, fontWeight: 600, color: 'var(--support)', cursor: 'pointer', borderBottom: '1px solid currentColor' }}>Details</a>
          </div>
          <div style={{ fontWeight: 700, fontSize: 17, marginTop: 8 }}>{plan.name}</div>
          <div style={{ fontSize: 13, color: 'var(--fg-3)' }}>{ACCOUNT.billingCycle} billing · since {ACCOUNT.startDate}</div>
          <div style={{ marginTop: 16, display: 'grid', gap: 8 }}>
            {plan.tariffs.slice(0, 3).map(t => (
              <div key={t.name} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5 }}>
                <span style={{ color: 'var(--fg-2)' }}>{t.name}</span>
                <span className="mono" style={{ fontWeight: 600 }}>{t.rateIncGst}{t.unit}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div style={{ marginTop: 24 }}>
        <div className="section-label">This month at a glance</div>
        <div className="grid-4">
          <Stat lab="Used this cycle" val="284" u="kWh" sub="11 May – 30 May" />
          <Stat lab="Avg / day" val="14.9" u="kWh" sub="↓ 6% vs last cycle" />
          <Stat lab="Est. this bill" val={fmt$0(118)} accent sub="Tracking below estimate" />
          <Stat lab="Days to bill" val="9" u="days" sub="Closes 9 Jun" />
        </div>
      </div>

      <div style={{ marginTop: 24 }}>
        <div className="section-label">Quick actions</div>
        <div className="qa-grid">
          {[
            { ic: 'activity', t: 'See my usage', go: 'usage' },
            { ic: 'fileText', t: 'Download a bill', go: 'invoices' },
            { ic: 'meter', t: 'Submit a meter read', go: 'details' },
          ].map(q => (
            <div className="qa" key={q.t} onClick={() => onNav(q.go)}>
              <div className="ico"><Icon n={q.ic} size={22} /></div>
              <div className="t">{q.t}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

const Stat = ({ lab, val, u, sub, accent }) => (
  <div className={'stat' + (accent ? ' stat-accent' : '')}>
    <div className="lab">{lab}</div>
    <div className="val tnum">{val}{u && <span className="u">{u}</span>}</div>
    {sub && <div className="sub">{sub}</div>}
  </div>
);

/* ---------------- Usage ---------------- */
// deterministic pseudo-random
const rng = (seed) => { let s = seed; return () => { s = (s * 9301 + 49297) % 233280; return s / 233280; }; };
const buildDaily = () => {
  const r = rng(7); const out = [];
  for (let i = 1; i <= 30; i++) {
    const base = 11 + r() * 7;
    const peak = base * (0.30 + r() * 0.1);
    const shoulder = base * (0.34 + r() * 0.08);
    const off = base - peak - shoulder;
    out.push({ label: i, peak, shoulder, off, total: base });
  }
  return out;
};
const buildWeekly = () => {
  const r = rng(13); const out = [];
  const wk = ['28 Apr', '5 May', '12 May', '19 May', '26 May'];
  for (let i = 0; i < 5; i++) {
    const base = 92 + r() * 30;
    const peak = base * 0.32, shoulder = base * 0.36, off = base - peak - shoulder;
    out.push({ label: wk[i], peak, shoulder, off, total: base });
  }
  return out;
};
const buildMonthly = () => {
  const r = rng(29); const out = [];
  const mo = ['Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May'];
  for (let i = 0; i < 12; i++) {
    const seasonal = [430, 470, 455, 380, 320, 300, 340, 410, 360, 330, 360, 410][i];
    const base = seasonal + r() * 30;
    const peak = base * 0.31, shoulder = base * 0.35, off = base - peak - shoulder;
    out.push({ label: mo[i], peak, shoulder, off, total: base });
  }
  return out;
};

const UsageChart = ({ data, unit, stacked }) => {
  const [tip, setTip] = pUseState(null);
  const W = 880, H = 300, PADL = 44, PADB = 36, PADT = 16, PADR = 12;
  const innerW = W - PADL - PADR, innerH = H - PADT - PADB;
  const max = Math.max(...data.map(d => d.total)) * 1.12;
  const bw = innerW / data.length;
  const bar = Math.min(bw * 0.62, 46);
  const yTicks = 4;
  const x = (i) => PADL + i * bw + (bw - bar) / 2;
  const yv = (v) => PADT + innerH - (v / max) * innerH;
  const segColors = { off: 'var(--rng-navy-deep)', shoulder: 'var(--rng-navy-400)', peak: 'var(--accent)' };
  return (
    <div className="chart-card" style={{ position: 'relative' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 16, flexWrap: 'wrap', gap: 10 }}>
        <div>
          <div className="eyebrow">Consumption · NMI {ACCOUNT.nmi}</div>
          <div style={{ fontSize: 20, fontWeight: 600, marginTop: 4 }} className="tnum">{Math.round(data.reduce((a, d) => a + d.total, 0)).toLocaleString()} <span style={{ fontSize: 13, color: 'var(--fg-3)', fontWeight: 400 }}>kWh · {unit}</span></div>
        </div>
        <div className="chart-legend">
          <span className="lg"><span className="sw" style={{ background: segColors.off }} />Off-peak</span>
          <span className="lg"><span className="sw" style={{ background: segColors.shoulder }} />Shoulder</span>
          <span className="lg"><span className="sw" style={{ background: segColors.peak }} />Peak</span>
        </div>
      </div>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: 'block', overflow: 'visible' }}>
        {Array.from({ length: yTicks + 1 }).map((_, i) => {
          const v = (max / yTicks) * i;
          return (
            <g key={i}>
              <line x1={PADL} x2={W - PADR} y1={yv(v)} y2={yv(v)} stroke="var(--data-grid)" strokeWidth="1" />
              <text x={PADL - 10} y={yv(v) + 4} textAnchor="end" fontSize="11" fill="var(--fg-3)" className="tnum">{Math.round(v)}</text>
            </g>
          );
        })}
        <text x={14} y={PADT + innerH / 2} fontSize="11" fill="var(--fg-3)" transform={`rotate(-90 14 ${PADT + innerH / 2})`} textAnchor="middle">kWh</text>
        {data.map((d, i) => {
          const segs = stacked ? [['off', d.off], ['shoulder', d.shoulder], ['peak', d.peak]] : [['total', d.total]];
          let acc = 0;
          const showLabel = data.length <= 13 || i % Math.ceil(data.length / 12) === 0;
          return (
            <g key={i} onMouseEnter={() => setTip({ i, d })} onMouseLeave={() => setTip(null)} style={{ cursor: 'default' }}>
              <rect x={x(i) - (bw - bar) / 2} y={PADT} width={bw} height={innerH} fill="transparent" />
              {segs.map(([k, val]) => {
                const h = (val / max) * innerH;
                const yTop = yv(acc + val);
                acc += val;
                return <rect key={k} className="bar" x={x(i)} y={yTop} width={bar} height={Math.max(h, 0)} rx="2"
                  fill={stacked ? segColors[k] : 'var(--rng-navy-deep)'} style={{ transition: 'opacity .12s' }} opacity={tip && tip.i !== i ? 0.4 : 1} />;
              })}
              {showLabel && <text x={x(i) + bar / 2} y={H - 14} textAnchor="middle" fontSize="11" fill="var(--fg-3)">{d.label}</text>}
            </g>
          );
        })}
      </svg>
      {tip && (
        <div className="bartip" style={{ left: `${(PADL + tip.i * bw + bw / 2) / W * 100}%`, top: 30 }}>
          <div className="tt tnum">{tip.d.total.toFixed(1)} kWh</div>
          <div style={{ fontSize: 11, opacity: 0.85, marginTop: 2 }} className="tnum">Peak {tip.d.peak.toFixed(1)} · Shoulder {tip.d.shoulder.toFixed(1)} · Off {tip.d.off.toFixed(1)}</div>
        </div>
      )}
    </div>
  );
};

const Usage = () => {
  const [period, setPeriod] = pUseState('daily');
  const [stacked, setStacked] = pUseState(true);
  const data = pUseMemo(() => period === 'daily' ? buildDaily() : period === 'weekly' ? buildWeekly() : buildMonthly(), [period]);
  const unitLabel = { daily: 'this billing cycle', weekly: 'last 5 weeks', monthly: 'last 12 months' }[period];
  const total = data.reduce((a, d) => a + d.total, 0);
  const peak = Math.max(...data.map(d => d.total));
  const low = Math.min(...data.map(d => d.total));
  const avg = total / data.length;
  return (
    <div style={{ display: 'contents' }}>
      <PageHead title="Usage" sub="Half-hourly data from your smart meter, the day after it happens." />
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20, flexWrap: 'wrap', gap: 12 }}>
        <div className="segmented">
          {['daily', 'weekly', 'monthly'].map(p => (
            <button key={p} aria-selected={period === p} onClick={() => setPeriod(p)} style={{ textTransform: 'capitalize' }}>{p}</button>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 12 }}>
          <div className="segmented">
            <button aria-selected={stacked} onClick={() => setStacked(true)}>Time of use</button>
            <button aria-selected={!stacked} onClick={() => setStacked(false)}>Total</button>
          </div>
          <Button variant="secondary" size="sm"><Icon n="download" size={16} /> CSV</Button>
        </div>
      </div>
      <UsageChart data={data} unit={unitLabel} stacked={stacked} />
      <div className="grid-4" style={{ marginTop: 20 }}>
        <Stat lab="Total used" val={Math.round(total).toLocaleString()} u="kWh" sub={unitLabel} accent />
        <Stat lab="Daily average" val={avg.toFixed(1)} u="kWh" />
        <Stat lab="Highest" val={peak.toFixed(1)} u="kWh" />
        <Stat lab="Lowest" val={low.toFixed(1)} u="kWh" />
      </div>
      <div className="banner banner-info" style={{ marginTop: 20 }}>
        <Icon n="info" size={18} />
        <div>Most of your use sits in the off-peak window — nicely suited to your Time-of-Use Saver plan. Shifting more of the orange (peak) block before 3pm or after 10pm would cut your bill further.</div>
      </div>
    </div>
  );
};

/* ---------------- Invoices ---------------- */
const INVOICES = [
  { period: '11 Apr – 10 May 2026', due: '27 May 2026', amount: 121.40, status: 'paid' },
  { period: '11 Mar – 10 Apr 2026', due: '27 Apr 2026', amount: 118.05, status: 'paid' },
  { period: '11 Feb – 10 Mar 2026', due: '27 Mar 2026', amount: 132.77, status: 'paid' },
  { period: '4 Feb – 10 Feb 2026', due: '24 Feb 2026', amount: 38.19, status: 'paid' },
];
const Invoices = () => (
  <div style={{ display: 'contents' }}>
    <PageHead title="Invoices" sub="Every bill since you joined, ready to download." />
    <div className="card card-sunken" style={{ marginBottom: 20, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16 }}>
      <div>
        <div className="eyebrow">Latest bill</div>
        <div style={{ display: 'flex', gap: 28, marginTop: 10, flexWrap: 'wrap' }}>
          <div><div style={{ fontSize: 12.5, color: 'var(--fg-3)' }}>Due date</div><div style={{ fontWeight: 700, marginTop: 2 }}>27 May 2026</div></div>
          <div><div style={{ fontSize: 12.5, color: 'var(--fg-3)' }}>Amount due</div><div style={{ fontWeight: 700, marginTop: 2 }} className="mono">$0.00</div></div>
          <div><div style={{ fontSize: 12.5, color: 'var(--fg-3)' }}>Status</div><div style={{ marginTop: 2 }}><Badge kind="good" icon="checkCircle">Paid</Badge></div></div>
        </div>
      </div>
      <Button variant="primary"><Icon n="download" size={17} /> Download latest bill</Button>
    </div>
    <div className="tbl-wrap">
      <table className="rng-table">
        <thead><tr><th>Billing period</th><th>Due date</th><th className="num">Amount</th><th>Status</th><th style={{ textAlign: 'right' }}>Bill</th></tr></thead>
        <tbody>
          {INVOICES.map((inv, i) => (
            <tr key={i}>
              <td style={{ fontWeight: 600 }}>{inv.period}</td>
              <td style={{ color: 'var(--fg-2)' }}>{inv.due}</td>
              <td className="num num-strong tnum">{fmt$(inv.amount)}</td>
              <td><Badge kind="good">Paid</Badge></td>
              <td><div className="row-act"><button className="icon-btn accent" aria-label="Download invoice"><Icon n="download" size={17} /></button></div></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </div>
);

/* ---------------- Payments ---------------- */
const Payments = () => {
  const [tab, setTab] = pUseState('make');
  const [checked, setChecked] = pUseState(false);
  return (
    <div style={{ display: 'contents' }}>
      <PageHead title="Payments" sub="Pay a bill, review history, or manage how you pay." />
      <div className="pilltabs" style={{ marginBottom: 24 }}>
        {[['make', 'Make a payment'], ['history', 'Payment history'], ['methods', 'Payment methods']].map(([id, l]) => (
          <button key={id} aria-selected={tab === id} onClick={() => setTab(id)}>{l}</button>
        ))}
      </div>

      {tab === 'make' && (
        <div style={{ maxWidth: 640 }}>
          <div className="card card-sunken">
            <div className="eyebrow">Total balance</div>
            <div className="balance" style={{ background: 'transparent', padding: 0, marginTop: 8 }}>
              <div className="amt tnum"><span className="c">$</span>0<span className="c">.00</span></div>
            </div>
            <Badge kind="good" icon="checkCircle">Paid in full</Badge>
            <hr className="hr" />
            <div className="section-label">Accounts</div>
            <label className={'radio-card' + (checked ? ' sel' : '')} style={{ alignItems: 'center' }}>
              <input className="cbox" type="checkbox" checked={checked} onChange={e => setChecked(e.target.checked)} />
              <div style={{ flex: 1, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
                <div><div className="mono" style={{ fontWeight: 700, fontSize: 15 }}>{ACCOUNT.account}</div><div className="csub">{ACCOUNT.address}</div></div>
                <div style={{ textAlign: 'right' }}><div className="mono" style={{ fontWeight: 700 }}>$0.00</div><div style={{ fontSize: 11, color: 'var(--fg-3)' }}>PAID</div></div>
              </div>
            </label>
            <div style={{ display: 'flex', gap: 12, marginTop: 18, alignItems: 'center' }}>
              <Button variant="secondary"><Icon n="creditCard" size={17} /> BPAY details</Button>
              <Button variant="primary" disabled={!checked} style={{ marginLeft: 'auto' }}>Pay now</Button>
            </div>
          </div>
        </div>
      )}

      {tab === 'history' && (
        <div className="tbl-wrap" style={{ maxWidth: 720 }}>
          <table className="rng-table">
            <thead><tr><th>Date</th><th>Method</th><th className="num">Amount</th><th>Status</th></tr></thead>
            <tbody>
              {[['27 May 2026', 'Direct debit · Visa ••42', 121.40], ['27 Apr 2026', 'Direct debit · Visa ••42', 118.05], ['27 Mar 2026', 'Direct debit · Visa ••42', 132.77]].map((p, i) => (
                <tr key={i}><td style={{ fontWeight: 600 }}>{p[0]}</td><td style={{ color: 'var(--fg-2)' }}>{p[1]}</td><td className="num num-strong tnum">{fmt$(p[2])}</td><td><Badge kind="good">Processed</Badge></td></tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'methods' && (
        <div style={{ maxWidth: 640 }}>
          <div className="card card-outline" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16 }}>
            <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
              <div className="prop-ico"><Icon n="creditCard" size={22} /></div>
              <div><div style={{ fontWeight: 600 }}>Visa ending 42</div><div className="csub">Direct debit · expires 09/28</div></div>
            </div>
            <Badge kind="navy">Default</Badge>
          </div>
          <div style={{ marginTop: 16 }}><Button variant="secondary"><Icon n="plus" size={17} /> Add a payment method</Button></div>
          <div className="banner banner-info" style={{ marginTop: 20 }}>
            <Icon n="info" size={18} /><div>Direct debit is taken on each bill's due date. Switch to BPAY anytime to pay manually instead.</div>
          </div>
        </div>
      )}
    </div>
  );
};

/* ---------------- Plan details ---------------- */
const PlanDetails = ({ onNav }) => {
  const plan = PLANS[ACCOUNT.planId];
  return (
    <div style={{ display: 'contents' }}>
      <PageHead title="Plan details" sub={`${plan.name} · ${ACCOUNT.region} · ${ACCOUNT.distributor}`}
        action={<Button variant="secondary" onClick={() => onNav('usage')}><Icon n="activity" size={17} /> View usage</Button>} />
      <div className="card card-outline">
        <div className="grid-2" style={{ gridTemplateColumns: '1fr 1fr', alignItems: 'start' }}>
          <div>
            <div className="section-label">Product information</div>
            <Spec k="Product" v={plan.name} />
            <Spec k="Description" v={plan.desc} />
            <Spec k="Billing cycle" v={ACCOUNT.billingCycle} />
            <Spec k="Meter type" v="Smart (Type 4)" />
            <Spec k="Network" v={ACCOUNT.distributor} />
          </div>
          <div>
            <div className="section-label">Status</div>
            <Spec k="Plan code" v={<span className="mono" style={{ fontSize: 12.5 }}>{plan.code}</span>} />
            <Spec k="State" v={<Badge kind="good" icon="checkCircle">Active</Badge>} />
            <Spec k="Reference price" v={`${plan.refPct}% below`} />
            <Spec k="Rate guarantee" v="12 months, no lock-in" />
          </div>
        </div>
        <hr className="hr" />
        <div className="section-label">Charges (incl. GST)</div>
        <div className="tariff-grid">
          {plan.tariffs.map(t => (
            <div className="tariff" key={t.name}>
              <h5>{t.name}</h5>
              <div className="trow"><span className="k">Rate excl. GST</span><span className="v">{t.rateExGst}{t.unit}</span></div>
              <div className="trow"><span className="k">Rate incl. GST</span><span className="v">{t.rateIncGst}{t.unit}</span></div>
              <div className="trow"><span className="k">Time of day</span><span className="v" style={{ fontSize: 12 }}>{t.tod}</span></div>
            </div>
          ))}
        </div>
        <div className="banner banner-info" style={{ marginTop: 20 }}>
          <Icon n="fileText" size={18} /><div>Full terms, fees and the reference-price comparison are in your <a style={{ color: 'var(--support)', borderBottom: '1px solid currentColor', cursor: 'pointer' }}>Basic Plan Information document</a>.</div>
        </div>
      </div>
    </div>
  );
};
const Spec = ({ k, v }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', gap: 20, padding: '12px 0', borderBottom: '1px solid var(--bg-sunken)', alignItems: 'baseline' }}>
    <span style={{ fontSize: 13.5, color: 'var(--fg-2)', flex: 'none' }}>{k}</span>
    <span style={{ fontSize: 14, fontWeight: 600, textAlign: 'right' }}>{v}</span>
  </div>
);

/* ---------------- My details ---------------- */
const MyDetails = () => (
  <div style={{ display: 'contents' }}>
    <PageHead title="My details" sub="Your account, sites and security." />
    <div style={{ maxWidth: 760, display: 'grid', gap: 20 }}>
      <div className="card card-outline">
        <div className="section-label">Personal information</div>
        <Spec k="Full name" v={ACCOUNT.name} />
        <Spec k="Email" v={ACCOUNT.email} />
        <Spec k="Phone" v="0412 884 109" />
        <Spec k="Date of birth" v="2 Aug 1990" />
      </div>
      <div className="card card-outline">
        <div className="section-label">My sites (1)</div>
        <div className="card card-sunken" style={{ padding: 18 }}>
          <div style={{ fontWeight: 700 }}>{ACCOUNT.address}</div>
          <div className="mono" style={{ fontSize: 12.5, color: 'var(--fg-3)', marginTop: 4 }}>Account {ACCOUNT.account} · NMI {ACCOUNT.nmi}</div>
          <hr className="hr" style={{ margin: '14px 0' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5 }}><span style={{ color: 'var(--fg-2)' }}>Plan</span><span style={{ fontWeight: 600 }}>{PLANS[ACCOUNT.planId].name}</span></div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5, marginTop: 6 }}><span style={{ color: 'var(--fg-2)' }}>Billing</span><span style={{ fontWeight: 600 }}>{ACCOUNT.billingCycle}</span></div>
        </div>
      </div>
      <div className="card card-outline">
        <div className="section-label">Actions</div>
        <div className="qa-grid">
          {[['meter', 'Submit meter read'], ['lock', 'Change password'], ['plus', 'Add another site']].map(([ic, t]) => (
            <div className="qa" key={t}><div className="ico"><Icon n={ic} size={22} /></div><div className="t">{t}</div></div>
          ))}
        </div>
      </div>
      <div className="card card-outline">
        <div className="section-label">Need to change something?</div>
        <p style={{ fontSize: 14 }}>Update your account details or close your account by contacting our Australia-based team — real humans, no offshore queue.</p>
        <div style={{ display: 'flex', gap: 24, marginTop: 12, flexWrap: 'wrap', fontSize: 14 }}>
          <span style={{ display: 'flex', gap: 8, alignItems: 'center' }}><Icon n="phone" size={16} style={{ color: 'var(--support)' }} /> <b>13 RENEG</b> (13 7363)</span>
          <span style={{ display: 'flex', gap: 8, alignItems: 'center' }}><Icon n="mail" size={16} style={{ color: 'var(--support)' }} /> <b>help@renegade.energy</b></span>
        </div>
      </div>
    </div>
  </div>
);

/* ---------------- Portal shell ---------------- */
const Portal = ({ page, onNav, onLogout }) => (
  <div style={{ display: 'contents' }}>
    <PortalNav active={page} onNav={onNav} onLogout={onLogout} />
    <div className="portal-body">
      <div className="container">
        {page === 'overview' && <Overview onNav={onNav} />}
        {page === 'usage' && <Usage />}
        {page === 'invoices' && <Invoices />}
        {page === 'payments' && <Payments />}
        {page === 'plan' && <PlanDetails onNav={onNav} />}
        {page === 'details' && <MyDetails />}
      </div>
    </div>
    <Footer onNav={() => {}} />
  </div>
);
window.Portal = Portal;
