import { useEffect, useState } from 'react'

/**
 * Inject custom font CSS (e.g., Elementor @font-face) into the document head.
 * Manages a single <style id="boostbot-custom-fonts-admin"> element.
 * Returns a version counter that increments when fonts are (re)loaded,
 * useful as a React key to force re-render of font-dependent components.
 */
export function useAppearanceFontCss(customFontCss: string | null | undefined) {
    const [fontCssVersion, setFontCssVersion] = useState(0)

    useEffect(() => {
        if (!customFontCss) return

        const existingStyle = document.getElementById('boostbot-custom-fonts-admin')
        if (existingStyle) {
            if (existingStyle.textContent === customFontCss) return
            existingStyle.remove()
        }

        const style = document.createElement('style')
        style.id = 'boostbot-custom-fonts-admin'
        style.textContent = customFontCss
        document.head.appendChild(style)

        setTimeout(() => setFontCssVersion(v => v + 1), 100)

        return () => {
            const styleToRemove = document.getElementById('boostbot-custom-fonts-admin')
            if (styleToRemove) {
                styleToRemove.remove()
            }
        }
    }, [customFontCss])

    return fontCssVersion
}
