/* Driftwood — Debt payoff. Visualizations (composition donut + payoff curve),
   editable debts, and a live avalanche/snowball simulation. */
const DEBT_COLORS = ["rose", "amber", "violet", "blue", "pink", "sky"];

function orderDebts(arr, strategy) {
  return [...arr].sort((a, b) => strategy === "avalanche" ? b.apr - a.apr : a.balance - b.balance);
}

/* Simulate payoff; optionally capture monthly total-balance series. */
function simulate(debts, strategy, extra, capture) {
  let bal = debts.map((d) => ({ ...d }));
  let months = 0, totalInterest = 0;
  const minSum = debts.reduce((s, d) => s + d.min, 0);
  const series = [debts.reduce((s, d) => s + d.balance, 0)];
  while (bal.some((d) => d.balance > 0.5) && months < 720) {
    months++;
    bal.forEach((d) => { if (d.balance > 0) { const i = d.balance * (d.apr / 100) / 12; d.balance += i; totalInterest += i; } });
    let pool = minSum + extra;
    bal.forEach((d) => { if (d.balance > 0) { const pay = Math.min(d.min, d.balance); d.balance -= pay; pool -= pay; } });
    for (const t of orderDebts(bal, strategy)) {
      if (pool <= 0) break;
      const live = bal.find((d) => d.name === t.name);
      if (live && live.balance > 0) { const pay = Math.min(pool, live.balance); live.balance -= pay; pool -= pay; }
    }
    if (capture) series.push(Math.max(0, bal.reduce((s, d) => s + d.balance, 0)));
  }
  return { months, totalInterest: Math.round(totalInterest), series };
}

/* Payoff projection: accelerated vs minimum-only balance curves. */
function PayoffChart({ accel, base, w = 720, h = 230 }) {
  const pad = { t: 14, r: 14, b: 26, l: 50 };
  const iw = w - pad.l - pad.r, ih = h - pad.t - pad.b;
  const maxLen = Math.max(accel.length, base.length);
  const top = Math.ceil(base[0] / 10000) * 10000 || 10000;
  const xx = (i) => pad.l + (i / (maxLen - 1)) * iw;
  const yy = (v) => pad.t + ih - (v / top) * ih;
  const line = (arr) => "M" + arr.map((v, i) => `${xx(i).toFixed(1)},${yy(v).toFixed(1)}`).join(" L");
  const area = (arr) => `${line(arr)} L${xx(arr.length - 1).toFixed(1)},${(pad.t + ih).toFixed(1)} L${pad.l},${(pad.t + ih).toFixed(1)} Z`;
  const ticks = [0, 0.5, 1].map((f) => Math.round(top * f));
  const yearTicks = [];
  for (let m = 0; m < maxLen; m += 12) yearTicks.push(m);
  return (
    <svg width="100%" viewBox={`0 0 ${w} ${h}`} style={{ display: "block" }}>
      <defs><linearGradient id="payG" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="var(--blue)" stopOpacity="0.28" /><stop offset="1" stopColor="var(--blue)" stopOpacity="0" /></linearGradient></defs>
      {ticks.map((t, i) => (
        <g key={i}>
          <line x1={pad.l} x2={w - pad.r} y1={yy(t)} y2={yy(t)} stroke="oklch(1 0 0 / 0.06)" />
          <text x={pad.l - 10} y={yy(t) + 4} textAnchor="end" fill="var(--dim)" fontSize="11" fontFamily="Space Grotesk">${(t / 1000).toFixed(0)}k</text>
        </g>
      ))}
      {yearTicks.map((m, i) => i > 0 && (
        <text key={m} x={xx(m)} y={h - 8} textAnchor="middle" fill="var(--dim)" fontSize="11" fontFamily="Space Grotesk">{m / 12}y</text>
      ))}
      <path d={line(base)} fill="none" stroke="var(--dim)" strokeWidth="2" strokeDasharray="5 5" />
      <path d={area(accel)} fill="url(#payG)" />
      <path d={line(accel)} fill="none" stroke="var(--blue-soft)" strokeWidth="2.6" strokeLinejoin="round" strokeLinecap="round" />
    </svg>
  );
}

function DebtModal({ initial, onClose, onSave, onDelete }) {
  const editing = !!initial;
  const [f, setF] = React.useState(initial
    ? { name: initial.name, balance: String(initial.balance), apr: String(initial.apr), min: String(initial.min), color: initial.color || "rose" }
    : { name: "", balance: "", apr: "", min: "", color: "rose" });
  const set = (k) => (v) => setF({ ...f, [k]: v });
  const save = () => {
    const balance = parseFloat(f.balance) || 0;
    if (!f.name.trim() || !balance) { onClose(); return; }
    onSave({ name: f.name.trim(), balance, apr: parseFloat(f.apr) || 0, min: parseFloat(f.min) || 0, color: f.color }, initial);
    onClose();
  };
  return (
    <Modal title={editing ? "Edit debt" : "New debt"} sub={editing ? "Update this balance." : "Add a loan, card, or other debt."}
      onClose={onClose} onSave={save} saveLabel={editing ? "Save" : "Add debt"} onDelete={editing ? () => { onDelete(initial); onClose(); } : null}>
      <TextField label="Name" value={f.name} onChange={set("name")} placeholder="e.g. Visa, Car loan" autoFocus />
      <div className="modal-row">
        <MoneyField label="Balance" value={f.balance} onChange={set("balance")} />
        <div className="field" style={{ marginBottom: 14 }}><label>APR %</label><div className="input"><input value={f.apr} onChange={(e) => set("apr")(e.target.value)} inputMode="decimal" placeholder="0.0" /><span className="pre" style={{ fontSize: 14 }}>%</span></div></div>
      </div>
      <MoneyField label="Minimum payment / month" value={f.min} onChange={set("min")} />
      <ColorPicker value={f.color} onChange={set("color")} colors={DEBT_COLORS} />
    </Modal>
  );
}

function ScreenDebt() {
  const { usd } = window.FP;
  const [debts, setDebts] = window.usePersist("debts", () => window.FP.debts.map((d, i) => ({ ...d, color: d.color || DEBT_COLORS[i % DEBT_COLORS.length] })));
  const [strategy, setStrategy] = window.usePersist("debt.strategy", "avalanche");
  const [extra, setExtra] = window.usePersist("debt.extra", 300);
  const [modal, setModal] = React.useState(null);

  const total = debts.reduce((s, d) => s + d.balance, 0);
  const minSum = debts.reduce((s, d) => s + d.min, 0);
  const ordered = orderDebts(debts, strategy);
  const hasDebt = debts.length > 0 && total > 0;

  const sim = hasDebt ? simulate(debts, strategy, extra, true) : { months: 0, totalInterest: 0, series: [0] };
  const baseline = hasDebt ? simulate(debts, strategy, 0, true) : { months: 0, totalInterest: 0, series: [0] };
  const monthsSaved = baseline.months - sim.months;
  const payoffDate = new Date(2026, 4 + sim.months);
  const dateStr = hasDebt ? payoffDate.toLocaleString("en-US", { month: "short", year: "numeric" }) : "—";
  const segs = debts.filter((d) => d.balance > 0).map((d) => ({ label: d.name, value: d.balance, color: PALETTE[d.color] }));

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

  return (
    <>
      <ScreenHeader title="Debt payoff" sub={`${debts.length} debts · ${usd(total)} remaining`}>
        <button className="btn btn-primary" onClick={() => setModal({ mode: "new" })}><Icon name="plus" /> New debt</button>
      </ScreenHeader>

      <div className="content">
        <div className="grid g4">
          {[["Total debt", usd(total), "var(--rose)"], ["Min payments", usd(minSum) + "/mo", "var(--mid)"], ["Debt-free", dateStr, "var(--pos)"], ["Interest saved", usd(baseline.totalInterest - sim.totalInterest), "var(--green)"]].map(([l, v, c]) => (
            <div className="stat" key={l}>
              <div className="stat-label">{l}</div>
              <div className="num stat-val" style={{ color: c, fontSize: 24 }}>{v}</div>
            </div>
          ))}
        </div>

        {/* Visualizations: composition donut + payoff projection */}
        <div className="grid" style={{ gridTemplateColumns: "0.85fr 1.15fr" }}>
          <div className="card">
            <div className="card-head"><h2>What you owe</h2></div>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 22 }}>
              <div style={{ position: "relative" }}>
                <Donut segments={segs.length ? segs : [{ label: "—", value: 1, color: "var(--panel3)" }]} size={186} />
                <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
                  <span className="num" style={{ fontSize: 25, fontWeight: 700, letterSpacing: "-0.03em" }}>{usd(total)}</span>
                  <span style={{ fontSize: 12, color: "var(--dim)" }}>total owed</span>
                </div>
              </div>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, width: "100%", display: "flex", flexDirection: "column", gap: 10 }}>
                {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, 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 className="card">
            <div className="card-head">
              <h2>Payoff projection</h2>
              <div style={{ display: "flex", gap: 16, fontSize: 12.5 }}>
                <span style={{ color: "var(--mid)" }}><span style={{ display: "inline-block", width: 14, height: 0, borderTop: "2.5px solid var(--blue-soft)", marginRight: 6, verticalAlign: "middle" }} />Your plan</span>
                <span style={{ color: "var(--mid)" }}><span style={{ display: "inline-block", width: 14, height: 0, borderTop: "2px dashed var(--dim)", marginRight: 6, verticalAlign: "middle" }} />Minimums only</span>
              </div>
            </div>
            {hasDebt ? <PayoffChart accel={sim.series} base={baseline.series} /> : <div style={{ color: "var(--dim)", textAlign: "center", padding: "60px 0" }}>Add a debt to see your payoff projection.</div>}
            <div style={{ fontSize: 12.5, color: "var(--dim)", marginTop: 8, textAlign: "center" }}>
              {hasDebt && `Debt-free in ${Math.floor(sim.months / 12)}y ${sim.months % 12}m${monthsSaved > 0 ? ` — ${monthsSaved} months sooner than minimums` : ""}`}
            </div>
          </div>
        </div>

        <div className="grid" style={{ gridTemplateColumns: "1fr 1fr" }}>
          {/* Strategy controls */}
          <div className="card">
            <div className="card-head"><h2>Payoff plan</h2></div>
            <div className="field" style={{ marginBottom: 22 }}>
              <label>Strategy</label>
              <div className="segctl">
                <button className={strategy === "avalanche" ? "on" : ""} onClick={() => setStrategy("avalanche")}>Avalanche (highest APR)</button>
                <button className={strategy === "snowball" ? "on" : ""} onClick={() => setStrategy("snowball")}>Snowball (smallest first)</button>
              </div>
            </div>
            <div className="field">
              <label style={{ display: "flex", justifyContent: "space-between" }}><span>Extra monthly payment</span><span className="num" style={{ color: "var(--blue-soft)" }}>{usd(extra)}</span></label>
              <input type="range" min="0" max="1500" step="50" value={extra} onChange={(e) => setExtra(+e.target.value)} style={{ width: "100%", accentColor: "var(--blue)" }} />
            </div>
            <div style={{ background: "var(--panel2)", borderRadius: 14, padding: "18px 20px", marginTop: 22, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div>
                <div style={{ fontSize: 12.5, color: "var(--dim)" }}>Debt-free in</div>
                <div className="num" style={{ fontSize: 28, fontWeight: 700, letterSpacing: "-0.03em" }}>{hasDebt ? `${Math.floor(sim.months / 12)}y ${sim.months % 12}m` : "—"}</div>
              </div>
              {monthsSaved > 0 && (
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontSize: 12.5, color: "var(--dim)" }}>vs minimums</div>
                  <div className="num" style={{ fontSize: 18, fontWeight: 600, color: "var(--pos)" }}>{monthsSaved} mo sooner</div>
                </div>
              )}
            </div>
          </div>

          {/* Editable debt list ordered by strategy */}
          <div className="card">
            <div className="card-head"><h2>Your debts</h2><span className="link" onClick={() => setModal({ mode: "new" })}>+ Add debt</span></div>
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              {ordered.map((d, i) => {
                const pct = total ? Math.round((d.balance / total) * 100) : 0;
                const col = PALETTE[d.color] || "var(--rose)";
                return (
                  <div key={i} onClick={() => setModal({ mode: "edit", debt: d })} className="bill-row"
                    style={{ padding: "11px 14px", margin: "0 -14px", borderRadius: 12, cursor: "pointer" }}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 11, minWidth: 0 }}>
                        <span style={{ width: 22, height: 22, borderRadius: 7, background: "var(--panel3)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 700, color: "var(--mid)", flexShrink: 0 }}>{i + 1}</span>
                        <span style={{ fontWeight: 500, fontSize: 14.5, whiteSpace: "nowrap" }}>{d.name}</span>
                        <span className="tag" style={{ whiteSpace: "nowrap", color: col, background: `color-mix(in oklch, ${col} 15%, transparent)` }}>{d.apr}% APR</span>
                      </div>
                      <span className="num" style={{ fontWeight: 600, whiteSpace: "nowrap" }}>{usd(d.balance)}</span>
                    </div>
                    <div className="bar"><span style={{ width: `${pct}%`, background: col }} /></div>
                  </div>
                );
              })}
              {debts.length === 0 && <div style={{ textAlign: "center", color: "var(--dim)", padding: "36px 0" }}>No debts tracked. 🎉 Add one to plan a payoff.</div>}
            </div>
          </div>
        </div>
      </div>

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