'use client';

import { IconNode } from 'lucide-react';
import { useEffect, useState } from 'react';

type IconMap = Record<string, IconNode[]>;

let iconCache: IconMap | null = null;
let iconPromise: Promise<IconMap> | null = null;

export function useLucideIcons(enabled: boolean) {
  const [icons, setIcons] = useState<IconMap | null>(iconCache);
  const [loading, setLoading] = useState<boolean>(false);

  useEffect(() => {
    if (!enabled || iconCache) {
      if (iconCache) setIcons(iconCache);
      return;
    }

    if (!iconPromise) {
      iconPromise = import('lucide-static/icon-nodes.json')
        .then((mod) => mod.default as unknown as IconMap)
        .then((data) => {
          iconCache = data;
          return data;
        });
    }

    setLoading(true);

    iconPromise
      .then((data) => setIcons(data))
      .catch((err) => {
        console.error('Lucide icon load error:', err);
      })
      .finally(() => setLoading(false));
  }, [enabled]);

  return { icons, loading };
}
