"use client"

import { lazy, Suspense, type ComponentType, type LazyExoticComponent } from "react"
import dynamicIconImports from "lucide-react/dynamicIconImports"
import { Building2, type LucideProps } from "lucide-react"

interface DynamicIconProps extends LucideProps {
  /** Lucide icon name in kebab-case, e.g. "users", "car", "monitor" */
  name: string | null | undefined
}

type IconName = keyof typeof dynamicIconImports
type LazyIconComponent = LazyExoticComponent<ComponentType<LucideProps>>

const lazyIcons = Object.fromEntries(
  Object.entries(dynamicIconImports).map(([iconName, iconLoader]) => [iconName, lazy(iconLoader)]),
) as Record<IconName, LazyIconComponent>

/**
 * Renders a Lucide icon by name (kebab-case).
 * Falls back to Building2 if the name is not found.
 */
export function DynamicIcon({ name, ...props }: DynamicIconProps) {
  if (!name || !(name in dynamicIconImports)) {
    return <Building2 {...props} />
  }

  const LazyIcon = lazyIcons[name as IconName]

  return (
    <Suspense fallback={<Building2 {...props} />}>
      <LazyIcon {...props} />
    </Suspense>
  )
}
