'use client';

import { useState, useEffect } from 'react';

interface PublicBranding {
  logoUrl: string;
  faviconUrl: string;
  siteTitle: string;
  siteTagline: string;
  loaded: boolean;
}

function applyFavicon(url: string) {
  let link = document.querySelector<HTMLLinkElement>('link[rel="icon"]');
  if (!link) {
    link = document.createElement('link');
    link.rel = 'icon';
    document.head.appendChild(link);
  }
  link.href = url;
}

export function usePublicBranding(): PublicBranding {
  const [logoUrl, setLogoUrl] = useState('');
  const [faviconUrl, setFaviconUrl] = useState('');
  const [siteTitle, setSiteTitle] = useState('RestroAgent');
  const [siteTagline, setSiteTagline] = useState('');
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    fetch('/api/public/branding')
      .then(r => r.json())
      .then((data: { branding: Record<string, string> }) => {
        const b = data.branding ?? {};
        if (b.site_logo_url) setLogoUrl(b.site_logo_url);
        if (b.site_favicon_url) {
          setFaviconUrl(b.site_favicon_url);
          applyFavicon(b.site_favicon_url);
        }
        const title = b.site_title || 'RestroAgent';
        const tagline = b.site_tagline || '';
        if (b.site_title) setSiteTitle(title);
        if (b.site_tagline) setSiteTagline(tagline);
        document.title = tagline ? `${tagline} — ${title}` : title;
      })
      .catch(() => {})
      .finally(() => setLoaded(true));
  }, []);

  return { logoUrl, faviconUrl, siteTitle, siteTagline, loaded };
}
