/* Driftwood — Income calculator. Each person sets pay + frequency + tax;
   names & roles are editable inline; add/remove household members. */
const FREQS = [
  { id: "weekly", label: "Weekly", periods: 52 },
  { id: "biweekly", label: "Bi-weekly", periods: 26 },
  { id: "semimonthly", label: "Semi-monthly", periods: 24 },
  { id: "monthly", label: "Monthly", periods: 12 },
  { id: "annual", label: "Annual salary", periods: 1 },
];
const PERSON_COLORS = ["var(--blue)", "var(--violet)", "var(--teal)", "var(--amber)", "var(--sky)", "var(--pink)", "var(--green)", "var(--rose)"];

function PersonCard({ p, color, onChange, onRemove, canRemove }) {
  const { usd } = window.FP;
  const periods = FREQS.find((f) => f.id === p.freq).periods;
  const gross = (parseFloat(p.amount) || 0) * periods;
  const net = gross * (1 - p.tax / 100);
  const initial = (p.name.trim()[0] || "?").toUpperCase();

  return (
    <div className="card" style={{ position: "relative" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 13, marginBottom: 22 }}>
        <span className="avs"><span style={{ background: color, marginLeft: 0 }}>{initial}</span></span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <input className="name-edit" value={p.name} onChange={(e) => onChange({ ...p, name: e.target.value })}
            placeholder="Name" aria-label="Name" />
          <input className="role-edit" value={p.role} onChange={(e) => onChange({ ...p, role: e.target.value })}
            placeholder="Role (e.g. Parent, Dependent)" aria-label="Role" />
        </div>
        {canRemove && (
          <button className="card-remove" onClick={onRemove} aria-label={`Remove ${p.name}`} title="Remove member">×</button>
        )}
      </div>

      <div className="field" style={{ marginBottom: 16 }}>
        <label>Pay amount</label>
        <div className="input">
          <span className="pre">$</span>
          <input value={p.amount} inputMode="decimal" placeholder="0" onChange={(e) => onChange({ ...p, amount: e.target.value })} />
          <select value={p.freq} onChange={(e) => onChange({ ...p, freq: e.target.value })}>
            {FREQS.map((f) => <option key={f.id} value={f.id}>{f.label}</option>)}
          </select>
        </div>
      </div>

      <div className="field" style={{ marginBottom: 22 }}>
        <label style={{ display: "flex", justifyContent: "space-between" }}>
          <span>Est. tax &amp; deductions</span><span className="num" style={{ color }}>{p.tax}%</span>
        </label>
        <input type="range" min="0" max="45" value={p.tax} onChange={(e) => onChange({ ...p, tax: +e.target.value })}
          style={{ width: "100%", accentColor: color }} />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <div style={{ background: "var(--panel2)", borderRadius: 14, padding: "16px 18px" }}>
          <div style={{ fontSize: 12, color: "var(--dim)" }}>Gross / year</div>
          <div className="num" style={{ fontSize: 23, fontWeight: 700, letterSpacing: "-0.03em", marginTop: 5 }}>{usd(Math.round(gross))}</div>
        </div>
        <div style={{ background: `color-mix(in oklch, ${color} 14%, var(--panel2))`, borderRadius: 14, padding: "16px 18px" }}>
          <div style={{ fontSize: 12, color: "var(--dim)" }}>Take-home / year</div>
          <div className="num" style={{ fontSize: 23, fontWeight: 700, letterSpacing: "-0.03em", marginTop: 5, color }}>{usd(Math.round(net))}</div>
        </div>
      </div>
      <div style={{ fontSize: 12.5, color: "var(--dim)", marginTop: 14 }}>
        {periods === 1 ? "Annual salary" : `${usd(parseFloat(p.amount) || 0)} × ${periods} pay periods`} · {usd(Math.round(net / 12))}/mo take-home
      </div>
    </div>
  );
}

function ScreenIncome() {
  const { usd } = window.FP;
  const [people, setPeople] = window.useMembers();
  const colorFor = (i) => PERSON_COLORS[i % PERSON_COLORS.length];
  const update = (i) => (np) => setPeople((ps) => ps.map((p, j) => (j === i ? np : p)));
  const remove = (i) => setPeople((ps) => ps.filter((_, j) => j !== i));
  const add = () => setPeople((ps) => [...ps, { name: "New member", role: "Dependent", amount: "", freq: "biweekly", tax: 12 }]);

  const calc = people.map((p) => {
    const periods = FREQS.find((f) => f.id === p.freq).periods;
    const gross = (parseFloat(p.amount) || 0) * periods;
    return { name: p.name, gross, net: gross * (1 - p.tax / 100) };
  });
  const totalGross = calc.reduce((s, c) => s + c.gross, 0);
  const totalNet = calc.reduce((s, c) => s + c.net, 0);
  const earners = calc.filter((c) => c.gross > 0);

  return (
    <>
      <ScreenHeader title="Income calculator" sub="Add each household member and set their pay — we'll project it across the year.">
        <button className="btn btn-primary" onClick={add}><Icon name="plus" /> Add person</button>
      </ScreenHeader>

      <div className="content">
        <div className="grid g2">
          {people.map((p, i) => (
            <PersonCard key={i} p={p} color={colorFor(i)} onChange={update(i)} onRemove={() => remove(i)} canRemove={people.length > 1} />
          ))}

          {/* Add-person tile */}
          <button onClick={add} className="add-person-tile">
            <span className="add-person-circle"><Icon name="plus" style={{ width: 22, height: 22 }} /></span>
            <span style={{ fontSize: 15, fontWeight: 600 }}>Add a household member</span>
            <span style={{ fontSize: 13, color: "var(--dim)" }}>Partner, child with a job, dependent…</span>
          </button>
        </div>

        {/* Combined household */}
        <div className="card" style={{ background: "linear-gradient(140deg, var(--hero-from), var(--hero-to))", border: "1px solid var(--hero-border)" }}>
          <div className="card-head"><h2 style={{ color: "#fff" }}>Combined household income</h2><span className="chip" style={{ background: "oklch(1 0 0 / 0.12)", color: "#fff" }}>{people.length} {people.length === 1 ? "member" : "members"}</span></div>
          <div className="grid g4" style={{ gap: 16 }}>
            {[
              ["Gross / year", usd(Math.round(totalGross))],
              ["Take-home / year", usd(Math.round(totalNet))],
              ["Take-home / month", usd(Math.round(totalNet / 12))],
              ["Per bi-weekly check", usd(Math.round(totalNet / 26))],
            ].map(([l, v], i) => (
              <div key={l}>
                <div style={{ fontSize: 12.5, color: "oklch(0.85 0.03 262)" }}>{l}</div>
                <div className="num" style={{ fontSize: i < 2 ? 30 : 24, fontWeight: 700, letterSpacing: "-0.03em", marginTop: 6, color: "#fff" }}>{v}</div>
              </div>
            ))}
          </div>

          {/* Split bar */}
          {earners.length > 0 && (
            <div style={{ marginTop: 28 }}>
              <div style={{ fontSize: 12.5, color: "oklch(0.85 0.03 262)", marginBottom: 10 }}>Contribution to household gross</div>
              <div style={{ display: "flex", height: 14, borderRadius: 999, overflow: "hidden", gap: 3 }}>
                {calc.map((c, i) => c.gross > 0 && (
                  <div key={i} style={{ width: `${(c.gross / totalGross) * 100}%`, background: colorFor(i) }} />
                ))}
              </div>
              <div style={{ display: "flex", gap: 24, marginTop: 12, flexWrap: "wrap" }}>
                {calc.map((c, i) => c.gross > 0 && (
                  <div key={i} style={{ fontSize: 13, color: "oklch(0.9 0.02 262)" }}>
                    <span className="dot" style={{ background: colorFor(i), marginRight: 7, display: "inline-block" }} />
                    {c.name || "—"} <b className="num" style={{ marginLeft: 4 }}>{usd(Math.round(c.gross))}</b>
                    <span style={{ color: "oklch(0.75 0.03 262)", marginLeft: 6 }}>({Math.round((c.gross / totalGross) * 100)}%)</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        <div style={{ fontSize: 13, color: "var(--dim)", textAlign: "center" }}>
          Tax estimate is a flat effective rate for planning only — adjust each slider to match real withholdings.
        </div>
      </div>
    </>
  );
}
window.ScreenIncome = ScreenIncome;
