/* Pólix — Comparador / multicotizador de aseguradoras */
function Comparador() {
  const { data, t } = useApp();
  const { companias } = data;
  const meta = window.POLIX_DATA.beneficiosMeta;

  const compsVeh = companias.filter((c) => c.ramos.includes("vehiculos"));
  const [sel, setSel] = React.useState(compsVeh.slice(0, 3).map((c) => c.id));
  // cobertura elegida por compañía (default: la más completa = primera)
  const [cobSel, setCobSel] = React.useState(() => {
    const o = {}; compsVeh.forEach((c) => { o[c.id] = (c.coberturas.find((cb) => cb.ramo === "vehiculos") || {}).nombre; }); return o;
  });
  const [veh, setVeh] = React.useState({ modelo: "", anio: "", valor: "" });

  const toggle = (id) => setSel((s) => s.includes(id) ? s.filter((x) => x !== id) : [...s, id].slice(-4));

  // columnas activas con su cobertura
  const cols = sel.map((id) => {
    const co = companias.find((c) => c.id === id);
    const cb = co.coberturas.find((x) => x.nombre === cobSel[id] && x.ramo === "vehiculos") || co.coberturas.find((x) => x.ramo === "vehiculos");
    return { co, cb };
  }).filter((c) => c.cb);

  // mejor valor por métrica
  const numify = (v) => v === "Ilimitado" || v === "Ilimitada" ? Infinity : (typeof v === "number" ? v : (v === true ? 1 : 0));
  const bestPrice = Math.min(...cols.map((c) => c.cb.precioMensual));
  const bestOf = (key) => Math.max(...cols.map((c) => numify(c.cb.beneficios[key])));

  const cardMode = t.comparadorStyle === "tarjetas";

  return (
    <div className="view-in">
      {/* parámetros de cotización */}
      <div className="card card-pad" style={{ marginBottom: 18 }}>
        <div className="between wrap" style={{ gap: 16 }}>
          <div className="row wrap" style={{ gap: 14, alignItems: "flex-end" }}>
            <div className="field" style={{ width: 200 }}><label>Vehículo a cotizar</label><input className="input" value={veh.modelo} onChange={(e) => setVeh({ ...veh, modelo: e.target.value })} placeholder="Ej. Toyota Corolla" /></div>
            <div className="field" style={{ width: 100 }}><label>Año</label><input className="input num" value={veh.anio} onChange={(e) => setVeh({ ...veh, anio: e.target.value })} placeholder="2023" /></div>
            <div className="field" style={{ width: 150 }}><label>Valor (USD)</label><input className="input num" value={veh.valor} onChange={(e) => setVeh({ ...veh, valor: e.target.value })} placeholder="25.000" /></div>
          </div>
          <div className="row" style={{ gap: 8 }}>
            <button className="btn btn-ghost"><Icon name="print" size={15} />PDF</button>
            <button className="btn btn-primary"><Icon name="sparkle" size={15} />Cotizar ({sel.length})</button>
          </div>
        </div>
        <div className="divider" style={{ margin: "18px 0 16px" }} />
        <div className="between wrap" style={{ gap: 10 }}>
          <div>
            <div className="row" style={{ gap: 8, marginBottom: 10 }}>
              <span style={{ fontSize: 12, fontWeight: 800, textTransform: "uppercase", letterSpacing: "0.05em", color: "var(--primary-strong)" }}>Compañías a comparar</span>
              <span className="muted" style={{ fontSize: 12 }}>hasta 4</span>
            </div>
            <div className="chips">
              {compsVeh.map((c) => (
                <button key={c.id} className={"chip" + (sel.includes(c.id) ? " on" : "")} onClick={() => toggle(c.id)} style={sel.includes(c.id) ? { background: c.color, borderColor: c.color } : null}>
                  {c.corto}
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>

      {cols.length < 2 && <Empty icon="compare" title="Elegí al menos 2 compañías" sub="Seleccioná aseguradoras arriba para ver el cuadro comparativo." />}

      {cols.length >= 2 && !cardMode && (
        <div className="card" style={{ overflow: "hidden" }}>
          <div className="table-wrap">
            <table className="tbl cmp">
              <thead>
                <tr>
                  <th style={{ minWidth: 190 }}>Beneficio</th>
                  {cols.map(({ co, cb }) => (
                    <th key={co.id} style={{ minWidth: 170, textAlign: "center", verticalAlign: "top", paddingTop: 14, paddingBottom: 14 }}>
                      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
                        <CoLogo co={co} size={34} />
                        <div style={{ fontWeight: 800, fontSize: 13, color: "var(--text)" }}>{co.corto}</div>
                        <select className="select" style={{ fontSize: 12, padding: "5px 26px 5px 9px", textTransform: "none", letterSpacing: 0, fontWeight: 600 }}
                          value={cobSel[co.id]} onChange={(e) => setCobSel({ ...cobSel, [co.id]: e.target.value })}>
                          {co.coberturas.filter((x) => x.ramo === "vehiculos").map((x) => <option key={x.nombre} value={x.nombre}>{x.nombre}</option>)}
                        </select>
                      </div>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                <tr style={{ background: "var(--primary-soft)" }}>
                  <td className="strong">Precio mensual</td>
                  {cols.map(({ co, cb }) => (
                    <td key={co.id} style={{ textAlign: "center" }}>
                      <div className="num" style={{ fontWeight: 800, fontSize: 18, color: cb.precioMensual === bestPrice ? "var(--ok)" : "var(--text)" }}>{fmtMoney(cb.precioMensual)}</div>
                      {cb.precioMensual === bestPrice && <Pill kind="ok" dot={false}>Mejor precio</Pill>}
                    </td>
                  ))}
                </tr>
                {meta.map((m) => (
                  <tr key={m.key}>
                    <td className="strong">{m.label}</td>
                    {cols.map(({ co, cb }) => {
                      const v = cb.beneficios[m.key];
                      const isBest = m.tipo !== "texto" && numify(v) === bestOf(m.key) && bestOf(m.key) > 0 && cols.length > 1;
                      return (
                        <td key={co.id} style={{ textAlign: "center", background: isBest ? "var(--ok-bg)" : "transparent" }}>
                          <CmpVal v={v} tipo={m.tipo} best={isBest} />
                        </td>
                      );
                    })}
                  </tr>
                ))}
                <tr>
                  <td></td>
                  {cols.map(({ co }) => <td key={co.id} style={{ textAlign: "center" }}><button className="btn btn-soft btn-sm">Seleccionar</button></td>)}
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      )}

      {cols.length >= 2 && cardMode && (
        <div className="grid" style={{ gridTemplateColumns: `repeat(${cols.length}, 1fr)`, gap: 16 }}>
          {cols.map(({ co, cb }) => {
            const winner = cb.precioMensual === bestPrice;
            return (
              <div key={co.id} className="card" style={{ overflow: "hidden", border: winner ? "2px solid var(--ok)" : "1px solid var(--border)", position: "relative" }}>
                {winner && <div style={{ position: "absolute", top: 0, right: 0, background: "var(--ok)", color: "#fff", fontSize: 11, fontWeight: 700, padding: "3px 12px", borderBottomLeftRadius: 10 }}>Mejor precio</div>}
                <div style={{ height: 6, background: co.color }} />
                <div className="card-pad" style={{ textAlign: "center" }}>
                  <CoLogo co={co} size={40} />
                  <div style={{ fontWeight: 800, marginTop: 8 }}>{co.corto}</div>
                  <select className="select" style={{ margin: "8px 0", fontSize: 12.5 }} value={cobSel[co.id]} onChange={(e) => setCobSel({ ...cobSel, [co.id]: e.target.value })}>
                    {co.coberturas.filter((x) => x.ramo === "vehiculos").map((x) => <option key={x.nombre} value={x.nombre}>{x.nombre}</option>)}
                  </select>
                  <div className="num" style={{ fontWeight: 800, fontSize: 28, color: "var(--primary-strong)" }}>{fmtMoney(cb.precioMensual)}</div>
                  <div className="cell-sub" style={{ marginBottom: 14 }}>por mes</div>
                </div>
                <div style={{ padding: "0 var(--card-pad) var(--card-pad)" }}>
                  {meta.map((m) => (
                    <div key={m.key} className="row" style={{ justifyContent: "space-between", gap: 10, alignItems: "center", padding: "8px 0", borderTop: "1px solid var(--border)", fontSize: 12.5 }}>
                      <span className="muted" style={{ flex: 1 }}>{m.label}</span><CmpVal v={cb.beneficios[m.key]} tipo={m.tipo} compact />
                    </div>
                  ))}
                  <button className="btn btn-primary btn-sm" style={{ width: "100%", marginTop: 14 }}>Seleccionar</button>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

function CmpVal({ v, tipo, best, compact }) {
  if (tipo === "bool") return v ? <Icon name="checkCircle" size={18} className="yes" /> : <Icon name="xCircle" size={17} className="no" />;
  if (v == null || v === 0) return <span className="no">—</span>;
  let txt = v;
  if (tipo === "moneda") txt = compact && v >= 1e6 ? "$ " + (v / 1e6).toLocaleString("es-UY", { maximumFractionDigits: 1 }) + " M" : fmtMoney(v);
  else if (tipo === "dias") txt = v + " días";
  else if (tipo === "cantidad") txt = v;
  return <span className="num" style={{ fontWeight: 700, whiteSpace: "nowrap", textAlign: "right", color: best ? "var(--ok)" : "var(--text)" }}>{txt}</span>;
}

window.Comparador = Comparador;
