'use client';

import { useEffect } from 'react';
import { useSiteFooter } from '@/lib/siteFooterContext';

/**
 * أيقونة التبويب من `fav_icon` في لوحة الإعدادات؛ إن لم تُرفَع يُستخدم `logo`.
 */
export default function DynamicFavicon() {
  const { footer } = useSiteFooter();

  useEffect(() => {
    const raw = (footer?.favicon_url ?? footer?.logo_url ?? '').trim();
    if (!raw) return;

    const upsert = (rel: string) => {
      let link = document.querySelector(`link[rel="${rel}"]`) as HTMLLinkElement | null;
      if (!link) {
        link = document.createElement('link');
        link.rel = rel;
        document.head.appendChild(link);
      }
      link.href = raw;
    };

    upsert('icon');
    upsert('shortcut icon');
    const apple = document.querySelector('link[rel="apple-touch-icon"]') as HTMLLinkElement | null;
    if (!apple) {
      const a = document.createElement('link');
      a.rel = 'apple-touch-icon';
      a.href = raw;
      document.head.appendChild(a);
    } else {
      apple.href = raw;
    }
  }, [footer?.favicon_url, footer?.logo_url]);

  return null;
}
