/* PDV — Picolezeiros (consignação) */

function PdvPicolezeiros({ ctx }) {
  const [sub, setSub] = useState("rota");
  const [saidaOpen, setSaidaOpen] = useState(false);
  const [retornoTrip, setRetornoTrip] = useState(null);
  const [viewTrip, setViewTrip] = useState(null);
  const [printSaida, setPrintSaida] = useState(null);     // trip snapshot p/ comprovante de saída
  const [printRetorno, setPrintRetorno] = useState(null); // trip snapshot p/ comprovante de retorno
  const [reprintTrip, setReprintTrip] = useState(null);   // {trip, kind}
  const [commissionTarget, setCommissionTarget] = useState(null); // trip p/ recibo de comissão
  const [historyPic, setHistoryPic] = useState(null);     // picolezeiro — abre histórico unificado

  const emRota = ctx.state.trips.filter(t => t.status === "em_rota");
  const fechados = ctx.state.trips.filter(t => t.status === "fechado");

  const totalFaturadoMes = fechados.reduce((s, t) => s + (t.faturado || 0), 0);
  const totalComissaoMes = fechados.reduce((s, t) => s + (t.comissao || 0), 0);

  return (
    <>
      <div className="page-head">
        <div>
          <h1>PDV Picolezeiros</h1>
          <p>Consignação por unidade · saídas e retornos por praia</p>
        </div>
        <div className="page-head__actions">
          <Button variant="primary" icon={<Icons.Plus size={14} strokeWidth={2.2}/>} onClick={() => setSaidaOpen(true)} disabled={ctx.state.picolezeiros.length === 0}>Nova saída</Button>
        </div>
      </div>

      <div className="grid-4" style={{ marginBottom: 14 }}>
        <KPI tone="warning" medal={<Icons.Sun size={18} strokeWidth={2}/>} label="Em rota agora" value={emRota.length + ""} sub={`${emRota.length} picolezeiro${emRota.length===1?"":"s"} ativo${emRota.length===1?"":"s"}`} />
        <KPI tone="info" medal={<Icons.Box size={18} strokeWidth={2}/>} label="Unidades em campo" value={fmtInt(emRota.reduce((s, t) => s + t.items.reduce((a,b)=>a+b.qty,0), 0))} sub="aguardando retorno" />
        <KPI tone="success" medal={<Icons.Wallet size={18} strokeWidth={2}/>} label="Faturado (período)" value={fmtBRL(totalFaturadoMes)} sub={`${fechados.length} retornos fechados`} />
        <KPI tone="brand" medal={<Icons.Receipt size={18} strokeWidth={2}/>} label="Comissão paga" value={fmtBRL(totalComissaoMes)} sub={`${ctx.state.picolezeiros.length} picolezeiros`} />
      </div>

      <Tabs
        items={[
          { value:"rota",         label:`Em rota · ${emRota.length}` },
          { value:"historico",    label:`Retornos · ${fechados.length}` },
          { value:"picolezeiros", label:`Picolezeiros · ${ctx.state.picolezeiros.length}` },
        ]}
        value={sub}
        onChange={setSub}
      />

      {sub === "rota" && (
        emRota.length === 0 ? (
          <Card><div className="empty">
            <Icons.Sun size={26} color="var(--ink-300)"/>
            <h4>Nenhum picolezeiro em rota</h4>
            <p>Use "Nova saída" para registrar uma consignação.</p>
          </div></Card>
        ) : (
        <div className="grid-3" style={{ gap:14 }}>
          {emRota.map(t => <TripCard key={t.id} ctx={ctx} trip={t}
            onClose={() => setRetornoTrip(t)}
            onCancel={() => ctx.askConfirm({
              title: "Cancelar saída?",
              message: "Esta ação remove a saída e retorna as unidades ao estoque.",
              danger: true,
              onConfirm: () => ctx.actions.cancelTrip(t.id),
            })}
          />)}
        </div>
        )
      )}

      {sub === "historico" && <HistPicolezeiros ctx={ctx} trips={fechados} onView={setViewTrip} onReprint={(t) => setReprintTrip({ trip:t, kind:"retorno" })} onPrintCommission={(t) => setCommissionTarget(t)} />}

      {sub === "picolezeiros" && <ListaPicolezeiros ctx={ctx} onHistory={setHistoryPic} />}

      {saidaOpen && <SaidaModal ctx={ctx} onClose={() => setSaidaOpen(false)}
        onConfirm={(payload) => {
          ctx.actions.recordSaida(payload);
          // monta snapshot para impressão
          const snap = {
            id: "SAI-" + Date.now().toString(36).toUpperCase(),
            picolezeiroId: payload.picolezeiroId,
            date: new Date().toISOString().slice(0,10),
            beachesPlanned: payload.beaches,
            items: Object.entries(payload.items).map(([productId, qty]) => ({ productId, qty })),
          };
          setSaidaOpen(false);
          setPrintSaida(snap);
        }}
      />}
      {retornoTrip && <RetornoModal ctx={ctx} trip={retornoTrip} onClose={() => setRetornoTrip(null)}
        onConfirm={(payload) => {
          ctx.actions.closeRetorno({ tripId: retornoTrip.id, ...payload });
          // monta snapshot do retorno fechado para impressão
          const pz = ctx.state.picolezeiros.find(p => p.id === retornoTrip.picolezeiroId);
          const soldArr = Object.entries(payload.sold).map(([productId, qty]) => ({ productId, qty }));
          const returnedArr = retornoTrip.items.map(it => ({
            productId: it.productId,
            qty: it.qty - (payload.sold[it.productId] || 0),
          }));
          const faturado = soldArr.reduce((s, it) => {
            const p = ctx.state.products.find(x => x.id === it.productId);
            return s + it.qty * (p?.price || 0);
          }, 0);
          const comissao = faturado * ((pz?.commission || 0) / 100);
          const snap = {
            ...retornoTrip,
            status: "fechado",
            sold: soldArr, returned: returnedArr,
            beachesActual: payload.beachesActual,
            faturado, comissao, recebido: payload.received,
          };
          setRetornoTrip(null);
          setPrintRetorno(snap);
        }}
      />}
      {viewTrip && <TripDetailModal ctx={ctx} trip={viewTrip} onClose={() => setViewTrip(null)} />}

      {printSaida && (
        <Modal title="✅ Saída registrada" subtitle="Estoque foi atualizado. Imprimir comprovante de saída?"
          onClose={() => setPrintSaida(null)}
          footer={<Button variant="ghost" onClick={() => setPrintSaida(null)}>Concluir sem imprimir</Button>}
        >
          <FormatChooser onPick={(fmt) => {
            printSaidaReceipt({
              company: ctx.state.company,
              trip: printSaida,
              picolezeiro: ctx.state.picolezeiros.find(p => p.id === printSaida.picolezeiroId),
              beaches: ctx.state.beaches,
              products: ctx.state.products,
              fmt,
            });
          }} />
        </Modal>
      )}

      {printRetorno && (
        <Modal title="✅ Retorno fechado" subtitle="Lançamentos gerados. Selecione um documento para imprimir:"
          onClose={() => setPrintRetorno(null)}
          size="lg"
          footer={<Button variant="ghost" onClick={() => setPrintRetorno(null)}>Concluir sem imprimir</Button>}
        >
          <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:14 }}>
            <DocumentChoiceCard
              title="Comprovante de Retorno"
              subtitle="Documento operacional com prest. de contas"
              detail="Mostra retirado / vendido / sobra / comissão"
              accent="#333"
              onPick={(fmt) => {
                printRetornoReceipt({
                  company: ctx.state.company, trip: printRetorno,
                  picolezeiro: ctx.state.picolezeiros.find(p => p.id === printRetorno.picolezeiroId),
                  beaches: ctx.state.beaches, products: ctx.state.products, fmt,
                });
              }}
            />
            <DocumentChoiceCard
              title="Recibo de Comissão"
              subtitle="Recibo de pagamento do lucro ao picolezeiro"
              detail={"Comissão devida: " + fmtBRL(printRetorno.comissao || 0)}
              accent="var(--brand-600)"
              highlight
              onPick={() => { setCommissionTarget(printRetorno); setPrintRetorno(null); }}
              isAction
            />
          </div>
        </Modal>
      )}

      {commissionTarget && (
        <CommissionReceiptModal
          ctx={ctx}
          trip={commissionTarget}
          onClose={() => setCommissionTarget(null)}
        />
      )}

      {reprintTrip && (
        <ReceiptFormatModal
          title="Reimprimir comprovante de retorno"
          subtitle={ctx.state.picolezeiros.find(p => p.id === reprintTrip.trip.picolezeiroId)?.name}
          onClose={() => setReprintTrip(null)}
          onPrint={(fmt) => {
            printRetornoReceipt({
              company: ctx.state.company,
              trip: reprintTrip.trip,
              picolezeiro: ctx.state.picolezeiros.find(p => p.id === reprintTrip.trip.picolezeiroId),
              beaches: ctx.state.beaches,
              products: ctx.state.products,
              fmt,
            });
            setReprintTrip(null);
          }}
        />
      )}

      {historyPic && (
        <ClientHistoryModal ctx={ctx} kind="picolezeiro" client={historyPic} onClose={() => setHistoryPic(null)} />
      )}
    </>
  );
}

/* Card de escolha de tipo de documento (Retorno vs. Comissão) com seletor de formato embutido */
function DocumentChoiceCard({ title, subtitle, detail, accent, highlight, isAction, onPick }) {
  const [fmt, setFmt] = useState(null);
  const select = (f) => {
    if (isAction) { onPick(f); return; }
    setFmt(f);
    onPick(f);
  };
  return (
    <div style={{
      border:"1px solid " + (highlight ? "var(--brand-600)" : "var(--line)"),
      borderRadius:12, padding:"14px 16px",
      background: highlight ? "linear-gradient(180deg, var(--brand-50) 0%, #FFFFFF 100%)" : "white",
      boxShadow: "var(--sh-2)",
      display:"flex", flexDirection:"column", gap:10,
    }}>
      <div style={{ borderLeft:`3px solid ${accent}`, paddingLeft:10 }}>
        <div style={{ fontFamily:"var(--font-display)", fontWeight:700, color:"var(--ink-900)", fontSize:15, letterSpacing:"-.01em" }}>{title}</div>
        <div className="subtle">{subtitle}</div>
        {detail && <div style={{ fontSize:11.5, fontWeight:600, color: accent, marginTop:4 }}>{detail}</div>}
      </div>
      {isAction ? (
        <Button variant="primary" icon={<Icons.ArrowRight size={14} strokeWidth={2.2}/>}
          onClick={() => onPick()}
          style={{ justifyContent:"center", marginTop:4 }}>Configurar e imprimir</Button>
      ) : (
        <div style={{ display:"grid", gridTemplateColumns:"repeat(3, 1fr)", gap:6 }}>
          {[{ v:"a4", l:"A4", i:"📄" }, { v:"mm80", l:"80mm", i:"🧾" }, { v:"mm58", l:"58mm", i:"🎫" }].map(o => (
            <button key={o.v} onClick={() => select(o.v)}
              style={{
                padding:"8px 6px", borderRadius:8, cursor:"pointer",
                border:"1px solid var(--line)", background:"white",
                display:"flex", flexDirection:"column", alignItems:"center", gap:2,
                fontSize:11.5, fontWeight:600, color:"var(--ink-700)",
              }}
              onMouseEnter={e => { e.currentTarget.style.background="var(--brand-50)"; e.currentTarget.style.borderColor="var(--brand-600)"; }}
              onMouseLeave={e => { e.currentTarget.style.background="white"; e.currentTarget.style.borderColor="var(--line)"; }}
            >
              <span style={{ fontSize:16 }}>{o.i}</span>
              <span>{o.l}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/* Modal: gerar Recibo de Comissão do Picolezeiro (lucro) */
function CommissionReceiptModal({ ctx, trip, onClose }) {
  const pz = ctx.state.picolezeiros.find(p => p.id === trip.picolezeiroId);
  const methods = (ctx.state.settings.methods || []).filter(m => m !== "Fiado");
  const [paymentMethod, setPaymentMethod] = useState(methods[0] || "Dinheiro");
  const [paymentDate, setPaymentDate] = useState(new Date().toISOString().slice(0,10));
  const [fmt, setFmt] = useState("a4");

  const generate = () => {
    printCommissionReceipt({
      company: ctx.state.company,
      picolezeiro: pz,
      trips: [trip],
      beaches: ctx.state.beaches,
      paymentMethod, paymentDate, fmt,
    });
    onClose();
  };

  return (
    <Modal title="Recibo de Comissão" subtitle={"Pagamento ao picolezeiro: " + (pz?.name || "—")} onClose={onClose} size="lg"
      footer={<>
        <Button variant="ghost" onClick={onClose}>Cancelar</Button>
        <Button variant="primary" icon={<Icons.Print size={14}/>} onClick={generate}>Gerar recibo</Button>
      </>}
    >
      <div style={{ padding:"14px 16px", background:"linear-gradient(180deg, var(--brand-50) 0%, #FFFFFF 100%)", border:"1px solid var(--brand-100)", borderRadius:12, marginBottom:14, display:"flex", gap:14, alignItems:"center", flexWrap:"wrap" }}>
        <div>
          <div className="subtle" style={{ textTransform:"uppercase", letterSpacing:".08em", fontWeight:700, fontSize:10 }}>Faturado</div>
          <strong className="numeric" style={{ fontSize:18, fontFamily:"var(--font-display)", color:"var(--ink-900)" }}>{fmtBRL(trip.faturado || 0)}</strong>
        </div>
        <div>
          <div className="subtle" style={{ textTransform:"uppercase", letterSpacing:".08em", fontWeight:700, fontSize:10 }}>Comissão ({pz?.commission||0}%)</div>
          <strong className="numeric" style={{ fontSize:18, fontFamily:"var(--font-display)", color:"var(--brand-600)" }}>{fmtBRL(trip.comissao || 0)}</strong>
        </div>
        <div style={{ marginLeft:"auto", textAlign:"right" }}>
          <div className="subtle" style={{ textTransform:"uppercase", letterSpacing:".08em", fontWeight:700, fontSize:10 }}>Lucro do picolezeiro</div>
          <strong className="numeric" style={{ fontSize:24, fontFamily:"var(--font-display)", color:"var(--brand-600)", fontWeight:800 }}>{fmtBRL(trip.comissao || 0)}</strong>
        </div>
      </div>

      <div className="grid-2" style={{ gap:14, marginBottom:14 }}>
        <Field label="Forma de pagamento da comissão" required>
          <select className="select" value={paymentMethod} onChange={e => setPaymentMethod(e.target.value)}>
            {methods.map(m => <option key={m}>{m}</option>)}
          </select>
        </Field>
        <Field label="Data do pagamento" required>
          <input className="input" type="date" value={paymentDate} onChange={e => setPaymentDate(e.target.value)} />
        </Field>
      </div>

      <Field label="Formato do recibo" required>
        <div style={{ display:"grid", gridTemplateColumns:"repeat(3, 1fr)", gap:8 }}>
          {[{ v:"a4", l:"Papel A4", h:"Recibo formal" }, { v:"mm80", l:"Térmica 80mm", h:"Cupom largo" }, { v:"mm58", l:"Térmica 58mm", h:"Cupom estreito" }].map(o => (
            <button key={o.v} onClick={() => setFmt(o.v)}
              style={{
                padding:"10px 12px", borderRadius:10, cursor:"pointer", textAlign:"left",
                border:"1px solid " + (fmt === o.v ? "var(--brand-600)" : "var(--line)"),
                background: fmt === o.v ? "var(--brand-50)" : "white",
                color: fmt === o.v ? "var(--brand-700)" : "var(--ink-700)",
                boxShadow: fmt === o.v ? "0 0 0 3px var(--brand-100)" : "none",
              }}>
              <div style={{ fontWeight:700, fontSize:12 }}>{o.l}</div>
              <div className="subtle" style={{ fontSize:11 }}>{o.h}</div>
            </button>
          ))}
        </div>
      </Field>

      <div style={{ marginTop:14, padding:"10px 14px", background:"var(--info-bg)", color:"var(--info)", borderRadius:8, fontSize:12, display:"flex", gap:8, alignItems:"flex-start" }}>
        <Icons.AlertTriangle size={13} style={{ marginTop:2, flexShrink:0 }}/>
        <span>O recibo é um documento formal de quitação: registra que o picolezeiro recebeu o lucro referente à comissão sobre o faturamento desta operação. Único p/ comprovação legal de pagamento.</span>
      </div>
    </Modal>
  );
}
function FormatChooser({ onPick }) {
  return (
    <div style={{ display:"flex", flexDirection:"column", gap:10 }}>
      {[
        { value:"a4",   label:"Papel A4",     hint:"Comprovante completo (impressora comum)", icon:"📄" },
        { value:"mm80", label:"Térmica 80mm", hint:"Cupom largo (impressora de cupom)",       icon:"🧾" },
        { value:"mm58", label:"Térmica 58mm", hint:"Cupom estreito (mini-impressora)",        icon:"🎫" },
      ].map(o => (
        <button key={o.value} onClick={() => onPick(o.value)}
          style={{
            padding:"14px 16px", borderRadius:10, textAlign:"left", cursor:"pointer",
            display:"flex", alignItems:"center", gap:14,
            border:"1px solid var(--line)", background:"white", transition:"all .12s",
          }}
          onMouseEnter={e => { e.currentTarget.style.background="var(--brand-50)"; e.currentTarget.style.borderColor="var(--brand-600)"; }}
          onMouseLeave={e => { e.currentTarget.style.background="white"; e.currentTarget.style.borderColor="var(--line)"; }}
        >
          <div style={{ fontSize:28 }}>{o.icon}</div>
          <div style={{ flex:1 }}>
            <div style={{ fontWeight:700, color:"var(--ink-900)", fontSize:14 }}>{o.label}</div>
            <div className="subtle">{o.hint}</div>
          </div>
          <Icons.Print size={16} color="var(--brand-600)" />
        </button>
      ))}
    </div>
  );
}

function TripCard({ ctx, trip, onClose, onCancel }) {
  const pz = ctx.state.picolezeiros.find(p => p.id === trip.picolezeiroId);
  const totalUnits = trip.items.reduce((s, i) => s + i.qty, 0);
  const expectedValue = trip.items.reduce((s, i) => {
    const p = ctx.state.products.find(x => x.id === i.productId);
    return s + i.qty * (p?.price || 0);
  }, 0);
  const beaches = trip.beachesPlanned.map(bid => ctx.state.beaches.find(b => b.id === bid)?.name).filter(Boolean);

  return (
    <Card flush>
      <div style={{ padding: 16, display:"flex", flexDirection:"column", gap: 12 }}>
        <div style={{ display:"flex", alignItems:"center", gap: 12 }}>
          <div className="avatar" style={{ width: 40, height: 40, fontSize:14, background:"linear-gradient(135deg, #333, #1a1a1a)" }}>{pz?.photo}</div>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontWeight:700, color:"var(--ink-900)", fontSize:14 }}>{pz?.name || "—"}</div>
            <div className="subtle">Saída {fmtDate(trip.date)}</div>
          </div>
          <Chip tone="warning" dot>em rota</Chip>
        </div>

        <div style={{ display:"flex", flexDirection:"column", gap:4 }}>
          <div className="subtle" style={{ display:"flex", alignItems:"center", gap:6 }}><Icons.MapPin size={12} /> Praias planejadas</div>
          <div style={{ display:"flex", flexWrap:"wrap", gap:6 }}>
            {beaches.map((b, i) => <Chip key={i}>{b}</Chip>)}
          </div>
        </div>

        <div style={{ background:"var(--ink-50)", borderRadius:8, padding:"10px 12px" }}>
          <div style={{ display:"flex", justifyContent:"space-between", marginBottom:8 }}>
            <span className="subtle">Produtos retirados</span>
            <span style={{ fontWeight:700, fontSize:13 }} className="numeric">{totalUnits} un</span>
          </div>
          <div style={{ display:"flex", flexDirection:"column", gap:4 }}>
            {trip.items.map(it => {
              const p = ctx.state.products.find(x => x.id === it.productId);
              return (
                <div key={it.productId} style={{ display:"flex", justifyContent:"space-between", fontSize:12 }}>
                  <span className="tag-flavor">
                    <span className="sw" style={{ background: p?.color }} />
                    {p?.flavor}
                  </span>
                  <span className="numeric">{it.qty} un</span>
                </div>
              );
            })}
          </div>
        </div>

        <div style={{ display:"flex", justifyContent:"space-between", padding: "6px 4px" }}>
          <span className="subtle">Faturamento máx.</span>
          <strong className="numeric">{fmtBRL(expectedValue)}</strong>
        </div>

        <div style={{ display:"flex", gap:6 }}>
          <Button variant="primary" style={{ flex:1, justifyContent:"center" }} onClick={onClose}>
            Registrar retorno →
          </Button>
          <Button variant="danger" icon={<Icons.Trash size={13}/>} onClick={onCancel} />
        </div>
      </div>
    </Card>
  );
}

/* ============ SAÍDA Modal ============ */
function SaidaModal({ ctx, onClose, onConfirm }) {
  const [step, setStep] = useState(0);
  const [picId, setPicId] = useState(null);
  const [search, setSearch] = useState("");
  const [beaches, setBeaches] = useState([]);
  const [items, setItems] = useState({});

  const pic = ctx.state.picolezeiros.find(p => p.id === picId);
  const availableBeaches = pic ? ctx.state.beaches.filter(b => pic.beaches.includes(b.id)) : [];
  const filteredPics = ctx.state.picolezeiros.filter(p => p.name.toLowerCase().includes(search.toLowerCase()));

  const setItem = (pid, qty) => {
    setItems(prev => {
      const c = { ...prev };
      if (qty <= 0) delete c[pid]; else c[pid] = qty;
      return c;
    });
  };

  const totalUnits = Object.values(items).reduce((s, x) => s + x, 0);
  const expected = Object.entries(items).reduce((s, [pid, qty]) => s + qty * (ctx.state.products.find(p => p.id === pid)?.price || 0), 0);

  const canNext = (step === 0 && picId) || (step === 1 && beaches.length > 0) || (step === 2 && totalUnits > 0);

  const submit = () => onConfirm({ picolezeiroId: picId, beaches, items });

  return (
    <Modal title="Nova saída de picolezeiro" subtitle="Consignação — unidades reservadas no estoque" size="lg" onClose={onClose}
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>Cancelar</Button>
          <div style={{ display:"flex", gap:8 }}>
            {step > 0 && <Button variant="secondary" onClick={() => setStep(step-1)}>Voltar</Button>}
            {step < 2 && <Button variant="primary" onClick={() => setStep(step+1)} disabled={!canNext}>Continuar →</Button>}
            {step === 2 && <Button variant="primary" icon={<Icons.Check size={14} strokeWidth={2.2}/>} onClick={submit} disabled={!canNext}>Confirmar saída · {totalUnits} un</Button>}
          </div>
        </>
      }
    >
      <Steps items={["Picolezeiro", "Praias", "Produtos"]} current={step} />

      {step === 0 && (
        <div>
          <Field label="Buscar picolezeiro" required>
            <input className="input" autoFocus placeholder="Nome do picolezeiro…" value={search} onChange={e => setSearch(e.target.value)} />
          </Field>
          <div style={{ marginTop:14, display:"flex", flexDirection:"column", gap:8, maxHeight: 360, overflow:"auto" }}>
            {filteredPics.length === 0 && <div className="empty"><p>Nenhum picolezeiro encontrado.</p></div>}
            {filteredPics.map(p => (
              <button key={p.id} onClick={() => setPicId(p.id)}
                style={{
                  padding:"12px 14px", borderRadius:10, textAlign:"left", cursor:"pointer",
                  display:"flex", alignItems:"center", gap:12,
                  border:"1px solid " + (picId === p.id ? "var(--brand-600)" : "var(--line)"),
                  background: picId === p.id ? "var(--brand-50)" : "white",
                }}>
                <div className="avatar" style={{ background:"linear-gradient(135deg, #333, #1a1a1a)" }}>{p.photo}</div>
                <div style={{ flex:1 }}>
                  <div style={{ fontWeight:600, color:"var(--ink-900)" }}>{p.name}</div>
                  <div className="subtle">{p.cpf} · {p.phone} · {p.beaches.length} praia(s)</div>
                </div>
                <div style={{ textAlign:"right" }}>
                  <div style={{ fontSize:12, fontWeight:700, color:"var(--brand-600)" }}>{p.commission}% comissão</div>
                  <div className="subtle">{p.totals.saidas} saídas</div>
                </div>
              </button>
            ))}
          </div>
        </div>
      )}

      {step === 1 && (
        <div>
          <p className="muted" style={{ fontSize:12.5, marginTop:0 }}>Selecione as praias onde {pic?.name.split(" ")[0]} vai trabalhar. Apenas praias atendidas aparecem.</p>
          {availableBeaches.length === 0 ? (
            <div className="empty"><p>Este picolezeiro não tem praias atribuídas. Edite o cadastro em Clientes.</p></div>
          ) : (
          <div className="grid-2" style={{ gap:10 }}>
            {availableBeaches.map(b => {
              const on = beaches.includes(b.id);
              return (
                <button key={b.id}
                  onClick={() => setBeaches(prev => prev.includes(b.id) ? prev.filter(x => x !== b.id) : [...prev, b.id])}
                  style={{
                    padding:"12px 14px", borderRadius:10, textAlign:"left", cursor:"pointer",
                    border:"1px solid " + (on ? "var(--brand-600)" : "var(--line)"),
                    background: on ? "var(--brand-50)" : "white",
                    display:"flex", justifyContent:"space-between", alignItems:"center", gap:10
                  }}>
                  <div style={{ display:"flex", gap:10, alignItems:"center" }}>
                    <Icons.MapPin size={16} color={on ? "var(--brand-600)" : "var(--ink-400)"}/>
                    <div>
                      <div style={{ fontWeight:600, color:"var(--ink-900)" }}>{b.name}</div>
                      <div className="subtle">{b.city}</div>
                    </div>
                  </div>
                  {on && <Icons.Check size={16} color="var(--brand-600)" strokeWidth={2.4} />}
                </button>
              );
            })}
          </div>
          )}
        </div>
      )}

      {step === 2 && (
        <div>
          <div style={{ display:"flex", justifyContent:"space-between", marginBottom:12 }}>
            <p className="muted" style={{ fontSize:12.5, margin:0 }}>Selecione produtos e quantidades. Estoque disponível por sabor.</p>
            <strong className="numeric">{totalUnits} unidades · {fmtBRL(expected)}</strong>
          </div>
          <div style={{ maxHeight: 360, overflow:"auto", border:"1px solid var(--line)", borderRadius:10 }}>
            {ctx.state.products.map(p => {
              const st = ctx.state.stock.find(s => s.productId === p.id && s.warehouseId === WH_PICOLE_ID);
              const avail = st?.units || 0;
              const qty = items[p.id] || 0;
              return (
                <div key={p.id} style={{ padding:"10px 14px", borderBottom:"1px solid var(--line)", display:"flex", alignItems:"center", gap: 12, opacity: avail === 0 ? .5 : 1 }}>
                  <span style={{ width:14, height:14, borderRadius:4, background:p.color, flexShrink:0 }} />
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontSize:13, fontWeight:600, color:"var(--ink-900)" }}>{p.flavor}</div>
                    <div className="subtle">{p.line} · {fmtBRL(p.price)} · estoque {avail}</div>
                  </div>
                  <Stepper value={qty} onChange={(v) => setItem(p.id, v)} max={avail} />
                </div>
              );
            })}
          </div>
        </div>
      )}
    </Modal>
  );
}

/* ============ RETORNO Modal ============ */
function RetornoModal({ ctx, trip, onClose, onConfirm }) {
  const pz = ctx.state.picolezeiros.find(p => p.id === trip.picolezeiroId);
  const [sold, setSold] = useState(Object.fromEntries(trip.items.map(it => [it.productId, it.qty])));
  const [beachesActual, setBeachesActual] = useState(trip.beachesPlanned);
  const [received, setReceived] = useState(0);
  const [initialized, setInitialized] = useState(false);

  const validations = trip.items.map(it => {
    const s = sold[it.productId] || 0;
    const rest = it.qty - s;
    return { ...it, sold: s, rest, ok: s >= 0 && rest >= 0 };
  });
  const allValid = validations.every(v => v.ok);

  const totalSold = validations.reduce((s, v) => s + v.sold, 0);
  const totalRest = validations.reduce((s, v) => s + v.rest, 0);
  const faturado = validations.reduce((s, v) => {
    const p = ctx.state.products.find(x => x.id === v.productId);
    return s + v.sold * (p?.price || 0);
  }, 0);
  const comissao = faturado * (pz.commission / 100);
  const liquido = faturado - comissao;
  const diff = received - faturado;

  useEffect(() => {
    if (!initialized) { setReceived(faturado); setInitialized(true); }
  }, [faturado, initialized]);

  const beaches = trip.beachesPlanned.map(bid => ctx.state.beaches.find(b => b.id === bid)).filter(Boolean);

  const submit = () => onConfirm({ sold, beachesActual, received });

  return (
    <Modal title={`Retorno de ${pz.name}`} subtitle={`Saída ${fmtDate(trip.date)}`} size="lg" onClose={onClose}
      footer={
        <>
          <span className="subtle">Sobras voltam ao estoque automaticamente</span>
          <div style={{ display:"flex", gap:8 }}>
            <Button variant="ghost" onClick={onClose}>Cancelar</Button>
            <Button variant="primary" icon={<Icons.Check size={14} strokeWidth={2.2}/>} onClick={submit} disabled={!allValid}>Fechar retorno</Button>
          </div>
        </>
      }
    >
      <SectionHead title="Produtos · vendidos vs. sobras" subtitle="A validação garante que vendido + sobra = retirado" />
      <div style={{ border:"1px solid var(--line)", borderRadius:10, overflow:"hidden", marginBottom:18 }}>
        <table className="tbl" style={{ fontSize:12.5 }}>
          <thead>
            <tr>
              <th>Produto</th>
              <th className="num">Retirado</th>
              <th className="num">Vendidos</th>
              <th className="num">Sobra</th>
              <th className="num">Faturado</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {validations.map(v => {
              const p = ctx.state.products.find(x => x.id === v.productId);
              return (
                <tr key={v.productId}>
                  <td>
                    <span className="tag-flavor"><span className="sw" style={{ background: p?.color }} />{p?.flavor}</span>
                  </td>
                  <td className="num strong numeric">{v.qty}</td>
                  <td className="num"><Stepper value={v.sold} onChange={(val) => setSold(prev => ({ ...prev, [v.productId]: val }))} max={v.qty} /></td>
                  <td className="num strong numeric" style={{ color: v.rest > 0 ? "var(--warning)" : "var(--ink-500)" }}>{v.rest}</td>
                  <td className="num strong numeric">{fmtBRL(v.sold * (p?.price || 0))}</td>
                  <td>{v.ok ? <Chip tone="success" dot>OK</Chip> : <Chip tone="danger" dot>erro</Chip>}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <div className="grid-2" style={{ gap: 14, marginBottom: 18 }}>
        <Card title="Praias onde efetivamente vendeu" flush>
          <div style={{ padding: 14, display:"flex", flexDirection:"column", gap:6 }}>
            {beaches.map(b => {
              const on = beachesActual.includes(b.id);
              return (
                <label key={b.id} className="check" style={{ padding: "6px 0" }}>
                  <input type="checkbox" checked={on} onChange={() => setBeachesActual(prev => on ? prev.filter(x => x !== b.id) : [...prev, b.id])} />
                  <Icons.MapPin size={13} color={on ? "var(--brand-600)":"var(--ink-400)"} />
                  <span style={{ flex:1 }}>{b.name}</span>
                  <span className="subtle">{b.city}</span>
                </label>
              );
            })}
          </div>
        </Card>

        <Card title="Valor entregue pelo picolezeiro" flush>
          <div style={{ padding:14, display:"flex", flexDirection:"column", gap:10 }}>
            <Field label="Valor em dinheiro recebido (R$)" hint={diff === 0 ? "Valor confere com o calculado" : (diff > 0 ? `+${fmtBRL(diff)} a mais` : `${fmtBRL(Math.abs(diff))} a menos`)}>
              <input className="input" value={received} onChange={(e) => setReceived(parseFloat(e.target.value) || 0)} style={{ fontSize:18, fontWeight:600, padding:"10px 12px" }} />
            </Field>
            {diff !== 0 && (
              <div style={{ padding: "8px 12px", borderRadius: 8, background: diff > 0 ? "var(--success-bg)" : "var(--danger-bg)", color: diff > 0 ? "var(--success)" : "var(--danger)", fontSize:12, display:"flex", gap:8, alignItems:"center" }}>
                <Icons.AlertTriangle size={13} />
                Divergência de {fmtBRL(Math.abs(diff))}.
              </div>
            )}
          </div>
        </Card>
      </div>

      <Card title="Resumo do retorno" flush>
        <div style={{ padding: 16 }}>
          <div className="grid-4">
            <SumBox label="Total vendido" value={totalSold + " un"} />
            <SumBox label="Sobra (volta ao estoque)" value={totalRest + " un"} tone="warn" />
            <SumBox label="Faturado" value={fmtBRL(faturado)} tone="success" />
            <SumBox label="Comissão" value={fmtBRL(comissao)} sub={`${pz.commission}% sobre faturado`} tone="danger" />
          </div>
          <hr className="divider" />
          <div style={{ display:"flex", justifyContent:"space-between", alignItems:"baseline" }}>
            <strong style={{ fontSize:14 }}>Líquido para a empresa</strong>
            <strong style={{ fontFamily:"var(--font-display)", fontSize:24, color:"var(--brand-600)" }}>{fmtBRL(liquido)}</strong>
          </div>
          <div className="subtle" style={{ textAlign:"right" }}>2 movimentações serão geradas: entrada {fmtBRL(faturado)} e saída {fmtBRL(comissao)}.</div>
        </div>
      </Card>
    </Modal>
  );
}

function TripDetailModal({ ctx, trip, onClose }) {
  const pz = ctx.state.picolezeiros.find(p => p.id === trip.picolezeiroId);
  return (
    <Modal title={`Retorno · ${pz?.name}`} subtitle={fmtDate(trip.date)} size="lg" onClose={onClose}
      footer={<Button variant="ghost" onClick={onClose}>Fechar</Button>}
    >
      <div className="grid-2" style={{ gap:14, marginBottom:14 }}>
        <SumBox label="Faturado" value={fmtBRL(trip.faturado || 0)} tone="success" />
        <SumBox label="Comissão" value={fmtBRL(trip.comissao || 0)} tone="danger" />
      </div>
      <SectionHead title="Produtos" />
      <div style={{ border:"1px solid var(--line)", borderRadius:10, overflow:"hidden", marginBottom:14 }}>
        <table className="tbl" style={{ fontSize:12.5 }}>
          <thead>
            <tr><th>Produto</th><th className="num">Retirado</th><th className="num">Vendido</th><th className="num">Sobra</th></tr>
          </thead>
          <tbody>
            {trip.items.map(it => {
              const p = ctx.state.products.find(x => x.id === it.productId);
              const s = trip.sold?.find(x => x.productId === it.productId)?.qty || 0;
              const r = trip.returned?.find(x => x.productId === it.productId)?.qty || (it.qty - s);
              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">{s}</td>
                  <td className="num numeric muted">{r}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      <SectionHead title="Praias visitadas" />
      <div style={{ display:"flex", flexWrap:"wrap", gap:6 }}>
        {(trip.beachesActual || []).map(bid => {
          const b = ctx.state.beaches.find(x => x.id === bid);
          return b ? <Chip key={bid}>{b.name}</Chip> : null;
        })}
      </div>
    </Modal>
  );
}

function SumBox({ label, value, sub, tone }) {
  const color = { success:"var(--success)", warn:"var(--warning)", danger:"var(--danger)" }[tone] || "var(--ink-900)";
  return (
    <div style={{ padding:"10px 12px", background:"var(--canvas)", border:"1px solid var(--line)", borderRadius:10 }}>
      <div style={{ fontSize:11.5, color:"var(--ink-500)", fontWeight:500 }}>{label}</div>
      <div className="numeric" style={{ fontFamily:"var(--font-display)", fontSize:18, fontWeight:700, color }}>{value}</div>
      {sub && <div className="subtle">{sub}</div>}
    </div>
  );
}

function HistPicolezeiros({ ctx, trips, onView, onReprint, onPrintCommission }) {
  if (trips.length === 0) {
    return <Card><div className="empty">
      <Icons.History size={26} color="var(--ink-300)"/>
      <h4>Nenhum retorno fechado</h4>
      <p>Quando uma saída for fechada, ela aparecerá aqui.</p>
    </div></Card>;
  }
  return (
    <Card title="Retornos fechados" flush>
      <table className="tbl">
        <thead>
          <tr>
            <th>Data</th>
            <th>Picolezeiro</th>
            <th>Praias</th>
            <th className="num">Vendidas</th>
            <th className="num">Sobra</th>
            <th className="num">Faturado</th>
            <th className="num">Comissão</th>
            <th></th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          {trips.map((t) => {
            const pz = ctx.state.picolezeiros.find(p => p.id === t.picolezeiroId);
            const vendido = t.sold ? t.sold.reduce((s, x) => s + x.qty, 0) : 0;
            const sobra   = t.returned ? t.returned.reduce((s, x) => s + x.qty, 0) : 0;
            return (
              <tr key={t.id} style={{ cursor:"pointer" }}>
                <td onClick={() => onView(t)}>{fmtDate(t.date)}</td>
                <td className="strong" onClick={() => onView(t)}>{pz?.name}</td>
                <td className="muted" onClick={() => onView(t)}>{t.beachesActual?.map(bid => ctx.state.beaches.find(b => b.id === bid)?.name).filter(Boolean).join(", ")}</td>
                <td className="num strong numeric" onClick={() => onView(t)}>{vendido}</td>
                <td className="num numeric muted" onClick={() => onView(t)}>{sobra}</td>
                <td className="num strong numeric" onClick={() => onView(t)}>{fmtBRL(t.faturado || 0)}</td>
                <td className="num numeric" style={{ color:"var(--brand-700)" }} onClick={() => onView(t)}>{fmtBRL(t.comissao || 0)}</td>
                <td onClick={() => onView(t)}><Chip tone="success" dot>fechado</Chip></td>
                <td>
                  <div style={{ display:"flex", gap:2 }}>
                    <button className="icon-btn" title="Comprovante de Retorno" onClick={(e) => { e.stopPropagation(); onReprint(t); }}><Icons.Print/></button>
                    <button className="icon-btn" title="Recibo de Comissão (lucro do picolezeiro)" onClick={(e) => { e.stopPropagation(); onPrintCommission(t); }} style={{ color:"var(--brand-600)" }}><Icons.Receipt/></button>
                  </div>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </Card>
  );
}

function ListaPicolezeiros({ ctx, onHistory }) {
  return (
    <Card title="Picolezeiros ativos" subtitle={`${ctx.state.picolezeiros.length} cadastrados`} flush
      action={<Button variant="ghost" size="sm" onClick={() => ctx.goTo("clientes")}>Gerenciar em Clientes →</Button>}
    >
      <table className="tbl">
        <thead>
          <tr>
            <th>Nome</th>
            <th>Contato</th>
            <th>Praias</th>
            <th>Comissão</th>
            <th className="num">Saídas</th>
            <th className="num">Faturado total</th>
            <th className="num">Comissão paga</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          {ctx.state.picolezeiros.map(p => (
            <tr key={p.id} style={{ cursor:"pointer" }} onClick={() => onHistory && onHistory(p)}>
              <td>
                <div style={{ display:"flex", gap:10, alignItems:"center" }}>
                  <div className="avatar" style={{ background:"linear-gradient(135deg, #333, #1a1a1a)", width:30, height:30, fontSize:11 }}>{p.photo}</div>
                  <div>
                    <div style={{ fontWeight:600, color:"var(--ink-900)" }}>{p.name}</div>
                    <div className="subtle">{p.cpf}</div>
                  </div>
                </div>
              </td>
              <td className="muted">{p.phone}</td>
              <td>
                <div style={{ display:"flex", flexWrap:"wrap", gap:4 }}>
                  {p.beaches.slice(0,2).map(bid => {
                    const b = ctx.state.beaches.find(x => x.id === bid);
                    return b ? <Chip key={bid}>{b.name}</Chip> : null;
                  })}
                  {p.beaches.length > 2 && <Chip>+{p.beaches.length - 2}</Chip>}
                </div>
              </td>
              <td><Chip tone="brand" dot>{p.commission}%</Chip></td>
              <td className="num strong numeric">{p.totals.saidas}</td>
              <td className="num strong numeric">{fmtBRL(p.totals.vendido)}</td>
              <td className="num numeric">{fmtBRL(p.totals.comissao)}</td>
              <td onClick={e => e.stopPropagation()}>
                <button className="icon-btn" title="Ver histórico" onClick={() => onHistory && onHistory(p)}><Icons.History /></button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}

window.PdvPicolezeiros = PdvPicolezeiros;
