/* ============================================================================
   MONEY — group expenses, per-person totals, who-owes-who settle up.
   ============================================================================ */
function MoneyScreen({ state, actions, openAddExpense }) {
  const T = window.TRIP;
  const exp = state.expenses;
  const total = exp.reduce((s, e) => s + e.vnd, 0);

  // paid & owed per person
  const paid = {}, owed = {};
  T.people.forEach((p) => { paid[p.id] = 0; owed[p.id] = 0; });
  exp.forEach((e) => {
    paid[e.by] += e.vnd;
    const share = e.vnd / e.split.length;
    e.split.forEach((id) => { owed[id] += share; });
  });
  const net = {};
  T.people.forEach((p) => { net[p.id] = Math.round(paid[p.id] - owed[p.id]); });

  // settle up (greedy)
  const settlements = computeSettlements(net, T.people);

  const maxOwed = Math.max(...T.people.map((p) => owed[p.id]), 1);

  return (
    <div style={{ padding: "8px 16px 8px", display: "flex", flexDirection: "column", gap: 16 }}>
      {/* total hero */}
      <Card pad={18} style={{ background: "linear-gradient(150deg, #0c5f63, var(--color-teal))", border: "none", color: "#fff" }}>
        <Overline color="rgba(255,255,255,0.72)">Total trip spend</Overline>
        <div style={{ display: "flex", alignItems: "flex-end", gap: 8, marginTop: 6 }}>
          <span style={{ fontSize: 38, fontWeight: 700, letterSpacing: "-0.02em", lineHeight: 1 }}>{T.toINR(total)}</span>
          <span style={{ fontSize: 14, color: "rgba(255,255,255,0.8)", paddingBottom: 4 }}>({T.fmtVNDFull(total)})</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 12 }}>
          <AvatarStack people={T.people} size={26} />
          <span style={{ fontSize: 13, color: "rgba(255,255,255,0.85)" }}>{T.toINR(total / T.people.length)} ({T.fmtVND(total / T.people.length)}) per person if split evenly</span>
        </div>
      </Card>

      {/* settle up */}
      <div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "2px 2px 10px" }}>
          <Overline>Settle up</Overline>
          <Chip tone={settlements.length ? "amber" : "green"}>{settlements.length ? `${settlements.length} transfer${settlements.length === 1 ? "" : "s"}` : "All square"}</Chip>
        </div>
        <Card pad={settlements.length ? 6 : 16}>
          {settlements.length === 0 ? (
            <div style={{ textAlign: "center", color: "var(--colorNeutralForeground3)", fontSize: 13.5, padding: "4px 0" }}>Everyone's even — nice.</div>
          ) : settlements.map((s, i) => {
            const from = T.people.find((p) => p.id === s.from);
            const to = T.people.find((p) => p.id === s.to);
            return (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 10px",
                borderBottom: i === settlements.length - 1 ? "none" : "1px solid var(--colorNeutralStroke3)" }}>
                <Avatar person={from} size={30} />
                <div style={{ display: "flex", alignItems: "center", gap: 6, flex: 1 }}>
                  <span style={{ fontSize: 13.5, fontWeight: 600 }}>{from.name}</span>
                  <Icon name="arrow_right" size={15} color="var(--colorNeutralForeground4)" />
                  <span style={{ fontSize: 13.5, fontWeight: 600 }}>{to.name}</span>
                </div>
                <Avatar person={to} size={30} />
                <div style={{ marginLeft: "auto", textAlign: "right" }}>
                  <div style={{ fontSize: 14.5, fontWeight: 700, color: "var(--color-darkTeal)" }}>{T.toINR(s.amount)}</div>
                  <div style={{ fontSize: 11, color: "var(--colorNeutralForeground4)" }}>({T.fmtVND(s.amount)})</div>
                </div>
              </div>
            );
          })}
        </Card>
      </div>

      {/* per person */}
      <div>
        <Overline style={{ margin: "2px 2px 10px" }}>Who spent what</Overline>
        <Card pad={14}>
          <div style={{ display: "flex", flexDirection: "column", gap: 13 }}>
            {T.people.map((p) => (
              <div key={p.id} style={{ display: "flex", alignItems: "center", gap: 11 }}>
                <Avatar person={p} size={32} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 5 }}>
                    <span style={{ fontSize: 13.5, fontWeight: 600 }}>{p.name}{p.id === "you" ? "" : ""}</span>
                    <span style={{ fontSize: 13, fontWeight: 700, color: net[p.id] >= 0 ? "var(--colorStatusSuccessForeground1)" : "var(--color-pumpkin)" }}>
                      {net[p.id] >= 0 ? "gets back " : "owes "}{T.toINR(Math.abs(net[p.id]))} <span style={{ fontWeight: 500, opacity: 0.75 }}>({T.fmtVND(Math.abs(net[p.id]))})</span>
                    </span>
                  </div>
                  <Progress value={paid[p.id]} max={maxOwed * 1.4} color={p.color} height={6} />
                  <div style={{ fontSize: 11.5, color: "var(--colorNeutralForeground3)", marginTop: 4 }}>paid {T.toINR(paid[p.id])} ({T.fmtVND(paid[p.id])})</div>
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* expense list */}
      <div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "2px 2px 10px" }}>
          <Overline>Expenses · {exp.length}</Overline>
          <button onClick={openAddExpense} style={{ border: "none", background: "none", color: "var(--color-darkTeal)", fontWeight: 700, fontSize: 13, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 4 }}>
            <Icon name="add_circle" size={16} filled color="var(--color-teal)" /> Add
          </button>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
          {[...exp].reverse().map((e) => {
            const payer = T.people.find((p) => p.id === e.by);
            const splitPeople = e.split.map((id) => T.people.find((p) => p.id === id));
            return (
              <Card key={e.id} pad={13}>
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <span style={{ width: 40, height: 40, borderRadius: 11, flexShrink: 0, background: catBg(e.cat),
                    display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                    <Icon name={catIcon(e.cat)} size={20} color={catFg(e.cat)} />
                  </span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14.5, fontWeight: 600, color: "var(--colorNeutralForeground1)" }}>{e.title}</div>
                    <div style={{ fontSize: 12, color: "var(--colorNeutralForeground3)", marginTop: 2, display: "flex", alignItems: "center", gap: 5 }}>
                      <span>{payer.name} paid</span>·<span>{e.day}</span>·
                      <AvatarStack people={splitPeople} size={16} />
                    </div>
                  </div>
                  <div style={{ textAlign: "right" }}>
                    <div style={{ fontSize: 15, fontWeight: 700, color: "var(--colorNeutralForeground1)" }}>{T.toINR(e.vnd)}</div>
                    <div style={{ fontSize: 11, color: "var(--colorNeutralForeground4)" }}>({T.fmtVND(e.vnd)})</div>
                  </div>
                </div>
              </Card>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function computeSettlements(net, people) {
  const debtors = [], creditors = [];
  people.forEach((p) => {
    const v = net[p.id];
    if (v < -1000) debtors.push({ id: p.id, amt: -v });
    else if (v > 1000) creditors.push({ id: p.id, amt: v });
  });
  debtors.sort((a, b) => b.amt - a.amt);
  creditors.sort((a, b) => b.amt - a.amt);
  const out = [];
  let i = 0, j = 0;
  while (i < debtors.length && j < creditors.length) {
    const pay = Math.min(debtors[i].amt, creditors[j].amt);
    out.push({ from: debtors[i].id, to: creditors[j].id, amount: Math.round(pay) });
    debtors[i].amt -= pay; creditors[j].amt -= pay;
    if (debtors[i].amt < 1000) i++;
    if (creditors[j].amt < 1000) j++;
  }
  return out;
}

function catIcon(c) {
  return { Tours: "ticket_diagonal", Stay: "bed", Transport: "vehicle_car", Food: "food", Other: "tag" }[c] || "tag";
}
function catBg(c) {
  return { Tours: "rgba(113,96,232,0.12)", Stay: "rgba(0,153,188,0.12)", Transport: "rgba(3,131,135,0.12)", Food: "rgba(202,80,16,0.12)", Other: "var(--colorNeutralBackground3)" }[c] || "var(--colorNeutralBackground3)";
}
function catFg(c) {
  return { Tours: "var(--color-lavender)", Stay: "var(--color-cyan)", Transport: "var(--color-teal)", Food: "var(--color-pumpkin)", Other: "var(--colorNeutralForeground3)" }[c] || "var(--colorNeutralForeground3)";
}

Object.assign(window, { MoneyScreen });
