// Overview extra cards — Recent Spending (donut), Subscriptions, Money (tabbed).

function Donut({ data, size = 128, stroke = 20 }) {
  const r = (size - stroke) / 2, c = 2 * Math.PI * r;
  let off = 0;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform:'rotate(-90deg)', transformOrigin:'center' }}>
      <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--surface-sunk)" strokeWidth={stroke} />
      {data.map((d, i) => {
        const len = c * d.pct / 100;
        const seg = Math.max(len - 2.5, 0);
        const el = (
          <circle key={i} cx={size/2} cy={size/2} r={r} fill="none" stroke={d.color} strokeWidth={stroke}
            strokeDasharray={`${seg} ${c - seg}`} strokeDashoffset={-off} />
        );
        off += len;
        return el;
      })}
    </svg>
  );
}

function RecentSpending({ go }) {
  const sp = window.ZD_DATA.spending;
  const total = parseFloat(sp.total.replace(/[$,]/g, ''));
  const dailyAvg = (total / 7).toFixed(2);
  const top = sp.categories[0];
  return (
    <div className="card card-pad">
      <SectionHeader title="Recent spending" sub={sp.caption} action="Details" onAction={() => go('bills')} />
      <div className="spend-wrap">
        <div className="donut-wrap">
          <Donut data={sp.categories} size={150} stroke={22} />
          <div className="donut-center">
            <div className="dc-val">{sp.total}</div>
            <div className="dc-lbl">7 days</div>
          </div>
        </div>
        <div className="spend-legend">
          {sp.categories.map((c, i) => (
            <div className="leg-row" key={i}>
              <span className="leg-dot" style={{ background: c.color }} />
              <span className="leg-lbl">{c.label}</span>
              <span className="leg-amt">{c.amount}</span>
              <span className="leg-pct">{c.pct}%</span>
            </div>
          ))}
        </div>
      </div>
      <div className="spend-foot">
        <div className="sf">
          <div className="sf-k">Daily average</div>
          <div className="sf-v">${dailyAvg}</div>
        </div>
        <div className="sf">
          <div className="sf-k">Top category</div>
          <div className="sf-v"><span className="leg-dot" style={{ background: top.color }} /> {top.label}</div>
        </div>
      </div>
    </div>
  );
}

const SUB_PALETTE = ['#A855F7','#E2913C','#15A36B','#14A89B','#2664C9','#E25C5C','#C19A4B','#8A8A90'];

function SubscriptionsCard({ go }) {
  const subs = window.ZD_DATA.subs;
  const CYCLE = { Monthly:1, Yearly:1/12, Weekly:52/12 };
  const val = s => (parseFloat(String(s.amount).replace(/[$,]/g,'')) || 0) * (CYCLE[s.cycle] ?? 1);
  const billing = subs.filter(s => s.status === 'active' || s.status === 'trial');
  const total = billing.reduce((s, x) => s + val(x), 0);
  // largest share first, each with a distinct color
  const ranked = billing
    .map((s, i) => ({ ...s, val: val(s), color: SUB_PALETTE[i % SUB_PALETTE.length] }))
    .sort((a, b) => b.val - a.val);
  const shown = ranked.slice(0, 4);
  const rest = ranked.slice(4);
  const restVal = rest.reduce((s, x) => s + x.val, 0);
  const pctOf = v => total ? Math.round(v / total * 100) : 0;

  return (
    <div className="card card-pad">
      <SectionHeader title="Subscriptions" sub={`${billing.length} active · ${ranked[0] ? ranked[0].name + ' is largest' : 'none'}`} action="Manage" onAction={() => go('subs')} />
      <div className="subs-total">
        <div>
          <div className="st-val">${total.toFixed(2)}</div>
          <div className="st-lbl">per month</div>
        </div>
        <span className="badge b-green">On track</span>
      </div>

      {/* proportional distribution bar — every subscription is a segment */}
      <div className="subs-seg">
        {ranked.map(s => (
          <span key={s.id} style={{ width: `${(s.val / total) * 100}%`, background: s.color }} title={`${s.name} · ${s.amount} (${pctOf(s.val)}%)`} />
        ))}
      </div>

      {/* legend with share + amount per service */}
      <div className="subs-dist">
        {shown.map(s => (
          <div className="sd-row" key={s.id} onClick={() => go('subs')}>
            <span className="sd-dot" style={{ background: s.color }} />
            <span className="sd-name">{s.name}</span>
            <span className="sd-share">{pctOf(s.val)}%</span>
            <span className="sd-amt">{s.amount}</span>
          </div>
        ))}
      </div>
      {rest.length > 0 && (
        <div className="subs-more" onClick={() => go('subs')}>
          +{rest.length} more · ${restVal.toFixed(2)}/mo <Icon name="arrow-right" size={13} />
        </div>
      )}
    </div>
  );
}

function MoneyCard({ go }) {
  const D = window.ZD_DATA;
  const [tab, setTab] = useState('bills');
  const bills = D.bills.filter(b => b.status !== 'paid').slice(0,4);
  return (
    <div className="card card-pad">
      <div className="section-h">
        <div className="seg">
          <button className={tab==='bills' ? 'on' : ''} onClick={() => setTab('bills')}>Bills</button>
          <button className={tab==='receipts' ? 'on' : ''} onClick={() => setTab('receipts')}>Receipts</button>
        </div>
        <button className="viewall" onClick={() => go('bills')}>All <Icon name="arrow-right" size={14} /></button>
      </div>
      <div className="list">
        {tab === 'bills' ? bills.map(b => (
          <div className="lrow" key={b.id} onClick={() => go('bills')} style={{ cursor:'pointer' }}>
            <IconChip icon={b.icon} tint={b.catTint} />
            <div className="m">
              <div className="t">{b.merchant}</div>
              <div className="s" style={b.status === 'overdue' ? { color:'var(--red-500)', fontWeight:600 } : undefined}>
                {b.status === 'overdue' ? `Overdue · ${b.due}` : `due ${b.due}`}
              </div>
            </div>
            <Money amount={b.amountVal} ccy={b.ccy} size={15} primaryClass={b.status === 'overdue' ? 'amt-overdue' : ''} />
          </div>
        )) : D.receipts.slice(0,5).map(r => (
          <div className="lrow" key={r.id} onClick={() => go('bills')} style={{ cursor:'pointer' }}>
            <IconChip icon={r.icon} tint={r.tint} />
            <div className="m"><div className="t">{r.merchant}</div><div className="s">{r.detail}</div></div>
            {r.amountVal === 0 ? <span className="amt" style={{ color:'var(--fg-4)' }}>—</span> : <Money amount={r.amountVal} ccy={r.ccy} size={14.5} primaryClass={r.amountVal < 0 ? 'amt-neg' : ''} />}
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { Donut, RecentSpending, SubscriptionsCard, MoneyCard });
