/* ============================================================
   SYMPHO · EB — componentes compartidos añadidos:
   firma autógrafa, ficha técnica/brochure, alta de producto,
   detalle de tarjetas del dashboard, comisiones por vendedor,
   estado de cuenta tipo TC, selector de catálogo (reservar),
   evidencia fotográfica (postventa / ciclo de vida).
   ============================================================ */

// ---------------- firma autógrafa (canvas) ----------------
function SignaturePad({ onChange }) {
  const ref = React.useRef(null);
  const drawing = React.useRef(false);
  const has = React.useRef(false);
  function pos(e, canvas) {
    const r = canvas.getBoundingClientRect();
    const p = e.touches ? e.touches[0] : e;
    return { x: p.clientX - r.left, y: p.clientY - r.top };
  }
  function start(e) {
    e.preventDefault();
    drawing.current = true;
    const c = ref.current, ctx = c.getContext("2d");
    const { x, y } = pos(e, c);
    ctx.beginPath(); ctx.moveTo(x, y);
  }
  function move(e) {
    if (!drawing.current) return;
    e.preventDefault();
    const c = ref.current, ctx = c.getContext("2d");
    const { x, y } = pos(e, c);
    ctx.lineTo(x, y); ctx.strokeStyle = "var(--text)"; ctx.lineWidth = 2.2; ctx.lineCap = "round"; ctx.stroke();
    has.current = true;
  }
  function end() {
    if (!drawing.current) return;
    drawing.current = false;
    if (has.current) onChange(ref.current.toDataURL("image/png"));
  }
  function clear() {
    const c = ref.current, ctx = c.getContext("2d");
    ctx.clearRect(0, 0, c.width, c.height);
    has.current = false;
    onChange(null);
  }
  return (
    <div>
      <canvas ref={ref} width={420} height={130}
        onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
        onTouchStart={start} onTouchMove={move} onTouchEnd={end}
        style={{ width: "100%", height: 130, borderRadius: 10, border: "1px dashed var(--line-2)", background: "var(--bg-2)", touchAction: "none", cursor: "crosshair" }} />
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 6 }}>
        <span className="muted" style={{ fontSize: 11 }}>Firma con el mouse o el dedo para dar tu Vo.Bo.</span>
        <button type="button" className="btn btn-sm" onClick={clear}>Limpiar</button>
      </div>
    </div>
  );
}

// ---------------- ficha técnica / brochure — chip de archivo ----------------
function EbFileChip({ name }) {
  return (
    <span className="chip" style={{ height: 26, fontSize: 11.5, gap: 6, cursor: "default" }}>
      <Icon name="doc" size={13} style={{ color: "var(--text-3)" }} /> {name}
    </span>
  );
}

// docs + foto de un producto de catálogo (unidad o refacción)
function EbProductAssets({ photoId, docs }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--line)" }}>
      <image-slot id={photoId} shape="rounded" radius="8" placeholder="Foto" style={{ width: 40, height: 40, flex: "none", fontSize: 9 }}></image-slot>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6, flex: 1, minWidth: 0 }}>
        {(docs || []).length ? docs.map((d, i) => <EbFileChip key={i} name={d.name} />) : <span className="mono" style={{ fontSize: 10.5, color: "var(--text-4)" }}>Sin archivos adjuntos</span>}
      </div>
    </div>
  );
}

// ---------------- ALTA DE PRODUCTO (vehículo o refacción) ----------------
function EbAltaProductoModal({ onClose, onCreate }) {
  const [tipo, setTipo] = React.useState("vehiculo");
  const [f, setF] = React.useState({
    brand: window.EB_BRANDS[0].name, model: "", cat: window.EB_BRANDS[0].cats[0], year: 2026,
    priceDealer: "", pricePublico: "", descuentoPromoPct: "", stock: 0, transit: 0,
    sku: "", name: "", qty: 0, min: 10, price: "",
  });
  const [docs, setDocs] = React.useState([]);
  const photoId = React.useRef("alta-photo-" + Math.random().toString(36).slice(2, 9)).current;
  const fileRef = React.useRef();
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));

  function addDoc(e) {
    const files = Array.from(e.target.files || []);
    if (files.length) setDocs(d => [...d, ...files.map(x => ({ name: x.name }))]);
    e.target.value = "";
  }
  function removeDoc(i) { setDocs(d => d.filter((_, j) => j !== i)); }

  function submit(e) {
    e.preventDefault();
    const brandObj = window.EB_BRANDS.find(b => b.name === f.brand);
    if (tipo === "vehiculo") {
      const model = {
        brand: f.brand, model: f.model || "Nuevo modelo", cat: f.cat, year: Number(f.year) || 2026,
        priceDealer: Number(f.priceDealer) || 0, pricePublico: Number(f.pricePublico) || 0,
        descuentoPromoPct: f.descuentoPromoPct ? Number(f.descuentoPromoPct) : null,
        stock: Number(f.stock) || 0, transit: Number(f.transit) || 0, color: brandObj ? brandObj.hue : "var(--eb)",
      };
      window.EB_CATALOG_DOCS[window.ebCatalogKey(model.brand, model.model)] = { docs, photoId };
      onCreate({ kind: "vehiculo", item: model, photoId });
    } else {
      const sku = {
        sku: f.sku || ("RF-" + Math.random().toString(36).slice(2, 7).toUpperCase()),
        name: f.name || "Nueva refacción", marca: f.brand, qty: Number(f.qty) || 0, min: Number(f.min) || 0, price: Number(f.price) || 0,
      };
      window.EB_SKU_DOCS[sku.sku] = { docs, photoId };
      onCreate({ kind: "sku", item: sku, photoId });
    }
    onClose();
  }

  return (
    <div className="cmd-overlay" onMouseDown={onClose}>
      <div className="cmd-panel" style={{ width: 560 }} onMouseDown={e => e.stopPropagation()}>
        <div className="cmd-input">
          <b style={{ fontSize: 14.5 }}>Alta de producto</b>
          <button className="ic-btn" style={{ marginLeft: "auto" }} onClick={onClose}><Icon name="ext" size={15} /></button>
        </div>
        <div style={{ padding: "14px 20px 0" }}>
          <div className="seg">
            <button type="button" className="seg-btn" data-on={tipo === "vehiculo"} onClick={() => setTipo("vehiculo")}><Icon name="moto" size={14} /> Vehículo</button>
            <button type="button" className="seg-btn" data-on={tipo === "sku"} onClick={() => setTipo("sku")}><Icon name="tag" size={14} /> Refacción</button>
          </div>
        </div>
        <form onSubmit={submit} style={{ padding: "16px 20px 20px", display: "flex", flexDirection: "column", gap: 12, maxHeight: "62vh", overflow: "auto" }}>
          <div>
            <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 6 }}>Fotografía del {tipo === "vehiculo" ? "vehículo" : "producto"}</label>
            <image-slot id={photoId} shape="rounded" radius="12" placeholder="Arrastra o sube la foto" style={{ width: 160, height: 120 }}></image-slot>
          </div>
          {tipo === "vehiculo" ? (
            <>
              <div className="grid-2" style={{ gap: 10 }}>
                <div>
                  <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>Marca</label>
                  <select className="field" value={f.brand} onChange={e => set("brand", e.target.value)}>
                    {window.EB_BRANDS.map(b => <option key={b.id} value={b.name}>{b.name}</option>)}
                  </select>
                </div>
                <div>
                  <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>Categoría</label>
                  <select className="field" value={f.cat} onChange={e => set("cat", e.target.value)}>
                    {(window.EB_BRANDS.find(b => b.name === f.brand)?.cats || []).map(c => <option key={c} value={c}>{c}</option>)}
                  </select>
                </div>
              </div>
              <div>
                <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>Modelo</label>
                <input className="field" value={f.model} onChange={e => set("model", e.target.value)} placeholder="Ej. TR 250 Rally" required />
              </div>
              <div className="grid-3" style={{ gap: 10 }}>
                <div>
                  <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>Año</label>
                  <input className="field" type="number" value={f.year} onChange={e => set("year", e.target.value)} />
                </div>
                <div>
                  <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>Stock CEDI</label>
                  <input className="field" type="number" value={f.stock} onChange={e => set("stock", e.target.value)} />
                </div>
                <div>
                  <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>En tránsito</label>
                  <input className="field" type="number" value={f.transit} onChange={e => set("transit", e.target.value)} />
                </div>
              </div>
              <div className="grid-3" style={{ gap: 10 }}>
                <div>
                  <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>Precio Dealer</label>
                  <input className="field" type="number" value={f.priceDealer} onChange={e => set("priceDealer", e.target.value)} required />
                </div>
                <div>
                  <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>Precio Cliente Final</label>
                  <input className="field" type="number" value={f.pricePublico} onChange={e => set("pricePublico", e.target.value)} required />
                </div>
                <div>
                  <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>% descuento promo</label>
                  <input className="field" type="number" value={f.descuentoPromoPct} onChange={e => set("descuentoPromoPct", e.target.value)} />
                </div>
              </div>
            </>
          ) : (
            <>
              <div className="grid-2" style={{ gap: 10 }}>
                <div>
                  <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>SKU</label>
                  <input className="field mono" value={f.sku} onChange={e => set("sku", e.target.value)} placeholder="Se genera si se deja vacío" />
                </div>
                <div>
                  <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>Marca</label>
                  <select className="field" value={f.brand} onChange={e => set("brand", e.target.value)}>
                    {window.EB_BRANDS.map(b => <option key={b.id} value={b.name}>{b.name}</option>)}
                  </select>
                </div>
              </div>
              <div>
                <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>Nombre de la refacción / accesorio</label>
                <input className="field" value={f.name} onChange={e => set("name", e.target.value)} required />
              </div>
              <div className="grid-3" style={{ gap: 10 }}>
                <div>
                  <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>Existencia</label>
                  <input className="field" type="number" value={f.qty} onChange={e => set("qty", e.target.value)} />
                </div>
                <div>
                  <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>Mínimo</label>
                  <input className="field" type="number" value={f.min} onChange={e => set("min", e.target.value)} />
                </div>
                <div>
                  <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>Precio</label>
                  <input className="field" type="number" value={f.price} onChange={e => set("price", e.target.value)} required />
                </div>
              </div>
            </>
          )}
          <div>
            <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>Ficha técnica / brochure</label>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 8 }}>
              {docs.map((d, i) => (
                <span key={i} className="chip" style={{ height: 26, fontSize: 11.5, gap: 6 }}>
                  <Icon name="doc" size={13} /> {d.name}
                  <button type="button" onClick={() => removeDoc(i)} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--text-4)", padding: 0, display: "flex" }}><Icon name="ext" size={11} /></button>
                </span>
              ))}
            </div>
            <input ref={fileRef} type="file" multiple style={{ display: "none" }} onChange={addDoc} accept=".pdf,.doc,.docx,.png,.jpg,.jpeg" />
            <button type="button" className="btn btn-sm" onClick={() => fileRef.current.click()}><Icon name="upload" size={13} /> Adjuntar archivo</button>
          </div>
          <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 6, borderTop: "1px solid var(--line)", paddingTop: 14 }}>
            <button type="button" className="btn btn-sm" onClick={onClose}>Cancelar</button>
            <button type="submit" className="btn btn-sm btn-primary" style={{ background: "var(--eb)" }}><Icon name="plus" size={13} /> Dar de alta</button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ---------------- detalle genérico de tarjeta del dashboard ----------------
function EbStatDetailModal({ title, icon, hue = "var(--eb)", sub, rows, table, onClose }) {
  return (
    <div className="cmd-overlay" onMouseDown={onClose}>
      <div className="cmd-panel" style={{ width: 560 }} onMouseDown={e => e.stopPropagation()}>
        <div className="cmd-input">
          <span className="feed-ic" style={{ "--c": hue, width: 30, height: 30 }}><Icon name={icon} size={15} /></span>
          <b style={{ fontSize: 14.5 }}>{title}</b>
          <button className="ic-btn" style={{ marginLeft: "auto" }} onClick={onClose}><Icon name="ext" size={15} /></button>
        </div>
        <div style={{ padding: "14px 20px 20px" }}>
          {sub && <p className="muted" style={{ fontSize: 12.5, marginBottom: 14 }}>{sub}</p>}
          {rows && (
            <div className="grid-2" style={{ gap: 10, marginBottom: table ? 18 : 0 }}>
              {rows.map(([k, v], i) => (
                <div key={i} className="card" style={{ padding: 12, background: "var(--bg-2)" }}>
                  <div className="muted" style={{ fontSize: 11 }}>{k}</div>
                  <div className="mono" style={{ fontSize: 15, color: "var(--text)", marginTop: 4, fontWeight: 600 }}>{v}</div>
                </div>
              ))}
            </div>
          )}
          {table && (
            <div style={{ maxHeight: 280, overflow: "auto", border: "1px solid var(--line)", borderRadius: 10 }}>
              <table className="tbl">
                <thead><tr>{table.head.map((h, i) => <th key={i}>{h}</th>)}</tr></thead>
                <tbody>
                  {table.rows.map((r, i) => <tr key={i}>{r.map((c, j) => <td key={j} style={j === 0 ? { color: "var(--text)", fontWeight: 500 } : {}}>{c}</td>)}</tr>)}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ---------------- comisiones por vendedor ----------------
function EbCommissionModal({ vendedor, onClose }) {
  const sales = window.EB_VENDEDOR_SALES[vendedor.name] || [];
  const comisionTotal = sales.reduce((s, x) => s + x.monto * x.comisionPct / 100, 0);
  const pagada = sales.filter(x => x.estadoPago === "Pagada").reduce((s, x) => s + x.monto * x.comisionPct / 100, 0);
  const pendiente = comisionTotal - pagada;
  return (
    <div className="cmd-overlay" onMouseDown={onClose}>
      <div className="cmd-panel" style={{ width: 680 }} onMouseDown={e => e.stopPropagation()}>
        <div className="cmd-input">
          <Avatar name={vendedor.name} initials={vendedor.name.split(" ").map(w => w[0]).join("")} hue={vendedor.hue} size={30} />
          <b style={{ fontSize: 14.5 }}>{vendedor.name} — comisiones y ventas</b>
          <button className="ic-btn" style={{ marginLeft: "auto" }} onClick={onClose}><Icon name="ext" size={15} /></button>
        </div>
        <div style={{ padding: "14px 20px 20px" }}>
          <div className="grid-3" style={{ gap: 10, marginBottom: 16 }}>
            <div className="card" style={{ padding: 12, background: "var(--bg-2)" }}>
              <div className="muted" style={{ fontSize: 11 }}>Ventas del mes</div>
              <div className="disp" style={{ fontSize: 18, fontWeight: 600, marginTop: 4 }}>{window.fmtK(vendedor.ventas)}</div>
              <div className="mono" style={{ fontSize: 10.5, color: "var(--text-4)" }}>{vendedor.unidades} unidades</div>
            </div>
            <div className="card" style={{ padding: 12, background: "color-mix(in oklch, var(--ok) 8%, var(--bg-2))" }}>
              <div className="muted" style={{ fontSize: 11 }}>Comisión ganada</div>
              <div className="disp" style={{ fontSize: 18, fontWeight: 600, marginTop: 4, color: "var(--ok)" }}>{window.fmtMoney(comisionTotal)}</div>
              <div className="mono" style={{ fontSize: 10.5, color: "var(--text-4)" }}>pagada {window.fmtMoney(pagada)}</div>
            </div>
            <div className="card" style={{ padding: 12, background: pendiente > 0 ? "color-mix(in oklch, var(--warn) 8%, var(--bg-2))" : "var(--bg-2)" }}>
              <div className="muted" style={{ fontSize: 11 }}>Pago pendiente</div>
              <div className="disp" style={{ fontSize: 18, fontWeight: 600, marginTop: 4, color: pendiente > 0 ? "var(--warn)" : "var(--text)" }}>{window.fmtMoney(pendiente)}</div>
              <div className="mono" style={{ fontSize: 10.5, color: "var(--text-4)" }}>{sales.filter(x => x.estadoPago !== "Pagada").length} venta(s)</div>
            </div>
          </div>
          <div style={{ border: "1px solid var(--line)", borderRadius: 10, overflow: "hidden" }}>
            <table className="tbl">
              <thead><tr><th>Fecha</th><th>Modelo</th><th>Cliente</th><th>Pago</th><th className="num">Monto</th><th className="num">Comisión</th><th>Estado</th></tr></thead>
              <tbody>
                {sales.map((s, i) => (
                  <tr key={i}>
                    <td className="mono" style={{ fontSize: 11.5 }}>{s.fecha}</td>
                    <td style={{ color: "var(--text)", fontWeight: 500 }}>{s.model}</td>
                    <td className="muted" style={{ fontSize: 12.5 }}>{s.cliente}</td>
                    <td><span className="chip" style={{ height: 22, fontSize: 11 }}>{s.tipoPago}</span></td>
                    <td className="num">{window.fmtMoney(s.monto)}</td>
                    <td className="num" style={{ color: "var(--ok)" }}>{window.fmtMoney(s.monto * s.comisionPct / 100)}</td>
                    <td>{s.estadoPago === "Pagada" ? <span className="badge ok dot">pagada</span> : <span className="badge warn dot">pendiente</span>}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------------- estado de cuenta tipo TC ----------------
function EbCreditStatementModal({ dealer, onClose }) {
  const t = window.EB_CREDIT_TERMS;
  const disp = dealer.linea - dealer.usado;
  const pagoMinimo = Math.round(dealer.usado * t.pagoMinimoPct / 100);
  return (
    <div className="cmd-overlay" onMouseDown={onClose}>
      <div className="cmd-panel" style={{ width: 520 }} onMouseDown={e => e.stopPropagation()}>
        <div className="cmd-input">
          <b style={{ fontSize: 14.5 }}>Estado de cuenta — {dealer.name}</b>
          <button className="ic-btn" style={{ marginLeft: "auto" }} onClick={onClose}><Icon name="ext" size={15} /></button>
        </div>
        <div style={{ padding: "14px 20px 20px" }}>
          <div className="card" style={{ padding: 18, background: "linear-gradient(150deg, color-mix(in oklch, var(--eb) 90%, black), color-mix(in oklch, var(--eb) 60%, black))", color: "white", marginBottom: 16 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
              <div>
                <div style={{ fontSize: 11, opacity: 0.75 }}>Línea de crédito Master ↔ Dealer</div>
                <div className="disp" style={{ fontSize: 24, fontWeight: 600, marginTop: 4 }}>{window.fmtMoney(dealer.usado)}</div>
                <div style={{ fontSize: 11.5, opacity: 0.8, marginTop: 2 }}>saldo actual</div>
              </div>
              <Pill status={dealer.estado} />
            </div>
            <div style={{ display: "flex", gap: 24, marginTop: 18, fontSize: 12 }}>
              <div><div style={{ opacity: 0.7 }}>Línea total</div><div className="mono" style={{ marginTop: 2 }}>{window.fmtMoney(dealer.linea)}</div></div>
              <div><div style={{ opacity: 0.7 }}>Disponible</div><div className="mono" style={{ marginTop: 2 }}>{window.fmtMoney(disp)}</div></div>
              {dealer.vencido > 0 && <div><div style={{ opacity: 0.7 }}>Vencido</div><div className="mono" style={{ marginTop: 2, color: "oklch(0.82 0.14 25)" }}>{window.fmtMoney(dealer.vencido)}</div></div>}
            </div>
          </div>
          <div className="grid-2" style={{ gap: 10 }}>
            {[
              ["Fecha de corte", "día " + t.corteDia + " de cada mes"],
              ["Fecha límite de pago", t.diasParaPago + " días después del corte"],
              ["Pago para no generar intereses", window.fmtMoney(dealer.usado)],
              ["Pago mínimo mensual", window.fmtMoney(pagoMinimo)],
              ["Tasa de interés anual", t.tasaAnual + "%"],
              ["Cargos de este periodo", window.fmtMoney(Math.round(dealer.ventasMes * 0.3))],
            ].map(([k, v], i) => (
              <div key={i} className="card" style={{ padding: 12, background: "var(--bg-2)" }}>
                <div className="muted" style={{ fontSize: 11 }}>{k}</div>
                <div className="mono" style={{ fontSize: 13.5, color: "var(--text)", marginTop: 4 }}>{v}</div>
              </div>
            ))}
          </div>
          {dealer.vencido > 0 && (
            <div className="card" style={{ padding: 12, marginTop: 12, borderColor: "color-mix(in oklch, var(--bad) 35%, var(--line))", display: "flex", gap: 10, alignItems: "center" }}>
              <Icon name="ext" size={16} style={{ color: "var(--bad)" }} />
              <span style={{ fontSize: 12.5 }}>Este Dealer tiene <b>{window.fmtMoney(dealer.vencido)}</b> vencidos — nuevas reservas quedarán bloqueadas hasta regularizar.</span>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ---------------- selector de catálogo (Reservar del Master) ----------------
function EbCatalogPickerModal({ onClose, onAdd }) {
  const [marca, setMarca] = React.useState("todas");
  const models = window.EB_MODELS.filter(m => (marca === "todas" || m.brand === marca) && m.stock > 0);
  return (
    <div className="cmd-overlay" onMouseDown={onClose}>
      <div className="cmd-panel" style={{ width: 620 }} onMouseDown={e => e.stopPropagation()}>
        <div className="cmd-input">
          <b style={{ fontSize: 14.5 }}>Agregar del catálogo Master</b>
          <button className="ic-btn" style={{ marginLeft: "auto" }} onClick={onClose}><Icon name="ext" size={15} /></button>
        </div>
        <div style={{ padding: "10px 20px 0", display: "flex", gap: 6, flexWrap: "wrap" }}>
          <button className="chip" data-on={marca === "todas"} style={{ cursor: "pointer" }} onClick={() => setMarca("todas")}>Todas</button>
          {window.EB_BRANDS.map(b => <button key={b.id} className="chip" data-on={marca === b.name} style={{ cursor: "pointer", color: marca === b.name ? b.hue : "var(--text-2)" }} onClick={() => setMarca(b.name)}>{b.name}</button>)}
        </div>
        <div style={{ padding: "12px 20px 20px", maxHeight: "56vh", overflow: "auto", display: "flex", flexDirection: "column", gap: 8 }}>
          {models.map((m, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: 10, borderRadius: 10, border: "1px solid var(--line)" }}>
              <window.ModelThumb color={m.color} size={38} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <b style={{ fontSize: 13 }}>{m.model}</b>
                <div className="mono" style={{ fontSize: 10.5, color: "var(--text-4)" }}>{m.brand} · {window.fmtMoney(m.priceDealer)} c/u · {m.stock} disponibles</div>
              </div>
              <button className="btn btn-sm btn-primary" style={{ background: "var(--eb)" }} onClick={() => { onAdd(m); onClose(); }}><Icon name="plus" size={13} /> Agregar</button>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ---------------- evidencia fotográfica (postventa / ciclo de vida) ----------------
function EbEvidenceGallery({ baseId, count = 0, label = "Evidencia" }) {
  const [extra, setExtra] = React.useState(0);
  const total = count + extra;
  const ids = Array.from({ length: Math.max(total, 1) }, (_, i) => baseId + "-" + i);
  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
        <span className="muted" style={{ fontSize: 11.5 }}>{label} · {total} archivo(s)</span>
        <button type="button" className="btn btn-sm" onClick={() => setExtra(v => v + 1)}><Icon name="camera" size={12} /> Agregar foto</button>
      </div>
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
        {ids.slice(0, Math.max(total, 0)).map((id, i) => (
          <image-slot key={id} id={id} shape="rounded" radius="8" placeholder="Foto" style={{ width: 64, height: 64 }}></image-slot>
        ))}
        {total === 0 && <span className="mono" style={{ fontSize: 10.5, color: "var(--text-4)" }}>Sin evidencia capturada aún.</span>}
      </div>
    </div>
  );
}

Object.assign(window, {
  SignaturePad, EbFileChip, EbProductAssets, EbAltaProductoModal,
  EbStatDetailModal, EbCommissionModal, EbCreditStatementModal, EbCatalogPickerModal, EbEvidenceGallery,
});
