import { useEffect } from 'react';

/**
 * Hook para gerenciar os metadados do documento (Título e Favicon)
 * baseado no ambiente e na página atual.
 * 
 * @param {string} title - O título da página
 * @param {'fleet' | 'finance' | 'rh' | 'login'} type - O tipo de ambiente para o favicon
 */
export const useDocumentMetadata = (title, type) => {
  useEffect(() => {
    // 1. Atualizar o Título
    if (title) {
      document.title = title;
    }

    // 2. Atualizar o Favicon (SVG dinâmico baseado no tipo)
    if (type) {
      const updateFavicon = () => {
        const colors = {
          fleet: '#10b981', // Emerald 500
          finance: '#059669', // Emerald 600
          rh: '#3b82f6', // Blue 500
          prafrot: '#eab308', // Yellow 500
          login: '#64748b', // Slate 500
        };

        const iconPaths = {
          fleet: '<path d="M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2" fill="none" stroke="white" stroke-width="2.5"/><circle cx="7" cy="18" r="2" fill="white"/><circle cx="17" cy="18" r="2" fill="white"/><path d="M13 18h7a2 2 0 0 0 2-2V9l-3-3h-6" fill="none" stroke="white" stroke-width="2.5"/>',
          finance: '<path d="M3 21h18" stroke="white" stroke-width="2.5"/><path d="M9 8h6" stroke="white" stroke-width="2.5"/><path d="M5 21V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16" stroke="white" stroke-width="2.5"/><path d="M9 12h6" stroke="white" stroke-width="2.5"/><path d="M9 16h6" stroke="white" stroke-width="2.5"/>',
          rh: '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" stroke="white" stroke-width="2.5"/><circle cx="9" cy="7" r="4" stroke="white" stroke-width="2.5"/><path d="M22 21v-2a4 4 0 0 0-3-3.87" stroke="white" stroke-width="2.5"/><path d="M16 3.13a4 4 0 0 1 0 7.75" stroke="white" stroke-width="2.5"/>',
          login: '<rect x="3" y="11" width="18" height="11" rx="2" ry="2" stroke="white" stroke-width="2.5" fill="none"/><path d="M7 11V7a5 5 0 0 1 10 0v4" stroke="white" stroke-width="2.5" fill="none"/>'
        };

        const color = colors[type] || colors.login;
        const path = (type === 'prafrot') ? iconPaths.fleet : (iconPaths[type] || iconPaths.login);

        const svg = `
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
            <rect width="24" height="24" rx="6" fill="${color}"/>
            <g transform="scale(0.6) translate(8, 8)">
              ${path}
            </g>
          </svg>
        `.replace(/\s+/g, ' ').trim();

        const dataUrl = `data:image/svg+xml;base64,${btoa(svg)}`;
        
        let link = document.querySelector("link[rel*='icon']");
        if (!link) {
          link = document.createElement('link');
          link.rel = 'icon';
          document.head.appendChild(link);
        }
        link.href = dataUrl;
      };

      updateFavicon();
    }
  }, [title, type]);
};
