/* ============================================================
   LIA · Componentes compartidos
   ============================================================ */
const { useState, useEffect, useRef } = React;
const D = window.LIA_DATA;

/* ---------- Iconos (línea, 1.6 stroke) ---------- */
function Icon({ name, size = 18, style }) {
  const s = { width: size, height: size, fill: "none", stroke: "currentColor", strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round", ...style };
  const paths = {
    inicio: <><path d="M3 10.5 12 3l9 7.5" /><path d="M5 9.5V21h14V9.5" /><path d="M9.5 21v-6h5v6" /></>,
    licitaciones: <><rect x="3.5" y="4.5" width="17" height="16" rx="2.5" /><path d="M8 3v3M16 3v3M3.5 9.5h17" /><path d="M7.5 13h5M7.5 16.5h8" /></>,
    analisis: <><path d="M12 3v3M12 18v3M4.2 7.2l2.1 2.1M17.7 14.7l2.1 2.1M3 12h3M18 12h3M4.2 16.8l2.1-2.1M17.7 9.3l2.1-2.1" /><circle cx="12" cy="12" r="3.2" /></>,
    documentos: <><path d="M6 3.5h8l4 4V20a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 6 20V5A1.5 1.5 0 0 1 6 3.5Z" /><path d="M13.5 3.5V8h4.5" /><path d="M9 13h6M9 16.5h6" /></>,
    ley: <><path d="M12 3v18M5 7h14M8 21h8" /><path d="M5 7 2.5 13a3 3 0 0 0 5 0L5 7ZM19 7l-2.5 6a3 3 0 0 0 5 0L19 7Z" /></>,
    creditos: <><ellipse cx="12" cy="6.5" rx="7.5" ry="3" /><path d="M4.5 6.5v5c0 1.66 3.36 3 7.5 3s7.5-1.34 7.5-3v-5" /><path d="M4.5 11.5v5c0 1.66 3.36 3 7.5 3s7.5-1.34 7.5-3v-5" /></>,
    search: <><circle cx="11" cy="11" r="7" /><path d="m20 20-3.2-3.2" /></>,
    clock: <><circle cx="12" cy="12" r="9" /><path d="M12 7.5V12l3 2" /></>,
    bell: <><path d="M18 8.5a6 6 0 1 0-12 0c0 6-2.5 7.5-2.5 7.5h17S18 14.5 18 8.5Z" /><path d="M10 19.5a2.2 2.2 0 0 0 4 0" /></>,
    upload: <><path d="M12 16V4M7.5 8.5 12 4l4.5 4.5" /><path d="M4 16v3a1.5 1.5 0 0 0 1.5 1.5h13A1.5 1.5 0 0 0 20 19v-3" /></>,
    plus: <><path d="M12 5v14M5 12h14" /></>,
    arrow: <><path d="M5 12h14M13 6l6 6-6 6" /></>,
    back: <><path d="M19 12H5M11 18l-6-6 6-6" /></>,
    check: <><path d="M5 12.5 10 17l9-10" /></>,
    spark: <><path d="M12 3l1.8 5.4L19 10l-5.2 1.6L12 17l-1.8-5.4L5 10l5.2-1.6L12 3Z" /></>,
    external: <><path d="M14 4h6v6M20 4l-9 9M18 13v5.5A1.5 1.5 0 0 1 16.5 20h-11A1.5 1.5 0 0 1 4 18.5v-11A1.5 1.5 0 0 1 5.5 6H11" /></>,
    filter: <><path d="M4 5h16l-6 7v6l-4 2v-8L4 5Z" /></>,
    alert: <><path d="M12 3 2.5 20h19L12 3Z" /><path d="M12 10v4.5M12 17.5h.01" /></>,
    download: <><path d="M12 4v11M7.5 10.5 12 15l4.5-4.5" /><path d="M5 19h14" /></>,
    dots: <><circle cx="5" cy="12" r="1.4" /><circle cx="12" cy="12" r="1.4" /><circle cx="19" cy="12" r="1.4" /></>,
    perfil: <><circle cx="12" cy="8" r="3.5"/><path d="M4 20c0-3.8 3.6-6.5 8-6.5s8 2.7 8 6.5"/></>,
  };
  return <svg viewBox="0 0 24 24" style={s}>{paths[name]}</svg>;
}

/* ---------- Badge de institución ---------- */
function InstBadge({ inst, size }) {
  const i = D.instituciones[inst];
  const st = { background: `linear-gradient(150deg, ${i.color}, ${shade(i.color, -28)})` };
  if (size) { st.width = size; st.height = size; st.fontSize = size * 0.28; }
  return <div className="inst-badge" style={st} title={i.nombre}>{i.sigla}</div>;
}
function shade(hex, amt) {
  const n = parseInt(hex.slice(1), 16);
  let r = (n >> 16) + amt, g = ((n >> 8) & 255) + amt, b = (n & 255) + amt;
  r = Math.max(0, Math.min(255, r)); g = Math.max(0, Math.min(255, g)); b = Math.max(0, Math.min(255, b));
  return `#${((r << 16) | (g << 8) | b).toString(16).padStart(6, "0")}`;
}

/* ---------- Anillo de match IA ---------- */
function MatchRing({ value, size = 36 }) {
  const col = value >= 85 ? "var(--success)" : value >= 75 ? "var(--accent-2)" : value >= 65 ? "var(--gold)" : "var(--muted)";
  return (
    <div className="match">
      <div className="ring" style={{ width: size, height: size, background: `conic-gradient(${col} ${value * 3.6}deg, rgba(96,165,250,0.12) 0)` }}>
        <div style={{ position: "absolute", inset: 3, borderRadius: "99px", background: "var(--surface)" }}></div>
        <span style={{ position: "relative", color: col }}>{value}</span>
      </div>
    </div>
  );
}

/* ---------- Estado label ---------- */
const ESTADO_LABEL = {
  nueva: "Nueva", analisis: "En análisis", preparando: "Preparando",
  presentada: "Presentada", adjudicada: "Adjudicada", perdida: "No adjudicada",
};
function Estado({ e }) {
  return <span className={"state " + e}>{ESTADO_LABEL[e]}</span>;
}

/* ---------- Días restantes ---------- */
function Plazo({ dias }) {
  if (dias < 0) return <span className="mono" style={{ fontSize: 12, color: "var(--muted)" }}>Cerrada</span>;
  const col = dias <= 7 ? "var(--danger)" : dias <= 14 ? "var(--gold)" : "var(--silver)";
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5, color: col, fontSize: 12, fontWeight: 600 }}>
      <Icon name="clock" size={13} />{dias} {dias === 1 ? "día" : "días"}
    </span>
  );
}

/* ---------- KPI card ---------- */
function Kpi({ label, value, sub, trend, accent, spark }) {
  return (
    <div className="card" style={{ position: "relative", overflow: "hidden" }}>
      <div style={{ fontSize: 11.5, color: "var(--muted)", textTransform: "uppercase", letterSpacing: ".09em", fontWeight: 600 }}>{label}</div>
      <div className="font-display" style={{ fontSize: 30, fontWeight: 800, marginTop: 10, letterSpacing: "-0.02em", color: accent || "var(--text)" }}>{value}</div>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 8 }}>
        {trend != null && (
          <span style={{ fontSize: 11.5, fontWeight: 700, color: trend >= 0 ? "var(--success)" : "var(--danger)", display: "inline-flex", alignItems: "center", gap: 3 }}>
            {trend >= 0 ? "▲" : "▼"} {Math.abs(trend)}%
          </span>
        )}
        <span style={{ fontSize: 11.5, color: "var(--muted)" }}>{sub}</span>
      </div>
      {spark && <Sparkline data={spark} color={accent || "var(--accent-2)"} />}
    </div>
  );
}
function Sparkline({ data, color }) {
  const w = 90, h = 30, max = Math.max(...data), min = Math.min(...data);
  const pts = data.map((d, i) => `${(i / (data.length - 1)) * w},${h - ((d - min) / (max - min || 1)) * h}`).join(" ");
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ position: "absolute", right: 16, bottom: 16, width: 90, height: 30, opacity: .55 }}>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

/* ---------- Tarjeta de licitación (con variantes de estilo) ---------- */
function LicCard({ lic, onOpen, variant }) {
  const i = D.instituciones[lic.inst];
  const v = variant || "completa";

  if (v === "minima") {
    return (
      <div className="card lic-card" onClick={() => onOpen(lic)} style={{ cursor: "pointer", display: "flex", alignItems: "center", gap: 14 }}>
        <InstBadge inst={lic.inst} />
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontWeight: 600, fontSize: 13.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{lic.titulo}</div>
          <div className="mono" style={{ fontSize: 11, color: "var(--muted)", marginTop: 3 }}>{lic.sicop}</div>
        </div>
        <div className="amt" style={{ fontSize: 14 }}>{D.fmtCRC(lic.monto)}</div>
        <MatchRing value={lic.match} size={32} />
        <Estado e={lic.estado} />
      </div>
    );
  }

  return (
    <div className="card lic-card fade-up" onClick={() => onOpen(lic)} style={{ cursor: "pointer", transition: "all .18s", display: "flex", flexDirection: "column", gap: 13 }}
      onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--border-hover)"; e.currentTarget.style.transform = "translateY(-2px)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.borderColor = ""; e.currentTarget.style.transform = ""; }}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 13 }}>
        <InstBadge inst={lic.inst} />
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 5 }}>
            <span className="chip" style={{ fontSize: 10 }}>{lic.modalidad}</span>
            {lic.analizado && <span className="tag" style={{ display: "inline-flex", alignItems: "center", gap: 4 }}><Icon name="spark" size={11} />Analizado</span>}
          </div>
          <div className="font-display" style={{ fontWeight: 700, fontSize: 15, lineHeight: 1.25, letterSpacing: "-0.01em" }}>{lic.titulo}</div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 6, color: "var(--muted)", fontSize: 11.5 }}>
            <span>{i.sigla}</span><span style={{ opacity: .4 }}>·</span>
            <span className="mono">{lic.sicop}</span>
          </div>
        </div>
        <MatchRing value={lic.match} />
      </div>

      {v === "completa" && (
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          {lic.tags.map((t, k) => <span key={k} className="tag">{t}</span>)}
        </div>
      )}

      <hr className="divider" style={{ margin: "3px 0" }} />
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div>
          <div style={{ fontSize: 10.5, color: "var(--muted)", textTransform: "uppercase", letterSpacing: ".08em" }}>Monto estimado</div>
          <div className="amt" style={{ fontSize: 17, marginTop: 2 }}>{D.fmtCRC(lic.monto)}</div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div style={{ marginBottom: 6 }}><Estado e={lic.estado} /></div>
          <Plazo dias={lic.diasRestantes} />
        </div>
      </div>
    </div>
  );
}

/* ---------- Barra de progreso ---------- */
function Bar({ value, color = "var(--accent-2)", h = 7 }) {
  return (
    <div style={{ height: h, borderRadius: 99, background: "rgba(96,165,250,0.1)", overflow: "hidden" }}>
      <div style={{ height: "100%", width: value + "%", borderRadius: 99, background: color, transition: "width .6s cubic-bezier(.2,.8,.2,1)" }}></div>
    </div>
  );
}

/* ---------- Empty / placeholder de imagen ---------- */
function ImgSlot({ label, h = 160 }) {
  return (
    <div style={{
      height: h, borderRadius: "var(--r-md)",
      background: "repeating-linear-gradient(135deg, rgba(96,165,250,0.05) 0 10px, rgba(96,165,250,0.02) 10px 20px)",
      border: "1px dashed var(--border-2)", display: "grid", placeItems: "center",
    }}>
      <span className="mono" style={{ fontSize: 11, color: "var(--muted)" }}>{label}</span>
    </div>
  );
}

Object.assign(window, { Icon, InstBadge, MatchRing, Estado, Plazo, Kpi, Sparkline, LicCard, Bar, ImgSlot, ESTADO_LABEL, shade });
