// Wrap lucide vanilla SVG nodes as React components so dashboard widgets can
// keep their `<Icon size strokeWidth className />` ergonomics.
(function () {
  const L = window.lucide;
  if (!L || !L.icons) {
    console.error("lucide global not loaded");
    return;
  }

  // lucide.icons keys are PascalCase (e.g. "ArrowUpRight") in 0.460.
  // Each value is [tag, attrs, children] arrays describing the SVG.
  const renderNode = (node, key) => {
    const [tag, attrs, children] = node;
    const props = { key, ...attrs };
    // SVG attrs come in kebab-case; React wants camelCase for some.
    const fix = (k) => k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
    const out = {};
    for (const [k, v] of Object.entries(props)) out[k === "key" ? "key" : fix(k)] = v;
    return React.createElement(
      tag,
      out,
      Array.isArray(children) ? children.map((c, i) => renderNode(c, i)) : children
    );
  };

  const makeIcon = (name) => {
    const data = L.icons[name];
    if (!data) return null;
    // lucide 0.460 stores as { name, attrs, children } OR as raw array — handle both.
    const children = Array.isArray(data) ? data[2] : data[2] || data.children;
    return React.forwardRef(function LucideIcon(
      { size = 24, color = "currentColor", strokeWidth = 2, className = "", style, ...rest },
      ref
    ) {
      return React.createElement(
        "svg",
        {
          ref,
          xmlns: "http://www.w3.org/2000/svg",
          width: size,
          height: size,
          viewBox: "0 0 24 24",
          fill: "none",
          stroke: color,
          strokeWidth,
          strokeLinecap: "round",
          strokeLinejoin: "round",
          className: "lucide " + className,
          style,
          ...rest,
        },
        (children || []).map((c, i) => renderNode(c, i))
      );
    });
  };

  // Build proxy so `LucideReact.AnyIcon` works on demand.
  const cache = {};
  window.LucideReact = new Proxy(
    {},
    {
      get(_, name) {
        if (typeof name !== "string") return undefined;
        if (cache[name]) return cache[name];
        // Try as-is, then with capital first.
        const candidates = [name, name[0].toUpperCase() + name.slice(1)];
        for (const n of candidates) {
          if (L.icons[n]) {
            cache[name] = makeIcon(n);
            return cache[name];
          }
        }
        // Fallback: empty span so nothing crashes.
        const Missing = () => React.createElement("span", { style: { display: "inline-block", width: 16, height: 16 } });
        cache[name] = Missing;
        return Missing;
      },
    }
  );
})();
