"use client"

import { useEffect, useState } from "react"

interface LucideIconsPayload {
  icons?: string[]
}

let cachedIconNames: string[] | null = null
let inFlightRequest: Promise<string[]> | null = null

async function loadLucideIconNames() {
  if (cachedIconNames) return cachedIconNames
  if (!inFlightRequest) {
    inFlightRequest = (async () => {
      try {
        const response = await fetch("/lucide-icons.json", { cache: "force-cache" })
        if (!response.ok) return []
        const payload = (await response.json()) as LucideIconsPayload
        const iconNames = Array.isArray(payload.icons)
          ? payload.icons.filter((name): name is string => typeof name === "string")
          : []
        cachedIconNames = iconNames
        return iconNames
      } catch {
        return []
      }
    })()
  }
  const iconNames = await inFlightRequest
  cachedIconNames = iconNames
  return iconNames
}

export function useLucideIconNames() {
  const [iconNames, setIconNames] = useState<string[]>(cachedIconNames ?? [])

  useEffect(() => {
    if (cachedIconNames) return
    let cancelled = false
    void loadLucideIconNames().then((names) => {
      if (!cancelled) setIconNames(names)
    })
    return () => {
      cancelled = true
    }
  }, [])

  return iconNames
}
