import React from 'react';
import { ExternalLink, Maximize2, Minimize2 } from 'lucide-react';
import { __ } from '@/lib/i18n';
import { ThemeToggle } from '@/components/ThemeToggle';

export function Header({ 
  onFullscreen, 
  fullscreen, 
  showToggle = true, 
  scrollContainerRef, 
  onVisibilityChange 
}: { 
  onFullscreen: () => void; 
  fullscreen: boolean; 
  showToggle?: boolean; 
  scrollContainerRef?: React.RefObject<HTMLDivElement>; 
  onVisibilityChange?: (visible: boolean) => void;
}) {
  const [siteTitle, setSiteTitle] = React.useState(window.wnw?.siteTitle || 'WooNooW');
  const [storeLogo, setStoreLogo] = React.useState('');
  const [storeLogoDark, setStoreLogoDark] = React.useState('');
  const [isVisible, setIsVisible] = React.useState(true);
  const lastScrollYRef = React.useRef(0);
  const isStandalone = window.WNW_CONFIG?.standaloneMode ?? false;
  const [isDark, setIsDark] = React.useState(false);

  // Detect dark mode
  React.useEffect(() => {
    const checkDarkMode = () => {
      const htmlEl = document.documentElement;
      setIsDark(htmlEl.classList.contains('dark'));
    };

    checkDarkMode();

    // Watch for theme changes
    const observer = new MutationObserver(checkDarkMode);
    observer.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ['class']
    });

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

  // Notify parent of visibility changes
  React.useEffect(() => {
    onVisibilityChange?.(isVisible);
  }, [isVisible, onVisibilityChange]);

  // Fetch store branding on mount
  React.useEffect(() => {
    const fetchBranding = async () => {
      try {
        const response = await fetch((window.WNW_CONFIG?.restUrl || '') + '/store/branding');
        if (response.ok) {
          const data = await response.json();
          if (data.store_logo) setStoreLogo(data.store_logo);
          if (data.store_logo_dark) setStoreLogoDark(data.store_logo_dark);
          if (data.store_name) setSiteTitle(data.store_name);
        }
      } catch (err) {
        console.error('Failed to fetch branding:', err);
      }
    };
    fetchBranding();
  }, []);

  // Listen for store settings updates
  React.useEffect(() => {
    const handleStoreUpdate = (event: CustomEvent) => {
      if (event.detail?.store_logo) setStoreLogo(event.detail.store_logo);
      if (event.detail?.store_logo_dark) setStoreLogoDark(event.detail.store_logo_dark);
      if (event.detail?.store_name) setSiteTitle(event.detail.store_name);
    };

    window.addEventListener('woonoow:store:updated' as any, handleStoreUpdate);
    return () => window.removeEventListener('woonoow:store:updated' as any, handleStoreUpdate);
  }, []);

  // Hide/show header on scroll (mobile only)
  React.useEffect(() => {
    const scrollContainer = scrollContainerRef?.current;
    if (!scrollContainer) return;

    const handleScroll = () => {
      const currentScrollY = scrollContainer.scrollTop;

      // Only apply on mobile (check window width)
      if (window.innerWidth >= 768) {
        setIsVisible(true);
        return;
      }

      if (currentScrollY > lastScrollYRef.current && currentScrollY > 50) {
        // Scrolling down & past threshold
        setIsVisible(false);
      } else if (currentScrollY < lastScrollYRef.current) {
        // Scrolling up
        setIsVisible(true);
      }

      lastScrollYRef.current = currentScrollY;
    };

    scrollContainer.addEventListener('scroll', handleScroll, { passive: true });

    return () => {
      scrollContainer.removeEventListener('scroll', handleScroll);
    };
  }, [scrollContainerRef]);

  const handleLogout = async () => {
    try {
      await fetch((window.WNW_CONFIG?.restUrl || '') + '/auth/logout', {
        method: 'POST',
        credentials: 'include',
      });
      window.location.reload();
    } catch (err) {
      console.error('Logout failed:', err);
    }
  };

  // Hide header completely on mobile in fullscreen mode (both standalone and wp-admin fullscreen)
  if (fullscreen && typeof window !== 'undefined' && window.innerWidth < 768) {
    return null;
  }

  // Choose logo based on theme
  const currentLogo = isDark && storeLogoDark ? storeLogoDark : storeLogo;

  return (
    <header className={`h-16 border-b border-border flex items-center px-4 justify-between sticky ${fullscreen ? `top-0` : `top-[32px]`} z-40 bg-background md:bg-background/95 md:backdrop-blur md:supports-[backdrop-filter]:bg-background/60 transition-transform duration-300 ${fullscreen && !isVisible ? '-translate-y-full md:translate-y-0' : 'translate-y-0'}`}>
      <div className="flex items-center gap-3">
        {currentLogo ? (
          <img src={currentLogo} alt={siteTitle} className="h-8 object-contain" />
        ) : (
          <div className="font-semibold">{siteTitle}</div>
        )}

        {!(window.WNW_CONFIG?.customerSpaEnabled) && (
          <a
            href={window.WNW_CONFIG?.storeUrl || '/store/'}
            target="_blank"
            rel="noopener noreferrer"
            className="ml-2 inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors"
            title={__('Visit Store')}
          >
            <ExternalLink className="w-4 h-4" />
            <span className="hidden sm:inline">{__('Store')}</span>
          </a>
        )}
      </div>
      <div className="flex items-center gap-3">
        <div className="text-sm opacity-70 hidden sm:block">{window.WNW_API?.isDev ? 'Dev Server' : 'Production'}</div>
        {isStandalone && (
          <>
            <a
              href={window.WNW_CONFIG?.wpAdminUrl || '/wp-admin'}
              className="inline-flex items-center gap-2 border rounded-md px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground"
              title="Go to WordPress Admin"
            >
              <span>{__('WordPress')}</span>
            </a>
            {window.WNW_CONFIG?.customerSpaEnabled && (
              <a
                href={window.WNW_CONFIG?.storeUrl || '/store/'}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center gap-2 border rounded-md px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground"
                title="Open Store"
              >
                <span>{__('Store')}</span>
              </a>
            )}
            <button
              onClick={handleLogout}
              className="inline-flex items-center gap-2 border rounded-md px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground"
              title="Logout"
            >
              <span>{__('Logout')}</span>
            </button>
          </>
        )}
        {!isStandalone && window.WNW_CONFIG?.customerSpaEnabled && (
          <a
            href={window.WNW_CONFIG?.storeUrl || '/store/'}
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center gap-2 border rounded-md px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground"
            title="Open Store"
          >
            <span>{__('Store')}</span>
          </a>
        )}
        <ThemeToggle />
        {showToggle && (
          <button
            onClick={onFullscreen}
            className="inline-flex items-center gap-2 border rounded-md px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground"
            title={fullscreen ? 'Exit fullscreen' : 'Enter fullscreen'}
          >
            {fullscreen ? <Minimize2 className="w-4 h-4" /> : <Maximize2 className="w-4 h-4" />}
            <span className="hidden sm:inline">{fullscreen ? 'Exit' : 'Fullscreen'}</span>
          </button>
        )}
      </div>
    </header>
  );
}
