/* ============================================================
   SYMPHO · EB — Finanzas, Facturación (puente a Muluk), Etiquetas QR
   y Transferencias/permutas entre Dealers.
   ============================================================ */

// ---------------- gráfica de barras simple (reutilizable) ----------------
function EbBars({ data, hue = "var(--eb)", height = 180, fmt }) {
  const max = Math.max(...data.map(d => d.value)) || 1;
  return (
    <div className="eb-bars" style={{ height }}>
      {data.map((d, i) => (
        <div key={i} className="eb-bar-col">
          <span className="mono" style={{ fontSize: 10.5, color: "var(--text-3)" }}>{fmt ? fmt(d.value) : d.value}</span>
          <i style={{ height: Math.max((d.value / max) * (height - 44), 4) + "px", background: d.hue || hue }} />
          <span>{d.label}</span>
        </div>
      ))}
    </div>
  );
}

// ---------------- FINANZAS · Master Dealer ----------------
function EbFinanzas() {
  const m = window.EB_METRICS.master;
  const dealers = window.EB_DEALERS;
  const bars = dealers.map(d => ({ label: d.name.split(" ")[0], value: d.ventasMes }));
  const totalVentas = dealers.reduce((s, d) => s + d.ventasMes, 0);
  const totalUsado = dealers.reduce((s, d) => s + d.usado, 0);
  const totalVenc = dealers.reduce((s, d) => s + d.vencido, 0);
  return (
    <div className="canvas-in wide rise">
      <AppHead app="eb" title="Finanzas" sub="Resumen financiero consolidado de la red — ventas, utilidad y cartera" />
      <div className="grid-4" style={{ marginBottom: 16 }}>
        <Stat icon="dollar" label="Venta a la red (mes)" value={window.fmtK(m.ventaRedMes)} hue="var(--eb)" trend={6} />
        <Stat icon="trend" label="Ventas de la red (suma)" value={window.fmtK(totalVentas)} hue="var(--eb)" />
        <Stat icon="wallet" label="Línea utilizada" value={window.fmtK(totalUsado)} hue="var(--eb)" />
        <Stat icon="ext" label="Cartera vencida" value={window.fmtK(totalVenc)} hue="var(--bad)" sub="2 dealers requieren atención" />
      </div>
      <div className="grid-2" style={{ alignItems: "start", gridTemplateColumns: "minmax(0,1.4fr) minmax(0,1fr)" }}>
        <div className="card" style={{ padding: 20 }}>
          <Section title="Ventas por Dealer" sub="Este mes · MXN" style={{ marginBottom: 6 }} />
          <EbBars data={bars} hue="var(--eb)" fmt={window.fmtK} />
        </div>
        <div className="card" style={{ padding: 20 }}>
          <Section title="Utilidad consolidada" sub="Desglose porcentual" style={{ marginBottom: 14 }} />
          <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
            <Donut segments={m.utilidad} size={112} thickness={14} />
            <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 7 }}>
              {m.utilidad.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>
    </div>
  );
}

// ---------------- FINANZAS · Dealer ----------------
function EbDFinanzas() {
  const m = window.EB_METRICS.dealer;
  const bars = window.EB_VENDEDORES.map(v => ({ label: v.name, value: v.ventas, hue: v.hue }));
  const disp = m.creditoLinea - m.creditoUsado, pct = m.creditoUsado / m.creditoLinea * 100;
  return (
    <div className="canvas-in wide rise">
      <AppHead app="eb" title="Finanzas" sub="Resumen financiero de tu agencia — ventas, crédito e inventario" />
      <div className="grid-4" style={{ marginBottom: 16 }}>
        <Stat icon="dollar" label="Ventas del mes" value={window.fmtK(m.ventasMes)} hue="var(--eb)" trend={5} />
        <Stat icon="wallet" label="Crédito disponible" value={window.fmtK(disp)} hue="var(--eb)" />
        <Stat icon="warehouse" label="Inventario en piso" value={m.inventario} hue="var(--eb)" />
        <Stat icon="shield" label="Garantías activas" value={m.garantiasActivas} hue="var(--eb)" />
      </div>
      <div className="grid-2" style={{ alignItems: "start", gridTemplateColumns: "minmax(0,1.4fr) minmax(0,1fr)" }}>
        <div className="card" style={{ padding: 20 }}>
          <Section title="Ventas por vendedor" sub="Este mes · MXN" style={{ marginBottom: 6 }} />
          <EbBars data={bars} fmt={window.fmtK} />
        </div>
        <div className="card" style={{ padding: 20 }}>
          <Section title="Uso de línea de crédito" style={{ marginBottom: 14 }} />
          <div className="disp" style={{ fontSize: 24, fontWeight: 600 }}>{Math.round(pct)}%<span style={{ fontSize: 12.5, color: "var(--text-4)", fontFamily: "var(--ui)", fontWeight: 400 }}> utilizado</span></div>
          <div className="bar" style={{ marginTop: 12, height: 8 }}><i style={{ width: pct + "%", background: "var(--eb)" }} /></div>
          <div style={{ marginTop: 18, paddingTop: 14, borderTop: "1px solid var(--line)" }}>
            <Section title="Inventario" sub="Split por tipo" style={{ marginBottom: 12 }} />
            <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
              <Donut segments={m.inventarioSplit} size={92} thickness={12} />
              <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 6 }}>
                {m.inventarioSplit.map(s => (
                  <div key={s.estado} style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 11.5 }}>
                    <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>
      </div>
    </div>
  );
}

// ---------------- FACTURACIÓN — puente hacia Muluk ----------------
function EbFacturaBridge({ dealerScope }) {
  const nav = useNav();
  const inv = window.EB_INVOICES;
  const entrantes = inv.entrantes;
  const salientes = dealerScope ? inv.salientes.filter(s => s.receptor === window.EB_CTX.dealerActual) : inv.salientes;
  return (
    <>
      <div className="card" style={{ padding: 18, marginBottom: 18, display: "flex", alignItems: "center", gap: 14, borderColor: "color-mix(in oklch, var(--eb) 30%, var(--line))" }}>
        <span className="feed-ic" style={{ "--c": "var(--muluk)", width: 40, height: 40 }}><Icon name="receipt" size={19} /></span>
        <div style={{ flex: 1 }}>
          <b style={{ fontSize: 14 }}>El motor de facturación (CFDI) vive en Muluk</b>
          <p className="muted" style={{ fontSize: 12.5, marginTop: 3 }}>Eb muestra el estatus de facturación de la red; el timbrado, cancelación y envío al SAT se hacen desde Muluk.</p>
        </div>
        <button className="btn btn-primary" style={{ background: "var(--muluk)", color: "oklch(0.16 0.02 264)" }} onClick={() => nav.openApp("muluk")}>
          <Icon name="arrowupr" size={14} /> Ir a Muluk
        </button>
      </div>
      <div className="grid-2" style={{ alignItems: "start" }}>
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          <div className="card-head"><b style={{ fontSize: 14 }}>Facturas entrantes</b><span className="badge">{entrantes.length}</span></div>
          <table className="tbl">
            <thead><tr><th>Folio</th><th>Emisor</th><th>Concepto</th><th>Estado</th><th className="num">Monto</th></tr></thead>
            <tbody>
              {entrantes.map((r, i) => (
                <tr key={i}>
                  <td className="mono" style={{ color: "var(--text)", fontSize: 12 }}>{r.folio}</td>
                  <td style={{ color: "var(--text)", fontWeight: 500 }}>{r.emisor}</td>
                  <td className="muted" style={{ fontSize: 12.5 }}>{r.concepto}</td>
                  <td><Pill status={r.estado} /></td>
                  <td className="num">{window.fmtMoney(r.monto)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          <div className="card-head"><b style={{ fontSize: 14 }}>Facturas salientes</b><span className="badge">{salientes.length}</span></div>
          <table className="tbl">
            <thead><tr><th>Folio</th><th>Receptor</th><th>Concepto</th><th>Estado</th><th className="num">Monto</th></tr></thead>
            <tbody>
              {salientes.map((r, i) => (
                <tr key={i}>
                  <td className="mono" style={{ color: "var(--text)", fontSize: 12 }}>{r.folio}</td>
                  <td style={{ color: "var(--text)", fontWeight: 500 }}>{r.receptor}</td>
                  <td className="muted" style={{ fontSize: 12.5 }}>{r.concepto}</td>
                  <td><Pill status={r.estado} /></td>
                  <td className="num">{window.fmtMoney(r.monto)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}
function EbFacturacion() {
  return (
    <div className="canvas-in wide rise">
      <AppHead app="eb" title="Facturación" sub="Facturación electrónica entrantes y salientes de toda la red" />
      <EbFacturaBridge />
    </div>
  );
}
function EbDFacturacion() {
  return (
    <div className="canvas-in wide rise">
      <AppHead app="eb" title="Facturación" sub="Tus facturas del Master Dealer — el timbrado se realiza en Muluk" />
      <EbFacturaBridge dealerScope />
    </div>
  );
}

// ---------------- TRANSFERENCIA / PERMUTA de unidades entre Dealers ----------------
function EbTransferModal({ onClose }) {
  const dealers = window.EB_DEALERS;
  const [origen, setOrigen] = useState(dealers[0].name);
  const [destino, setDestino] = useState(dealers[1].name);
  const [item, setItem] = useState("");
  const [qty, setQty] = useState(1);
  const [permuta, setPermuta] = useState(false);
  const [itemB, setItemB] = useState("");
  const [done, setDone] = useState(false);

  function submit(e) {
    e.preventDefault();
    setDone(true);
  }
  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 }}>Transferir / permutar unidades</b>
          <button className="ic-btn" style={{ marginLeft: "auto" }} onClick={onClose}><Icon name="ext" size={15} /></button>
        </div>
        {done ? (
          <div style={{ padding: 28, textAlign: "center" }}>
            <Icon name="check" size={30} style={{ color: "var(--ok)" }} />
            <p style={{ marginTop: 12, fontSize: 14 }}>{permuta ? "Permuta registrada" : "Transferencia registrada"} entre <b>{origen}</b> y <b>{destino}</b>.</p>
            <button className="btn btn-sm" style={{ marginTop: 16 }} onClick={onClose}>Cerrar</button>
          </div>
        ) : (
          <form onSubmit={submit} style={{ padding: "16px 20px 20px", display: "flex", flexDirection: "column", gap: 14 }}>
            <div className="seg" onClick={() => setPermuta(v => !v)} style={{ cursor: "pointer" }}>
              <span className="seg-btn" data-on={!permuta}>Transferencia simple</span>
              <span className="seg-btn" data-on={permuta}>Permuta (2 vías)</span>
            </div>
            <div className="grid-2" style={{ gap: 10 }}>
              <div>
                <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>Dealer origen</label>
                <select className="field" value={origen} onChange={e => setOrigen(e.target.value)}>
                  {dealers.map(d => <option key={d.name} value={d.name}>{d.name}</option>)}
                </select>
              </div>
              <div>
                <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>Dealer destino</label>
                <select className="field" value={destino} onChange={e => setDestino(e.target.value)}>
                  {dealers.map(d => <option key={d.name} value={d.name}>{d.name}</option>)}
                </select>
              </div>
            </div>
            <div>
              <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>Unidad / modelo (VIN o modelo)</label>
              <input className="field" value={item} onChange={e => setItem(e.target.value)} placeholder="Ej. Vairo RS 400 Sport" required />
            </div>
            {permuta && (
              <div>
                <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>A cambio, {destino} entrega</label>
                <input className="field" value={itemB} onChange={e => setItemB(e.target.value)} placeholder="Ej. Kentaro Kargo 150" required />
              </div>
            )}
            <div>
              <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>Cantidad</label>
              <input className="field" type="number" min="1" value={qty} onChange={e => setQty(e.target.value)} style={{ width: 100 }} />
            </div>
            <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 6 }}>
              <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="route" size={13} /> Confirmar</button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

// ---------------- ALTA MANUAL — vehículo ----------------
function EbAddVehicleModal({ onClose, onAdd }) {
  const [f, setF] = useState({ vin: "", brand: "Vairo", model: "", year: 2026, color: "", price: "" });
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));
  function submit(e) {
    e.preventDefault();
    onAdd({ ...f });
    onClose();
  }
  return (
    <div className="cmd-overlay" onMouseDown={onClose}>
      <div className="cmd-panel" style={{ width: 480 }} onMouseDown={e => e.stopPropagation()}>
        <div className="cmd-input">
          <b style={{ fontSize: 14.5 }}>Agregar vehículo manualmente</b>
          <button className="ic-btn" style={{ marginLeft: "auto" }} onClick={onClose}><Icon name="ext" size={15} /></button>
        </div>
        <form onSubmit={submit} style={{ padding: "16px 20px 20px", display: "flex", flexDirection: "column", gap: 12 }}>
          <div>
            <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>VIN</label>
            <input className="field mono" value={f.vin} onChange={e => set("vin", e.target.value)} placeholder="Número de serie" required />
          </div>
          <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 }}>Modelo</label>
              <input className="field" value={f.model} onChange={e => set("model", e.target.value)} required />
            </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 }}>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 }}>Color</label>
              <input className="field" value={f.color} onChange={e => set("color", 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)} />
            </div>
          </div>
          <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 6 }}>
            <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} /> Agregar al inventario</button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ---------------- ALTA MANUAL — refacción ----------------
function EbAddPartModal({ onClose, onAdd }) {
  const [f, setF] = useState({ sku: "", name: "", marca: "Vairo", qty: 1, min: 10, price: "" });
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));
  function submit(e) {
    e.preventDefault();
    onAdd({ ...f });
    onClose();
  }
  return (
    <div className="cmd-overlay" onMouseDown={onClose}>
      <div className="cmd-panel" style={{ width: 480 }} onMouseDown={e => e.stopPropagation()}>
        <div className="cmd-input">
          <b style={{ fontSize: 14.5 }}>Agregar refacción manualmente</b>
          <button className="ic-btn" style={{ marginLeft: "auto" }} onClick={onClose}><Icon name="ext" size={15} /></button>
        </div>
        <form onSubmit={submit} style={{ padding: "16px 20px 20px", display: "flex", flexDirection: "column", gap: 12 }}>
          <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)} required />
            </div>
            <div>
              <label className="lbl" style={{ fontSize: 11.5, color: "var(--text-3)", display: "block", marginBottom: 5 }}>Marca</label>
              <select className="field" value={f.marca} onChange={e => set("marca", 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 }}>Cantidad</label>
              <input className="field" type="number" min="1" 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" min="0" 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)} />
            </div>
          </div>
          <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 6 }}>
            <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} /> Agregar al inventario</button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ---------------- UNIDADES por modelo: VIN/NS disponibles, o ubicaci\u00f3n en tr\u00e1nsito ----------------
function EbUnitsModal({ model, mode, onClose }) {
  const estadoWanted = mode === "stock" ? "Disponible" : "En tránsito";
  const rows = window.EB_CEDI.unidades.filter(u => u.brand === model.brand && u.model === model.model && u.estado === estadoWanted);
  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 }}>{model.brand} {model.model} — {mode === "stock" ? "unidades disponibles" : "unidades en tránsito"}</b>
          <button className="ic-btn" style={{ marginLeft: "auto" }} onClick={onClose}><Icon name="ext" size={15} /></button>
        </div>
        <div style={{ padding: "6px 20px 20px" }}>
          {rows.length === 0 && <p className="muted" style={{ fontSize: 12.5, padding: "16px 0" }}>No hay VIN serializados de muestra para este modelo en la demo — el conteo de {mode === "stock" ? model.stock : model.transit} unidades proviene del agregado de inventario.</p>}
          {rows.map((u, i) => (
            <div key={i} className="eb-units-modal-row">
              <span className="mono" style={{ fontSize: 12.5, color: "var(--eb)", flex: "none", width: 210 }}>{u.vin}</span>
              {mode === "stock" ? (
                <span className="muted" style={{ fontSize: 12.5 }}>{u.ubic}</span>
              ) : (
                <>
                  <span className="muted" style={{ fontSize: 12.5, flex: 1 }}>{u.ubic} · rumbo a {u.dealer}</span>
                  <span className="mono" style={{ fontSize: 11, color: "var(--text-4)" }}>{u.ultimoEscaneo}</span>
                </>
              )}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  EbBars, EbFinanzas, EbDFinanzas, EbFacturacion, EbDFacturacion, EbFacturaBridge,
  EbTransferModal, EbAddVehicleModal, EbAddPartModal, EbUnitsModal,
});
