import { t } from 'i18next';
import { useEffect, useState } from 'react';

import { flagsHooks } from '@/hooks/flags-hooks';
import { useTheme } from '@/components/theme-provider';

const FullLogo = () => {
  const branding = flagsHooks.useWebsiteBranding();
  const { theme } = useTheme();

  // Track resolved theme from DOM (handles 'system' theme correctly)
  const [isDark, setIsDark] = useState(() =>
    document.documentElement.classList.contains('dark')
  );

  useEffect(() => {
    // Update when theme changes - check the actual applied class
    const checkDark = () => {
      setIsDark(document.documentElement.classList.contains('dark'));
    };
    checkDark();

    // Observe class changes on documentElement
    const observer = new MutationObserver((mutations) => {
      for (const mutation of mutations) {
        if (mutation.attributeName === 'class') {
          checkDark();
        }
      }
    });
    observer.observe(document.documentElement, { attributes: true });

    return () => observer.disconnect();
  }, [theme]);

  // Support dark mode by switching logo URLs
  // Light logo (dark text) for light mode, dark logo (light text) for dark mode
  const baseLogoUrl = branding.logos.fullLogoUrl;

  // Compute the appropriate logo URL based on theme
  let logoUrl = baseLogoUrl;
  if (isDark) {
    // Need dark logo (light text for dark background)
    if (baseLogoUrl.includes('-light.svg')) {
      logoUrl = baseLogoUrl.replace('-light.svg', '-dark.svg');
    } else if (!baseLogoUrl.includes('-dark.svg')) {
      logoUrl = baseLogoUrl.replace(/\.svg$/, '-dark.svg');
    }
  } else {
    // Need light logo (dark text for light background)
    if (baseLogoUrl.includes('-dark.svg')) {
      logoUrl = baseLogoUrl.replace('-dark.svg', '-light.svg');
    }
    // Otherwise use base URL as-is (assumed to be light version)
  }

  return (
    <div className="h-[60px]">
      <img
        className="h-full"
        src={logoUrl}
        alt={t('logo')}
      />
    </div>
  );
};
FullLogo.displayName = 'FullLogo';
export { FullLogo };
