/* Pólix — helpers, contexto y componentes compartidos */

/* ---------- Formato ---------- */
function fmtMoney(n, sign = "$") {
  if (n == null || n === "") return "—";
  return sign + " " + Math.round(n).toLocaleString("es-UY");
}
function fmtNum(n) { return (n == null) ? "—" : n.toLocaleString("es-UY"); }
function fmtDate(iso) {
  if (!iso) return "—";
  const [y, m, d] = iso.split("-");
  return `${d}/${m}/${y}`;
}
function fmtDateLong(iso) {
  if (!iso) return "—";
  const meses = ["enero","febrero","marzo","abril","mayo","junio","julio","agosto","setiembre","octubre","noviembre","diciembre"];
  const [y, m, d] = iso.split("-").map(Number);
  return `${d} de ${meses[m - 1]} de ${y}`;
}
function daysUntil(iso, hoy) {
  const a = new Date(hoy + "T00:00:00"), b = new Date(iso + "T00:00:00");
  return Math.round((b - a) / 86400000);
}
function nombreCompleto(c) { return c.empresa ? c.nombre : `${c.nombre} ${c.apellido}`.trim(); }

/* WhatsApp: arma link wa.me con código de país UY (598) */
function waLink(tel) {
  if (!tel) return null;
  let d = ("" + tel).replace(/\D/g, "");
  if (d.startsWith("0")) d = d.slice(1);
  if (!d.startsWith("598")) d = "598" + d;
  return "https://wa.me/" + d;
}

/* Fecha de hoy en largo con día de semana */
function fmtHoyLong(iso) {
  const dias = ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"];
  const d = new Date(iso + "T00:00:00");
  return `${dias[d.getDay()]} ${fmtDateLong(iso)}`;
}
function iniciales(c) {
  if (c.empresa) return c.nombre.slice(0, 2).toUpperCase();
  return ((c.nombre[0] || "") + (c.apellido[0] || "")).toUpperCase();
}

/* ---------- Exportación CSV (compatible con Excel en español) ----------
   Delimitador ';' + saltos '\r\n' + BOM, para que Excel-UY abra en columnas y filas. */
function downloadCSV(filename, headerArr, rowsArr) {
  const esc = (v) => { v = (v == null ? "" : "" + v); return /[";\n\r]/.test(v) ? '"' + v.replace(/"/g, '""') + '"' : v; };
  const lines = [headerArr.map(esc).join(";")].concat(rowsArr.map((r) => r.map(esc).join(";")));
  const blob = new Blob(["\ufeff" + lines.join("\r\n")], { type: "text/csv;charset=utf-8" });
  const a = document.createElement("a");
  a.href = URL.createObjectURL(blob);
  a.download = filename;
  document.body.appendChild(a); a.click(); a.remove();
}
const TIER_TO_CODE = { GLOBAL: "G", TOTAL: "G", SOA: "S", TRIPLE: "T" };
function polizaToRow(p, data) {
  const cli = data.clientes.find((c) => c.id === p.clienteId);
  const co = data.companias.find((c) => c.id === p.companiaId);
  const ramoLabel = window.POLIX_DATA.ramos[p.ramo]?.label || p.ramo;
  let tipoBien = ramoLabel, bien = ramoLabel;
  if (p.vehiculo) { tipoBien = p.vehiculo.tipoBien || "Automóvil"; bien = `${p.vehiculo.descripcion || (p.vehiculo.marca + " " + p.vehiculo.modelo)} ${p.vehiculo.anio || ""}`.trim(); }
  else if (p.objeto) bien = p.objeto.descripcion;
  else if (p.garantia) bien = p.garantia.inmueble;
  else if (p.hogar) bien = p.hogar.tipo;
  return [
    cli ? nombreCompleto(cli) : "", p.cobertura, co ? co.corto : "",
    p.anulada ? "AN" : (TIER_TO_CODE[p.tier] || ""), tipoBien, bien,
    p.inicio ? fmtDate(p.inicio) : "", (p.fin && !p.fin.startsWith("9999")) ? fmtDate(p.fin) : "",
    p.premio || "", p.total || "", p.cuotas || "", p.metodoPago || "",
  ];
}
function exportarPolizasCSV(polizas, data, nombre) {
  const header = window.POLIX_DATA.importCols.map((c) => c.label);
  const rows = polizas.map((p) => polizaToRow(p, data));
  downloadCSV(nombre || "polizas-polix.csv", header, rows);
}

/* ---------- Lógica de alertas de vencimiento ----------
   🔴 vencida o ≤7 días · 🟠 vence este mes (≤30) · 🔵 sin renovar (31-60) · 🟢 vigente */
function ventStatus(p, hoy) {
  if (p.anulada) return { key: "anulada", label: "Anulada", pill: "pill-neutral", days: 0 };
  if (p.mensual) {
    const d0 = daysUntil(p.fin, hoy);
    if (d0 < 0) return { key: "vencida", label: "Vencida", pill: "pill-danger", days: d0 };
    if (d0 <= 7) return { key: "critico", label: d0 === 0 ? "Vence hoy" : `Vence en ${d0}d`, pill: "pill-danger", days: d0 };
    return { key: "vigente", label: "Vigente (mensual)", pill: "pill-ok", days: d0 };
  }
  const d = daysUntil(p.fin, hoy);
  if (d < 0) return { key: "vencida", label: "Vencida", pill: "pill-danger", days: d };
  if (d <= 7) return { key: "critico", label: d === 0 ? "Vence hoy" : `Vence en ${d} día${d > 1 ? "s" : ""}`, pill: "pill-danger", days: d };
  if (d <= 30) return { key: "mes", label: "Vence este mes", pill: "pill-warn", days: d };
  if (d <= 60 && !p.renovada) return { key: "sinrenovar", label: "Sin renovar", pill: "pill-info", days: d };
  return { key: "vigente", label: "Vigente", pill: "pill-ok", days: d };
}

/* ---------- Contexto ---------- */
const AppCtx = React.createContext(null);
const useApp = () => React.useContext(AppCtx);

/* ---------- Componentes de presentación ---------- */
function Pill({ kind = "neutral", children, dot = true }) {
  return <span className={"pill pill-" + kind}>{dot && <span className="dot" />}{children}</span>;
}
function StatusPill({ poliza, hoy }) {
  const s = ventStatus(poliza, hoy);
  const k = s.pill.replace("pill-", "");
  return <span className={"pill " + s.pill}><span className="dot" />{s.label}</span>;
}
function CoLogo({ co, size = 26 }) {
  if (!co) return null;
  return (
    <span className="co-logo" style={{ background: co.color, width: size, height: size, fontSize: size * 0.36 }}>
      {co.corto.slice(0, 3).toUpperCase()}
    </span>
  );
}
function CoChip({ co }) {
  if (!co) return <span className="muted">—</span>;
  return <span className="co-chip"><CoLogo co={co} /><span className="cell-main">{co.corto}</span></span>;
}
function RamoTag({ ramo }) {
  const meta = window.POLIX_DATA.ramos[ramo];
  if (!meta) return null;
  return <span className="tag"><span className="swatch" style={{ background: meta.color }} />{meta.label}</span>;
}
function Avatar({ c, size = 34 }) {
  return <span className="avatar" style={{ width: size, height: size, fontSize: size * 0.38 }}>{iniciales(c)}</span>;
}

function StatCard({ icon, iconColor, iconBg, label, value, valueSize = 30, delta, deltaDir }) {
  return (
    <div className="stat">
      <div className="ico-wrap" style={{ background: iconBg, color: iconColor }}><Icon name={icon} size={20} /></div>
      <div className="label">{label}</div>
      <div className="value num" style={{ fontSize: valueSize, whiteSpace: "nowrap" }}>{value}</div>
      {delta != null && (
        <div className={"delta " + (deltaDir || "flat")}>
          {deltaDir === "up" && <Icon name="arrowUp" size={13} />}
          {deltaDir === "down" && <Icon name="arrowDown" size={13} />}
          {delta}
        </div>
      )}
    </div>
  );
}

function Empty({ icon = "search", title, sub, action }) {
  return (
    <div className="empty">
      <Icon name={icon} size={40} className="ico" stroke={1.5} />
      <div style={{ fontWeight: 700, color: "var(--text-soft)", fontSize: 15 }}>{title}</div>
      {sub && <div style={{ marginTop: 4 }}>{sub}</div>}
      {action && <div style={{ marginTop: 16 }}>{action}</div>}
    </div>
  );
}

/* Modal genérico */
function Modal({ title, sub, onClose, children, footer, wide }) {
  React.useEffect(() => {
    const h = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, []);
  return (
    <div className="overlay center" onMouseDown={onClose}>
      <div className="modal" style={wide ? { width: "min(820px, 94vw)" } : null} onMouseDown={(e) => e.stopPropagation()}>
        <div className="card-head between">
          <div>
            <h3>{title}</h3>
            {sub && <div className="sub">{sub}</div>}
          </div>
          <button className="iconbtn" onClick={onClose}><Icon name="x" /></button>
        </div>
        <div className="card-pad">{children}</div>
        {footer && <div className="drawer-foot" style={{ position: "static" }}>{footer}</div>}
      </div>
    </div>
  );
}

/* Drawer lateral (fichas/detalle) */
function Drawer({ onClose, head, children, footer }) {
  React.useEffect(() => {
    const h = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, []);
  return (
    <div className="overlay" onMouseDown={onClose}>
      <div className="drawer" onMouseDown={(e) => e.stopPropagation()}>
        <div className="drawer-head">{head}<button className="iconbtn" onClick={onClose} style={{ marginLeft: "auto" }}><Icon name="x" /></button></div>
        <div className="drawer-body">{children}</div>
        {footer && <div className="drawer-foot">{footer}</div>}
      </div>
    </div>
  );
}

Object.assign(window, {
  fmtMoney, fmtNum, fmtDate, fmtDateLong, fmtHoyLong, daysUntil, nombreCompleto, iniciales, ventStatus, waLink,
  downloadCSV, exportarPolizasCSV, polizaToRow,
  AppCtx, useApp, Pill, StatusPill, CoLogo, CoChip, RamoTag, Avatar, StatCard, Empty, Modal, Drawer,
});
