/* Driftwood — Budgets screen.
   Create / edit / delete budget categories; live totals. */
const BUDGET_COLORS = ["blue", "teal", "violet", "amber", "sky", "pink", "green", "rose"];

function BudgetModal({ initial, onClose, onSave, onDelete }) {
  const editing = !!initial;
  const [name, setName] = React.useState(initial ? initial.name : "");
  const [planned, setPlanned] = React.useState(initial ? String(initial.planned) : "");
  const [color, setColor] = React.useState(initial ? initial.color : "blue");

  const save = () => {
    const amt = parseFloat(planned) || 0;
    if (!name.trim() || !amt) { onClose(); return; }
    onSave({ name: name.trim(), planned: amt, color }, initial);
    onClose();
  };

  return (
    <div className="modal-bg" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <h2>{editing ? "Edit budget" : "New budget"}</h2>
        <p className="sub">{editing ? "Adjust this category's monthly allotment." : "Create a spending category and set its monthly limit."}</p>

        <div className="field" style={{ marginBottom: 14 }}>
          <label>Category name</label>
          <div className="input"><input value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Pets, Childcare, Travel" style={{ fontSize: 15, fontWeight: 500 }} autoFocus /></div>
        </div>

        <div className="field" style={{ marginBottom: 18 }}>
          <label>Monthly budget</label>
          <div className="input"><span className="pre">$</span><input value={planned} onChange={(e) => setPlanned(e.target.value)} placeholder="0" inputMode="decimal" /></div>
        </div>

        <div className="field">
          <label>Color</label>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
            {BUDGET_COLORS.map((c) => (
              <button key={c} onClick={() => setColor(c)} aria-label={c}
                style={{ width: 30, height: 30, borderRadius: 9, background: PALETTE[c], cursor: "pointer",
                  border: color === c ? "2px solid var(--hi)" : "2px solid transparent",
                  boxShadow: color === c ? "0 0 0 2px var(--bg) inset" : "none", padding: 0 }} />
            ))}
          </div>
        </div>

        <div className="modal-foot" style={{ justifyContent: editing ? "space-between" : "flex-end" }}>
          {editing && <button className="btn btn-ghost" style={{ color: "var(--neg)" }} onClick={() => { onDelete(initial); onClose(); }}>Delete</button>}
          <div style={{ display: "flex", gap: 10 }}>
            <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
            <button className="btn btn-primary" onClick={save}>{editing ? "Save" : "Create budget"}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function statusOf(pct) {
  if (pct > 100) return { label: "Over", color: "var(--neg)" };
  if (pct >= 85) return { label: "Close", color: "var(--amber)" };
  return { label: "On track", color: "var(--pos)" };
}

function ScreenBudgets({ txns, nav }) {
  const { usd, budget } = window.FP;
  const [cats, setCats] = window.usePersist("budgets", () => budget.categories.map((c) => ({ name: c.name, planned: c.planned, color: c.color })));
  const [modal, setModal] = React.useState(null); // {mode:'new'} | {mode:'edit', cat}

  // ---- Spend is pulled live from the Transactions screen ----
  // Normalize category names so a "Housing"/"Healthcare" budget matches its txns.
  const CAT_ALIAS = { healthcare: "health" };
  const catKey = (s) => { const n = (s || "").trim().toLowerCase(); return CAT_ALIAS[n] || n; };
  const txList = txns || window.FP.transactions;
  const spendByCat = {}, countByCat = {};
  txList.forEach((t) => {
    if (t.amount < 0) {
      const k = catKey(t.cat);
      spendByCat[k] = (spendByCat[k] || 0) + Math.abs(t.amount);
      countByCat[k] = (countByCat[k] || 0) + 1;
    }
  });
  const actualOf = (c) => spendByCat[catKey(c.name)] || 0;
  const countOf = (c) => countByCat[catKey(c.name)] || 0;
  const budgetKeys = new Set(cats.map((c) => catKey(c.name)));
  const matchedTxCount = txList.filter((t) => t.amount < 0 && budgetKeys.has(catKey(t.cat))).length;

  const totalPlanned = cats.reduce((s, c) => s + c.planned, 0);
  const totalActual = cats.reduce((s, c) => s + actualOf(c), 0);
  const remaining = totalPlanned - totalActual;
  const overCount = cats.filter((c) => actualOf(c) > c.planned).length;
  const segs = cats.map((c) => ({ label: c.name, value: actualOf(c), color: PALETTE[c.color] })).filter((s) => s.value > 0);

  const saveCat = (data, original) => {
    setCats((list) => original
      ? list.map((c) => (c === original ? data : c))
      : [...list, data]);
  };
  const deleteCat = (cat) => setCats((list) => list.filter((c) => c !== cat));

  const tiles = [
    ["Total budget", usd(totalPlanned), "var(--blue)", `${cats.length} categories`],
    ["Spent so far", usd(totalActual), "var(--amber)", `${matchedTxCount} matched transaction${matchedTxCount === 1 ? "" : "s"}`],
    ["Remaining", usd(remaining), remaining >= 0 ? "var(--pos)" : "var(--neg)", overCount ? `${overCount} over budget` : "All on track"],
  ];

  return (
    <>
      <ScreenHeader title="Budgets" sub="Limits you set, matched against real spending pulled from your Transactions.">
        <button className="btn btn-primary" onClick={() => setModal({ mode: "new" })}><Icon name="plus" /> New budget</button>
      </ScreenHeader>

      <div className="content">
        <div className="grid g3">
          {tiles.map(([l, v, c, foot]) => (
            <div className="stat" key={l}>
              <div className="stat-label">{l}</div>
              <div className="num stat-val" style={{ color: l === "Total budget" ? "var(--hi)" : c }}>{v}</div>
              <div className="bar" style={{ marginTop: 14 }}><span style={{ width: `${Math.min(100, (totalActual / totalPlanned) * 100)}%`, background: c }} /></div>
              <div className="stat-foot">{foot}</div>
            </div>
          ))}
        </div>

        <div className="grid" style={{ gridTemplateColumns: "1.4fr 1fr" }}>
          <div className="card">
            <div className="card-head">
              <h2>Categories</h2>
              <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
                {nav && <span className="link" onClick={() => nav("transactions")}>From Transactions →</span>}
                <span className="link" onClick={() => setModal({ mode: "new" })}>+ Add category</span>
              </div>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {cats.map((c, i) => {
                const actual = actualOf(c);
                const count = countOf(c);
                const pct = c.planned ? Math.round((actual / c.planned) * 100) : 0;
                const over = actual > c.planned;
                const left = c.planned - actual;
                const st = statusOf(pct);
                return (
                  <div key={i} onClick={() => setModal({ mode: "edit", cat: c })}
                    style={{ padding: "13px 14px", margin: "0 -14px", borderRadius: 12, cursor: "pointer", transition: "background .14s" }}
                    onMouseEnter={(e) => (e.currentTarget.style.background = "oklch(1 0 0 / 0.03)")}
                    onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 9 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 11, minWidth: 0 }}>
                        <span className="dot" style={{ width: 11, height: 11, background: PALETTE[c.color], flexShrink: 0 }} />
                        <span style={{ fontWeight: 500, fontSize: 14.5, whiteSpace: "nowrap" }}>{c.name}</span>
                        <span className="tag" style={{ whiteSpace: "nowrap", color: st.color, background: `color-mix(in oklch, ${st.color} 15%, transparent)` }}>{st.label}</span>
                      </div>
                      <div className="num" style={{ fontSize: 14, whiteSpace: "nowrap" }}>
                        <b>{usd(actual)}</b> <span style={{ color: "var(--dim)" }}>/ {usd(c.planned)}</span>
                      </div>
                    </div>
                    <div className="bar lg"><span className={over ? "over" : ""} style={{ width: `${Math.min(100, pct)}%`, background: over ? "var(--neg)" : PALETTE[c.color] }} /></div>
                    <div style={{ fontSize: 12, color: over ? "var(--neg)" : "var(--dim)", marginTop: 7 }}>
                      {over ? `Over by ${usd(actual - c.planned)}` : `${usd(left)} left`}
                      <span style={{ color: "var(--dim)" }}> · {count} transaction{count === 1 ? "" : "s"}</span>
                    </div>
                  </div>
                );
              })}
              {cats.length === 0 && (
                <div style={{ textAlign: "center", color: "var(--dim)", padding: "40px 0", fontSize: 14 }}>
                  No budgets yet. Create your first category to start tracking.
                </div>
              )}
            </div>
          </div>

          <div className="card">
            <div className="card-head"><h2>Where it goes</h2></div>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 24 }}>
              <div style={{ position: "relative" }}>
                <Donut segments={segs.length ? segs : [{ label: "—", value: 1, color: "var(--panel3)" }]} size={200} />
                <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
                  <span className="num" style={{ fontSize: 28, fontWeight: 700, letterSpacing: "-0.03em" }}>{usd(totalActual)}</span>
                  <span style={{ fontSize: 12.5, color: "var(--dim)" }}>spent</span>
                </div>
              </div>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, width: "100%", display: "flex", flexDirection: "column", gap: 11 }}>
                {segs.map((s) => (
                  <li key={s.label} style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 13, color: "var(--mid)" }}>
                    <span className="dot" style={{ background: s.color, marginRight: 2, flexShrink: 0 }} />
                    <span style={{ flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{s.label}</span>
                    <b className="num" style={{ color: "var(--hi)", fontWeight: 600, flexShrink: 0 }}>{usd(s.value)}</b>
                  </li>
                ))}
              </ul>
            </div>
          </div>
        </div>
      </div>

      {modal && (
        <BudgetModal
          initial={modal.mode === "edit" ? modal.cat : null}
          onClose={() => setModal(null)}
          onSave={saveCat}
          onDelete={deleteCat}
        />
      )}
    </>
  );
}
window.ScreenBudgets = ScreenBudgets;
