/* ============================================================
   EDUCARE — Tela "Atendimentos por Paciente"
   Lente Semanal/Mensal sobre as cobranças por atendimento realizado.
   Cards por paciente, modal de detalhe com histórico e ações de
   pagamento. Fonte de dados: window.Billing.
   ============================================================ */
(function () {
  const { useState } = React;
  const Icon = window.Icon;
  const B = () => window.Billing;
  const brl = (v) => "R$ " + (Math.round(v || 0)).toLocaleString("pt-BR");
  const METHODS = ["Pix", "Dinheiro", "Cartão", "Transferência"];
  const cmpNome = (a, b) => a.name.localeCompare(b.name, "pt-BR", { sensitivity: "base" });

  function Toast({ toast, onUndo }) {
    if (!toast) return null;
    return (
      <div style={{ position: "fixed", left: "50%", bottom: 22, transform: "translateX(-50%)", zIndex: 120, display: "flex", alignItems: "center", gap: 12, padding: "11px 16px", borderRadius: 12, boxShadow: "var(--shadow-lg)", fontSize: 13.5, fontWeight: 700, color: "#fff", background: toast.err ? "#DC2626" : "var(--primary)" }}>
        <Icon name={toast.err ? "x" : "clipboardCheck"} size={16} /> {toast.text}
        {toast.undo && <button onClick={onUndo} style={{ background: "rgba(255,255,255,.25)", border: "none", color: "#fff", fontWeight: 800, fontSize: 12.5, borderRadius: 8, padding: "3px 10px", cursor: "pointer" }}>Desfazer</button>}
      </div>
    );
  }

  // -------------------- Modal de detalhe --------------------
  function DetailModal({ pid, type, pkey, onClose, onChange, setToast }) {
    const bi = B();
    const p = (window.PATIENTS || []).find((x) => x.id === pid) || {};
    const [, force] = useState(0);
    const refresh = () => { force((n) => n + 1); onChange && onChange(); };
    const info = bi.periodInfo(pid, type, pkey);
    const prior = bi.priorOpen(pid, type, pkey);
    const st = (window.BillingUI.STMETA[info.status] || {});

    const [method, setMethod] = useState("Pix");
    const [parcial, setParcial] = useState("");
    const [novoData, setNovoData] = useState(bi.todayISO());
    const [novoValor, setNovoValor] = useState(String(bi.feeOf(p) || ""));
    const [editIso, setEditIso] = useState(null);
    const [editVal, setEditVal] = useState("");
    const [histFiltro, setHistFiltro] = useState("12");
    const [histAberto, setHistAberto] = useState(() => new Set());
    const [phist, setPhist] = useState({});
    const [confirmUndo, setConfirmUndo] = useState(false);

    function marcarPago() {
      bi.payPeriod(pid, type, pkey, null, method);
      setToast({ text: "Período marcado como pago." }); refresh();
    }
    function pagarParcial() {
      const v = Math.max(0, Math.round(Number(parcial)) || 0); if (v <= 0) return;
      bi.payPeriod(pid, type, pkey, v, method); setParcial("");
      setToast({ text: brl(v) + " registrado (abatido do mais antigo)." }); refresh();
    }
    function desfazerPagamento() { bi.unpayPeriod(pid, type, pkey); setConfirmUndo(false); setToast({ text: "Pagamento do período desfeito." }); refresh(); }
    // Ações direto no histórico (quitar/estornar qualquer mês, inclusive os atrasados)
    function pagarHist(ym) { bi.payPeriod(pid, "mes", ym, null, method); setToast({ text: bi.monthLabel(ym) + " marcado como pago." }); refresh(); }
    function pagarHistParcial(ym) { const v = Math.max(0, Math.round(Number(phist[ym])) || 0); if (v <= 0) return; bi.payPeriod(pid, "mes", ym, v, method); setPhist((s) => ({ ...s, [ym]: "" })); setToast({ text: brl(v) + " registrado em " + bi.monthLabel(ym) + "." }); refresh(); }
    function desfazerHist(ym) { bi.unpayPeriod(pid, "mes", ym); setToast({ text: "Pagamento de " + bi.monthLabel(ym) + " desfeito." }); refresh(); }
    function lancar(kind) {
      const r = bi.recordSession(pid, novoData, Math.round(Number(novoValor)) || 0, kind, type, pkey);
      if (r && r.warnPaidPeriod) setToast({ text: "Atenção: o período estava quitado e voltou a Parcial com o novo valor em aberto.", err: true });
      else setToast({ text: kind === "falta" ? "Falta registrada (R$ 0,00)." : "Atendimento lançado." });
      refresh();
    }
    function salvarEdicao(iso) { bi.recordSession(pid, iso, Math.round(Number(editVal)) || 0, "realizado", type, pkey); setEditIso(null); setToast({ text: "Valor atualizado." }); refresh(); }
    function remover(iso) { bi.removeSession(pid, iso); setToast({ text: "Atendimento removido." }); refresh(); }

    function compartilhar() {
      const linhas = info.atendimentos.map((c) => `• ${bi.fmtDMY(c.dateISO)} — ${c.kind === "falta" ? "Falta (R$ 0,00)" : brl(c.value)}`).join("\n");
      const abertoTxt = info.rem > 0 ? `\nEm aberto: ${brl(info.rem)}` : "\nTudo quitado. Obrigado!";
      const priorTxt = prior.rem > 0 ? `\nPendência anterior: ${brl(prior.rem)}` : "";
      const msg = `Olá! Resumo dos atendimentos de ${p.name} — ${bi.periodLabel(type, pkey)}:\n${linhas || "• (sem atendimentos)"}\nTotal: ${brl(info.total)}${abertoTxt}${priorTxt}`;
      const tel = String(p.phone || "").replace(/\D/g, "");
      const num = tel ? (tel.length <= 11 ? "55" + tel : tel) : "";
      window.open(`https://wa.me/${num}?text=` + encodeURIComponent(msg), "_blank");
    }

    const hist = bi.history(pid).filter((h) => {
      if (histFiltro === "all") return true;
      const y = bi.todayISO().slice(0, 4);
      if (histFiltro === "year") return h.ym.slice(0, 4) === y;
      const cutoff = (function () { const d = new Date(); d.setMonth(d.getMonth() - 12); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`; })();
      return h.ym >= cutoff;
    });

    const ind = (lbl, val, col) => <div style={{ background: "var(--surface-2)", borderRadius: 10, padding: "8px 10px", textAlign: "center" }}><div style={{ fontSize: 10.5, color: "var(--text-3)", fontWeight: 700 }}>{lbl}</div><b style={{ fontSize: 16, color: col || "var(--text)" }}>{val}</b></div>;

    return (
      <div className="modal-scrim" onClick={onClose}>
        <div className="modal" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 540, maxHeight: "90vh", overflowY: "auto" }}>
          <div className="modal-head"><div><h3>{p.name}</h3><p style={{ textTransform: "capitalize" }}>{bi.periodLabel(type, pkey)}</p></div><button className="x" onClick={onClose} aria-label="Fechar"><Icon name="x" size={18} /></button></div>
          <div className="modal-body">
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 6, marginBottom: 8 }}>
              {ind("Atend.", info.count)}
              {ind("Valor", brl(info.total))}
              {ind("Pago", brl(info.paid), "#16A34A")}
              {ind("Falta", brl(info.rem), info.rem > 0 ? "#DC2626" : "var(--text-3)")}
            </div>
            <div style={{ marginBottom: 12 }}>{window.BillingUI.stBadge(info.status, info.rem)}{prior.rem > 0 && <span style={{ marginLeft: 8, fontSize: 12, fontWeight: 700, color: "#DC2626" }}>+{brl(prior.rem)} de {prior.label} em atraso</span>}</div>

            {/* Lista de atendimentos do período */}
            <p className="section-label" style={{ marginTop: 0 }}>ATENDIMENTOS DO PERÍODO</p>
            <div style={{ display: "flex", flexDirection: "column", gap: 5, marginBottom: 10 }}>
              {info.atendimentos.length === 0 && <p className="help-text" style={{ margin: 0 }}>Nenhum atendimento neste período.</p>}
              {info.atendimentos.map((c) => (
                <div key={c.dateISO} style={{ display: "flex", alignItems: "center", gap: 8, padding: "7px 10px", borderRadius: 9, background: c.kind === "falta" ? "var(--surface-3)" : "var(--surface-2)" }}>
                  <span style={{ fontSize: 12.5, fontWeight: 700, color: c.kind === "falta" ? "var(--text-3)" : "var(--text)" }}>{bi.fmtDMY(c.dateISO)}</span>
                  {editIso === c.dateISO ? (
                    <><input className="ctrl" type="number" value={editVal} onChange={(e) => setEditVal(e.target.value)} style={{ width: 90, marginLeft: "auto", padding: "4px 8px" }} /><button className="btn btn-primary btn-xs" onClick={() => salvarEdicao(c.dateISO)}>OK</button></>
                  ) : (
                    <>
                      <span style={{ marginLeft: "auto", fontSize: 12.5, fontWeight: 800, color: c.kind === "falta" ? "var(--text-3)" : (c.paid >= c.value && c.value > 0 ? "#16A34A" : "var(--text)") }}>{c.kind === "falta" ? "Falta · R$ 0,00" : brl(c.value)}</span>
                      {c.kind !== "falta" && <button className="icon-btn-plain" title="Editar valor" onClick={() => { setEditIso(c.dateISO); setEditVal(String(c.value)); }}><Icon name="fileText" size={14} /></button>}
                      <button className="icon-btn-plain" title="Remover" onClick={() => remover(c.dateISO)}><Icon name="x" size={14} /></button>
                    </>
                  )}
                </div>
              ))}
            </div>

            {/* Lançar novo atendimento / falta */}
            <div style={{ display: "flex", gap: 6, alignItems: "flex-end", flexWrap: "wrap", background: "var(--surface-2)", borderRadius: 10, padding: "10px 11px", marginBottom: 14 }}>
              <div className="fld" style={{ margin: 0, flex: "1 1 130px" }}><label style={{ fontSize: 11 }}>Data</label><input className="ctrl" type="date" value={novoData} onChange={(e) => setNovoData(e.target.value)} style={{ padding: "6px 8px" }} /></div>
              <div className="fld" style={{ margin: 0, flex: "1 1 90px" }}><label style={{ fontSize: 11 }}>Valor (R$)</label><input className="ctrl" type="number" min="0" value={novoValor} onChange={(e) => setNovoValor(e.target.value)} style={{ padding: "6px 8px" }} /></div>
              <button className="btn btn-primary btn-sm" onClick={() => lancar("realizado")}><Icon name="plus" size={14} /> Realizado</button>
              <button className="btn btn-ghost btn-sm" onClick={() => lancar("falta")}>Falta</button>
            </div>

            {/* Ações de pagamento */}
            <p className="section-label">PAGAMENTO DO PERÍODO</p>
            <div className="fld"><label>Forma de pagamento</label>
              <select className="ctrl" value={method} onChange={(e) => setMethod(e.target.value)}>{METHODS.map((x) => <option key={x} value={x}>{x}</option>)}</select>
            </div>
            {info.status === "pago" ? (
              confirmUndo ? (
                <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
                  <span style={{ fontSize: 12.5, fontWeight: 700 }}>Desfazer o pagamento deste período?</span>
                  <button className="btn btn-ghost btn-sm" onClick={() => setConfirmUndo(false)}>Cancelar</button>
                  <button className="btn btn-sm" style={{ background: "#DC2626", color: "#fff" }} onClick={desfazerPagamento}>Desfazer</button>
                </div>
              ) : <button className="btn btn-ghost btn-sm" onClick={() => setConfirmUndo(true)}><Icon name="arrowRight" size={15} /> Desfazer pagamento deste período</button>
            ) : info.rem > 0 ? (
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "flex-end" }}>
                <button className="btn btn-primary btn-sm" onClick={marcarPago}><Icon name="wallet" size={15} /> Marcar como pago ({brl(info.rem)})</button>
                <div className="fld" style={{ margin: 0, flex: "1 1 120px" }}><label style={{ fontSize: 11 }}>Valor recebido (parcial)</label><input className="ctrl" type="number" min="0" value={parcial} onChange={(e) => setParcial(e.target.value)} placeholder={"Ex.: " + Math.round(info.rem / 2)} style={{ padding: "6px 8px" }} /></div>
                <button className="btn btn-ghost btn-sm" onClick={pagarParcial} disabled={!parcial.trim()}>Registrar parcial</button>
              </div>
            ) : <p className="help-text" style={{ margin: 0 }}>Nada a cobrar neste período.</p>}

            <button className="btn btn-ghost btn-sm" style={{ marginTop: 10 }} onClick={compartilhar}><Icon name="chat" size={15} /> Compartilhar com responsável</button>

            {/* Histórico */}
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "18px 0 6px" }}>
              <p className="section-label" style={{ margin: 0 }}>HISTÓRICO</p>
              <select className="ctrl" value={histFiltro} onChange={(e) => setHistFiltro(e.target.value)} style={{ width: "auto", padding: "4px 8px", fontSize: 12 }}>
                <option value="12">Últimos 12 meses</option><option value="year">Ano corrente</option><option value="all">Todo o histórico</option>
              </select>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
              {hist.length === 0 && <p className="help-text" style={{ margin: 0 }}>Sem histórico no período selecionado.</p>}
              {hist.map((h) => {
                const paid = h.status === "pago";
                const aberto = histAberto.has(h.ym);
                const recolhido = paid && !aberto;
                return (
                  <div key={h.ym} style={{ border: "1px solid var(--border)", borderRadius: 9, padding: "8px 10px", background: "var(--surface)" }}>
                    <button type="button" onClick={() => setHistAberto((s) => { const n = new Set(s); n.has(h.ym) ? n.delete(h.ym) : n.add(h.ym); return n; })} style={{ width: "100%", background: "none", border: "none", padding: 0, cursor: "pointer", textAlign: "left", color: "var(--text)", display: "flex", alignItems: "center", gap: 8 }}>
                      <b style={{ fontSize: 13 }}>{bi.monthLabel(h.ym)}</b>
                      <span style={{ marginLeft: "auto" }}>{window.BillingUI.stBadge(h.status, h.rem)}</span>
                      <Icon name="chevDown" size={15} style={{ transform: aberto || !paid ? "none" : "rotate(-90deg)", transition: "transform .15s" }} />
                    </button>
                    {!recolhido && (
                      <div style={{ marginTop: 6, fontSize: 12, lineHeight: 1.6 }}>
                        {h.status === "pago" && <div><span style={{ color: "#16A34A", fontWeight: 700 }}>pago em {h.payDate ? bi.fmtDMY(h.payDate) : "—"}</span> · {brl(h.total)}{h.method ? " · " + h.method : ""}</div>}
                        {(h.status === "atrasado") && <div><span style={{ color: "#DC2626", fontWeight: 700 }}>vencido em {bi.fmtDMY(h.due)}</span> · {brl(h.total)} · <span style={{ color: "#DC2626" }}>{h.overdueDays} dias em atraso</span></div>}
                        {h.status === "parcial" && <div><span style={{ color: "#16A34A", fontWeight: 700 }}>pago {brl(h.paid)}</span> · <span style={{ color: "#DC2626", fontWeight: 700 }}>resta {brl(h.rem)}</span>{h.overdueDays ? <span style={{ color: "#DC2626" }}> · {h.overdueDays} dias em atraso</span> : null}</div>}
                        {h.status === "aberto" && <div>em aberto · {brl(h.total)} · vence em {bi.fmtDMY(h.due)}</div>}
                        {h.rem > 0 ? (
                          <div style={{ display: "flex", gap: 6, flexWrap: "wrap", alignItems: "center", marginTop: 8 }}>
                            <button className="btn btn-primary btn-sm" onClick={() => pagarHist(h.ym)}><Icon name="wallet" size={14} /> Marcar como pago ({brl(h.rem)})</button>
                            <input className="ctrl" type="number" min="0" value={phist[h.ym] || ""} onChange={(e) => setPhist((s) => ({ ...s, [h.ym]: e.target.value }))} placeholder="parcial" style={{ width: 84, padding: "5px 8px" }} />
                            <button className="btn btn-ghost btn-sm" onClick={() => pagarHistParcial(h.ym)} disabled={!(phist[h.ym] || "").trim()}>Parcial</button>
                          </div>
                        ) : (h.total > 0 && (
                          <div style={{ marginTop: 8 }}>
                            <button className="btn btn-ghost btn-sm" onClick={() => desfazerHist(h.ym)}><Icon name="arrowRight" size={14} /> Desfazer pagamento</button>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    );
  }

  window.AtendDetailModal = DetailModal;

  // -------------------- Tela --------------------
  function AtendPagamentos({ onNavigate, embed }) {
    const bi = B();
    const [type, setType] = useState("mes");
    const [key, setKey] = useState(() => B().currentKey("mes"));
    const [detail, setDetail] = useState(null);
    const [toast, setToast] = useState(null);
    const [undoFn, setUndoFn] = useState(null);
    const [grupo, setGrupo] = useState("todos"); // todos | pend | pago
    const [, force] = useState(0);
    const refresh = () => force((n) => n + 1);

    React.useEffect(() => {
      if (bi.migratedOld) setToast({ text: "Dados migrados: mensalidades fixas duplicadas removidas; pagamentos preservados." });
    }, []);
    React.useEffect(() => { if (!toast) return; const id = setTimeout(() => setToast(null), 6000); return () => clearTimeout(id); }, [toast]);

    function switchType(t) { setType(t); setKey(bi.currentKey(t)); }
    const isCurrent = key === bi.currentKey(type);

    // TODOS os pacientes com atendimento no período (ou pendência anterior), pagos inclusive.
    const withInfo = (window.PATIENTS || [])
      .filter((p) => { const i = bi.periodInfo(p.id, type, key); const pr = bi.priorOpen(p.id, type, key); return i.count > 0 || pr.rem > 0; })
      .map((p) => ({ p, i: bi.periodInfo(p.id, type, key), pr: bi.priorOpen(p.id, type, key) }));
    // Rank: atrasado (0, inclui pendência anterior) · parcial (1) · em aberto (2) · pago/quitado (3)
    const rankOf = (x) => {
      if (x.i.rem <= 0 && x.pr.rem <= 0) return 3;          // quitado
      if (x.i.status === "atrasado" || x.pr.rem > 0) return 0;
      if (x.i.status === "parcial") return 1;
      return 2;                                              // em aberto
    };
    const withRank = withInfo.map((x) => ({ ...x, rank: rankOf(x) }));
    const visiveis = withRank.filter((x) => grupo === "todos" ? true : grupo === "pago" ? x.rank === 3 : x.rank < 3);
    const ordered = visiveis.slice().sort((a, b) => (a.rank - b.rank) || cmpNome(a.p, b.p));
    const firstPagoIdx = ordered.findIndex((x) => x.rank === 3);

    // Resumo — totais corrigidos (mês exibido + atrasos anteriores)
    let totalPeriodo = 0, recebido = 0, emAbertoMes = 0, atrasadoAnterior = 0, comPend = 0;
    withInfo.forEach((x) => { totalPeriodo += x.i.total; recebido += x.i.paid; emAbertoMes += x.i.rem; atrasadoAnterior += x.pr.rem; if (x.i.rem > 0 || x.pr.rem > 0) comPend++; });
    const totalReceber = emAbertoMes + atrasadoAnterior;

    return (
      <>
        {!embed && <div className="crumb">Dashboard <Icon name="chevR" size={13} /> <span className="cur">Atendimentos por paciente</span></div>}
        {!embed && (
          <div className="page-head">
            <div><h1><Icon name="wallet" size={25} /> Atendimentos por paciente</h1><p className="sub" style={{ textTransform: "capitalize" }}>{bi.periodLabel(type, key)}</p></div>
          </div>
        )}
        <div className="agenda-bar" style={{ flexWrap: "wrap", gap: 8 }}>
          <div className="seg">
            {[["semana", "Semanal"], ["mes", "Mensal"]].map(([k, l]) => <button key={k} className={type === k ? "on" : ""} onClick={() => switchType(k)}>{l}</button>)}
          </div>
          <div className="date-nav">
            <button className="nav" onClick={() => setKey(bi.prevKey(type, key))}><Icon name="chevL" size={18} /></button>
            <span className="rangelbl" style={{ textTransform: "capitalize" }}>{bi.periodLabel(type, key)}</span>
            <button className="nav" onClick={() => setKey(bi.nextKey(type, key))} disabled={isCurrent} style={{ opacity: isCurrent ? 0.4 : 1 }}><Icon name="chevR" size={18} /></button>
          </div>
          <button className="today-btn" onClick={() => setKey(bi.currentKey(type))}>Hoje</button>
        </div>

        {/* Resumo */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(115px,1fr))", gap: 8, margin: "4px 0 12px" }}>
          <div className="card card-pad" style={{ padding: "10px 12px" }}><div style={{ fontSize: 11, color: "var(--text-3)", fontWeight: 700 }}>Total do período</div><b style={{ fontSize: 18 }}>{brl(totalPeriodo)}</b></div>
          <div className="card card-pad" style={{ padding: "10px 12px" }}><div style={{ fontSize: 11, color: "var(--text-3)", fontWeight: 700 }}>Recebido</div><b style={{ fontSize: 18, color: "#16A34A" }}>{brl(recebido)}</b></div>
          <div className="card card-pad" style={{ padding: "10px 12px" }}><div style={{ fontSize: 11, color: "var(--text-3)", fontWeight: 700 }}>Em aberto ({bi.periodLabel(type, key).split(" de ")[0].replace("Semana", "semana")})</div><b style={{ fontSize: 18, color: "#DC2626" }}>{brl(emAbertoMes)}</b></div>
          <div className="card card-pad" style={{ padding: "10px 12px" }}><div style={{ fontSize: 11, color: "var(--text-3)", fontWeight: 700 }}>Atrasado (anterior)</div><b style={{ fontSize: 18, color: "#B91C1C" }}>{brl(atrasadoAnterior)}</b></div>
          <div className="card card-pad" style={{ padding: "10px 12px", background: "var(--primary-soft)", border: "1px solid var(--primary)" }}><div style={{ fontSize: 11, color: "var(--primary)", fontWeight: 800 }}>Total a receber</div><b style={{ fontSize: 20, color: "var(--primary)" }}>{brl(totalReceber)}</b></div>
          <div className="card card-pad" style={{ padding: "10px 12px" }}><div style={{ fontSize: 11, color: "var(--text-3)", fontWeight: 700 }}>Com pendência</div><b style={{ fontSize: 18 }}>{comPend}</b></div>
        </div>

        {/* Filtro rápido */}
        <div className="seg" style={{ marginBottom: 12 }}>
          {[["todos", "Todos"], ["pend", "Pendentes"], ["pago", "Pagos"]].map(([k, l]) => <button key={k} className={grupo === k ? "on" : ""} onClick={() => setGrupo(k)}>{l}</button>)}
        </div>

        {/* Cards */}
        {ordered.length === 0 ? (
          <div className="card card-pad" style={{ textAlign: "center", color: "var(--text-3)", fontWeight: 600 }}>Nenhum atendimento neste período. Marque uma sessão como realizada para gerar a cobrança.</div>
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {ordered.map((x, idx) => {
              const { p, i, pr, rank } = x;
              const pago = rank === 3;
              // dados do pagamento (para o card pago): último payDate + forma
              const pagosCharges = (i.atendimentos || []).filter((c) => c.kind !== "falta" && c.payDate);
              let pagoEm = "", forma = "";
              if (pagosCharges.length) { const last = pagosCharges.slice().sort((a, b) => a.payDate.localeCompare(b.payDate))[pagosCharges.length - 1]; const dd = last.payDate.split("-"); pagoEm = `${dd[2]}/${dd[1]}`; forma = last.method || ""; }
              const stripe = pago ? "#16A34A" : (i.status === "atrasado" || pr.rem > 0) ? "#DC2626" : i.status === "parcial" ? "#D97706" : "var(--border-2)";
              const sep = idx === firstPagoIdx && firstPagoIdx > 0;
              return (
                <React.Fragment key={p.id}>
                  {sep && <div style={{ display: "flex", alignItems: "center", gap: 8, margin: "4px 2px 0" }}><span style={{ flex: 1, height: 1, background: "var(--border)" }} /><span style={{ fontSize: 10.5, fontWeight: 800, color: "var(--text-3)", letterSpacing: ".04em" }}>PAGOS</span><span style={{ flex: 1, height: 1, background: "var(--border)" }} /></div>}
                  <button type="button" onClick={() => setDetail(p.id)} style={{ display: "block", width: "100%", textAlign: "left", cursor: "pointer", border: "1px solid " + (pago ? "rgba(22,163,74,.35)" : "var(--border)"), borderLeft: "4px solid " + stripe, borderRadius: 12, background: pago ? "rgba(22,163,74,.05)" : "var(--surface)", padding: "11px 13px" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <span className={"avatar sm " + p.color} style={{ flex: "none" }}>{p.initials}</span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 7, flexWrap: "wrap" }}>
                          <b style={{ fontSize: 14 }}>{p.name}</b>
                          <span style={{ fontSize: 10.5, fontWeight: 800, color: "var(--primary)", background: "var(--primary-soft)", borderRadius: 20, padding: "1px 8px" }}>{i.count}x</span>
                        </div>
                        {pago && pagoEm
                          ? <div style={{ fontSize: 12, color: "#16A34A", fontWeight: 700, marginTop: 1 }}>Pago em {pagoEm}{forma ? " · " + forma : ""}</div>
                          : pr.rem > 0 && <div style={{ fontSize: 12, color: "#DC2626", fontWeight: 700, marginTop: 1 }}>+{brl(pr.rem)} de {pr.label} em atraso</div>}
                      </div>
                      <div style={{ textAlign: "right", flex: "none" }}>
                        <b style={{ fontSize: 15 }}>{brl(i.total)}</b><br />
                        {window.BillingUI.stBadge(i.status, i.rem)}
                      </div>
                    </div>
                  </button>
                </React.Fragment>
              );
            })}
          </div>
        )}

        {detail && <DetailModal pid={detail} type={type} pkey={key} onClose={() => setDetail(null)} onChange={refresh} setToast={(t) => { setToast(t); if (t && t.undo) setUndoFn(() => t.undo); }} />}
        <Toast toast={toast} onUndo={() => { if (undoFn) undoFn(); setToast(null); refresh(); }} />
      </>
    );
  }

  window.AtendPagamentos = AtendPagamentos;
})();
