/* CoHaven — Expense Split Calculator (free tool)
   Fair-split logic (50/50 · by income · by custody time) + running settle-up + print. */
const { useState, useEffect, useMemo } = React;
const { LeadGateModal, useLeadGate, PrintBrand, ResultsGate, LeadNextStep } = window;

const COLORS = [
  { key:"teal",  c:"#1b4d4a", tint:"#d9e7e2", name:"Teal" },
  { key:"clay",  c:"#c96f4c", tint:"#f0d8c8", name:"Clay" },
  { key:"plum",  c:"#6d5080", tint:"#e4dcec", name:"Plum" },
  { key:"slate", c:"#3f6079", tint:"#d8e2ea", name:"Slate" },
  { key:"olive", c:"#6f7a3a", tint:"#e6e8d2", name:"Olive" },
  { key:"rose",  c:"#a8506a", tint:"#f0d6df", name:"Rose" },
];
const getColor = (key) => COLORS.find(c => c.key === key) || COLORS[0];

const CATEGORIES = ["Medical", "School", "Activities", "Childcare", "Clothing", "Other"];

function Seg({ options, value, onChange }) {
  return (
    <div className="seg">
      {options.map(o => (
        <button key={o.v} className={"seg-btn" + (value === o.v ? " on" : "")} onClick={() => onChange(o.v)}>{o.label}</button>
      ))}
    </div>
  );
}
function ColorRow({ selected, exclude, onPick }) {
  return (
    <div className="colorrow">
      {COLORS.map(col => (
        <button key={col.key} className={"sw" + (selected === col.key ? " on" : "")}
          disabled={col.key === exclude} style={{ background: col.c, opacity: col.key === exclude ? 0.25 : 1 }}
          title={col.name} onClick={() => onPick(col.key)} />
      ))}
    </div>
  );
}
const money = (n) => "$" + (Math.round(n * 100) / 100).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const uid = () => Math.random().toString(36).slice(2, 9);

const SEED = [
  { id: uid(), desc: "After-school program", amount: 240, cat: "Childcare", paidBy: "A" },
  { id: uid(), desc: "Pediatrician visit", amount: 85, cat: "Medical", paidBy: "B" },
  { id: uid(), desc: "Soccer cleats & league", amount: 130, cat: "Activities", paidBy: "A" },
  { id: uid(), desc: "Winter coats (both kids)", amount: 96, cat: "Clothing", paidBy: "B" },
];

function App() {
  const load = (k, def) => { try { const v = JSON.parse(localStorage.getItem("cohaven.split") || "{}")[k]; return v === undefined ? def : v; } catch (e) { return def; } };

  const [aName, setAName] = useState(() => load("aName", "Parent A"));
  const [bName, setBName] = useState(() => load("bName", "Parent B"));
  const [aColor, setAColor] = useState(() => load("aColor", "teal"));
  const [bColor, setBColor] = useState(() => load("bColor", "clay"));
  const [basis, setBasis] = useState(() => load("basis", "even")); // even | income | custody
  const [incomeA, setIncomeA] = useState(() => load("incomeA", "60000"));
  const [incomeB, setIncomeB] = useState(() => load("incomeB", "40000"));
  const [custodyA, setCustodyA] = useState(() => load("custodyA", 50)); // % of time with A
  const [expenses, setExpenses] = useState(() => load("expenses", SEED));

  // add-form local state
  const [fDesc, setFDesc] = useState("");
  const [fAmt, setFAmt] = useState("");
  const [fCat, setFCat] = useState("Medical");
  const [fPaid, setFPaid] = useState("A");

  useEffect(() => {
    localStorage.setItem("cohaven.split", JSON.stringify({ aName, bName, aColor, bColor, basis, incomeA, incomeB, custodyA, expenses }));
  }, [aName, bName, aColor, bColor, basis, incomeA, incomeB, custodyA, expenses]);

  const { captured, open, gate, onCapture } = useLeadGate();
  const colA = getColor(aColor), colB = getColor(bColor);

  // share of each expense that parent A is responsible for
  const shareA = useMemo(() => {
    if (basis === "even") return 0.5;
    if (basis === "income") {
      const a = Math.max(0, parseFloat(incomeA) || 0), b = Math.max(0, parseFloat(incomeB) || 0);
      return (a + b) === 0 ? 0.5 : a / (a + b);
    }
    return Math.min(1, Math.max(0, custodyA / 100)); // custody time
  }, [basis, incomeA, incomeB, custodyA]);
  const shareB = 1 - shareA;

  const stats = useMemo(() => {
    let total = 0, paidA = 0, paidB = 0, oweAtoB = 0;
    const cats = {};
    expenses.forEach(e => {
      const amt = Math.max(0, parseFloat(e.amount) || 0);
      total += amt;
      cats[e.cat] = (cats[e.cat] || 0) + amt;
      if (e.paidBy === "A") { paidA += amt; oweAtoB -= amt * shareB; } // B owes A their share
      else { paidB += amt; oweAtoB += amt * shareA; } // A owes B their share
    });
    // oweAtoB > 0  => A owes B ; < 0 => B owes A
    const respA = total * shareA, respB = total * shareB;
    return { total, paidA, paidB, respA, respB, net: oweAtoB, cats };
  }, [expenses, shareA, shareB]);

  const addExpense = () => {
    const amt = parseFloat(fAmt);
    if (!fDesc.trim() || !amt || amt <= 0) return;
    setExpenses(x => [{ id: uid(), desc: fDesc.trim(), amount: amt, cat: fCat, paidBy: fPaid }, ...x]);
    setFDesc(""); setFAmt("");
  };
  const removeExpense = (id) => setExpenses(x => x.filter(e => e.id !== id));
  const resetAll = () => { if (confirm("Clear all expenses and reset to defaults?")) { setExpenses([]); setBasis("even"); } };

  const nameOf = (p) => p === "A" ? aName : bName;
  const colOf = (p) => p === "A" ? colA : colB;

  const catEntries = Object.entries(stats.cats).sort((a, b) => b[1] - a[1]);
  const maxCat = catEntries.length ? catEntries[0][1] : 1;

  // who owes whom
  const net = stats.net;
  const settleEven = Math.abs(net) < 0.005;
  const debtor = net > 0 ? aName : bName;
  const creditor = net > 0 ? bName : aName;

  return (
    <div className="sb">
      <header className="sb-nav no-print">
        <a className="brand" href="/">
          <svg className="logo-mark" viewBox="0 0 40 40" aria-hidden="true">
            <path className="a" d="M20 4 6 15v3l14-11 14 11v-3z" />
            <path className="b" d="M13 19c0-1 .8-2 2-2h10c1.2 0 2 1 2 2v13c0 1-.8 2-2 2H15c-1.2 0-2-1-2-2z" />
            <rect className="a" x="18" y="25" width="4" height="9" rx="1" />
          </svg>
          CoHaven
        </a>
        <span className="tool-tag">Free tool</span>
        <a className="btn btn-primary sb-cta" href="/pricing">Try the full app</a>
      </header>

      <div className="sb-head no-print">
        <span className="eyebrow">Expense Split Calculator</span>
        <h1>Split the kids' costs fairly.</h1>
        <p className="muted">Choose how you share costs — evenly, by income, or by custody time — then log who paid for what. CoHaven nets it out to a single, clear number. Saves automatically; no account needed.</p>
      </div>

      <div className="sb-grid">
        {/* ---------------- controls ---------------- */}
        <aside className="panel controls no-print">
          <div className="ctl">
            <label className="ctl-label">Parents</label>
            <div className="parent-row">
              <span className="pdot" style={{ background: colA.c }}></span>
              <input className="pin" value={aName} maxLength={18} onChange={e => setAName(e.target.value)} />
            </div>
            <ColorRow selected={aColor} exclude={bColor} onPick={setAColor} />
            <div className="parent-row" style={{ marginTop: 12 }}>
              <span className="pdot" style={{ background: colB.c }}></span>
              <input className="pin" value={bName} maxLength={18} onChange={e => setBName(e.target.value)} />
            </div>
            <ColorRow selected={bColor} exclude={aColor} onPick={setBColor} />
          </div>

          <div className="ctl">
            <label className="ctl-label">How you split costs</label>
            <Seg options={[{ v: "even", label: "50 / 50" }, { v: "income", label: "By income" }, { v: "custody", label: "By time" }]} value={basis} onChange={setBasis} />

            {basis === "income" && (
              <div>
                <div className="field">
                  <div className="field-label"><span className="pdot" style={{ width: 11, height: 11, background: colA.c }}></span>{aName} — annual income</div>
                  <div className="money-in"><span className="cur">$</span><input inputMode="numeric" value={incomeA} onChange={e => setIncomeA(e.target.value.replace(/[^0-9.]/g, ""))} /></div>
                </div>
                <div className="field">
                  <div className="field-label"><span className="pdot" style={{ width: 11, height: 11, background: colB.c }}></span>{bName} — annual income</div>
                  <div className="money-in"><span className="cur">$</span><input inputMode="numeric" value={incomeB} onChange={e => setIncomeB(e.target.value.replace(/[^0-9.]/g, ""))} /></div>
                </div>
              </div>
            )}

            {basis === "custody" && (
              <div className="slider-wrap field">
                <input type="range" min="0" max="100" step="5" value={custodyA} onChange={e => setCustodyA(parseInt(e.target.value))} />
                <div className="slider-read">
                  <span>{aName} <b>{custodyA}%</b></span>
                  <span>{bName} <b>{100 - custodyA}%</b></span>
                </div>
              </div>
            )}

            <div className="ratio-note">
              {aName} covers <b>{Math.round(shareA * 100)}%</b> · {bName} covers <b>{Math.round(shareB * 100)}%</b> of each shared cost.
            </div>
          </div>

          <div className="ctl">
            <label className="ctl-label">Add an expense</label>
            <div className="addform">
              <input placeholder="What was it for?" value={fDesc} maxLength={40} onChange={e => setFDesc(e.target.value)} onKeyDown={e => e.key === "Enter" && addExpense()} />
              <div className="two">
                <div className="money-in"><span className="cur">$</span><input inputMode="decimal" placeholder="0.00" value={fAmt} onChange={e => setFAmt(e.target.value.replace(/[^0-9.]/g, ""))} onKeyDown={e => e.key === "Enter" && addExpense()} style={{ paddingLeft: 26 }} /></div>
                <select value={fCat} onChange={e => setFCat(e.target.value)}>
                  {CATEGORIES.map(c => <option key={c} value={c}>{c}</option>)}
                </select>
              </div>
              <div className="paidby">
                <button className={fPaid === "A" ? "on" : ""} onClick={() => setFPaid("A")}><span className="pd" style={{ background: colA.c }}></span>{aName} paid</button>
                <button className={fPaid === "B" ? "on" : ""} onClick={() => setFPaid("B")}><span className="pd" style={{ background: colB.c }}></span>{bName} paid</button>
              </div>
              <button className="btn btn-accent full" onClick={addExpense}>
                <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M12 5v14M5 12h14" strokeLinecap="round" /></svg>
                Add expense
              </button>
            </div>
          </div>

          <div className="ctl">
            <button className="btn btn-ghost full" onClick={() => gate(() => window.print())}>
              <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 9V2h12v7M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2M6 14h12v8H6z" strokeLinecap="round" strokeLinejoin="round" /></svg>
              Print / save as PDF
            </button>
            <div style={{ textAlign: "right", marginTop: 12 }}>
              <button className="link-btn" onClick={resetAll}>Reset all</button>
            </div>
          </div>
        </aside>

        {/* ---------------- results ---------------- */}
        <main className="panel res">
          <PrintBrand toolName="Expense Split Calculator" />
          <div className="res-top">
            <h2>Settle up</h2>
            <span className="print-only sched-name" style={{ fontFamily: "var(--mono)", fontSize: 13, color: "var(--ink-500)" }}>
              {aName} &amp; {bName} · split {Math.round(shareA * 100)}/{Math.round(shareB * 100)}
            </span>
          </div>

          <ResultsGate
            captured={captured}
            onOpen={() => gate(null)}
            heading="See who owes what."
            body="Enter your email to unlock the full breakdown and get a copy sent to you."
          >
          <div>
          <div className={"settle" + (settleEven ? " even" : "")}>
            <div className="lab">{settleEven ? "All square" : "Current balance"}</div>
            <div className="amt">{settleEven ? money(0) : money(Math.abs(net))}</div>
            <div className="who">{settleEven ? "Nobody owes anybody — you're even." : <span><b>{debtor}</b> owes <b>{creditor}</b> to settle up.</span>}</div>
          </div>

          <div className="psum">
            <div className="pcard">
              <div className="ph"><i style={{ background: colA.c }}></i> {aName}</div>
              <div className="prow"><span>Paid out</span><b>{money(stats.paidA)}</b></div>
              <div className="prow"><span>Fair share ({Math.round(shareA * 100)}%)</span><b>{money(stats.respA)}</b></div>
            </div>
            <div className="pcard">
              <div className="ph"><i style={{ background: colB.c }}></i> {bName}</div>
              <div className="prow"><span>Paid out</span><b>{money(stats.paidB)}</b></div>
              <div className="prow"><span>Fair share ({Math.round(shareB * 100)}%)</span><b>{money(stats.respB)}</b></div>
            </div>
          </div>

          {catEntries.length > 0 && (
            <div className="cats">
              <h3>Where it went · {money(stats.total)} total</h3>
              <div className="catbar">
                {catEntries.map(([cat, amt]) => (
                  <div className="catrow" key={cat}>
                    <span className="cn">{cat}</span>
                    <span className="ct"><span style={{ width: (amt / maxCat * 100) + "%" }}></span></span>
                    <span className="cv">{money(amt)}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          </div>
          </ResultsGate>
          <LeadNextStep
            captured={captured}
            title="Stop recalculating the same costs."
            body="Your expense split is unlocked. CoHaven can keep shared costs, balances, receipts, and reminders in one place."
          />
          <div className="elist">
            <h3>Logged expenses</h3>
            {expenses.length === 0 ? (
              <div className="empty-state">
                <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M12 1v22M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" strokeLinecap="round" strokeLinejoin="round" /></svg>
                <p>No expenses yet. Add the first shared cost on the left to see how it splits.</p>
              </div>
            ) : expenses.map(e => {
              const amt = parseFloat(e.amount) || 0;
              const owedToPayer = e.paidBy === "A" ? amt * shareB : amt * shareA;
              const other = e.paidBy === "A" ? bName : aName;
              return (
                <div className="erow" key={e.id}>
                  <div className="ed">
                    <div className="et">{e.desc}</div>
                    <div className="es">
                      <span><span className="pdot2" style={{ background: colOf(e.paidBy).c }}></span> {nameOf(e.paidBy)} paid</span>
                      <span>· {e.cat}</span>
                    </div>
                  </div>
                  <span className="esplit">{other} owes {money(owedToPayer)}</span>
                  <span className="eamt">{money(amt)}</span>
                  <button className="edel no-print" onClick={() => removeExpense(e.id)} aria-label="Remove">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6 6 18M6 6l12 12" strokeLinecap="round" /></svg>
                  </button>
                </div>
              );
            })}
          </div>
        </main>
      </div>

      <LeadGateModal
        isOpen={open}
        onCapture={onCapture}
        headline="See exactly who owes what."
        subline="Enter your email to unlock the full breakdown — and get a copy sent to you."
      />

      <footer className="sb-footer no-print">
        <p>Free from <b>CoHaven</b> — keep your schedule, expenses and reminders in one shared place. <a href="/pricing">Start a 30-day trial →</a></p>
      </footer>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
