"use client"

import { useEffect, useRef, useState, type ReactElement, type ReactNode } from "react"

function childKey(child: ReactNode, index: number): string {
  if (child && typeof child === "object" && "key" in child) {
    return String((child as ReactElement).key ?? index)
  }
  return String(index)
}

/** Clés des items ajoutés récemment (pour animation d'entrée unique). */
export function useEnteringItemKeys(items: ReactNode[]): Set<string> {
  const seenKeysRef = useRef(new Set<string>())
  const [enteringKeys, setEnteringKeys] = useState<Set<string>>(() => new Set())

  const itemKeys = items.map(childKey).join("\0")

  useEffect(() => {
    const keys = items.map(childKey)
    const keySet = new Set(keys)
    const added = keys.filter((key) => !seenKeysRef.current.has(key))

    for (const key of keys) {
      seenKeysRef.current.add(key)
    }
    for (const key of [...seenKeysRef.current]) {
      if (!keySet.has(key)) seenKeysRef.current.delete(key)
    }

    if (added.length === 0) return

    setEnteringKeys(new Set(added))
    const timer = window.setTimeout(() => setEnteringKeys(new Set()), 360)
    return () => window.clearTimeout(timer)
  }, [itemKeys, items])

  return enteringKeys
}
