// Receipts — order confirmations, refunds & statements from email.
// Search + date-range filter, source links, attachments, multi-currency amounts,
// row actions (edit / ignore / delete) and an editable detail drawer.

const RECEIPT_TYPES = [
  { value:'all',       label:'All types' },
  { value:'purchase',  label:'Purchases' },
  { value:'refund',    label:'Refunds' },
  { value:'statement', label:'Statements' },
];
const RCPT_CATS = ['Shopping','Food & Dining','Transport','Subscriptions','Utilities','Services','Healthcare','Travel','Other'];
const rcptTypeTint = t => t === 'refund' ? 'b-red' : t === 'statement' ? 'b-blue' : 'b-teal';
const RCPT_MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
const rcptFmt = d => `${RCPT_MONTHS[d.getMonth()]} ${d.getDate()}`;

// ---- edit / create drawer ----
function ReceiptDrawer({ rcpt, creating, onClose, onSave, onDelete, onIgnore, dismissed }) {
  const D = window.ZD_DATA;
  const [form, setForm] = useState(rcpt);
  const fileRef = useRef(null);
  useEffect(() => { setForm(rcpt); }, [rcpt]);
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const atts = form.attachments || [];
  const ccyOpts = Object.keys(D.fx.rates).map(c => ({ value:c, label:c }));
  const addFiles = e => { const p = [...e.target.files].map(f => ({ id:'at' + Date.now() + Math.random().toString(36).slice(2,5), name:f.name, size:f.size, url:URL.createObjectURL(f) })); set('attachments', [...atts, ...p]); e.target.value = ''; };
  const setDate = iso => setForm(f => ({ ...f, dateISO: iso, date: iso ? rcptFmt(new Date(iso)) : '' }));
  const valid = String(form.merchant || '').trim();
  const save = () => onSave({ ...form, amountVal: (form.type === 'refund' ? -Math.abs(parseFloat(String(form.amountVal).replace(/[^0-9.]/g,'')) || 0) : Math.abs(parseFloat(String(form.amountVal).replace(/[^0-9.]/g,'')) || 0)) });

  return (
    <React.Fragment>
      <div className="scrim" onClick={onClose} />
      <div className="drawer zd-scroll">
        <div className="dhead">
          <IconChip icon={form.icon || 'receipt'} tint={form.tint || 'teal'} 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.merchant || (creating ? 'New receipt' : '')}</div>
            <div style={{ fontSize:12.5, color:'var(--fg-3)' }}>{creating ? 'Log a purchase or refund' : (form.detail || 'Receipt')}</div>
          </div>
          <button className="iconbtn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>
        <div className="dbody">
          {!creating && form.items && form.items.length > 0 && (
            <div className="field"><div className="k">{form.type === 'refund' ? 'What was refunded' : 'What was purchased'}</div>
              <LineItems items={form.items} ccy={form.ccy} total={Math.abs(form.amountVal)} /></div>
          )}
          <label className="fl">Merchant</label>
          <div className="finput"><Icon name="store" size={16} color="var(--fg-4)" /><input value={form.merchant || ''} onChange={e => set('merchant', e.target.value)} placeholder="Where from?" /></div>

          <label className="fl">Description</label>
          <div className="finput"><Icon name="text" size={16} color="var(--fg-4)" /><input value={form.detail || ''} onChange={e => set('detail', e.target.value)} placeholder="What was it?" /></div>

          <div className="drow">
            <div style={{ flex:1.4 }}>
              <label className="fl">Amount</label>
              <div className="finput"><span className="fpre">{(CCY_META[form.ccy] || CCY_META.USD).sym}</span><input value={String(Math.abs(form.amountVal ?? 0) || '')} onChange={e => set('amountVal', e.target.value)} inputMode="decimal" placeholder="0.00" /></div>
            </div>
            <div style={{ flex:1 }}>
              <label className="fl">Currency</label>
              <Dropdown value={form.ccy || 'USD'} options={ccyOpts} onChange={v => set('ccy', v)} minWidth={'100%'} />
            </div>
          </div>

          {form.ccy && form.ccy !== D.fx.home && Math.abs(parseFloat(String(form.amountVal)) || 0) > 0 && (
            <div className="ccy-preview">
              <div className="k">Display preview · {D.fx.home}</div>
              <Money amount={Math.abs(parseFloat(String(form.amountVal).replace(/[^0-9.]/g,'')) || 0)} ccy={form.ccy} align="left" size={22} primaryClass="zd-stat" />
            </div>
          )}

          <div className="drow">
            <div style={{ flex:1 }}>
              <label className="fl">Date</label>
              <div className="finput"><Icon name="calendar" size={16} color="var(--fg-4)" /><input type="date" value={form.dateISO || ''} onChange={e => setDate(e.target.value)} /></div>
            </div>
            <div style={{ flex:1 }}>
              <label className="fl">Order # <span className="fl-opt">optional</span></label>
              <div className="finput"><Icon name="hash" size={16} color="var(--fg-4)" /><input value={form.order || ''} onChange={e => set('order', e.target.value)} placeholder="#1234" /></div>
            </div>
          </div>

          <label className="fl">Type</label>
          <div className="seg-full">
            {[['purchase','Purchase'],['refund','Refund'],['statement','Statement']].map(([v,l]) => (
              <button key={v} className={form.type === v ? 'on' : ''} onClick={() => set('type', v)}>{l}</button>
            ))}
          </div>

          <label className="fl">Category</label>
          <Dropdown value={form.cat} options={RCPT_CATS.map(c => ({ value:c, label:c }))} onChange={v => set('cat', v)} minWidth={'100%'} icon="tag" />

          <label className="fl">Attachments</label>
          <AttachmentList items={atts} onRemove={id => set('attachments', atts.filter(a => a.id !== id))} onAdd={() => fileRef.current && fileRef.current.click()} />
          <input ref={fileRef} type="file" multiple style={{ display:'none' }} onChange={addFiles} />

          {form.source && <button className="viewall" style={{ paddingLeft:0, marginTop:6 }}><Icon name="mail" size={14} /> View source email</button>}

          <div className="drawer-foot">
            {!creating && <button className="iconbtn danger" onClick={() => onDelete(form.id)} title="Delete"><Icon name="trash-2" size={17} /></button>}
            {!creating && <button className="iconbtn" onClick={onIgnore} title={dismissed ? 'Un-ignore' : 'Ignore'}><Icon name={dismissed ? 'rotate-ccw' : 'ban'} 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 receipt' : 'Save receipt'}</button>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}

function Receipts() {
  const D = window.ZD_DATA;
  const [receipts, setReceipts] = useState(D.receipts);
  const [q, setQ] = useState('');
  const [type, setType] = useState('all');
  const [from, setFrom] = useState('');
  const [to, setTo] = useState('');
  const [dismissed, setDismissed] = useState(new Set());
  const [showDismissed, setShowDismissed] = useState(false);
  const [sel, setSel] = useState(null);
  const [creating, setCreating] = useState(false);
  const sort = useSort('dateISO', 'desc');

  const blank = () => ({ id:'r' + Date.now(), merchant:'', detail:'', icon:'receipt', tint:'teal', order:'', ccy:'USD', amountVal:0, date:'', dateISO:'', cat:'Shopping', type:'purchase', source:false, attachments:[] });
  const saveRcpt = upd => { setReceipts(list => list.some(r => r.id === upd.id) ? list.map(r => r.id === upd.id ? upd : r) : [upd, ...list]); setSel(null); setCreating(false); };
  const delRcpt = id => { setReceipts(list => list.filter(r => r.id !== id)); setSel(null); setCreating(false); };
  const toggleDismiss = id => setDismissed(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });

  let rows = receipts.filter(r =>
    (type === 'all' || r.type === type) &&
    (showDismissed || !dismissed.has(r.id)) &&
    (!from || r.dateISO >= from) && (!to || r.dateISO <= to) &&
    (r.merchant.toLowerCase().includes(q.toLowerCase()) || r.detail.toLowerCase().includes(q.toLowerCase()) || (r.cat || '').toLowerCase().includes(q.toLowerCase()))
  );
  rows = sort.apply(rows, {
    merchant:  r => r.merchant.toLowerCase(),
    cat:       r => (r.cat || '').toLowerCase(),
    amountVal: r => toHome(r.amountVal, r.ccy),
    dateISO:   r => r.dateISO,
  });
  const net = rows.reduce((s, r) => s + toHome(r.amountVal, r.ccy), 0);
  const filtering = q || type !== 'all' || from || to;

  return (
    <React.Fragment>
    <div className="card rise" style={{ overflow:'hidden' }}>
      <div className="card-pad" style={{ paddingBottom:0 }}>
        <SectionHeader title="Receipts" sub="Order confirmations, refunds & statements from your email"
          actionEl={<Btn variant="primary" icon="plus" onClick={() => { setSel(blank()); setCreating(true); }}>Add receipt</Btn>} />
        <div className="filterbar">
          <div className="search" style={{ flex:'1 1 200px' }}><Icon name="search" size={17} /><input placeholder="Search by store, item or category…" value={q} onChange={e => setQ(e.target.value)} />{q && <button className="x-clear" onClick={() => setQ('')}><Icon name="x" size={14} /></button>}</div>
          <div className="date-range">
            <div className="finput date-mini"><input type="date" value={from} onChange={e => setFrom(e.target.value)} aria-label="From date" /></div>
            <span className="dr-sep">to</span>
            <div className="finput date-mini"><input type="date" value={to} onChange={e => setTo(e.target.value)} aria-label="To date" /></div>
          </div>
          <Dropdown value={type} options={RECEIPT_TYPES} onChange={setType} icon="filter" minWidth={146} />
          <MobileSort sort={sort} options={[
            { value:'dateISO:desc',   label:'Date (newest)' },
            { value:'dateISO:asc',    label:'Date (oldest)' },
            { value:'amountVal:desc', label:'Amount (high → low)' },
            { value:'amountVal:asc',  label:'Amount (low → high)' },
            { value:'merchant:asc',   label:'Merchant (A → Z)' },
          ]} />
        </div>
        <div className="filtbar-2">
          <div className="result-meta" style={{ marginLeft:0 }}>
            <span>{rows.length} {rows.length === 1 ? 'receipt' : 'receipts'} · net <b style={{ color:'var(--fg-1)' }}>{fmtCcy(net, D.fx.home)}</b></span>
            {dismissed.size > 0 && <button className="viewall" onClick={() => setShowDismissed(s => !s)}>{showDismissed ? 'Hide' : 'Show'} {dismissed.size} ignored</button>}
            {filtering && <button className="viewall" onClick={() => { setQ(''); setType('all'); setFrom(''); setTo(''); }}>Clear</button>}
          </div>
        </div>
      </div>
      <table className="table sortable">
        <thead><tr>
          <SortTh label="Merchant" k="merchant" sort={sort} />
          <SortTh label="Category" k="cat" sort={sort} />
          <SortTh label="Amount" k="amountVal" sort={sort} align="right" />
          <SortTh label="Date" k="dateISO" sort={sort} />
          <th>Type</th>
          <th style={{ width:96, textAlign:'right' }}>Actions</th>
        </tr></thead>
        <tbody>
          {rows.map(r => {
            const ign = dismissed.has(r.id);
            const isZero = r.amountVal === 0;
            return (
              <tr key={r.id} onClick={() => { setSel(r); setCreating(false); }} style={{ cursor:'pointer', opacity: ign ? .5 : 1 }}>
                <td className="cell-first">
                  <div className="cellmain"><IconChip icon={r.icon} tint={r.tint} />
                    <div><div className="nm">{r.merchant}</div>
                      <div className="sub-acct">{r.order}{r.source && <button className="src-pin" title="View source email" onClick={e => { e.stopPropagation(); openAttachment({ name:'Source email · ' + r.merchant }); }}><Icon name="mail" size={11} /></button>}{r.attachments && r.attachments.length > 0 && <span className="att-pin" onClick={e => { e.stopPropagation(); openAttachment(r.attachments[0]); }} style={{ marginLeft: 4, cursor:'pointer' }}><Icon name="paperclip" size={11} /> {r.attachments.length}</span>}{r.items && r.items.length > 1 && <span className="att-pin" title={`${r.items.length} line items`} style={{ marginLeft: 4 }}><Icon name="list" size={11} /> {r.items.length}</span>}<MailboxBadge addr={mailboxFor(r)} variant="mini" /></div>
                    </div>
                  </div>
                </td>
                <td data-label="Category"><span className="cat-tag"><span className="dd-dot" style={{ background: tintFg(r.tint) }} />{r.cat}</span></td>
                <td className="amt-cell" data-label="Amount" style={{ textAlign:'right' }}>
                  {isZero ? <span className="muted">—</span> : <Money amount={r.amountVal} ccy={r.ccy} primaryClass={r.amountVal < 0 ? 'amt-neg' : ''} />}
                </td>
                <td className="muted" data-label="Date">{r.date}, {r.dateISO.slice(0,4)}</td>
                <td data-label="Type"><span className={`badge ${rcptTypeTint(r.type)}`}>{r.type === 'refund' ? 'Return' : r.type}</span></td>
                <td data-label="Actions" style={{ textAlign:'right' }}>
                  <div className="row-acts" onClick={e => e.stopPropagation()}>
                    <button className="iconbtn" title="Edit" onClick={() => { setSel(r); setCreating(false); }}><Icon name="pencil" size={16} /></button>
                    <button className="iconbtn danger" title="Delete" onClick={() => delRcpt(r.id)}><Icon name="trash-2" size={16} /></button>
                  </div>
                </td>
              </tr>
            );
          })}
          {rows.length === 0 && <tr><td colSpan="6"><div className="table-empty"><Icon name="search-x" size={26} color="var(--fg-4)" /><span>No receipts match your filters.</span>{filtering && <button className="viewall" onClick={() => { setQ(''); setType('all'); setFrom(''); setTo(''); }}>Clear filters</button>}</div></td></tr>}
        </tbody>
      </table>
    </div>

    {sel && <ReceiptDrawer rcpt={sel} creating={creating} onClose={() => { setSel(null); setCreating(false); }} onSave={saveRcpt} onDelete={delRcpt}
      dismissed={dismissed.has(sel.id)} onIgnore={() => { toggleDismiss(sel.id); setSel(null); setCreating(false); }} />}
    </React.Fragment>
  );
}
window.Receipts = Receipts;
