/* Driftwood — Goals. Add / edit / delete savings goals. */
const GOAL_ICONS = ["◆", "▲", "●", "■", "★", "♦"];
const GOAL_COLORS = ["teal", "violet", "amber", "sky", "pink", "green"];

function GoalModal({ initial, onClose, onSave, onDelete }) {
  const editing = !!initial;
  const [f, setF] = React.useState(initial
    ? { name: initial.name, saved: String(initial.saved), target: String(initial.target), eta: initial.eta, color: initial.color || "teal" }
    : { name: "", saved: "", target: "", eta: "", color: "teal" });
  const set = (k) => (v) => setF({ ...f, [k]: v });
  const save = () => {
    const target = parseFloat(f.target) || 0;
    const saved = parseFloat(f.saved) || 0;
    if (!f.name.trim() || !target) { onClose(); return; }
    onSave({ name: f.name.trim(), saved, target, eta: f.eta.trim() || "—", color: f.color }, initial);
    onClose();
  };
  return (
    <Modal title={editing ? "Edit goal" : "New goal"} sub={editing ? "Update your savings goal." : "Set something you're saving toward."}
      onClose={onClose} onSave={save} saveLabel={editing ? "Save" : "Create goal"} onDelete={editing ? () => { onDelete(initial); onClose(); } : null}>
      <TextField label="Goal name" value={f.name} onChange={set("name")} placeholder="e.g. Emergency fund, Vacation" autoFocus />
      <div className="modal-row">
        <MoneyField label="Saved so far" value={f.saved} onChange={set("saved")} />
        <MoneyField label="Target amount" value={f.target} onChange={set("target")} />
      </div>
      <TextField label="Target date" value={f.eta} onChange={set("eta")} placeholder="e.g. Dec 2026" />
      <ColorPicker value={f.color} onChange={set("color")} colors={GOAL_COLORS} />
    </Modal>
  );
}

function ScreenGoals() {
  const { usd } = window.FP;
  const [goals, setGoals] = window.usePersist("goals", () => window.FP.goals.map((g, i) => ({ ...g, color: g.color || GOAL_COLORS[i % GOAL_COLORS.length] })));
  const [modal, setModal] = React.useState(null);

  const totalSaved = goals.reduce((s, g) => s + g.saved, 0);
  const totalTarget = goals.reduce((s, g) => s + g.target, 0) || 1;

  const save = (data, original) => setGoals((list) => original ? list.map((g) => (g === original ? { ...data } : g)) : [...list, data]);
  const del = (g) => setGoals((list) => list.filter((x) => x !== g));
  const addFunds = (g, e) => { e.stopPropagation(); setGoals((list) => list.map((x) => x === g ? { ...x, saved: Math.min(x.target, x.saved + 250) } : x)); };

  return (
    <>
      <ScreenHeader title="Goals" sub={`${goals.length} active · ${usd(totalSaved)} saved toward ${usd(goals.reduce((s, g) => s + g.target, 0))}`}>
        <button className="btn btn-primary" onClick={() => setModal({ mode: "new" })}><Icon name="plus" /> New goal</button>
      </ScreenHeader>

      <div className="content">
        <div className="card" style={{ background: "linear-gradient(140deg, var(--hero-from), var(--hero-to))", border: "1px solid var(--hero-border)" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 16 }}>
            <div>
              <div style={{ fontSize: 13, color: "oklch(0.85 0.03 262)" }}>Combined progress</div>
              <div className="num" style={{ fontSize: 38, fontWeight: 700, letterSpacing: "-0.03em", marginTop: 6, color: "#fff", whiteSpace: "nowrap" }}>{usd(totalSaved)} <span style={{ fontSize: 18, color: "oklch(0.8 0.03 262)", fontWeight: 500 }}>/ {usd(goals.reduce((s, g) => s + g.target, 0))}</span></div>
            </div>
            <div className="num" style={{ fontSize: 30, fontWeight: 700, color: "#fff" }}>{Math.round((totalSaved / totalTarget) * 100)}%</div>
          </div>
          <div className="bar lg" style={{ background: "oklch(1 0 0 / 0.15)" }}><span style={{ width: `${Math.min(100, (totalSaved / totalTarget) * 100)}%`, background: "#fff" }} /></div>
        </div>

        <div className="grid g2">
          {goals.map((g, i) => {
            const col = PALETTE[g.color] || "var(--teal)";
            const pct = Math.round((g.saved / g.target) * 100);
            const remaining = Math.max(0, g.target - g.saved);
            const done = pct >= 100;
            return (
              <div className="card goal-card" key={i} onClick={() => setModal({ mode: "edit", goal: g })} style={{ cursor: "pointer" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 20 }}>
                  <div style={{ width: 46, height: 46, borderRadius: 13, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 19, color: col, background: `color-mix(in oklch, ${col} 18%, transparent)` }}>{GOAL_ICONS[i % GOAL_ICONS.length]}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 16, fontWeight: 600 }}>{g.name}</div>
                    <div style={{ fontSize: 12.5, color: "var(--dim)" }}>{done ? "Reached 🎉" : `Target ${g.eta}`}</div>
                  </div>
                  <div className="num" style={{ fontSize: 22, fontWeight: 700, color: col }}>{pct}%</div>
                </div>

                <div className="bar lg"><span style={{ width: `${Math.min(100, pct)}%`, background: col }} /></div>

                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginTop: 18 }}>
                  <div style={{ display: "flex", gap: 26 }}>
                    {[["Saved", usd(g.saved)], ["Remaining", usd(remaining)], ["Target", usd(g.target)]].map(([l, v]) => (
                      <div key={l}>
                        <div style={{ fontSize: 11.5, color: "var(--dim)" }}>{l}</div>
                        <div className="num" style={{ fontSize: 16, fontWeight: 600, marginTop: 3 }}>{v}</div>
                      </div>
                    ))}
                  </div>
                  {!done && <button className="btn btn-ghost goal-add" onClick={(e) => addFunds(g, e)} style={{ padding: "8px 14px", fontSize: 13 }}>+ $250</button>}
                </div>
              </div>
            );
          })}

          <button onClick={() => setModal({ mode: "new" })} className="add-person-tile" style={{ minHeight: 180 }}>
            <span className="add-person-circle"><Icon name="plus" style={{ width: 22, height: 22 }} /></span>
            <span style={{ fontSize: 15, fontWeight: 600 }}>Add a savings goal</span>
            <span style={{ fontSize: 13, color: "var(--dim)" }}>House, trip, emergency fund…</span>
          </button>
        </div>
      </div>

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