/* =====================================================================
   ui.jsx — primitivas visuales del Cotizador (Sell-U Design System).
   OptionCard (single), CheckCard (multi), CompactChoice, Tooltip, Modal,
   Icon, Eyebrow. Todas atan a window al final.
   ===================================================================== */
const { useState: useStateUI, useEffect: useEffectUI, useRef: useRefUI, useCallback: useCbUI } = React;

/* Icono Lucide por nombre — usa la fuente UMD cargada en la página. */
function Icon({ name, size = 20, color = "currentColor", strokeWidth = 1.5, style }) {
  const ref = useRefUI(null);
  useEffectUI(() => {
    if (ref.current && window.lucide) {
      ref.current.innerHTML = "";
      const el = document.createElement("i");
      el.setAttribute("data-lucide", name);
      ref.current.appendChild(el);
      try {
        window.lucide.createIcons({
          attrs: { width: size, height: size, "stroke-width": strokeWidth, stroke: color },
          nameAttr: "data-lucide",
        });
      } catch (e) {}
    }
  }, [name, size, color, strokeWidth]);
  return <span ref={ref} aria-hidden="true" style={Object.assign({ display: "inline-flex", lineHeight: 0 }, style)} />;
}

/* Eyebrow label */
function Eyebrow({ children, style }) {
  return (
    <div style={Object.assign({
      fontSize: 12, fontWeight: 600, letterSpacing: "0.12em",
      textTransform: "uppercase", color: "var(--fg-tertiary)",
    }, style)}>{children}</div>
  );
}

/* Tooltip informativo accesible (para términos técnicos) */
function Tooltip({ text, label }) {
  const [open, setOpen] = useStateUI(false);
  return (
    <span style={{ position: "relative", display: "inline-flex", verticalAlign: "middle" }}>
      <button
        type="button"
        aria-label={label || "Más información"}
        onMouseEnter={() => setOpen(true)}
        onMouseLeave={() => setOpen(false)}
        onFocus={() => setOpen(true)}
        onBlur={() => setOpen(false)}
        onClick={(e) => { e.preventDefault(); e.stopPropagation(); setOpen(o => !o); }}
        style={{
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          width: 18, height: 18, borderRadius: 999, border: "1px solid var(--border-strong)",
          background: "var(--white)", color: "var(--fg-tertiary)", cursor: "help", padding: 0,
          marginLeft: 6, flex: "none",
        }}
      >
        <Icon name="info" size={11} strokeWidth={2} />
      </button>
      {open && (
        <span role="tooltip" style={{
          position: "absolute", bottom: "calc(100% + 8px)", left: "50%", transform: "translateX(-50%)",
          width: 220, background: "var(--navy-900)", color: "var(--paper)", fontSize: 12.5,
          lineHeight: "18px", fontWeight: 400, padding: "10px 12px", borderRadius: "var(--radius-md)",
          boxShadow: "var(--shadow-lg)", zIndex: 80, textTransform: "none", letterSpacing: 0,
          textAlign: "left",
        }}>{text}</span>
      )}
    </span>
  );
}

/* Tarjeta de opción single-select (grande). */
function OptionCard({ selected, onClick, icon, title, desc, badge, tone, density, disabled }) {
  const [hover, setHover] = useStateUI(false);
  const pad = density === "compact" ? "16px 16px" : density === "comfy" ? "24px 22px" : "20px 20px";
  const accent = tone === "accent";
  const borderColor = selected ? (accent ? "var(--accent-500)" : "var(--navy-700)") : (hover ? "var(--border-strong)" : "var(--border-default)");
  return (
    <button
      type="button"
      role="radio"
      aria-checked={selected}
      disabled={disabled}
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        textAlign: "left", width: "100%", cursor: disabled ? "not-allowed" : "pointer",
        background: selected ? (accent ? "var(--accent-50)" : "var(--white)") : (hover && !disabled ? "var(--bg-subtle)" : "var(--white)"),
        border: "1.5px solid " + borderColor,
        borderRadius: "var(--radius-lg)", padding: pad,
        boxShadow: selected ? "var(--shadow-md)" : (hover && !disabled ? "var(--shadow-md)" : "var(--shadow-sm)"),
        display: "flex", gap: 14, alignItems: "flex-start",
        transition: "background 200ms var(--ease-out), box-shadow 200ms var(--ease-out), border-color 200ms var(--ease-out)",
        opacity: disabled ? 0.55 : 1, position: "relative", fontFamily: "var(--font-sans)",
      }}
    >
      {icon && (
        <span style={{
          flex: "none", width: 40, height: 40, borderRadius: "var(--radius-md)",
          display: "flex", alignItems: "center", justifyContent: "center",
          background: selected ? (accent ? "var(--accent-500)" : "var(--navy-700)") : "var(--paper-2)",
          color: selected ? (accent ? "var(--navy-900)" : "var(--paper)") : "var(--navy-700)",
          transition: "background 200ms var(--ease-out)",
        }}>
          <Icon name={icon} size={20} />
        </span>
      )}
      <span style={{ flex: 1, minWidth: 0 }}>
        <span style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
          <span style={{ fontFamily: "var(--font-display)", fontSize: 16, fontWeight: 600, color: "var(--navy-900)", letterSpacing: "-0.01em" }}>{title}</span>
          {badge && <span style={{ fontSize: 11, fontWeight: 600, padding: "2px 8px", borderRadius: 999, background: "var(--accent-100)", color: "var(--accent-700)" }}>{badge}</span>}
        </span>
        {desc && <span style={{ display: "block", marginTop: 4, fontSize: 13, lineHeight: "19px", color: "var(--fg-tertiary)" }}>{desc}</span>}
      </span>
      <span style={{
        flex: "none", width: 22, height: 22, borderRadius: 999, marginTop: 2,
        border: selected ? "none" : "1.5px solid var(--border-strong)",
        background: selected ? (accent ? "var(--accent-500)" : "var(--navy-700)") : "transparent",
        display: "flex", alignItems: "center", justifyContent: "center",
        color: accent ? "var(--navy-900)" : "var(--paper)",
        transition: "all 160ms var(--ease-out)",
      }}>
        {selected && <Icon name="check" size={13} strokeWidth={3} />}
      </span>
    </button>
  );
}

/* Tarjeta multi-select (checkbox). */
function CheckCard({ checked, onClick, icon, title, desc, density }) {
  const [hover, setHover] = useStateUI(false);
  const pad = density === "compact" ? "14px 16px" : "18px 18px";
  return (
    <button
      type="button"
      role="checkbox"
      aria-checked={checked}
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        textAlign: "left", width: "100%", cursor: "pointer",
        background: checked ? "var(--white)" : (hover ? "var(--bg-subtle)" : "var(--white)"),
        border: "1.5px solid " + (checked ? "var(--navy-700)" : (hover ? "var(--border-strong)" : "var(--border-default)")),
        borderRadius: "var(--radius-lg)", padding: pad,
        boxShadow: checked ? "var(--shadow-md)" : "var(--shadow-sm)",
        display: "flex", gap: 12, alignItems: "flex-start", fontFamily: "var(--font-sans)",
        transition: "background 200ms var(--ease-out), box-shadow 200ms var(--ease-out), border-color 200ms var(--ease-out)",
      }}
    >
      <span style={{
        flex: "none", width: 22, height: 22, borderRadius: "var(--radius-xs)", marginTop: 1,
        border: checked ? "none" : "1.5px solid var(--border-strong)",
        background: checked ? "var(--navy-700)" : "transparent",
        display: "flex", alignItems: "center", justifyContent: "center", color: "var(--paper)",
        transition: "all 160ms var(--ease-out)",
      }}>
        {checked && <Icon name="check" size={14} strokeWidth={3} />}
      </span>
      <span style={{ flex: 1, minWidth: 0 }}>
        <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
          {icon && <Icon name={icon} size={16} color="var(--navy-700)" />}
          <span style={{ fontSize: 15, fontWeight: 600, color: "var(--navy-900)" }}>{title}</span>
        </span>
        {desc && <span style={{ display: "block", marginTop: 3, fontSize: 13, lineHeight: "18px", color: "var(--fg-tertiary)" }}>{desc}</span>}
      </span>
    </button>
  );
}

/* Grupo de opciones compactas tipo "segmented" / pills (para sub-preguntas). */
function CompactChoice({ value, options, onChange, name }) {
  return (
    <div role="radiogroup" aria-label={name} style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
      {options.map(opt => {
        const sel = value === opt.value;
        return (
          <button
            key={opt.value}
            type="button"
            role="radio"
            aria-checked={sel}
            onClick={() => onChange(opt.value)}
            style={{
              cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 600,
              padding: "9px 16px", borderRadius: "var(--radius-pill)",
              border: "1.5px solid " + (sel ? "var(--navy-700)" : "var(--border-strong)"),
              background: sel ? "var(--navy-700)" : "var(--white)",
              color: sel ? "var(--paper)" : "var(--navy-900)",
              boxShadow: sel ? "var(--shadow-sm)" : "none",
              transition: "all 160ms var(--ease-out)",
            }}
          >{opt.label}</button>
        );
      })}
    </div>
  );
}

/* Modal accesible con overlay. */
function Modal({ open, onClose, children, maxWidth = 520, labelledBy }) {
  useEffectUI(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose && onClose(); };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div
      role="dialog" aria-modal="true" aria-labelledby={labelledBy}
      onMouseDown={(e) => { if (e.target === e.currentTarget) onClose && onClose(); }}
      style={{
        position: "fixed", inset: 0, zIndex: 200, background: "rgba(20, 24, 42, 0.36)",
        display: "flex", alignItems: "center", justifyContent: "center", padding: 20,
        animation: "cotz-fade 200ms var(--ease-out)",
      }}
    >
      <div style={{
        background: "var(--white)", borderRadius: "var(--radius-xl)", boxShadow: "var(--shadow-xl)",
        maxWidth, width: "100%", maxHeight: "90vh", overflow: "auto",
        animation: "cotz-pop 240ms var(--ease-out)",
      }}>
        {children}
      </div>
    </div>
  );
}

Object.assign(window, { Icon, Eyebrow, Tooltip, OptionCard, CheckCard, CompactChoice, Modal });
