"use client";

import { useEffect } from "react";

interface DynamicFaviconProps {
    logoUrl: string | null;
    orgName: string;
    primaryColor: string;
}

export function DynamicFavicon({ logoUrl, orgName, primaryColor }: DynamicFaviconProps) {
    useEffect(() => {
        // If there's a logo URL, use it as favicon
        if (logoUrl) {
            // Remove any existing favicon links
            const existingLinks = document.querySelectorAll("link[rel*='icon']");
            existingLinks.forEach(link => link.remove());

            // Create new favicon link
            const link = document.createElement("link");
            link.rel = "icon";
            link.type = "image/png";
            link.href = logoUrl;
            document.head.appendChild(link);

            // Also add apple touch icon
            const appleLink = document.createElement("link");
            appleLink.rel = "apple-touch-icon";
            appleLink.href = logoUrl;
            document.head.appendChild(appleLink);
        } else {
            // Generate a simple SVG favicon with the first letter
            const svg = `
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
                    <rect width="32" height="32" rx="6" fill="${primaryColor}"/>
                    <text x="16" y="22" text-anchor="middle" fill="white" font-family="Arial, sans-serif" font-size="18" font-weight="bold">
                        ${orgName.charAt(0).toUpperCase()}
                    </text>
                </svg>
            `;
            const blob = new Blob([svg], { type: "image/svg+xml" });
            const url = URL.createObjectURL(blob);

            const existingLinks = document.querySelectorAll("link[rel*='icon']");
            existingLinks.forEach(link => link.remove());

            const link = document.createElement("link");
            link.rel = "icon";
            link.type = "image/svg+xml";
            link.href = url;
            document.head.appendChild(link);
        }
    }, [logoUrl, orgName, primaryColor]);

    return null;
}
