/* ============================================================
   INside — Calculadora de CBM
   Sub-módulo de Logística
   ============================================================ */

// ── Tablas de referencia ─────────────────────────────────────

const CBM_DENSIDAD = {
  aluminio: 2700,
  vidrio:   2500,
  acero:    7850,
  mdf:      720,
  hpl:      1400,
  pet:      215,
  otros:    500,
};

const CBM_EMBALAJE = {
  aluminio: "Paquete flejado",
  vidrio:   "Rack de madera",
  acero:    "Pallet",
  mdf:      "Pallet",
  hpl:      "Pallet",
  pet:      "Pallet",
  otros:    "Caja de cartón",
};

// Holgura del embalaje por material [L, W, H] en mm
const CBM_TOL = {
  aluminio: [50,  80,  100],
  vidrio:   [100, 150, 200],
  acero:    [80,  80,  60 ],
  mdf:      [100, 100, 60 ],
  hpl:      [100, 100, 60 ],
  pet:      [100, 100, 80 ],
  otros:    [40,  40,  40 ],
};

// % extra que pesa el embalaje sobre el producto
const CBM_PKG_PCT = {
  aluminio: 0.05,
  vidrio:   0.18,
  acero:    0.05,
  mdf:      0.08,
  hpl:      0.08,
  pet:      0.10,
  otros:    0.12,
};

const MATERIAL_OPTS = [
  { value: "",         label: "Detectar automático" },
  { value: "aluminio", label: "Aluminio" },
  { value: "vidrio",   label: "Vidrio" },
  { value: "mdf",      label: "MDF / Melamina" },
  { value: "hpl",      label: "HPL / Laminado" },
  { value: "pet",      label: "PET Acústico / Foam" },
  { value: "acero",    label: "Acero / Metal" },
  { value: "otros",    label: "Otro" },
];

// ── Lógica ───────────────────────────────────────────────────

function detectarMat(nombre, matForzado) {
  if (matForzado) return matForzado;
  const s = (nombre || "").toLowerCase();
  if (/alum|perfil/.test(s))            return "aluminio";
  if (/vidr|glass|crista|mampara/.test(s)) return "vidrio";
  if (/acer|steel|hierr/.test(s))       return "acero";
  if (/mdf|melam/.test(s))              return "mdf";
  if (/hpl|lamin/.test(s))              return "hpl";
  if (/pet|acus|foam|felt|panel/.test(s)) return "pet";
  return "otros";
}

function calcItem(it) {
  const qty = Math.max(1, parseFloat(it.qty) || 1);
  const L   = parseFloat(it.largo) || 0;   // mm
  const W   = parseFloat(it.ancho) || 0;   // mm
  const H   = parseFloat(it.alto)  || 0;   // mm
  if (!L || !W || !H) return null;

  const mat = detectarMat(it.nombre, it.mat);
  const tol = CBM_TOL[mat];

  // Aluminio: apilar hasta 20 perfiles por paquete flejado
  let numBultos, stackH;
  if (mat === "aluminio") {
    const porBulto = 20;
    numBultos = Math.ceil(qty / porBulto);
    stackH    = H * Math.min(qty, porBulto);
  } else {
    // Resto: un solo pallet/caja apilando todo
    numBultos = 1;
    stackH    = H * qty;
  }

  const pkgL = (L + tol[0]) / 1000;   // m
  const pkgW = (W + tol[1]) / 1000;
  const pkgH = (stackH + tol[2]) / 1000;

  const cbmBulto = pkgL * pkgW * pkgH;
  const cbmTotal = parseFloat((cbmBulto * numBultos).toFixed(4));

  // Peso
  const volProd  = (L / 1000) * (W / 1000) * (H / 1000) * qty;
  const pesoNeto = parseFloat((volProd * CBM_DENSIDAD[mat]).toFixed(1));
  const pesoBruto = parseFloat((pesoNeto * (1 + CBM_PKG_PCT[mat])).toFixed(1));

  return {
    mat,
    embalaje: CBM_EMBALAJE[mat],
    pkgDims: `${(pkgL * 100).toFixed(0)}×${(pkgW * 100).toFixed(0)}×${(pkgH * 100).toFixed(0)} cm`,
    numBultos,
    cbmTotal,
    pesoNeto,
    pesoBruto,
    estimado: !it.mat,   // true si el material fue auto-detectado
  };
}

// ── Componente ────────────────────────────────────────────────

function CbmCalculator() {
  const uid = () => Math.random().toString(36).slice(2);
  const emptyItem = () => ({ id: uid(), nombre: "", mat: "", qty: "1", largo: "", ancho: "", alto: "" });

  const [items,  setItems]  = React.useState([emptyItem()]);
  const [copied, setCopied] = React.useState(false);

  const setField = (id, patch) =>
    setItems(prev => prev.map(it => it.id === id ? { ...it, ...patch } : it));
  const remove = (id) => setItems(prev => prev.filter(it => it.id !== id));
  const add    = ()   => setItems(prev => [...prev, emptyItem()]);
  const reset  = ()   => setItems([emptyItem()]);

  const rows = items.map(it => ({ ...it, calc: calcItem(it) }));
  const withCalc = rows.filter(r => r.calc);

  const cbmTotal      = withCalc.reduce((s, r) => s + r.calc.cbmTotal, 0);
  const pesoNetoTotal = withCalc.reduce((s, r) => s + r.calc.pesoNeto, 0);
  const pesoBrutoTotal = withCalc.reduce((s, r) => s + r.calc.pesoBruto, 0);
  const bultosTotal   = withCalc.reduce((s, r) => s + r.calc.numBultos, 0);
  const hayEstimados  = withCalc.some(r => r.calc.estimado);

  const copiarResumen = () => {
    const lineas = [
      `── RESUMEN LOGÍSTICO ──`,
      `CBM Total:   ${cbmTotal.toFixed(3)} m³`,
      `Peso Neto:   ${pesoNetoTotal.toFixed(1)} kg`,
      `Peso Bruto:  ${pesoBrutoTotal.toFixed(1)} kg`,
      `Bultos:      ${bultosTotal}`,
      "",
      ...withCalc.map(r =>
        `• ${r.nombre || "Producto"}: ${r.calc.cbmTotal.toFixed(3)} m³ | ${r.calc.embalaje} | ${r.calc.pkgDims} | ${r.calc.pesoBruto.toFixed(1)} kg bruto`
      ),
    ].join("\n");
    navigator.clipboard.writeText(lineas).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2500);
    });
  };

  const INP = { padding: "5px 8px", fontSize: 12, width: "100%", boxSizing: "border-box" };

  return (
    <div style={{ padding: "28px 32px 80px" }}>

      {/* encabezado */}
      <div style={{ marginBottom: 24 }}>
        <div className="eyebrow">Logística · Sub-módulo</div>
        <h1 className="page-title" style={{ marginBottom: 6 }}>Calculadora CBM</h1>
        <p style={{ fontSize: 13, color: "var(--muted)", margin: 0, maxWidth: 640 }}>
          Ingresa las dimensiones de cada producto (en mm) para obtener el volumen de carga,
          peso estimado y tipo de embalaje — lista para solicitar cotización de flete.
        </p>
      </div>

      {/* tabla de entrada */}
      <window.Card pad={0} style={{ overflow: "hidden", marginBottom: 20 }}>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 820 }}>
            <thead>
              <tr style={{ background: "var(--surface-2)" }}>
                {[
                  ["Producto / descripción", "left",  220],
                  ["Material",               "left",  150],
                  ["Cant.",                  "right",  60],
                  ["Largo (mm)",             "right",  95],
                  ["Ancho (mm)",             "right",  95],
                  ["Alto / Esp. (mm)",       "right",  105],
                  ["",                       "center",  36],
                ].map(([h, align, w], i) => (
                  <th key={i} style={{ padding: "10px 10px", fontSize: 11, fontWeight: 700,
                    color: "var(--muted)", textAlign: align, width: w, whiteSpace: "nowrap" }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {items.map((it) => (
                <tr key={it.id} style={{ borderTop: "1px solid var(--border)" }}>
                  <td style={{ padding: "8px 10px" }}>
                    <input className="inp" style={INP} placeholder="Ej: Perfil aluminio T-60"
                      value={it.nombre} onChange={e => setField(it.id, { nombre: e.target.value })} />
                  </td>
                  <td style={{ padding: "8px 10px" }}>
                    <select className="inp" style={{ ...INP, cursor: "pointer" }}
                      value={it.mat} onChange={e => setField(it.id, { mat: e.target.value })}>
                      {MATERIAL_OPTS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                    </select>
                  </td>
                  <td style={{ padding: "8px 10px" }}>
                    <input className="inp" style={{ ...INP, textAlign: "right" }}
                      type="number" min="1" value={it.qty}
                      onChange={e => setField(it.id, { qty: e.target.value })} />
                  </td>
                  {["largo","ancho","alto"].map(dim => (
                    <td key={dim} style={{ padding: "8px 10px" }}>
                      <input className="inp" style={{ ...INP, textAlign: "right" }}
                        type="number" min="0" step="1" placeholder="mm"
                        value={it[dim]} onChange={e => setField(it.id, { [dim]: e.target.value })} />
                    </td>
                  ))}
                  <td style={{ padding: "8px 10px", textAlign: "center" }}>
                    {items.length > 1 && (
                      <button className="iconbtn danger" title="Eliminar" onClick={() => remove(it.id)}>
                        <window.Icon name="trash" size={14} />
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div style={{ padding: "10px 14px", borderTop: "1px solid var(--border)", display: "flex", gap: 10 }}>
          <window.Btn variant="outline" icon="plus" onClick={add}>Agregar producto</window.Btn>
          {items.length > 1 && (
            <window.Btn variant="ghost" onClick={reset}>Limpiar todo</window.Btn>
          )}
        </div>
      </window.Card>

      {/* resultados */}
      {withCalc.length > 0 && (
        <>
          {/* tabla de resultados */}
          <window.Card pad={0} style={{ overflow: "hidden", marginBottom: 16 }}>
            <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--border)",
              display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <span style={{ fontWeight: 700, fontSize: 13 }}>Resultados del cálculo</span>
              {hayEstimados && (
                <span style={{ fontSize: 11, color: "var(--gold)", background: "var(--gold-dim)",
                  padding: "2px 10px", borderRadius: 99, border: "1px solid var(--gold-dim)" }}>
                  ⚠ Material auto-detectado — verificar
                </span>
              )}
            </div>
            <div style={{ overflowX: "auto" }}>
              <table className="hist-table">
                <thead><tr>
                  <th>Producto</th>
                  <th>Material</th>
                  <th>Embalaje</th>
                  <th>Dims. embalaje</th>
                  <th style={{ textAlign: "center" }}>Bultos</th>
                  <th style={{ textAlign: "right" }}>CBM</th>
                  <th style={{ textAlign: "right" }}>Peso neto</th>
                  <th style={{ textAlign: "right" }}>Peso bruto</th>
                </tr></thead>
                <tbody>
                  {rows.map(r => {
                    if (!r.calc) return (
                      <tr key={r.id} className="hist-row">
                        <td style={{ fontWeight: 600, color: "var(--muted)" }}>
                          {r.nombre || <em>Sin nombre</em>}
                        </td>
                        <td colSpan={7} style={{ color: "var(--muted)", fontSize: 11, fontStyle: "italic" }}>
                          Completa Largo, Ancho y Alto para calcular
                        </td>
                      </tr>
                    );
                    return (
                      <tr key={r.id} className="hist-row">
                        <td style={{ fontWeight: 600 }}>{r.nombre || "—"}</td>
                        <td style={{ textTransform: "capitalize", color: "var(--muted)" }}>
                          {r.calc.mat}
                          {r.calc.estimado && <span title="Auto-detectado" style={{ marginLeft: 4, opacity: .5 }}>*</span>}
                        </td>
                        <td style={{ fontSize: 12 }}>{r.calc.embalaje}</td>
                        <td style={{ fontFamily: "var(--mono)", fontSize: 11 }}>{r.calc.pkgDims}</td>
                        <td style={{ fontFamily: "var(--mono)", textAlign: "center" }}>{r.calc.numBultos}</td>
                        <td style={{ fontFamily: "var(--mono)", textAlign: "right", fontWeight: 700, color: "var(--gold)" }}>
                          {r.calc.cbmTotal.toFixed(3)} m³
                        </td>
                        <td style={{ fontFamily: "var(--mono)", textAlign: "right" }}>
                          {r.calc.pesoNeto.toFixed(1)} kg
                        </td>
                        <td style={{ fontFamily: "var(--mono)", textAlign: "right" }}>
                          {r.calc.pesoBruto.toFixed(1)} kg
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </window.Card>

          {/* KPIs totales */}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 20 }}>
            {[
              { label: "CBM Total",    value: cbmTotal.toFixed(3) + " m³",      gold: true },
              { label: "Peso Neto",    value: pesoNetoTotal.toFixed(1) + " kg"            },
              { label: "Peso Bruto",   value: pesoBrutoTotal.toFixed(1) + " kg"           },
              { label: "Total Bultos", value: String(bultosTotal)                         },
            ].map(({ label, value, gold }) => (
              <window.Card key={label} style={{ textAlign: "center" }}>
                <div style={{ fontSize: 10, color: "var(--muted)", marginBottom: 6,
                  textTransform: "uppercase", letterSpacing: ".08em" }}>{label}</div>
                <div style={{ fontFamily: "var(--mono)", fontWeight: 800, fontSize: 22,
                  color: gold ? "var(--gold)" : "var(--text)" }}>{value}</div>
              </window.Card>
            ))}
          </div>

          {/* acciones */}
          <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
            <window.Btn variant="gold" onClick={copiarResumen}>
              {copied ? "✓ Copiado al portapapeles" : "Copiar resumen"}
            </window.Btn>
          </div>
          {hayEstimados && (
            <p style={{ fontSize: 11, color: "var(--muted)", marginTop: 10 }}>
              * El material fue detectado automáticamente desde el nombre del producto.
              Selecciona el material manualmente para mayor precisión.
            </p>
          )}
          <p style={{ fontSize: 11, color: "var(--muted)", marginTop: 6 }}>
            Los pesos se estiman por densidad estándar del material + peso del embalaje.
            Para vidrio, aluminio y paquetes flejados se aplican holguras industriales de exportación.
          </p>
        </>
      )}

      {withCalc.length === 0 && items.length > 0 && (
        <div style={{ textAlign: "center", padding: "48px 0", color: "var(--muted)" }}>
          <div style={{ fontSize: 32, marginBottom: 12 }}>📦</div>
          <div style={{ fontWeight: 700, marginBottom: 4 }}>Ingresa las dimensiones</div>
          <div style={{ fontSize: 13 }}>Completa Largo, Ancho y Alto de al menos un producto para ver el cálculo.</div>
        </div>
      )}
    </div>
  );
}

window.CbmCalculator = CbmCalculator;
