/* Driftwood — Bills & subscriptions. Add / edit / delete recurring bills. */
const BILL_CATS = ["Housing", "Utilities", "Insurance", "Subscription", "Health", "Transportation", "Other"];
const BILL_CAT_COLOR = { Housing: "blue", Utilities: "sky", Insurance: "violet", Subscription: "pink", Health: "green", Transportation: "amber", Other: "teal" };

function BillModal({ initial, onClose, onSave, onDelete }) {
  const editing = !!initial;
  const [f, setF] = React.useState(initial || { name: "", amount: "", due: "1", cat: "Utilities" });
  const set = (k) => (v) => setF({ ...f, [k]: v });
  const save = () => {
    const amount = parseFloat(f.amount) || 0;
    const due = Math.min(28, Math.max(1, parseInt(f.due) || 1));
    if (!f.name.trim() || !amount) { onClose(); return; }
    onSave({ name: f.name.trim(), amount, due, cat: f.cat }, initial);
    onClose();
  };
  return (
    <Modal title={editing ? "Edit bill" : "New bill"} sub={editing ? "Update this recurring payment." : "Add a recurring bill or subscription."}
      onClose={onClose} onSave={save} saveLabel={editing ? "Save" : "Add bill"} onDelete={editing ? () => { onDelete(initial); onClose(); } : null}>
      <TextField label="Name" value={f.name} onChange={set("name")} placeholder="e.g. Rent, Hulu, Car insurance" autoFocus />
      <div className="modal-row">
        <MoneyField label="Amount / month" value={f.amount} onChange={set("amount")} />
        <div className="field"><label>Due day</label><div className="input"><span className="pre" style={{ fontSize: 13 }}>Day</span><input value={f.due} onChange={(e) => set("due")(e.target.value)} inputMode="numeric" placeholder="1" /></div></div>
      </div>
      <SelectField label="Category" value={f.cat} onChange={set("cat")} options={BILL_CATS} />
    </Modal>
  );
}

function ScreenBills() {
  const { usd } = window.FP;
  const [bills, setBills] = window.usePersist("bills", () => window.FP.bills.map((b) => ({ ...b })));
  const [modal, setModal] = React.useState(null);

  const total = bills.reduce((s, b) => s + b.amount, 0);
  const subsTotal = bills.filter((b) => b.cat === "Subscription").reduce((s, b) => s + b.amount, 0);
  const next7 = bills.filter((b) => b.due <= 8).reduce((s, b) => s + b.amount, 0);
  const sorted = [...bills].sort((a, b) => a.due - b.due);

  const save = (data, original) => setBills((list) => original ? list.map((b) => (b === original ? data : b)) : [...list, data]);
  const del = (b) => setBills((list) => list.filter((x) => x !== b));

  return (
    <>
      <ScreenHeader title="Bills & subscriptions" sub={`${bills.length} recurring · ${usd(total)} / month`}>
        <button className="btn btn-primary" onClick={() => setModal({ mode: "new" })}><Icon name="plus" /> New bill</button>
      </ScreenHeader>

      <div className="content">
        <div className="grid g3">
          {[["Monthly total", usd(total), "var(--blue)"], ["Subscriptions", usd(subsTotal), "var(--pink)"], ["Next 7 days", usd(next7), "var(--amber)"]].map(([l, v, c]) => (
            <div className="stat" key={l}>
              <div className="stat-label">{l}</div>
              <div className="num stat-val" style={{ color: c }}>{v}</div>
            </div>
          ))}
        </div>

        <div className="card">
          <div className="card-head"><h2>Payment schedule</h2><span className="link" onClick={() => setModal({ mode: "new" })}>+ Add bill</span></div>
          <div style={{ display: "flex", flexDirection: "column" }}>
            {sorted.map((b, i) => {
              const col = PALETTE[BILL_CAT_COLOR[b.cat] || "blue"];
              const passed = b.due < 30;
              return (
                <div key={i} onClick={() => setModal({ mode: "edit", bill: b })} className="bill-row"
                  style={{ display: "flex", alignItems: "center", gap: 16, padding: "13px 14px", margin: "0 -14px", borderRadius: 12, cursor: "pointer", borderBottom: i < sorted.length - 1 ? "1px solid var(--line2)" : "none" }}>
                  <div style={{ width: 50, height: 50, borderRadius: 13, background: "var(--panel2)", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                    <span style={{ fontSize: 9.5, letterSpacing: "0.08em", color: "var(--dim)" }}>MAY</span>
                    <span className="num" style={{ fontSize: 17, fontWeight: 700, lineHeight: 1 }}>{b.due}</span>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 500, fontSize: 15 }}>{b.name}</div>
                    <div style={{ marginTop: 4 }}><span className="tag" style={{ color: col, background: `color-mix(in oklch, ${col} 15%, transparent)` }}>{b.cat}</span></div>
                  </div>
                  <span style={{ fontSize: 12.5, color: passed ? "var(--pos)" : "var(--dim)" }}>{passed ? "✓ Paid" : "Upcoming"}</span>
                  <div className="num" style={{ fontSize: 16, fontWeight: 600, width: 80, textAlign: "right" }}>{usd(b.amount)}</div>
                  <span className="row-edit"><Icon name="chevron" style={{ width: 16, height: 16 }} /></span>
                </div>
              );
            })}
            {bills.length === 0 && <div style={{ textAlign: "center", color: "var(--dim)", padding: "40px 0" }}>No bills yet. Add your first recurring payment.</div>}
          </div>
        </div>
      </div>

      {modal && <BillModal initial={modal.mode === "edit" ? modal.bill : null} onClose={() => setModal(null)} onSave={save} onDelete={del} />}
    </>
  );
}
window.ScreenBills = ScreenBills;
