/* ===== Transactions + Receipts views ===== */
const Dv = window.DATA;

function FilterBar({ tabs, active, setActive, right }) {
  return (
    <div style={{ display:"flex", alignItems:"center", gap:12, marginBottom:"var(--gap)" }}>
      <div className="seg">
        {tabs.map(t => <button key={t.id} className={active===t.id?"on":""} onClick={() => setActive(t.id)}>{t.label}</button>)}
      </div>
      <button className="btn"><Icon name="filter" size={15}/> Filter</button>
      <div style={{ flex:1 }}></div>
      {right}
    </div>
  );
}

// ---------- TRANSACTIONS ----------
function Transactions({ openReceipt }) {
  const [tab, setTab] = useState("all");
  const [sel, setSel] = useState([]);
  const tabs = [
    { id:"all", label:"All" }, { id:"review", label:"Needs review" },
    { id:"uncategorized", label:"Uncategorized" }, { id:"income", label:"Income" }, { id:"expense", label:"Expenses" },
  ];
  let rows = Dv.txns;
  if (tab==="review") rows = rows.filter(t => t.status==="review");
  else if (tab==="uncategorized") rows = rows.filter(t => t.status==="uncategorized");
  else if (tab==="income") rows = rows.filter(t => t.amount>0);
  else if (tab==="expense") rows = rows.filter(t => t.amount<0);

  const toggle = (id) => setSel(s => s.includes(id) ? s.filter(x=>x!==id) : [...s, id]);
  const allSel = rows.length>0 && rows.every(r => sel.includes(r.id));

  return (
    <div className="view content-inner">
      <FilterBar tabs={tabs} active={tab} setActive={setTab}
        right={<><button className="btn"><Icon name="upload" size={15}/> Import</button>
          <button className="btn btn-primary"><Icon name="arrowDownRight" size={15}/> Export</button></>}/>

      {sel.length>0 && (
        <div className="card" style={{ marginBottom:"var(--gap)", padding:"12px 16px", display:"flex", alignItems:"center", gap:14,
          borderColor:"var(--accent)", background:"var(--accent-soft)" }}>
          <b style={{ fontSize:13.5 }}>{sel.length} selected</b>
          <button className="btn" style={{ background:"var(--surface)" }}><Icon name="edit" size={14}/> Categorize</button>
          <button className="btn" style={{ background:"var(--surface)" }}><Icon name="link" size={14}/> Match receipt</button>
          <div style={{ flex:1 }}></div>
          <button className="btn" style={{ background:"var(--surface)" }} onClick={() => setSel([])}>Clear</button>
        </div>
      )}

      <Card style={{ padding:0, overflow:"hidden" }}>
        <table className="tbl">
          <thead><tr>
            <th style={{ width:40, paddingLeft:18 }}>
              <input type="checkbox" checked={allSel} onChange={() => setSel(allSel ? [] : rows.map(r=>r.id))}/>
            </th>
            <th>Date</th><th>Vendor</th><th>Category</th><th>Method</th><th>Status</th><th className="num" style={{ paddingRight:20 }}>Amount</th>
          </tr></thead>
          <tbody>
            {rows.map(t => (
              <tr key={t.id} className="clickable">
                <td style={{ paddingLeft:18 }}><input type="checkbox" checked={sel.includes(t.id)} onChange={() => toggle(t.id)}/></td>
                <td style={{ color:"var(--text-2)", whiteSpace:"nowrap" }}>{t.date}</td>
                <td>
                  <div style={{ fontWeight:600 }}>{t.vendor}</div>
                  <div style={{ fontSize:12, color:"var(--text-3)" }}>{t.desc}</div>
                </td>
                <td>
                  {t.status==="uncategorized"
                    ? <span className="badge warn"><Icon name="plus" size={12}/> Add category</span>
                    : <span style={{ display:"inline-flex", alignItems:"center", gap:7 }}><CatDot cat={t.cat}/>{t.cat}</span>}
                </td>
                <td style={{ color:"var(--text-2)" }}>{t.method}</td>
                <td>{t.receipt
                  ? <span className="badge info" style={{ cursor:"pointer" }} onClick={() => openReceipt(t.receipt)}><Icon name="receipt" size={12}/> Receipt</span>
                  : <StatusBadge status={t.status}/>}</td>
                <td className="num mono" style={{ paddingRight:20, fontWeight:600, color: t.amount>0?"var(--accent-ink)":"var(--text)" }}>
                  {t.amount>0?"+":""}{Dv.eur(t.amount)}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// ---------- RECEIPTS ----------
function Receipts({ openReceipt, openAdd }) {
  const [tab, setTab] = useState("all");
  const tabs = [
    { id:"all", label:"All" }, { id:"review", label:"Needs review" },
    { id:"extracted", label:"Extracted" }, { id:"matched", label:"Matched" },
  ];
  let rows = Dv.receipts;
  if (tab!=="all") rows = rows.filter(r => r.status===tab);

  return (
    <div className="view content-inner">
      <FilterBar tabs={tabs} active={tab} setActive={setTab}
        right={<><button className="btn"><Icon name="camera" size={15}/> Capture photo</button>
          <button className="btn btn-accent" onClick={openAdd}><Icon name="upload" size={15}/> Upload</button></>}/>

      <div className="grid" style={{ gridTemplateColumns:"repeat(3, 1fr)" }}>
        {rows.map(r => (
          <div key={r.id} className="card lift" style={{ padding:0, overflow:"hidden", cursor:"pointer" }} onClick={() => openReceipt(r.id)}>
            <div className="ph" style={{ height:140, position:"relative" }}>
              <span className="ph-label">{r.source==="Photo" ? "Receipt photo" : "Invoice PDF"}</span>
              <div style={{ position:"absolute", top:10, left:10 }}><StatusBadge status={r.status}/></div>
              <div style={{ position:"absolute", top:10, right:10 }} className="badge neutral">
                <Icon name={r.source==="Photo"?"camera":"doc"} size={12}/>{r.source}</div>
            </div>
            <div style={{ padding:"14px 16px" }}>
              <div style={{ display:"flex", justifyContent:"space-between", alignItems:"baseline" }}>
                <span style={{ fontWeight:600, fontSize:14 }}>{r.vendor}</span>
                <span className="mono" style={{ fontWeight:600 }}>{Dv.eur(r.total)}</span>
              </div>
              <div style={{ fontSize:12, color:"var(--text-3)", marginTop:3 }}>{r.date}</div>
              <div style={{ display:"flex", alignItems:"center", gap:7, marginTop:10, fontSize:12.5, color:"var(--text-2)" }}>
                {r.cat ? <><CatDot cat={r.cat}/>{r.cat}</> : <span className="badge warn"><Icon name="plus" size={12}/> Categorize</span>}
                <span style={{ flex:1 }}></span>
                <span style={{ color:"var(--text-3)" }}>{r.items.length} items</span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---------- Receipt review modal (extraction) ----------
function ReceiptModal({ id, onClose }) {
  const r = Dv.receipts.find(x => x.id === id);
  const [edited, setEdited] = useState({});
  const [done, setDone] = useState(false);
  const [catErr, setCatErr] = useState(false);
  if (!r) return null;
  const f = (key, def) => edited[key] !== undefined ? edited[key] : def;
  const set = (key, v) => setEdited(e => ({ ...e, [key]: v }));
  const approve = async () => {
    if (!f("cat", r.cat)) {
      setCatErr(true);
      setTimeout(() => setCatErr(false), 600);
      return;
    }
    try {
      if (window.ContaAPI) {
        await window.ContaAPI.approveReceipt(id, {
          vendor: f("vendor", r.vendor),
          date: f("date", r.date),
          total: f("total", r.total),
          cat: f("cat", r.cat),
        });
      }
      setDone(true);
    } catch (err) {
      console.error(err);
      setDone(true);
    }
  };

  if (done) {
    return (
      <Modal title="Receipt processed" onClose={onClose}
        foot={<button className="btn btn-accent" onClick={onClose}>Done</button>}>
        <div style={{ textAlign:"center", padding:"20px 0 8px" }}>
          <div className="check-circle"><svg viewBox="0 0 24 24"><path d="M5 12.5 10 17l9-10"/></svg></div>
          <div style={{ fontSize:16, fontWeight:600 }}>Saved & matched</div>
          <div style={{ fontSize:13.5, color:"var(--text-2)", marginTop:6, maxWidth:340, margin:"6px auto 0" }}>
            <b>{r.vendor}</b> · {Dv.eur(f("total", r.total))} categorized as <b>{f("cat", r.cat) || "Food & Beverage"}</b> and linked to a bank transaction.
          </div>
        </div>
      </Modal>
    );
  }

  return (
    <Modal wide title="Review extracted receipt" sub={`${r.source} · ContaBilè OCR · 97% confidence`} onClose={onClose}
      foot={<>
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn btn-accent" onClick={approve}><Icon name="check" size={15}/> Approve & match</button>
      </>}>
      <div style={{ display:"grid", gridTemplateColumns:"260px 1fr", gap:22 }}>
        <div className="ph" style={{ borderRadius:12, minHeight:300, alignSelf:"start", position:"relative" }}>
          <span className="ph-label">{r.source==="Photo"?"Receipt photo":"Invoice PDF"}</span>
        </div>
        <div>
          <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:12 }}>
            <div className="field"><label>Vendor</label>
              <input className={"ipt " + (edited.vendor!==undefined?"edited":"")} value={f("vendor", r.vendor)} onChange={e=>set("vendor", e.target.value)}/></div>
            <div className="field"><label>Date</label>
              <input className={"ipt " + (edited.date!==undefined?"edited":"")} value={f("date", r.date)} onChange={e=>set("date", e.target.value)}/></div>
          </div>
          <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:12 }}>
            <div className="field"><label>Total</label>
              <input className={"ipt mono " + (edited.total!==undefined?"edited":"")} value={f("total", r.total)} onChange={e=>set("total", e.target.value)}/></div>
            <div className="field"><label>VAT</label>
              <input className="ipt mono" defaultValue={r.tax}/></div>
            <div className="field"><label>Category</label>
              <select className={"ipt " + (catErr?"error shake ":"") + (edited.cat!==undefined?"edited":"")} value={f("cat", r.cat) || ""} onChange={e=>set("cat", e.target.value)}>
                <option value="">Select…</option>
                {Dv.categories.map(c => <option key={c} value={c}>{c}</option>)}
              </select>
              {catErr && <div className="err-text"><Icon name="alert" size={13}/> Pick a category to approve</div>}</div>
          </div>
          <div style={{ fontSize:12, fontWeight:600, color:"var(--text-2)", margin:"6px 0 8px" }}>Line items</div>
          <div style={{ border:"1px solid var(--line)", borderRadius:10, overflow:"hidden" }}>
            <table className="tbl" style={{ fontSize:13 }}>
              <thead><tr><th style={{ paddingLeft:14 }}>Item</th><th className="num">Qty</th><th className="num" style={{ paddingRight:14 }}>Price</th></tr></thead>
              <tbody>
                {r.items.map((it,i) => (
                  <tr key={i}><td style={{ paddingLeft:14 }}>{it.d}</td><td className="num mono">{it.q}</td>
                    <td className="num mono" style={{ paddingRight:14 }}>{Dv.eur(it.p)}</td></tr>
                ))}
              </tbody>
            </table>
          </div>
          {r.status==="review" && (
            <div className="card" style={{ marginTop:14, padding:"11px 14px", display:"flex", gap:10, alignItems:"center", background:"var(--accent-soft)", borderColor:"var(--accent)" }}>
              <Icon name="spark" size={18} style={{ color:"var(--accent-ink)" }}/>
              <span style={{ fontSize:12.5, color:"var(--text)" }}>ContaBilè flagged this: line items sum to <b>{Dv.eur(r.items.reduce((s,i)=>s+i.q*i.p,0))}</b>, check against the printed total.</span>
            </div>
          )}
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { Transactions, Receipts, ReceiptModal, FilterBar });
