"use client";

import { useEffect, useState } from 'react';

interface DynamicFaviconProps {
    logoUrl?: string;
}

export default function DynamicFavicon({ logoUrl }: DynamicFaviconProps) {
    const [mounted, setMounted] = useState(false);

    useEffect(() => {
        setMounted(true);
    }, []);

    useEffect(() => {
        if (!mounted || !logoUrl) return;

        // Usar requestAnimationFrame para garantir que a hidratação terminou
        requestAnimationFrame(() => {
            // Remove favicons antigos
            const existingLinks = document.querySelectorAll("link[rel*='icon']");
            existingLinks.forEach(link => link.remove());

            // Adiciona novo favicon
            const link = document.createElement('link');
            link.type = 'image/x-icon';
            link.rel = 'shortcut icon';
            link.href = logoUrl;
            document.getElementsByTagName('head')[0].appendChild(link);

            // Adiciona Apple touch icon
            const appleLink = document.createElement('link');
            appleLink.rel = 'apple-touch-icon';
            appleLink.href = logoUrl;
            document.getElementsByTagName('head')[0].appendChild(appleLink);
        });

    }, [mounted, logoUrl]);

    return null;
}
