/* Histórico do cliente — modal compartilhado
   Mostra todas as transações de um distribuidor ou picolezeiro num único cadastro.
   - Distribuidor: lista vendas com itens, hora, forma de pagamento, status
   - Picolezeiro: lista saídas/retornos com itens, praias, faturado, comissão
   Cada linha pode ser expandida e impressa individualmente. */

function ClientHistoryModal({ ctx, kind, client, onClose }) {
  // kind: "distributor" | "picolezeiro"
  const [expanded, setExpanded] = useState(null);
  const [printPick, setPrintPick] = useState(null); // {kind, payload}
  const [period, setPeriod] = useState({ kind: "all" });

  const isDist = kind === "distributor";

  // pega registros
  const records = useMemo(() => {
    if (isDist) {
      return ctx.state.sales
        .filter(s => s.clientId === client.id)
        .filter(s => inPeriod(s.date, period, DEFAULT_REF_DATE))
        .sort((a,b) => (b.date + " " + (b.time||"")).localeCompare(a.date + " " + (a.time||"")));
    } else {
      return ctx.state.trips
        .filter(t => t.picolezeiroId === client.id)
        .filter(t => inPeriod(t.date, period, DEFAULT_REF_DATE))
        .sort((a,b) => b.date.localeCompare(a.date));
    }
  }, [ctx.state.sales, ctx.state.trips, client.id, isDist, period]);

  const totalFat = isDist
    ? records.reduce((s, r) => s + r.total, 0)
    : records.filter(t => t.status === "fechado").reduce((s, t) => s + (t.faturado || 0), 0);

  const totalUnidades = isDist
    ? records.reduce((s, r) => s + r.items.reduce((a, i) => a + i.units, 0), 0)
    : records.reduce((s, t) => s + t.items.reduce((a, i) => a + i.qty, 0), 0);

  const aReceber = isDist
    ? records.filter(r => r.status === "a_receber").reduce((s, r) => s + r.total, 0)
    : 0;

  const comissaoTotal = !isDist
    ? records.filter(t => t.status === "fechado").reduce((s, t) => s + (t.comissao || 0), 0)
    : 0;

  /* Impressão de uma transação específica */
  const reprintSale = (sale, fmt) => {
    const distClient = ctx.state.distributors.find(d => d.id === sale.clientId) || client;
    printSaleReceipt({
      company: ctx.state.company,
      sale: { id: sale.id, date: sale.date, client: distClient, payment: sale.payment, subtotal: sale.subtotal, discount: sale.discount, total: sale.total, perBox: sale.perBox },
      items: sale.items.map(({productId, boxes}) => ({ productId, boxes })),
      products: ctx.state.products,
      fmt,
    });
  };

  const reprintTrip = (trip, fmt) => {
    const pz = client;
    if (trip.status === "fechado") {
      printRetornoReceipt({
        company: ctx.state.company,
        trip, picolezeiro: pz, beaches: ctx.state.beaches, products: ctx.state.products, fmt,
      });
    } else {
      printSaidaReceipt({
        company: ctx.state.company,
        trip, picolezeiro: pz, beaches: ctx.state.beaches, products: ctx.state.products, fmt,
      });
    }
  };

  /* Impressão do histórico inteiro do cliente */
  const printFullHistory = () => {
    const logo = ctx.state.company.logo;
    const logoIsImage = logo && !/^data:application\/pdf/i.test(logo);
    const headerHtml = `
      <div style="display:flex;gap:16px;align-items:center;border-bottom:2px solid #1A1A1A;padding-bottom:14px;margin-bottom:18px;">
        ${logoIsImage ? `<img src="${logo}" style="width:60px;height:60px;object-fit:contain;" />` : `<div style="width:60px;height:60px;background:#D4310B;color:white;border-radius:10px;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:28px;font-family:'Bricolage Grotesque', sans-serif;">P</div>`}
        <div style="flex:1">
          <div style="font-family:'Bricolage Grotesque',sans-serif;font-size:22px;font-weight:700;letter-spacing:-.02em;">Histórico de ${isDist ? "compras" : "consignação"}</div>
          <div style="font-size:12px;color:#666;">${ctx.state.company.name} · Gerado em ${new Date().toLocaleString("pt-BR")}</div>
        </div>
      </div>
      <div style="background:#FAFAFB;border:1px solid #eee;border-radius:10px;padding:14px 16px;margin-bottom:18px;">
        <div style="font-family:'Bricolage Grotesque',sans-serif;font-size:18px;font-weight:700;color:#1A1A1A;">${client.name}</div>
        <div style="font-size:12px;color:#555;">${isDist ? (client.doc||"") + " · " + (client.city||"") : (client.cpf||"") + " · " + (client.phone||"")}</div>
        <div style="display:flex;gap:20px;margin-top:10px;font-size:11.5px;">
          <div><strong style="font-size:16px;color:#1A1A1A;display:block;">${records.length}</strong>${isDist ? "compras" : "saídas/retornos"}</div>
          <div><strong style="font-size:16px;color:#1A1A1A;display:block;">${totalUnidades}</strong>unidades</div>
          <div><strong style="font-size:16px;color:#15803D;display:block;">${fmtBRL(totalFat)}</strong>${isDist ? "faturado" : "faturado (fechados)"}</div>
          ${isDist ? `<div><strong style="font-size:16px;color:#B45309;display:block;">${fmtBRL(aReceber)}</strong>a receber</div>` : `<div><strong style="font-size:16px;color:#D4310B;display:block;">${fmtBRL(comissaoTotal)}</strong>comissão paga</div>`}
        </div>
      </div>
    `;

    const rows = records.map(r => {
      if (isDist) {
        const itemsTxt = r.items.map(it => {
          const p = ctx.state.products.find(x => x.id === it.productId);
          return `${p?.flavor||"?"} ${it.boxes}cx`;
        }).join(" · ");
        return `<tr>
          <td>${fmtDate(r.date)}<br/><span style="color:#888;font-size:10.5px">${r.time||""}</span></td>
          <td style="font-size:11px;color:#444;">${itemsTxt}</td>
          <td>${r.payment||"—"}</td>
          <td style="text-align:right;font-weight:700;">${fmtBRL(r.total)}</td>
          <td>${r.status === "confirmado" ? "✓ Pago" : "⏳ A receber"}</td>
        </tr>`;
      } else {
        const itemsTxt = r.items.map(it => {
          const p = ctx.state.products.find(x => x.id === it.productId);
          return `${p?.flavor||"?"} ${it.qty}un`;
        }).join(" · ");
        const sold = (r.sold||[]).reduce((s,x)=>s+x.qty,0);
        return `<tr>
          <td>${fmtDate(r.date)}</td>
          <td style="font-size:11px;color:#444;">${itemsTxt}</td>
          <td>${r.status === "fechado" ? `${sold} un vendidas` : "—"}</td>
          <td style="text-align:right;font-weight:700;">${r.status === "fechado" ? fmtBRL(r.faturado||0) : "—"}</td>
          <td>${r.status === "fechado" ? "✓ Fechado" : "⏳ Em rota"}</td>
        </tr>`;
      }
    }).join("");

    const headers = isDist
      ? `<tr><th>Data / Hora</th><th>Itens</th><th>Pagamento</th><th style="text-align:right;">Total</th><th>Status</th></tr>`
      : `<tr><th>Data</th><th>Itens retirados</th><th>Resultado</th><th style="text-align:right;">Faturado</th><th>Status</th></tr>`;

    const body = `<div style="padding:8px;">
      ${headerHtml}
      <table style="width:100%;border-collapse:collapse;font-size:12px;">
        <thead>${headers}</thead>
        <tbody>${rows}</tbody>
      </table>
      <div style="margin-top:24px;padding-top:14px;border-top:1px dashed #999;font-size:10.5px;color:#666;text-align:center;">${ctx.state.company.name} · Documento sem valor fiscal</div>
    </div>`;
    const css = `@page { size: A4; margin: 12mm 10mm; } * { box-sizing: border-box; } html, body { margin:0; padding:0; } body { font-family: Helvetica, Arial, sans-serif; color:#222; font-size:11px; line-height:1.5; }
      table { width:100%; border-collapse:collapse; table-layout:auto; word-wrap:break-word; }
      table th { background:transparent; font-weight:700; font-size:9.5px; text-transform:uppercase; letter-spacing:.08em; padding:7px 6px; border-bottom:1.5px solid #333; text-align:left; color:#555; }
      table td { padding:6px; border-bottom:1px solid #eee; font-size:10.5px; vertical-align:top; }
      tbody tr:last-child td { border-bottom:none; }`;
    const win = window.open("", "_blank", "width=1000,height=900");
    win.document.open();
    win.document.write(`<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Histórico — ${client.name}</title><style>${css}
      .toolbar { position:sticky; top:0; background:#1A1A1A; color:white; padding:10px 14px; display:flex; gap:8px; align-items:center; z-index:50; }
      .toolbar h3 { margin:0; flex:1; font-size:13px; font-weight:600; }
      .toolbar button { background:white; color:#1A1A1A; border:none; padding:7px 12px; border-radius:6px; font-weight:600; font-size:12px; cursor:pointer; }
      .doc { background:white; max-width:760px; margin:14px auto; padding:22px 24px; box-shadow:0 4px 24px rgba(0,0,0,.12); }
      @media print { .toolbar { display:none !important; } body { background:white !important; padding:0 !important; } .doc { box-shadow:none !important; margin:0 !important; max-width:none !important; width:auto !important; padding:0 !important; } }
      body { background:#f0f0f0; }
      </style></head><body>
      <div class="toolbar"><h3>Histórico — ${client.name}</h3><button onclick="window.print()">🖨 Imprimir / PDF</button><button onclick="window.close()" style="background:transparent;color:white;border:1px solid rgba(255,255,255,.4);">Fechar</button></div>
      <div class="doc">${body}</div></body></html>`);
    win.document.close();
  };

  const initial = client.name.split(" ").map(w => w[0]).slice(0,2).join("");
  const subtitle = isDist
    ? `${client.doc || ""} · ${client.city || ""}`
    : `${client.cpf || ""} · ${client.phone || ""} · ${client.commission || 0}% comissão`;

  return (
    <Modal title={client.name} subtitle={subtitle} size="lg" onClose={onClose}
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>Fechar</Button>
          <Button variant="secondary" icon={<Icons.Print size={14}/>} onClick={printFullHistory} disabled={records.length === 0}>Imprimir histórico</Button>
        </>
      }
    >
      {/* Sumário */}
      <div style={{
        background:"linear-gradient(180deg, var(--brand-50) 0%, #FFFFFF 100%)",
        border:"1px solid var(--brand-100)", borderRadius:12, padding:"16px 18px", marginBottom:14,
        display:"flex", gap:14, alignItems:"center",
      }}>
        <div className="avatar" style={{ width:54, height:54, fontSize:16, background:"linear-gradient(135deg, var(--brand-500), var(--brand-700))" }}>{initial}</div>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ display:"flex", gap:22, flexWrap:"wrap" }}>
            <SumPill label="Transações" value={records.length+""} />
            <SumPill label="Unidades" value={fmtInt(totalUnidades)} />
            <SumPill label={isDist ? "Faturado" : "Faturado fechado"} value={fmtBRL(totalFat)} color="var(--success)" />
            {isDist
              ? <SumPill label="A receber" value={fmtBRL(aReceber)} color="var(--warning)" />
              : <SumPill label="Comissão paga" value={fmtBRL(comissaoTotal)} color="var(--brand-600)" />
            }
          </div>
        </div>
        <PeriodPicker value={period} onChange={setPeriod} refDate={DEFAULT_REF_DATE} compact />
      </div>

      {records.length === 0 ? (
        <div className="empty">
          <Icons.History size={26} color="var(--ink-300)" />
          <h4>Nenhuma {isDist ? "compra" : "saída"} registrada</h4>
          <p>Quando este cliente realizar uma {isDist ? "compra" : "saída"}, ela aparece aqui.</p>
        </div>
      ) : (
        <div style={{ border:"1px solid var(--line)", borderRadius:10, overflow:"hidden" }}>
          {records.map((r, idx) => (
            <ClientHistoryRow
              key={r.id || idx}
              kind={kind}
              record={r}
              products={ctx.state.products}
              beaches={ctx.state.beaches}
              expanded={expanded === (r.id || idx)}
              onToggle={() => setExpanded(expanded === (r.id || idx) ? null : (r.id || idx))}
              onPrint={() => setPrintPick({ record: r })}
              isLast={idx === records.length - 1}
            />
          ))}
        </div>
      )}

      {printPick && (
        <ReceiptFormatModal
          title="Imprimir comprovante"
          subtitle={isDist
            ? `Venda ${fmtDate(printPick.record.date)} · ${fmtBRL(printPick.record.total)}`
            : `${printPick.record.status === "fechado" ? "Retorno" : "Saída"} ${fmtDate(printPick.record.date)}`
          }
          onClose={() => setPrintPick(null)}
          onPrint={(fmt) => {
            if (isDist) reprintSale(printPick.record, fmt);
            else reprintTrip(printPick.record, fmt);
            setPrintPick(null);
          }}
        />
      )}
    </Modal>
  );
}

function SumPill({ label, value, color }) {
  return (
    <div style={{ display:"flex", flexDirection:"column", gap:0 }}>
      <span style={{ fontSize:10.5, color:"var(--ink-500)", textTransform:"uppercase", letterSpacing:".08em", fontWeight:700 }}>{label}</span>
      <strong className="numeric" style={{ fontFamily:"var(--font-display)", fontSize:18, fontWeight:700, color: color || "var(--ink-900)", letterSpacing:"-.015em", lineHeight:1.1 }}>{value}</strong>
    </div>
  );
}

function ClientHistoryRow({ kind, record, products, beaches, expanded, onToggle, onPrint, isLast }) {
  const isDist = kind === "distributor";
  const isFechado = !isDist && record.status === "fechado";

  const totalUnits = isDist
    ? record.items.reduce((s, i) => s + i.units, 0)
    : record.items.reduce((s, i) => s + i.qty, 0);

  const headLeft = isDist ? (
    <>
      <div style={{ fontWeight:700, color:"var(--ink-900)", fontSize:14 }}>
        Venda <span style={{ color:"var(--ink-400)", fontWeight:500 }}>· {record.id?.slice(-6).toUpperCase()}</span>
      </div>
      <div className="subtle" style={{ display:"flex", gap:10, alignItems:"center" }}>
        <span><Icons.Calendar size={11}/> {fmtDate(record.date)}{record.time ? " · " + record.time : ""}</span>
        <span>·</span>
        <span><Icons.Wallet size={11}/> {record.payment}</span>
        <span>·</span>
        <span>{record.items.length} sabor{record.items.length===1?"":"es"} · {totalUnits} un</span>
      </div>
    </>
  ) : (
    <>
      <div style={{ fontWeight:700, color:"var(--ink-900)", fontSize:14 }}>
        {isFechado ? "Retorno fechado" : "Saída em rota"} <span style={{ color:"var(--ink-400)", fontWeight:500 }}>· {record.id?.slice(-6).toUpperCase()}</span>
      </div>
      <div className="subtle" style={{ display:"flex", gap:10, alignItems:"center", flexWrap:"wrap" }}>
        <span><Icons.Calendar size={11}/> {fmtDate(record.date)}</span>
        <span>·</span>
        <span><Icons.MapPin size={11}/> {(record.beachesActual || record.beachesPlanned || []).map(bid => beaches.find(b=>b.id===bid)?.name).filter(Boolean).join(", ") || "—"}</span>
        <span>·</span>
        <span>{totalUnits} un retiradas</span>
      </div>
    </>
  );

  const headRight = isDist ? (
    <div style={{ display:"flex", alignItems:"center", gap:10 }}>
      <div style={{ textAlign:"right" }}>
        <strong className="numeric" style={{ fontSize:15, color:"var(--ink-900)" }}>{fmtBRL(record.total)}</strong>
        <div className="subtle">
          {record.status === "confirmado" ? <Chip tone="success" dot>pago</Chip> : <Chip tone="warning" dot>a receber</Chip>}
        </div>
      </div>
    </div>
  ) : (
    <div style={{ display:"flex", alignItems:"center", gap:10 }}>
      <div style={{ textAlign:"right" }}>
        <strong className="numeric" style={{ fontSize:15, color:"var(--ink-900)" }}>{isFechado ? fmtBRL(record.faturado||0) : "—"}</strong>
        <div className="subtle">
          {isFechado ? <Chip tone="success" dot>fechado</Chip> : <Chip tone="warning" dot>em rota</Chip>}
        </div>
      </div>
    </div>
  );

  return (
    <div style={{ borderBottom: isLast ? "none" : "1px solid var(--line)" }}>
      <div
        onClick={onToggle}
        style={{
          display:"flex", alignItems:"center", gap:12, padding:"12px 16px",
          cursor:"pointer", background: expanded ? "var(--ink-50)" : "white",
          transition:"background .12s",
        }}>
        <Icons.ChevDown size={14} color="var(--ink-400)" style={{ transition:"transform .15s", transform: expanded ? "rotate(0)" : "rotate(-90deg)", flexShrink:0 }} />
        <div style={{ flex:1, minWidth:0 }}>
          {headLeft}
        </div>
        {headRight}
        <button className="icon-btn" title="Imprimir comprovante desta transação"
          onClick={(e) => { e.stopPropagation(); onPrint(); }}
          style={{ border:"1px solid var(--line-strong)", background:"white" }}>
          <Icons.Print size={14} />
        </button>
      </div>

      {expanded && (
        <div style={{ padding:"6px 16px 16px 42px", background:"var(--canvas)", borderTop:"1px solid var(--line)" }}>
          {isDist ? (
            <table className="tbl" style={{ marginInline: 0, fontSize:12.5, background:"white", borderRadius:8, overflow:"hidden", border:"1px solid var(--line)" }}>
              <thead>
                <tr>
                  <th>Produto</th>
                  <th className="num">Caixas</th>
                  <th className="num">Unidades</th>
                  <th className="num">Preço un.</th>
                  <th className="num">Subtotal</th>
                </tr>
              </thead>
              <tbody>
                {record.items.map(it => {
                  const p = products.find(x => x.id === it.productId);
                  return (
                    <tr key={it.productId}>
                      <td><span className="tag-flavor"><span className="sw" style={{ background: p?.color }} />{p?.flavor||"?"}</span></td>
                      <td className="num strong numeric">{it.boxes}</td>
                      <td className="num numeric">{it.units}</td>
                      <td className="num numeric">{fmtBRL(it.unitPrice)}</td>
                      <td className="num strong numeric">{fmtBRL(it.subtotal)}</td>
                    </tr>
                  );
                })}
                <tr style={{ background:"var(--ink-50)" }}>
                  <td colSpan="4" style={{ fontWeight:700, textAlign:"right" }}>Total da venda</td>
                  <td className="num strong numeric" style={{ color:"var(--brand-600)", fontSize:14 }}>{fmtBRL(record.total)}</td>
                </tr>
                {record.discount > 0 && (
                  <tr><td colSpan="4" className="muted" style={{ textAlign:"right", fontSize:11.5 }}>(desconto aplicado: {fmtBRL(record.discount)})</td><td></td></tr>
                )}
              </tbody>
            </table>
          ) : (
            <table className="tbl" style={{ marginInline:0, fontSize:12.5, background:"white", borderRadius:8, overflow:"hidden", border:"1px solid var(--line)" }}>
              <thead>
                <tr>
                  <th>Produto</th>
                  <th className="num">Retirado</th>
                  <th className="num">Vendido</th>
                  <th className="num">Sobra</th>
                  <th className="num">Faturado</th>
                </tr>
              </thead>
              <tbody>
                {record.items.map(it => {
                  const p = products.find(x => x.id === it.productId);
                  const sold = (record.sold||[]).find(x => x.productId === it.productId)?.qty || 0;
                  const ret  = (record.returned||[]).find(x => x.productId === it.productId)?.qty;
                  const sobra = ret !== undefined ? ret : (isFechado ? it.qty - sold : null);
                  return (
                    <tr key={it.productId}>
                      <td><span className="tag-flavor"><span className="sw" style={{ background: p?.color }} />{p?.flavor||"?"}</span></td>
                      <td className="num numeric">{it.qty}</td>
                      <td className="num strong numeric">{isFechado ? sold : "—"}</td>
                      <td className="num numeric muted">{isFechado ? sobra : "—"}</td>
                      <td className="num strong numeric">{isFechado ? fmtBRL(sold * (p?.price||0)) : "—"}</td>
                    </tr>
                  );
                })}
                {isFechado && (
                  <>
                    <tr style={{ background:"var(--ink-50)" }}>
                      <td colSpan="4" style={{ fontWeight:700, textAlign:"right" }}>Faturado</td>
                      <td className="num strong numeric">{fmtBRL(record.faturado||0)}</td>
                    </tr>
                    <tr style={{ background:"var(--ink-50)" }}>
                      <td colSpan="4" style={{ textAlign:"right", color:"var(--danger)" }}>Comissão</td>
                      <td className="num numeric" style={{ color:"var(--danger)" }}>− {fmtBRL(record.comissao||0)}</td>
                    </tr>
                    <tr style={{ background:"var(--brand-50)" }}>
                      <td colSpan="4" style={{ fontWeight:700, textAlign:"right", color:"var(--brand-700)" }}>Líquido para empresa</td>
                      <td className="num strong numeric" style={{ color:"var(--brand-700)", fontSize:14 }}>{fmtBRL((record.faturado||0) - (record.comissao||0))}</td>
                    </tr>
                  </>
                )}
              </tbody>
            </table>
          )}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ClientHistoryModal });
