import { useEffect } from 'react';
import itguysFavicon from '@/assets/Img/Util/iT_Guys/Logo 32x32.png';
import oestPanLogo from '@/assets/Img/Util/Oeste_Pan/Logo Oeste Pan.png';

/**
 * 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' | 'workspace' | 'gr' | 'prafrot' | 'cnab'} 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) {
      console.log(`[useDocumentMetadata] Iniciando atualização para tipo: ${type}`);
      const updateFavicon = () => {
        const colors = {
          gr: '#10b981', // Emerald 500
          fleet: '#10b981', // Emerald 500
          finance: '#059669', // Emerald 600
          rh: '#10b981', // Emerald 500 (alinhado com o tema do ambiente RH)
          prafrot: '#eab308', // Yellow 500
          login: '#64748b', // Slate 500
          cnab: '#059669', // Emerald 600 (mesma cor do finance, mas com ícone diferente)
          cnab240: '#059669', // Emerald 600
          workspace: '#26b1c7', // Workspace Blue
          'oest-pan': '#f97316', // Orange 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: '<rect x="2" y="7" width="20" height="14" rx="2" ry="2" stroke="white" stroke-width="2.5" fill="none"/><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16" stroke="white" stroke-width="2.5" fill="none"/>',
          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"/>',
          cnab: '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" fill="none" stroke="white" stroke-width="2.5"/><path d="M14 2v6h6" fill="none" 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"/>',
          cnab240: '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" fill="none" stroke="white" stroke-width="2.5"/><path d="M14 2v6h6" fill="none" 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"/>'
        };

        const color = colors[type] || colors.login;
        let svgContent;

        if (type === 'gr') {
          svgContent = `
            <rect width="24" height="24" rx="6" fill="${color}"/>
            <text x="50%" y="50%" text-anchor="middle" dy=".35em" fill="white" font-family="Arial, sans-serif" font-weight="900" font-size="14">GR</text>
          `;
        } else if (type === 'cnab' || type === 'cnab240') {
          const path = iconPaths.cnab || iconPaths.cnab240;
          svgContent = `
            <rect width="24" height="24" rx="6" fill="${color}"/>
            <g transform="scale(0.6) translate(8, 8)">
              ${path}
            </g>
          `;
        } else if (type === 'workspace') {
          const path = iconPaths.fleet;
          svgContent = `
            <rect width="24" height="24" rx="6" fill="${color}"/>
            <g transform="scale(0.6) translate(8, 8)">
              ${path}
            </g>
          `;
        } else {
          const path = (type === 'prafrot') ? iconPaths.fleet : (iconPaths[type] || iconPaths.login);
          svgContent = `
            <rect width="24" height="24" rx="6" fill="${color}"/>
            <g transform="scale(0.6) translate(8, 8)">
              ${path}
            </g>
          `;
        }

        const svg = `
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
            ${svgContent}
          </svg>
        `.replace(/\s+/g, ' ').trim();

        const dataUrl = `data:image/svg+xml;base64,${btoa(svg)}`;
        
        // Remove ALL existing icons to avoid conflicts and ensure browser refresh
        const existingIcons = document.querySelectorAll("link[rel*='icon']");
        existingIcons.forEach(el => el.parentNode.removeChild(el));

        // Create new link element
        const link = document.createElement('link');
        link.rel = 'icon';

        if (type === 'workspace') {
          link.type = 'image/png';
          link.href = itguysFavicon;
        } else if (type === 'oest-pan') {
          link.type = 'image/png';
          link.href = oestPanLogo;
        } else {
          link.type = 'image/svg+xml';
          link.href = dataUrl;
        }

        document.head.appendChild(link);
        console.log(`[useDocumentMetadata] Favicon atualizado: ${link.href} (${link.type})`);
      };

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