/* ============================================================
   SYMPHO · EB — vistas Dealer (agencia) + Gerencia + dispatcher
   ============================================================ */

const { useState: useStateD } = React;

// stepper horizontal de la orden
function OrderStepper({ estado }) {
  const flow = window.EB_ORDER_FLOW;
  const idx = flow.indexOf(estado);
  return (
    <div className="eb-steps">
      {flow.map((st, j) => (
        <div key={st} className="eb-step" data-on={j <= idx} data-cur={j === idx}>
          <span className="eb-step-dot">{j < idx ? <Icon name="check" size={11} /> : null}</span>
          <span className="eb-step-label">{st}</span>
          {j < flow.length - 1 && <span className="eb-step-line" data-on={j < idx} />}
        </div>
      ))}
    </div>
  );
}

// =================== DEALER ===================
function EbDResumen() {
  const m = window.EB_METRICS.dealer, c = window.EB_CTX;
  const nav = useNav();
  const disp = m.creditoLinea - m.creditoUsado, pct = m.creditoUsado / m.creditoLinea * 100;
  const [detail, setDetail] = useStateD(null);
  const [commission, setCommission] = useStateD(null);

  const detalles = {
    inventario: {
      title: "Inventario en piso", icon: "warehouse",
      rows: [["Motocicletas", m.inventarioSplit[0].n], ["Refacciones", m.inventarioSplit[1].n], ["Accesorios", m.inventarioSplit[2].n], ["Total en piso", m.inventario]],
      table: { head: ["VIN", "Modelo", "Ubicación"], rows: window.EB_CEDI.unidades.slice(0, 5).map(u => [u.vin, u.brand + " " + u.model, u.ubic]) },
    },
    transito: {
      title: "En tránsito", icon: "route",
      rows: [["Unidades en camino", m.enTransito], ["Entrega promedio", window.EB_METRICS.master.entregaDias + " días"]],
      table: { head: ["VIN", "Modelo", "Último escaneo"], rows: window.EB_CEDI.unidades.filter(u => u.estado === "En tránsito").map(u => [u.vin, u.brand + " " + u.model, u.ultimoEscaneo]) },
    },
    ventas: {
      title: "Ventas del mes", icon: "dollar",
      rows: [["Total del mes", window.fmtK(m.ventasMes)], ["Unidades vendidas", 16], ["Tendencia", "+5% vs mes anterior"]],
      table: { head: ["Fecha", "Modelo", "Cliente", "Monto"], rows: window.EB_SELLOUT_DETALLE.map(s => [s.fecha, s.model, s.cliente, window.fmtMoney(s.monto)]) },
    },
    garantias: {
      title: "Garantías activas", icon: "shield",
      rows: [["Garantías activas", m.garantiasActivas], ["Por vencer", window.EB_WARRANTY.garantias.filter(g => g.estado === "Por vencer").length]],
      table: { head: ["VIN", "Modelo", "Activada", "Estado"], rows: window.EB_WARRANTY.garantias.map(g => [g.vin, g.model, g.activada, g.estado]) },
    },
  };

  return (
    <div className="canvas-in wide rise">
      <AppHead app="eb" title="Resumen" sub={`${c.dealerActual} · agencia distribuidora · ${c.pais}`}
        action={{ label: "Reservar del Master", icon: "cart", primary: true, onClick: () => nav.openApp("eb", "d-reservar") }} />
      <div className="grid-4" style={{ marginBottom: 14 }}>
        <div onClick={() => setDetail("inventario")} style={{ cursor: "pointer" }}><Stat icon="warehouse" label="Inventario en piso" value={m.inventario} hue="var(--eb)" /></div>
        <div onClick={() => setDetail("transito")} style={{ cursor: "pointer" }}><Stat icon="route" label="En tránsito" value={m.enTransito} hue="var(--eb)" sub="próximas entregas" /></div>
        <div onClick={() => setDetail("ventas")} style={{ cursor: "pointer" }}><Stat icon="dollar" label="Ventas del mes" value={window.fmtK(m.ventasMes)} hue="var(--eb)" trend={5} /></div>
        <div onClick={() => setDetail("garantias")} style={{ cursor: "pointer" }}><Stat icon="shield" label="Garantías activas" value={m.garantiasActivas} hue="var(--eb)" /></div>
      </div>
      <div className="grid-2" style={{ alignItems: "start", gridTemplateColumns: "minmax(0,1.3fr) minmax(0,1fr)", marginBottom: 14 }}>
        <div className="card" style={{ padding: 20 }}>
          <Section title="Sell-out local" sub="Unidades vendidas a cliente final — detalle por venta" right={<span className="badge">2026</span>} style={{ marginBottom: 16 }} />
          <Spark data={m.sellout} hue="var(--eb)" w={620} h={88} />
          <div style={{ display: "flex", gap: 24, marginTop: 16, paddingTop: 14, borderTop: "1px solid var(--line)" }}>
            <div><div className="disp" style={{ fontSize: 18, fontWeight: 600 }}>{window.EB_SELLOUT_DETALLE.length}</div><div className="muted" style={{ fontSize: 11.5 }}>ventas recientes</div></div>
            <div><div className="disp" style={{ fontSize: 18, fontWeight: 600 }}>{window.EB_SELLOUT_DETALLE.filter(s => s.tipoPago === "Contado").length}</div><div className="muted" style={{ fontSize: 11.5 }}>de contado</div></div>
            <div><div className="disp" style={{ fontSize: 18, fontWeight: 600 }}>{window.EB_SELLOUT_DETALLE.filter(s => s.tipoPago === "Financiado").length}</div><div className="muted" style={{ fontSize: 11.5 }}>financiadas</div></div>
          </div>
          <div style={{ marginTop: 14, maxHeight: 190, overflow: "auto", border: "1px solid var(--line)", borderRadius: 10 }}>
            <table className="tbl">
              <thead><tr><th>Fecha</th><th>Modelo</th><th>Cliente</th><th>Vendedor</th><th>Pago</th><th className="num">Monto</th></tr></thead>
              <tbody>
                {window.EB_SELLOUT_DETALLE.map((s, i) => (
                  <tr key={i}>
                    <td className="mono" style={{ fontSize: 11 }}>{s.fecha}</td>
                    <td style={{ color: "var(--text)", fontWeight: 500 }}>{s.model}</td>
                    <td className="muted" style={{ fontSize: 12 }}>{s.cliente}</td>
                    <td className="muted" style={{ fontSize: 12 }}>{s.vendedor}</td>
                    <td><span className="chip" style={{ height: 20, fontSize: 10.5 }}>{s.tipoPago}</span></td>
                    <td className="num">{window.fmtMoney(s.monto)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
        <div className="card" style={{ padding: 20 }}>
          <Section title="Mi crédito" sub="Línea con el Master Dealer" style={{ marginBottom: 16 }} />
          <div className="disp" style={{ fontSize: 28, fontWeight: 600 }}>{window.fmtK(disp)}<span style={{ fontSize: 13, color: "var(--text-4)" }}> disponible</span></div>
          <div className="bar" style={{ marginTop: 14, height: 8 }}><i style={{ width: pct + "%", background: "var(--eb)" }} /></div>
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8 }}>
            <span className="mono" style={{ fontSize: 11.5, color: "var(--text-3)" }}>Usado {window.fmtK(m.creditoUsado)}</span>
            <span className="mono" style={{ fontSize: 11.5, color: "var(--text-3)" }}>Línea {window.fmtK(m.creditoLinea)}</span>
          </div>
          <span className="badge ok dot" style={{ marginTop: 14 }}>Al corriente</span>
        </div>
      </div>
      <div className="grid-2" style={{ alignItems: "start", gridTemplateColumns: "minmax(0,1fr) minmax(0,1fr)" }}>
        <div className="card" style={{ padding: 20 }}>
          <Section title="Ventas por vendedor" sub="Comisión del mes — click en un vendedor para ver el detalle" style={{ marginBottom: 14 }} />
          <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
            <Donut segments={window.EB_VENDEDORES.map(v => ({ estado: v.name, n: v.ventas, hue: v.hue }))} size={110} thickness={14} />
            <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 7 }}>
              {window.EB_VENDEDORES.map(v => (
                <div key={v.name} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, cursor: "pointer" }} onClick={() => setCommission(v)}>
                  <span className="dot" style={{ background: v.hue }} />
                  <span style={{ flex: 1, color: "var(--text-2)" }}>{v.name}</span>
                  <span className="mono" style={{ color: "var(--text)" }}>{window.fmtK(v.ventas)}</span>
                  <Icon name="chevright" size={13} style={{ color: "var(--text-4)" }} />
                </div>
              ))}
            </div>
          </div>
        </div>
        <window.EbBoletin />
      </div>
      {detail && <window.EbStatDetailModal {...detalles[detail]} hue="var(--eb)" onClose={() => setDetail(null)} />}
      {commission && <window.EbCommissionModal vendedor={commission} onClose={() => setCommission(null)} />}
    </div>
  );
}

function EbDCatalogo() {
  const [unitsModal, setUnitsModal] = useStateD(null);
  const [tipo, setTipo] = useStateD("unidad");
  return (
    <div className="canvas-in wide rise">
      <AppHead app="eb" title="Catálogo Master" sub="Oferta del Master Dealer con disponibilidad en tiempo real — reserva directo desde aquí" />
      <div className="seg" style={{ marginBottom: 18 }}>
        <button className="seg-btn" data-on={tipo === "unidad"} onClick={() => setTipo("unidad")}><Icon name="moto" size={15} /> Motocicletas</button>
        <button className="seg-btn" data-on={tipo === "sku"} onClick={() => setTipo("sku")}><Icon name="tag" size={15} /> Refacciones</button>
      </div>
      {tipo === "unidad" ? (
      <div className="grid-3">
        {window.EB_MODELS.map((m, i) => {
          const precioFinal = m.descuentoPromoPct ? Math.round(m.pricePublico * (1 - m.descuentoPromoPct / 100)) : null;
          return (
          <div key={i} className="card eb-model" style={{ padding: 16, "--c": m.color }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <ModelThumb color={m.color} size={46} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <b style={{ fontSize: 14.5 }}>{m.model}</b>
                <div className="mono" style={{ fontSize: 10.5, color: m.color, marginTop: 2 }}>{m.brand} · {m.year}</div>
              </div>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 14 }}>
              {m.stock > 0 ? <button className="badge ok dot" style={{ border: "none", cursor: "pointer" }} onClick={() => setUnitsModal({ model: m, mode: "stock" })}>{m.stock} disponibles</button> : <span className="badge bad dot">agotado</span>}
              {m.transit > 0 && <button className="badge dot" style={{ border: "none", cursor: "pointer" }} onClick={() => setUnitsModal({ model: m, mode: "transito" })}>{m.transit} en tránsito</button>}
            </div>
            <div style={{ marginTop: 16, paddingTop: 14, borderTop: "1px solid var(--line)" }}>
              <div className="eb-price-row" data-tone="master"><span className="k">Precio Master</span><span className="v">{window.fmtMoney(m.priceDealer)}</span></div>
              <div className="eb-price-row" data-tone="dist"><span className="k">Precio público</span><span className="v">{window.fmtMoney(m.pricePublico)}</span></div>
              <div className="eb-price-row" data-tone="promo"><span className="k">Precio final (con descuento)</span><span className="v">{precioFinal ? window.fmtMoney(precioFinal) : "—"}</span></div>
            </div>
            <window.EbProductAssets photoId={"cat-" + window.ebCatalogKey(m.brand, m.model).replace(/[^a-z0-9]+/gi, "-")} docs={(window.EB_CATALOG_DOCS[window.ebCatalogKey(m.brand, m.model)] || {}).docs} />
            <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 14 }}>
              <button className="btn btn-sm" disabled={m.stock === 0} style={m.stock > 0 ? { background: "var(--eb)", color: "oklch(0.16 0.02 264)", borderColor: "transparent", fontWeight: 600 } : {}}><Icon name="cart" size={13} /> Reservar</button>
            </div>
          </div>
          );
        })}
      </div>
      ) : (
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          <table className="tbl">
            <thead><tr><th>SKU</th><th>Refacción / accesorio</th><th>Marca</th><th>Existencia</th><th>Mínimo</th><th>Archivos</th><th className="num">Precio</th><th></th></tr></thead>
            <tbody>
              {window.EB_CEDI.skus.map((s, i) => (
                <tr key={i}>
                  <td className="mono" style={{ color: "var(--text)", fontSize: 12 }}>{s.sku}</td>
                  <td style={{ color: "var(--text)", fontWeight: 500 }}>{s.name}</td>
                  <td>{s.marca}</td>
                  <td><span className={"badge dot " + (s.qty < s.min ? "bad" : "ok")}>{s.qty} u</span></td>
                  <td className="mono" style={{ fontSize: 12 }}>{s.min}</td>
                  <td>
                    <div style={{ display: "flex", gap: 5, flexWrap: "wrap", maxWidth: 200 }}>
                      {((window.EB_SKU_DOCS[s.sku] || {}).docs || []).map((d, j) => <window.EbFileChip key={j} name={d.name} />)}
                    </div>
                  </td>
                  <td className="num">{window.fmtMoney(s.price)}</td>
                  <td style={{ textAlign: "right" }}><button className="btn btn-sm" style={{ background: "var(--eb)", color: "oklch(0.16 0.02 264)", borderColor: "transparent", fontWeight: 600 }} disabled={s.qty === 0}><Icon name="cart" size={13} /> Reservar</button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
      {unitsModal && <window.EbUnitsModal model={unitsModal.model} mode={unitsModal.mode} onClose={() => setUnitsModal(null)} />}
    </div>
  );
}

function EbDReservar() {
  const [cart, setCart] = useStateD([
    { model: "Vairo RS 400 Sport", qty: 3, price: 112400, color: "var(--pakal)" },
    { model: "Kentaro City 125", qty: 2, price: 33500, color: "var(--manik)" },
  ]);
  const [picker, setPicker] = useStateD(false);
  const [confirmed, setConfirmed] = useStateD(false);
  const subtotal = cart.reduce((s, x) => s + x.qty * x.price, 0);
  const iva = subtotal * 0.16, total = subtotal + iva;
  const m = window.EB_METRICS.dealer;
  const disp = m.creditoLinea - m.creditoUsado;
  const ok = total <= disp && cart.length > 0;

  function addFromCatalog(model) {
    setCart(c => {
      const idx = c.findIndex(x => x.model === model.model);
      if (idx >= 0) { const copy = [...c]; copy[idx] = { ...copy[idx], qty: copy[idx].qty + 1 }; return copy; }
      return [...c, { model: model.model, qty: 1, price: model.priceDealer, color: model.color }];
    });
  }
  function changeQty(i, d) {
    setCart(c => c.map((x, j) => j === i ? { ...x, qty: Math.max(1, x.qty + d) } : x));
  }

  if (confirmed) {
    return (
      <div className="canvas-in rise">
        <AppHead app="eb" title="Reservar del Master" sub="Selecciona unidades del CEDI — el crédito se valida en el momento de reservar" />
        <div className="card" style={{ padding: 32, textAlign: "center" }}>
          <Icon name="check" size={34} style={{ color: "var(--ok)" }} />
          <p style={{ marginTop: 14, fontSize: 15 }}>Reserva confirmada por <b>{window.fmtMoney(total)}</b> — se generó una orden pendiente de aprobación del Master.</p>
          <button className="btn btn-sm" style={{ marginTop: 16 }} onClick={() => setConfirmed(false)}>Hacer otra reserva</button>
        </div>
      </div>
    );
  }

  return (
    <div className="canvas-in rise">
      <AppHead app="eb" title="Reservar del Master" sub="Selecciona unidades del CEDI — el crédito se valida en el momento de reservar" />
      <div className="grid-2" style={{ alignItems: "start", gridTemplateColumns: "minmax(0,1.5fr) minmax(0,1fr)" }}>
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          <div className="card-head"><b style={{ fontSize: 14 }}>Carrito de reserva</b><span className="mono" style={{ fontSize: 11, color: "var(--text-4)" }}>{cart.reduce((s,x)=>s+x.qty,0)} unidades</span></div>
          <div style={{ padding: 8 }}>
            {cart.map((x, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: 12, borderRadius: 10 }}>
                <ModelThumb color={x.color} size={42} />
                <div style={{ flex: 1 }}>
                  <b style={{ fontSize: 13.5 }}>{x.model}</b>
                  <div className="mono" style={{ fontSize: 11, color: "var(--text-4)", marginTop: 2 }}>{window.fmtMoney(x.price)} c/u</div>
                </div>
                <div className="qty"><button onClick={() => changeQty(i, -1)}>−</button><span className="mono">{x.qty}</span><button onClick={() => changeQty(i, 1)}>+</button></div>
                <div className="mono" style={{ width: 110, textAlign: "right", color: "var(--text)", fontSize: 13 }}>{window.fmtMoney(x.qty * x.price)}</div>
                <button className="ic-btn" style={{ width: 26, height: 26 }} onClick={() => setCart(c => c.filter((_, j) => j !== i))}><Icon name="ext" size={12} /></button>
              </div>
            ))}
            <button className="kan-add" style={{ margin: 8 }} onClick={() => setPicker(true)}><Icon name="plus" size={14} /> Agregar del catálogo</button>
          </div>
        </div>
        <div className="card" style={{ padding: 22 }}>
          <Section title="Resumen y crédito" style={{ marginBottom: 16 }} />
          {[["Subtotal", subtotal],["IVA 16%", iva]].map(([k, v]) => (
            <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", fontSize: 13 }}>
              <span className="muted">{k}</span><span className="mono" style={{ color: "var(--text)" }}>{window.fmtMoney(v)}</span>
            </div>
          ))}
          <div style={{ display: "flex", justifyContent: "space-between", padding: "12px 0", borderTop: "1px solid var(--line)", marginTop: 4 }}>
            <b>Total de la orden</b><span className="disp" style={{ fontSize: 20, fontWeight: 600 }}>{window.fmtMoney(total)}</span>
          </div>
          <div className="eb-credit-check" data-ok={ok} style={{ marginTop: 14 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
              <Icon name={ok ? "check" : "lock"} size={16} style={{ color: ok ? "var(--ok)" : "var(--bad)" }} />
              <b style={{ fontSize: 13 }}>{ok ? "Dentro de tu línea de crédito" : "Excede tu línea disponible"}</b>
            </div>
            {[["Línea disponible", disp],["Esta orden", total],["Quedará disponible", disp - total]].map(([k, v]) => (
              <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "4px 0", fontSize: 12 }}>
                <span className="muted">{k}</span><span className="mono" style={{ color: v < 0 ? "var(--bad)" : "var(--text-2)" }}>{window.fmtMoney(v)}</span>
              </div>
            ))}
          </div>
          <button className="btn btn-primary" disabled={!ok} style={{ width: "100%", justifyContent: "center", height: 44, marginTop: 16, background: "var(--eb)" }} onClick={() => setConfirmed(true)}>
            <Icon name="check" size={16} /> Confirmar reserva
          </button>
        </div>
      </div>
      {picker && <window.EbCatalogPickerModal onClose={() => setPicker(false)} onAdd={addFromCatalog} />}
    </div>
  );
}

function EbDOrdenes() {
  const mine = window.EB_ORDERS.filter(o => o.dealer === "Moto Centro Roma");
  const facturable = ["Facturada", "Despachada", "Recibida"];
  return (
    <div className="canvas-in wide rise">
      <AppHead app="eb" title="Mis órdenes" sub="Trazabilidad de cada orden — del CEDI a tu piso de venta" />
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {mine.concat(window.EB_ORDERS.filter(o => o.dealer !== "Moto Centro Roma").slice(0, 2)).map((o, i) => (
          <div key={i} className="card" style={{ padding: 18 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16 }}>
              <span className="feed-ic" style={{ "--c": "var(--eb)", width: 36, height: 36 }}><Icon name="receipt" size={17} /></span>
              <div style={{ flex: 1 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 9 }}><b style={{ fontSize: 14 }}>{o.folio}</b><span className="muted" style={{ fontSize: 12.5 }}>· {o.items}</span></div>
                <div className="mono" style={{ fontSize: 11, color: "var(--text-4)", marginTop: 2 }}>{o.fecha} · {window.fmtMoney(o.value)}</div>
              </div>
              <Pill status={o.estado} />
              {facturable.includes(o.estado) && (
                o.facturada === false
                  ? <button className="btn btn-sm" style={{ marginLeft: 8, borderColor: "color-mix(in oklch, var(--bad) 40%, var(--line-2))", color: "var(--bad)" }}><Icon name="ext" size={13} /> Sin facturar</button>
                  : <button className="btn btn-sm" style={{ marginLeft: 8 }}><Icon name="download" size={13} /> Factura</button>
              )}
            </div>
            <OrderStepper estado={o.estado} />
          </div>
        ))}
      </div>
    </div>
  );
}

// ---------------- Verificar embarque (Vo.Bo. + firma autógrafa) — vehículos y refacciones ----------------
function EbEmbarqueModal({ onClose, onReceivePart }) {
  const { units, transition } = window.useEbQrUnits();
  const [tab, setTab] = useStateD("vehiculos");
  const [signingKey, setSigningKey] = useStateD(null); // vin o "parte"
  const [firmante, setFirmante] = useStateD("");
  const [sigData, setSigData] = useStateD(null);
  const [partShip, setPartShip] = useStateD({ sku: "RF-VAI-AC-0440", name: "Kit de cadena Vairo 250", qty: 24, stage: "transito" });
  const incomingV = units.filter(u => u.dealer === window.EB_CTX.dealerActual && (u.stage === "transito" || u.stage === "recibido_pendiente"));

  function scan(key) {
    if (key === "parte") { setPartShip(p => ({ ...p, stage: "recibido_pendiente" })); return; }
    transition(key, "recibido_pendiente", { stage: "Embarque escaneado en Dealer — Vo.Bo. pendiente", ts: "ahora", ubic: window.EB_CTX.dealerActual, usuario: "Sin firmar", note: "El operador debe validar y firmar para acreditar la entrada." });
  }
  function firmar(key) {
    if (!firmante.trim() || !sigData) return;
    if (key === "parte") {
      onReceivePart(partShip);
      setPartShip(p => ({ ...p, stage: "inventario_dealer" }));
    } else {
      const u = units.find(x => x.vin === key);
      transition(key, "inventario_dealer", { stage: "Vo.Bo. de recepción en Dealer", ts: "ahora", ubic: window.EB_CTX.dealerActual, usuario: firmante, note: "Firma electrónica registrada — sin discrepancias." });
      u.history.push({ stage: "Alta a inventario del Dealer", ts: "ahora", ubic: window.EB_CTX.dealerActual + " · piso de venta", usuario: "Sistema" });
    }
    setFirmante(""); setSigData(null); setSigningKey(null);
  }

  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 }}>Verificar embarque</b>
          <button className="ic-btn" style={{ marginLeft: "auto" }} onClick={onClose}><Icon name="ext" size={15} /></button>
        </div>
        <div style={{ padding: "12px 20px 0" }}>
          <div className="seg">
            <button type="button" className="seg-btn" data-on={tab === "vehiculos"} onClick={() => setTab("vehiculos")}><Icon name="moto" size={14} /> Vehículos</button>
            <button type="button" className="seg-btn" data-on={tab === "refacciones"} onClick={() => setTab("refacciones")}><Icon name="tag" size={14} /> Refacciones</button>
          </div>
        </div>
        <div style={{ padding: "14px 20px 20px", maxHeight: "62vh", overflow: "auto", display: "flex", flexDirection: "column", gap: 14 }}>
          {tab === "vehiculos" ? (
            incomingV.length === 0 ? <p className="muted" style={{ fontSize: 12.5 }}>No tienes embarques de vehículos pendientes de verificar.</p> :
            incomingV.map((u, i) => (
              <div key={i} className="card" style={{ padding: 16 }}>
                <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
                  <window.EbQrVisual seed={u.vin} size={52} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <b style={{ fontSize: 13.5 }}>{u.brand} {u.model}</b>
                    <div className="mono" style={{ fontSize: 10.5, color: "var(--eb)", marginTop: 2 }}>{u.vin}</div>
                  </div>
                  <span className={"badge dot" + (u.stage === "recibido_pendiente" ? " bad" : " warn")}>{window.EB_QR_STAGE_META[u.stage].label}</span>
                </div>
                <div style={{ marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--line)" }}>
                  {u.stage === "transito" ? (
                    <button className="btn btn-primary" style={{ background: "var(--eb)" }} onClick={() => scan(u.vin)}><Icon name="qr" size={14} /> Escanear QR de llegada</button>
                  ) : signingKey === u.vin ? (
                    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                      <window.SignaturePad onChange={setSigData} />
                      <input className="field" placeholder="Nombre de quien firma (Vo.Bo.)" value={firmante} onChange={e => setFirmante(e.target.value)} />
                      <button className="btn btn-primary" style={{ background: "var(--eb)", justifyContent: "center" }} disabled={!firmante.trim() || !sigData} onClick={() => firmar(u.vin)}><Icon name="check" size={14} /> Firmar Vo.Bo. y dar entrada</button>
                    </div>
                  ) : (
                    <button className="btn" onClick={() => setSigningKey(u.vin)}><Icon name="key" size={14} /> Dar Vo.Bo. y firmar</button>
                  )}
                </div>
              </div>
            ))
          ) : (
            <div className="card" style={{ padding: 16 }}>
              <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
                <window.EbQrVisual seed={partShip.sku} size={52} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <b style={{ fontSize: 13.5 }}>{partShip.name} · {partShip.qty} pzas</b>
                  <div className="mono" style={{ fontSize: 10.5, color: "var(--eb)", marginTop: 2 }}>{partShip.sku}</div>
                </div>
                <span className={"badge dot" + (partShip.stage === "recibido_pendiente" ? " bad" : partShip.stage === "inventario_dealer" ? " ok" : " warn")}>
                  {partShip.stage === "transito" ? "En tránsito" : partShip.stage === "recibido_pendiente" ? "Vo.Bo. pendiente" : "En inventario"}
                </span>
              </div>
              <div style={{ marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--line)" }}>
                {partShip.stage === "transito" ? (
                  <button className="btn btn-primary" style={{ background: "var(--eb)" }} onClick={() => scan("parte")}><Icon name="qr" size={14} /> Escanear QR de llegada</button>
                ) : partShip.stage === "recibido_pendiente" ? (
                  signingKey === "parte" ? (
                    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                      <window.SignaturePad onChange={setSigData} />
                      <input className="field" placeholder="Nombre de quien firma (Vo.Bo.)" value={firmante} onChange={e => setFirmante(e.target.value)} />
                      <button className="btn btn-primary" style={{ background: "var(--eb)", justifyContent: "center" }} disabled={!firmante.trim() || !sigData} onClick={() => firmar("parte")}><Icon name="check" size={14} /> Firmar Vo.Bo. y dar entrada</button>
                    </div>
                  ) : (
                    <button className="btn" onClick={() => setSigningKey("parte")}><Icon name="key" size={14} /> Dar Vo.Bo. y firmar</button>
                  )
                ) : (
                  <span className="badge ok dot">Alta confirmada en inventario</span>
                )}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function EbDInventario() {
  const piso = window.EB_CEDI.unidades.filter(u => u.dealer === "Moto Centro Roma" || u.estado === "Disponible").slice(0, 5);
  const { units: qrUnits } = window.useEbQrUnits();
  const misUnidades = qrUnits.filter(u => u.dealer === window.EB_CTX.dealerActual && u.stage === "inventario_dealer");
  const [sellUnit, setSellUnit] = useStateD(null);
  const [manualVehicles, setManualVehicles] = useStateD([]);
  const [manualParts, setManualParts] = useStateD([]);
  const [showAddVehicle, setShowAddVehicle] = useStateD(false);
  const [showAddPart, setShowAddPart] = useStateD(false);
  const [showEmbarque, setShowEmbarque] = useStateD(false);
  const parts = window.EB_CEDI.skus.slice(0, 3).concat(manualParts.map(p => ({ sku: p.sku, name: p.name, marca: p.marca, qty: Number(p.qty) || 0, min: Number(p.min) || 0, price: Number(p.price) || 0 })));
  function receivePart(ship) {
    setManualParts(ps => [...ps, { sku: ship.sku, name: ship.name + " (embarque verificado)", marca: "Vairo", qty: ship.qty, min: 10, price: 1280 }]);
  }
  return (
    <div className="canvas-in wide rise">
      <AppHead app="eb" title="Mi inventario" sub="Piso de venta sincronizado con las entregas del Master Dealer"
        action={{ label: "Verificar embarque (QR)", icon: "qr", primary: true, onClick: () => setShowEmbarque(true) }} />
      <div className="grid-3" style={{ marginBottom: 16 }}>
        <Stat icon="warehouse" label="En piso de venta" value={window.EB_METRICS.dealer.inventario + manualVehicles.length} hue="var(--eb)" />
        <Stat icon="route" label="En tránsito" value={window.EB_METRICS.dealer.enTransito} hue="var(--eb)" />
        <Stat icon="moto" label="Vendidas (mes)" value={16} hue="var(--eb)" />
      </div>
      <div className="card" style={{ padding: 20, marginBottom: 16 }}>
        <Section title="Inventario por tipo" sub="Motocicletas · refacciones · accesorios" style={{ marginBottom: 14 }} />
        <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
          <Donut segments={window.EB_METRICS.dealer.inventarioSplit} size={110} thickness={14} />
          <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 7 }}>
            {window.EB_METRICS.dealer.inventarioSplit.map(s => (
              <div key={s.estado} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12 }}>
                <span className="dot" style={{ background: s.hue }} />
                <span style={{ flex: 1, color: "var(--text-2)" }}>{s.estado}</span>
                <span className="mono" style={{ color: "var(--text)" }}>{s.n}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
      <div className="card" style={{ padding: 0, overflow: "hidden", marginBottom: 16 }}>
        <div className="card-head"><b style={{ fontSize: 14 }}>Motocicletas</b><button className="btn btn-sm btn-primary" style={{ background: "var(--eb)" }} onClick={() => setShowAddVehicle(true)}><Icon name="plus" size={13} /> Agregar vehículo</button></div>
        <table className="tbl">
          <thead><tr><th>VIN</th><th>Modelo</th><th>Año</th><th>Estado</th><th>Ubicación</th><th></th></tr></thead>
          <tbody>
            {misUnidades.map((u, i) => (
              <tr key={"qr" + i}>
                <td className="mono" style={{ color: "var(--eb)", fontSize: 12 }}>{u.vin}</td>
                <td style={{ color: "var(--text)", fontWeight: 500 }}>{u.brand} {u.model}</td>
                <td className="mono" style={{ fontSize: 12 }}>{u.year}</td>
                <td><span className="badge ok dot">Lista para venta</span></td>
                <td className="muted" style={{ fontSize: 12.5 }}>Piso · {window.EB_CTX.dealerActual}</td>
                <td style={{ textAlign: "right" }}><button className="btn btn-sm" onClick={() => setSellUnit(u)}><Icon name="qr" size={13} /> Vender a cliente</button></td>
              </tr>
            ))}
            {piso.map((u, i) => (
              <tr key={i}>
                <td className="mono" style={{ color: "var(--text)", fontSize: 12 }}>{u.vin}</td>
                <td style={{ color: "var(--text)", fontWeight: 500 }}>{u.brand} {u.model}</td>
                <td className="mono" style={{ fontSize: 12 }}>{u.year}</td>
                <td><Pill status={u.estado === "Disponible" ? "En tránsito" : u.estado} /></td>
                <td className="muted" style={{ fontSize: 12.5 }}>{u.estado === "Vendido" ? "Vendida" : "Piso · Moto Centro Roma"}</td>
                <td></td>
              </tr>
            ))}
            {manualVehicles.map((u, i) => (
              <tr key={"m" + i}>
                <td className="mono" style={{ color: "var(--text)", fontSize: 12 }}>{u.vin}</td>
                <td style={{ color: "var(--text)", fontWeight: 500 }}>{u.brand} {u.model}</td>
                <td className="mono" style={{ fontSize: 12 }}>{u.year}</td>
                <td><span className="badge dot">Alta manual</span></td>
                <td className="muted" style={{ fontSize: 12.5 }}>Piso · Moto Centro Roma</td>
                <td></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div className="card-head"><b style={{ fontSize: 14 }}>Refacciones y accesorios</b><button className="btn btn-sm btn-primary" style={{ background: "var(--eb)" }} onClick={() => setShowAddPart(true)}><Icon name="plus" size={13} /> Agregar refacción</button></div>
        <table className="tbl">
          <thead><tr><th>SKU</th><th>Refacción / accesorio</th><th>Marca</th><th>Existencia</th><th>Mínimo</th><th className="num">Precio</th></tr></thead>
          <tbody>
            {parts.map((s, i) => (
              <tr key={i}>
                <td className="mono" style={{ color: "var(--text)", fontSize: 12 }}>{s.sku}</td>
                <td style={{ color: "var(--text)", fontWeight: 500 }}>{s.name}</td>
                <td>{s.marca}</td>
                <td><span className={"badge dot " + (s.qty < s.min ? "bad" : "ok")}>{s.qty} u</span></td>
                <td className="mono" style={{ fontSize: 12 }}>{s.min}</td>
                <td className="num">{window.fmtMoney(s.price)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {showAddVehicle && <EbAddVehicleModal onClose={() => setShowAddVehicle(false)} onAdd={(v) => setManualVehicles(vs => [...vs, v])} />}
      {showAddPart && <EbAddPartModal onClose={() => setShowAddPart(false)} onAdd={(p) => setManualParts(ps => [...ps, p])} />}
      {sellUnit && <window.EbSellModal unit={sellUnit} onClose={() => setSellUnit(null)} />}
      {showEmbarque && <EbEmbarqueModal onClose={() => setShowEmbarque(false)} onReceivePart={receivePart} />}
    </div>
  );
}

function EbDGarantias() {
  const w = window.EB_WARRANTY.garantias.filter(g => g.dealer === "Moto Centro Roma").concat(window.EB_WARRANTY.garantias.slice(0, 2));
  return (
    <div className="canvas-in wide rise">
      <AppHead app="eb" title="Garantías" sub="Activa la garantía al entregar a 0 km y registra los servicios por kilometraje" />
      <div className="card" style={{ padding: 18, marginBottom: 16, display: "flex", gap: 10, alignItems: "center" }}>
        <Icon name="vin" size={20} style={{ color: "var(--eb)" }} />
        <input className="field mono" placeholder="VIN de la unidad vendida…" style={{ flex: 1, fontSize: 13 }} />
        <button className="btn btn-primary" style={{ background: "var(--eb)" }}><Icon name="shield" size={15} /> Activar garantía</button>
      </div>
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div className="card-head"><b style={{ fontSize: 14 }}>Garantías activas</b></div>
        <table className="tbl">
          <thead><tr><th>VIN</th><th>Modelo</th><th>Activada</th><th style={{width:200}}>Kilometraje</th><th>Estado</th></tr></thead>
          <tbody>
            {w.map((g, i) => (
              <tr key={i}>
                <td className="mono" style={{ color: "var(--text)", fontSize: 12 }}>{g.vin}</td>
                <td style={{ color: "var(--text)", fontWeight: 500 }}>{g.model}</td>
                <td className="mono" style={{ fontSize: 12 }}>{g.activada}</td>
                <td><KmBar km={g.km} limite={g.limite} /></td>
                <td><Pill status={g.estado} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ciclo de vida postventa — buscable por VIN, incluye motos de otros dealers de la red
function EbDPostventa() {
  const [vin, setVin] = useStateD("");
  const rows = window.EB_POSTVENTA.filter(p => !vin || p.vin.toLowerCase().includes(vin.toLowerCase()));
  const { find } = window.useEbQrUnits();
  const qrUnit = vin.trim() ? find(vin.trim()) : null;
  return (
    <div className="canvas-in wide rise">
      <AppHead app="eb" title="Postventa" sub="Historial de servicios y garantías por unidad — consulta cualquier VIN de la red, no solo el tuyo" />
      <div className="card" style={{ padding: 16, marginBottom: 16, display: "flex", gap: 10, alignItems: "center" }}>
        <Icon name="vin" size={20} style={{ color: "var(--eb)" }} />
        <input className="field mono" value={vin} onChange={e => setVin(e.target.value)} placeholder="Buscar por VIN…" style={{ flex: 1, fontSize: 13 }} />
        <button className="btn btn-primary" style={{ background: "var(--eb)" }}><Icon name="search" size={15} /> Buscar en la red</button>
      </div>
      {qrUnit && (
        <div className="card" style={{ padding: 20, marginBottom: 16 }}>
          <Section title="Trazabilidad por QR" sub="Ciclo de vida completo de la unidad — cualquier Dealer de la red puede consultarlo" style={{ marginBottom: 16 }} />
          <window.EbQrTimeline unit={qrUnit} />
        </div>
      )}
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div className="card-head"><b style={{ fontSize: 14 }}>Ciclo de vida postventa</b><span className="badge">{rows.length} eventos</span></div>
        <table className="tbl">
          <thead><tr><th>VIN</th><th>Modelo</th><th>Dealer</th><th>Evento</th><th>Fecha</th><th>Observaciones</th><th style={{width:220}}>Evidencia fotográfica</th></tr></thead>
          <tbody>
            {rows.map((p, i) => (
              <tr key={i}>
                <td className="mono" style={{ color: "var(--text)", fontSize: 12 }}>{p.vin}</td>
                <td style={{ color: "var(--text)", fontWeight: 500 }}>{p.model}</td>
                <td className="muted">{p.dealer}</td>
                <td>{p.tipo}</td>
                <td className="mono" style={{ fontSize: 12 }}>{p.fecha}</td>
                <td className="muted" style={{ fontSize: 12.5 }}>{p.obs}</td>
                <td><window.EbEvidenceGallery baseId={"postventa-" + i} count={i % 2 === 0 ? 2 : 0} label="" /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// =================== GERENCIA ===================
function EbGDashboard() {
  const g = window.EB_METRICS.gerencia, m = window.EB_METRICS.master;
  return (
    <div className="canvas-in wide rise">
      <AppHead app="eb" title="Dashboard ejecutivo" sub="Consolidado nacional · sell-in vs sell-out, tiempos de entrega y cartera" />
      <div className="grid-4" style={{ marginBottom: 14 }}>
        <Stat icon="ship" label="Sell-in (Master→red)" value={window.fmtK(g.sellin)} hue="var(--eb)" trend={6} />
        <Stat icon="moto" label="Sell-out (red→cliente)" value={window.fmtK(g.sellout)} hue="var(--eb)" trend={9} />
        <Stat icon="clock" label="Entrega promedio" value={g.entregaProm + " d"} hue="var(--eb)" sub="meta 14 días" />
        <Stat icon="wallet" label="Cartera total vencida" value={window.fmtK(g.carteraTotal)} hue="var(--eb)" />
      </div>
      <div className="card" style={{ padding: 22 }}>
        <Section title="Sell-in vs Sell-out" sub="Unidades · 12 periodos" style={{ marginBottom: 18 }} />
        <div style={{ position: "relative" }}>
          <Spark data={m.sellinSeries} hue="var(--eb)" w={1080} h={120} />
          <div style={{ position: "absolute", inset: 0 }}><Spark data={window.EB_METRICS.dealer.sellout.map(x => x * 1.3)} hue="var(--manik)" w={1080} h={120} fill={false} /></div>
        </div>
        <div style={{ display: "flex", gap: 20, marginTop: 12 }}>
          <span style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 12.5 }}><span className="dot" style={{ background: "var(--eb)" }} /> Sell-in</span>
          <span style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 12.5 }}><span className="dot" style={{ background: "var(--manik)" }} /> Sell-out</span>
        </div>
      </div>
    </div>
  );
}

function EbGRanking() {
  const r = window.EB_METRICS.gerencia.ranking;
  const max = Math.max(...r.map(x => x.ventas));
  return (
    <div className="canvas-in wide rise">
      <AppHead app="eb" title="Ranking de Dealers" sub="Desempeño por agencia · ventas del mes" />
      <div className="card" style={{ padding: 22 }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {r.map((x, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <span className="disp" style={{ width: 28, fontSize: 18, fontWeight: 600, color: i < 3 ? "var(--eb)" : "var(--text-4)" }}>{i + 1}</span>
              <div style={{ width: 180 }}>
                <b style={{ fontSize: 13.5 }}>{x.dealer}</b>
                <div className="mono" style={{ fontSize: 10.5, color: "var(--text-4)" }}>{x.units} unidades</div>
              </div>
              <div className="bar" style={{ flex: 1, height: 20, borderRadius: 6 }}><i style={{ width: (x.ventas / max * 100) + "%", background: "var(--eb)", borderRadius: 6 }} /></div>
              <span className="mono" style={{ width: 90, textAlign: "right", fontSize: 13, color: "var(--text)" }}>{window.fmtK(x.ventas)}</span>
              <span className="mono" style={{ width: 48, textAlign: "right", fontSize: 12, color: x.trend >= 0 ? "var(--ok)" : "var(--bad)" }}>{x.trend >= 0 ? "+" : ""}{x.trend}%</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function EbGDemanda() {
  const d = window.EB_METRICS.gerencia.demanda;
  const max = Math.max(...d.map(x => x.proy));
  return (
    <div className="canvas-in wide rise">
      <AppHead app="eb" title="Proyección de demanda" sub="Forecast por categoría — insumo para los pedidos de importación a marca" />
      <div className="card" style={{ padding: 24 }}>
        <div style={{ display: "flex", gap: 12, marginBottom: 22 }}>
          <span style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 12.5 }}><span className="dot" style={{ background: "var(--text-3)" }} /> Demanda actual</span>
          <span style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 12.5 }}><span className="dot" style={{ background: "var(--eb)" }} /> Proyección 90 días</span>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          {d.map((x, i) => (
            <div key={i}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
                <b style={{ fontSize: 13.5 }}>{x.cat}</b>
                <span className="mono" style={{ fontSize: 12, color: "var(--text-3)" }}>{x.actual} → <span style={{ color: "var(--eb)" }}>{x.proy}</span> u</span>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
                <div className="bar" style={{ height: 10 }}><i style={{ width: (x.actual / max * 100) + "%", background: "var(--text-3)" }} /></div>
                <div className="bar" style={{ height: 10 }}><i style={{ width: (x.proy / max * 100) + "%", background: "var(--eb)" }} /></div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// =================== DISPATCHER ===================
function EbApp({ role, sub }) {
  const VIEWS = {
    // master
    resumen: window.EbResumen, catalogo: window.EbCatalogo, cedi: window.EbCedi,
    ordenes: window.EbOrdenes, importaciones: window.EbImportaciones, logistica: window.EbLogistica,
    almacen: window.EbAlmacen, credito: window.EbCredito, garantias: window.EbGarantias, dealers: window.EbDealers,
    finanzas: window.EbFinanzas, facturacion: window.EbFacturacion, etiquetas: window.EbEtiquetas,
    // dealer
    "d-resumen": EbDResumen, "d-catalogo": EbDCatalogo, "d-reservar": EbDReservar,
    "d-ordenes": EbDOrdenes, "d-inventario": EbDInventario, "d-garantias": EbDGarantias,
    "d-postventa": EbDPostventa, "d-scanner": window.EbDScanner || null,
    "d-finanzas": window.EbDFinanzas, "d-facturacion": window.EbDFacturacion,
    // gerencia (visible para superadmin/gerencia dentro de Master — ver EB_NAV.master)
    "g-dashboard": EbGDashboard, "g-ranking": EbGRanking, "g-demanda": EbGDemanda,
  };
  const Comp = VIEWS[sub] || VIEWS[(window.EB_NAV[role] || window.EB_NAV.master)[0].id];
  return Comp ? <Comp /> : null;
}

Object.assign(window, { EbApp, EbDResumen, EbDCatalogo, EbDReservar, EbDOrdenes, EbDInventario, EbDGarantias, EbDPostventa, EbGDashboard, EbGRanking, EbGDemanda, OrderStepper, EbEmbarqueModal });
