// Installment Manager — pool, contracts, buyers, collections
function Installments() {
  const { useState } = React;
  const [tab, setTab] = useState("pool");
  const [contribs, setContribs] = useState(D.poolContribs);
  const [contracts, setContracts] = useState(D.instContracts);
  const [collections, setCollections] = useState(D.instCollections || []);
  const [people, setPeople] = useState(D.poolPeople);
  const [personEdit, setPersonEdit] = useState(null); // null | "new" | person
  const [showFunds, setShowFunds] = useState(false);
  const [showContract, setShowContract] = useState(false);

  const poolTotal = contribs.reduce((s, c) => s + c.amount, 0);
  const spent = contracts.reduce((s, c) => s + contractTotal(c), 0);
  const balance = poolTotal - spent;
  const contributors = [...new Set(contribs.map((c) => c.person))];

  const plans = [];
  contracts.forEach((c) => c.shares.forEach((s) => plans.push(sharePlan(c, s, collections))));
  const receivable = plans.reduce((s, p) => s + (p.owed - p.paidAmt), 0);
  const collectedJul = plans.reduce((s, p) => s + p.schedule.filter((i) => i.paidOn && i.paidOn.startsWith("Jul")).reduce((x, i) => x + i.amount, 0), 0);
  const activePlans = plans.filter((p) => p.status !== "Completed").length;

  const addFunds = (c) => {
    const next = [...contribs, c]; setContribs(next); D.poolContribs = next;
    audit("Pool contribution", c.person, money(c.amount)); notify(T("inst.fundsAdded", { amount: money(c.amount), name: c.person }));
    setShowFunds(false);
  };
  const addContract = (c) => {
    const next = [c, ...contracts]; setContracts(next); D.instContracts = next;
    audit("Purchase contract created", c.id, money(contractTotal(c)) + " \u00b7 " + c.shares.length + " members \u00b7 " + (c.months || 6) + " months");
    notify(T("inst.contractCreated", { id: c.id, n: c.shares.length }));
    setShowContract(false);
  };
  const nextRef = (list) => "RC-" + (1001 + list.length);
  const collect = (c, person, inst, method, note) => {
    const ref = nextRef(collections);
    const next = [...collections, { contract: c.id, person, date: "Jul 27, 2026", method, ref, note: note || "" }];
    setCollections(next); D.instCollections = next;
    audit("Installment collected", person, c.id + " \u00b7 #" + inst.no + " \u00b7 " + money(inst.amount) + " \u00b7 " + method + " \u00b7 " + ref + (note ? " \u00b7 " + note : ""));
    notify(T("inst.collectedFrom", { amount: money(inst.amount), name: person, ref: ref }));
  };
  const settleEarly = (c, person, remaining, discount) => {
    const ref = nextRef(collections);
    const next = [...collections, { contract: c.id, person, date: "Jul 27, 2026", method: "Early settlement", settle: true, discount, ref }];
    setCollections(next); D.instCollections = next;
    audit("Early settlement", person, c.id + " \u00b7 " + money(remaining - discount) + (discount ? " \u00b7 " + money(discount) + " interest discount" : ""));
    notify(T("inst.settledEarly", { name: person, id: c.id, amount: money(remaining - discount) }));
  };
  const savePerson = (p) => {
    const exists = people.some((x) => x.id === p.id);
    const next = exists ? people.map((x) => (x.id === p.id ? p : x)) : [...people, p];
    setPeople(next); D.poolPeople = next;
    audit(exists ? "Buyer updated" : "Buyer added", p.name, p.phone || "");
    notify(exists ? T("inst.buyerUpdated", { name: p.name }) : T("inst.buyerAdded", { name: p.name }));
    setPersonEdit(null);
  };

  return (
    <div className="page" data-screen-label="Installments">
      <KpiBar>
        <Stat label={T("inst.poolBalance")} value={money(balance)} sub={T("inst.contributedAmount", { amount: money(poolTotal) })} />
        <Stat label={T("inst.purchases")} value={money(spent)} sub={T("inst.contractsN", { n: contracts.length })} />
        <Stat label={T("inst.receivable")} value={money(receivable)} sub={T("inst.activePlansN", { n: activePlans })} />
        <Stat label={T("inst.collectedInMonth", { month: TV("July") })} value={money(collectedJul)} sub={T("inst.acrossAllBuyers")} />
      </KpiBar>

      <Tabs active={tab} onChange={setTab} tabs={[
        { id: "pool", label: T("inst.pool"), count: contributors.length },
        { id: "contracts", label: T("inst.contracts"), count: contracts.length },
        { id: "payments", label: T("inst.payments") },
        { id: "people", label: T("inst.buyers"), count: people.length }
      ]} />

      {tab === "pool" ? <PoolTab contribs={contribs} contracts={contracts} balance={balance} onAddFunds={() => setShowFunds(true)} /> : null}
            {tab === "contracts" ? <ContractsTab contracts={contracts} collections={collections} balance={balance} onNew={() => setShowContract(true)} onCollect={collect} onSettle={settleEarly} /> : null}
      {tab === "payments" ? <PaymentsTab contracts={contracts} collections={collections} onCollect={collect} /> : null}
      {tab === "people" ? <PeopleTab people={people} contribs={contribs} contracts={contracts} onAdd={() => setPersonEdit("new")} onEdit={(p) => setPersonEdit(p)} /> : null}

      <AddFundsModal open={showFunds} people={contributors} onClose={() => setShowFunds(false)} onSave={addFunds} />
      <NewContractModal open={showContract} contribs={contribs} people={people} balance={balance} onClose={() => setShowContract(false)} onSave={addContract} onAddPerson={savePerson} />
      <PersonModal open={!!personEdit} person={personEdit === "new" ? null : personEdit} onClose={() => setPersonEdit(null)} onSave={savePerson} />
    </div>
  );
}
Object.assign(window, { Installments });
