/* ============================================================
   Icon — React-compatible wrapper around lucide.icons[name].toSvg()
   Reemplaza el patrón <i data-lucide="..."/> + createIcons(),
   que rompe el reconciler de React cuando re-renderiza.
   ============================================================ */

const __ICON_CACHE = {};
const __toPascal = (kebab) =>
  kebab.split("-").map(s => s.charAt(0).toUpperCase() + s.slice(1)).join("");

const Icon = ({ name, size, strokeWidth = 1.75, style, color, className }) => {
  // Honor width/height passed via inline style (legacy pattern from migrated <i> tags)
  const styleW = style && (style.width || style.height);
  const finalSize = size || styleW || 16;

  const html = React.useMemo(() => {
    if (!name) return "";
    const key = `${name}::${finalSize}::${strokeWidth}`;
    if (__ICON_CACHE[key]) return __ICON_CACHE[key];
    if (!window.lucide || !window.lucide.icons) return "";
    const pascal = __toPascal(name);
    const iconData = window.lucide.icons[pascal];
    if (!iconData) {
      console.warn("[Icon] missing lucide icon:", name, "→", pascal);
      return "";
    }
    // lucide CDN exposes each icon as an array of [tag, attrs] child descriptors.
    // We wrap them in a standard lucide <svg> root.
    const children = iconData.map(([tag, attrs]) => {
      const attrStr = Object.entries(attrs)
        .map(([k, v]) => `${k}="${String(v).replace(/"/g, "&quot;")}"`)
        .join(" ");
      return `<${tag} ${attrStr}/>`;
    }).join("");
    const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${finalSize}" height="${finalSize}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${strokeWidth}" stroke-linecap="round" stroke-linejoin="round">${children}</svg>`;
    __ICON_CACHE[key] = svg;
    return svg;
  }, [name, finalSize, strokeWidth]);

  return (
    <span
      className={className}
      style={{
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        color: color || (style && style.color) || "currentColor",
        flexShrink: 0,
        lineHeight: 0,
        width: finalSize,
        height: finalSize,
        ...style,
      }}
      dangerouslySetInnerHTML={{ __html: html }}
    />
  );
};

window.Icon = Icon;
