'use client';

import { useEffect } from 'react';
import { getCanonicalUrlClient } from '@/lib/getCanonicalUrl';

/**
 * Client-side canonical URL handler
 * Use this component in pages that need dynamic canonical URLs
 * that can't be determined at build time or in generateMetadata
 */
export default function CanonicalHandler() {
    useEffect(() => {
        // Only run on client side
        if (typeof window === 'undefined') return;

        const canonicalUrl = getCanonicalUrlClient();

        if (canonicalUrl) {
            // Check if canonical link already exists
            let canonicalLink = document.querySelector('link[rel="canonical"]');

            if (canonicalLink) {
                // Update existing canonical link
                canonicalLink.href = canonicalUrl;
            } else {
                // Create new canonical link
                canonicalLink = document.createElement('link');
                canonicalLink.rel = 'canonical';
                canonicalLink.href = canonicalUrl;
                document.head.appendChild(canonicalLink);
            }
        }
    }, []);

    return null; // This component doesn't render anything
}