// Lucide UMD -> React adapter.
// In lucide@0.453 the icons are exported as IconNode arrays in one of two shapes:
//   A) ["svg", svgAttrs, [["path", {...}], ...]]   (full svg)
//   B) [["path", {...}], ["circle", {...}], ...]   (children only)
// We accept both and skip non-array entries safely.

function toPascal(name) {
  return name.split(/[-_ ]/g).map(s => s ? s[0].toUpperCase() + s.slice(1) : '').join('');
}
function toKebab(name) {
  return name.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
}

function lookupIcon(name) {
  const lib = window.lucide;
  if (!lib) return null;
  const candidates = [name, toPascal(name), toKebab(name), name.toLowerCase()];
  for (const k of candidates) {
    if (lib[k] && (Array.isArray(lib[k]) || typeof lib[k] === 'object')) return lib[k];
    if (lib.icons && lib.icons[k]) return lib.icons[k];
  }
  return null;
}

function renderNode(node, keyPrefix) {
  if (!Array.isArray(node)) return null;
  const [tag, attrs, kids] = node;
  if (typeof tag !== 'string') return null;
  const kidsArr = Array.isArray(kids) ? kids : null;
  const children = kidsArr ? kidsArr.map((k, i) => renderNode(k, `${keyPrefix}-${i}`)).filter(Boolean) : null;
  return React.createElement(tag, { key: keyPrefix, ...(attrs || {}) }, children);
}

function extractChildren(iconNode) {
  // Form A: ["svg", attrs, children-array]
  if (Array.isArray(iconNode) && typeof iconNode[0] === 'string' && Array.isArray(iconNode[2])) {
    return iconNode[2];
  }
  // Form B: array of child nodes
  if (Array.isArray(iconNode) && Array.isArray(iconNode[0])) {
    return iconNode;
  }
  // Single node
  if (Array.isArray(iconNode) && typeof iconNode[0] === 'string') {
    return [iconNode];
  }
  // Object with body: [...]
  if (iconNode && typeof iconNode === 'object' && Array.isArray(iconNode.body)) {
    return iconNode.body;
  }
  return [];
}

function Icon({ name, size = 20, className = '', strokeWidth = 1.6, style }) {
  const iconNode = lookupIcon(name);
  const childNodes = iconNode ? extractChildren(iconNode) : [];
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size}
      viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round"
      className={`lucide ${className}`} style={style}>
      {childNodes.map((n, i) => renderNode(n, `c-${i}`))}
      {!iconNode && <rect x="3" y="3" width="18" height="18" rx="2" />}
    </svg>
  );
}

window.Icon = Icon;
