// Subscriptions — tracked recurring charges with status filters, search, sort,
// cycle-normalized spend, renewal signals, and an editable detail drawer.

const SUB_STATUS = {
  active:   { cls:'b-green', label:'Active' },
  trial:    { cls:'b-blue',  label:'Trial' },
  paused:   { cls:'b-gray',  label:'Paused' },
  canceled: { cls:'b-red',   label:'Cancelled' },
};
const SUB_STATUS_RANK = { active:0, trial:1, paused:2, canceled:3 };
const CYCLE_TO_MONTHLY = { Monthly:1, Yearly:1/12, Weekly:52/12 };
const SUB_BILLING = s => s.status === 'active' || s.status === 'trial';
const subAmt = s => parseFloat(String(s.amount).replace(/[$,]/g,'')) || 0;
const subMonthly = s => subAmt(s) * (CYCLE_TO_MONTHLY[s.cycle] ?? 1);
const SUB_TODAY = new Date().toISOString().slice(0,10);
const SUB_MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
const subFmt = d => `${SUB_MONTHS[d.getMonth()]} ${d.getDate()}`;
const daysUntil = iso => iso ? Math.round((new Date(iso) - new Date(SUB_TODAY)) / 86400000) : Infinity;

// ---- editable detail drawer ----
function SubDrawer({ sub, creating, onClose, onSave, onDelete }) {
  const [form, setForm] = useState(sub);
  useEffect(() => { setForm(sub); }, [sub]);
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const setNext = iso => setForm(f => ({ ...f, nextISO: iso, next: iso ? subFmt(new Date(iso)) : '—' }));
  const valid = String(form.name || '').trim();
  const save = () => onSave({ ...form, amount: '$' + (parseFloat(String(form.amount).replace(/[$,]/g,'')) || 0).toFixed(2) });
  const m = SUB_STATUS[form.status] || SUB_STATUS.active;

  return (
    <React.Fragment>
      <div className="scrim" onClick={onClose} />
      <div className="drawer zd-scroll">
        <div className="dhead">
          <IconChip icon={form.icon || 'credit-card'} tint={form.tint || 'green'} size={40} radius={12} />
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontFamily:'var(--font-display)', fontWeight:700, fontSize:18, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{form.name || (creating ? 'New subscription' : '')}</div>
            <div style={{ fontSize:12.5, color:'var(--fg-3)' }}>{creating ? 'Track a recurring charge' : `${form.plan || '—'} · ${form.cycle}`}</div>
          </div>
          <button className="iconbtn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>
        <div className="dbody">
          {!creating && (
            <div className="field"><div className="k">Cost</div>
              <div className="v zd-stat" style={{ fontSize:30 }}>{form.amount}<span style={{ fontSize:14, fontWeight:600, color:'var(--fg-3)' }}> / {form.cycle.toLowerCase()}</span></div>
              {form.cycle !== 'Monthly' && <div style={{ fontSize:12.5, color:'var(--fg-3)', marginTop:2 }}>≈ ${subMonthly(form).toFixed(2)} / month</div>}
            </div>
          )}

          <label className="fl">Service</label>
          <div className="finput"><Icon name="credit-card" size={16} color="var(--fg-4)" /><input value={form.name || ''} onChange={e => set('name', e.target.value)} placeholder="e.g. Notion" /></div>

          <div className="drow">
            <div style={{ flex:1 }}><label className="fl">Plan</label>
              <div className="finput"><Icon name="tag" size={16} color="var(--fg-4)" /><input value={form.plan || ''} onChange={e => set('plan', e.target.value)} placeholder="e.g. Pro" /></div>
            </div>
            <div style={{ flex:1 }}><label className="fl">Amount</label>
              <div className="finput"><span className="fpre">$</span><input value={String(form.amount ?? '').replace(/^\$/, '')} onChange={e => set('amount', e.target.value)} inputMode="decimal" placeholder="0.00" /></div>
            </div>
          </div>

          <div className="drow">
            <div style={{ flex:1 }}><label className="fl">Billing cycle</label>
              <Dropdown value={form.cycle} options={['Monthly','Yearly','Weekly'].map(c => ({ value:c, label:c }))} onChange={v => set('cycle', v)} minWidth={'100%'} />
            </div>
            <div style={{ flex:1 }}><label className="fl">Next billing</label>
              <div className="finput"><Icon name="calendar" size={16} color="var(--fg-4)" /><input type="date" value={form.nextISO || ''} onChange={e => setNext(e.target.value)} /></div>
            </div>
          </div>

          <label className="fl">Status</label>
          <div className="seg-full" style={{ flexWrap:'wrap' }}>
            {Object.keys(SUB_STATUS).map(st => (
              <button key={st} className={form.status === st ? 'on' : ''} onClick={() => set('status', st)}>{SUB_STATUS[st].label}</button>
            ))}
          </div>

          {!creating && (
            <div className="field"><div className="k">Detected from</div>
              <div className="v" style={{ display:'flex', alignItems:'center', gap:7, color:'var(--gold-600)', fontWeight:600, fontSize:14 }}>
                <Icon name="mail" size={15} color="var(--gold-600)" /> Receipt email · {form.name}
              </div>
            </div>
          )}

          <div className="drawer-foot">
            {!creating && <button className="iconbtn danger" onClick={() => onDelete(form.id)} title="Delete"><Icon name="trash-2" size={17} /></button>}
            <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
            <button className="btn btn-primary" style={{ flex:1, justifyContent:'center', opacity: valid ? 1 : .5, pointerEvents: valid ? 'auto' : 'none' }} onClick={save}>
              <Icon name="check" size={16} />{creating ? 'Add subscription' : 'Save changes'}
            </button>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}

function Subscriptions({ go }) {
  const D = window.ZD_DATA;
  const [subs, setSubs] = useState(D.subs);
  const [tab, setTab] = useState('all');
  const [q, setQ] = useState('');
  const [sel, setSel] = useState(null);
  const [creating, setCreating] = useState(false);
  const sort = useSort('nextISO', 'asc');

  const blank = () => ({ id:'s' + Date.now(), name:'', plan:'', amount:'', cycle:'Monthly', next:'—', nextISO:'', status:'active', tint:'green', icon:'credit-card' });
  const openNew = () => { setSel(blank()); setCreating(true); };
  useCreateShortcut(openNew);

  const counts = {
    all: subs.length,
    active: subs.filter(s => s.status === 'active').length,
    trial: subs.filter(s => s.status === 'trial').length,
    paused: subs.filter(s => s.status === 'paused').length,
    canceled: subs.filter(s => s.status === 'canceled').length,
  };
  const billing = subs.filter(SUB_BILLING);
  const monthly = billing.reduce((s, x) => s + subMonthly(x), 0);
  const renewSoon = billing.filter(s => { const d = daysUntil(s.nextISO); return d >= 0 && d <= 7; })
    .sort((a, b) => daysUntil(a.nextISO) - daysUntil(b.nextISO));

  let rows = subs.filter(s =>
    (tab === 'all' || s.status === tab) &&
    (s.name.toLowerCase().includes(q.toLowerCase()) || s.plan.toLowerCase().includes(q.toLowerCase()))
  );
  rows = sort.apply(rows, {
    name:    s => s.name.toLowerCase(),
    amountVal: s => subMonthly(s),
    nextISO: s => s.nextISO || '9999',
    status:  s => SUB_STATUS_RANK[s.status],
  });
  // keep inactive (paused/canceled) at the bottom of the "All" view
  if (tab === 'all' && sort.sortKey !== 'status') {
    rows = [...rows].sort((a, b) => (SUB_BILLING(a) ? 0 : 1) - (SUB_BILLING(b) ? 0 : 1));
  }
  const filtering = q || tab !== 'all';

  const saveSub = upd => {
    setSubs(list => list.some(s => s.id === upd.id) ? list.map(s => s.id === upd.id ? upd : s) : [upd, ...list]);
    setSel(null); setCreating(false);
  };
  const delSub = id => { setSubs(list => list.filter(s => s.id !== id)); setSel(null); setCreating(false); };

  return (
    <div className="screen-inner">
      <div className="statrow">
        <StatCard label="Active subscriptions" value={counts.active + counts.trial} sub={`${counts.trial} on trial · ${counts.paused + counts.canceled} inactive`} icon="trending-up" tint="purple" />
        <StatCard label="Monthly cost" value={`$${monthly.toFixed(2)}`} sub={`≈ $${(monthly * 12).toFixed(0)} / year`} icon="dollar-sign" tint="green" />
        <StatCard label="Renews this week" value={renewSoon.length} sub={renewSoon[0] ? `${renewSoon[0].name} — ${renewSoon[0].next}` : 'Nothing due soon'} icon="calendar-clock" tint={renewSoon.length ? 'gold' : 'green'} />
      </div>

      <div className="card rise" style={{ overflow:'hidden' }}>
        <div className="card-pad" style={{ paddingBottom:0 }}>
          <SectionHeader title="All subscriptions" sub="Automatically tracked from your email"
            actionEl={<Btn variant="primary" icon="plus" kbd="C" title="Add subscription — press C" onClick={openNew}>Add subscription</Btn>} />

          <div className="filterbar">
            <div className="search" style={{ flex:'1 1 220px' }}><Icon name="search" size={17} /><input placeholder="Search service or plan…" value={q} onChange={e => setQ(e.target.value)} />{q && <button className="x-clear" onClick={() => setQ('')}><Icon name="x" size={14} /></button>}</div>
            <MobileSort sort={sort} options={[
              { value:'nextISO:asc',    label:'Next billing (soonest)' },
              { value:'amountVal:desc', label:'Cost (high → low)' },
              { value:'amountVal:asc',  label:'Cost (low → high)' },
              { value:'name:asc',       label:'Name (A → Z)' },
              { value:'status:asc',     label:'Status' },
            ]} />
          </div>

          <div className="filtbar-2">
            <div className="tabs">
              {[['all','All'],['active','Active'],['trial','Trial'],['paused','Paused'],['canceled','Cancelled']].map(([id,lbl]) => (
                <button key={id} className={tab === id ? 'on' : ''} onClick={() => setTab(id)}>{lbl} <span className="tab-n">{counts[id]}</span></button>
              ))}
            </div>
            <div className="result-meta">
              <span>{rows.length} {rows.length === 1 ? 'sub' : 'subs'}</span>
              {filtering && <button className="viewall" onClick={() => { setQ(''); setTab('all'); }}>Clear</button>}
            </div>
          </div>
        </div>

        <table className="table sortable">
          <thead><tr>
            <SortTh label="Service" k="name" sort={sort} />
            <th>Plan</th>
            <SortTh label="Amount" k="amountVal" sort={sort} align="right" />
            <th>Cycle</th>
            <SortTh label="Next billing" k="nextISO" sort={sort} />
            <SortTh label="Status" k="status" sort={sort} />
            <th style={{ width:44 }}></th>
          </tr></thead>
          <tbody>
            {rows.map(s => {
              const st = SUB_STATUS[s.status] || SUB_STATUS.active;
              const soon = SUB_BILLING(s) && daysUntil(s.nextISO) >= 0 && daysUntil(s.nextISO) <= 7;
              const inactive = !SUB_BILLING(s);
              return (
                <tr key={s.id} onClick={() => { setSel(s); setCreating(false); }} style={{ cursor:'pointer', opacity: inactive ? .6 : 1 }}>
                  <td className="cell-first"><div className="cellmain"><IconChip icon={s.icon} tint={s.tint} /><span className="nm">{s.name}</span><MailboxBadge addr={mailboxFor(s)} variant="mini" /></div></td>
                  <td className="muted" data-label="Plan">{s.plan}</td>
                  <td className="amt-cell" data-label="Amount" style={{ textAlign:'right' }}>
                    {s.amount}{s.cycle !== 'Monthly' && <div className="sub-permo">≈ ${subMonthly(s).toFixed(2)}/mo</div>}
                  </td>
                  <td className="muted" data-label="Cycle">{s.cycle}</td>
                  <td className="muted" data-label="Next billing">{s.nextISO ? <span className={soon ? 'sub-soon' : ''}>{s.next}{soon ? ' · soon' : ''}</span> : '—'}</td>
                  <td data-label="Status"><span className={`badge ${st.cls}`}>{st.label}</span></td>
                  <td style={{ textAlign:'right' }} data-label="">
                    <button className="iconbtn" onClick={e => { e.stopPropagation(); setSel(s); setCreating(false); }} title="Edit"><Icon name="pencil" size={16} /></button>
                  </td>
                </tr>
              );
            })}
            {rows.length === 0 && <tr><td colSpan="7"><div className="table-empty"><Icon name="search-x" size={26} color="var(--fg-4)" /><span>No subscriptions match your filters.</span><button className="viewall" onClick={() => { setQ(''); setTab('all'); }}>Clear filters</button></div></td></tr>}
          </tbody>
        </table>
      </div>

      {sel && <SubDrawer sub={sel} creating={creating} onClose={() => { setSel(null); setCreating(false); }} onSave={saveSub} onDelete={delSub} />}
    </div>
  );
}
window.Subscriptions = Subscriptions;
