import React, { useEffect, useRef, useState } from 'react';
import { SlMenu } from "react-icons/sl";
import useRenderTracker from '../../hooks/useRenderTracker';
import { useSetIsMobileSidebarOpen } from '../../contexts/UIContext';
import { useAuth } from '../../contexts/AuthContext';
import { useSetIsSettingsModalOpen } from '../../contexts/UIContext';
import ProfileLogo from '../Logos/ProfileLogo';
import SeoConsentBanner from '../SeoConsent/SeoConsentBanner';
import { IS_WORDPRESS } from '../../constants';

const MobileHeader: React.FC = () => {
  const setIsMobileSidebarOpen = useSetIsMobileSidebarOpen();
  const setIsSettingsModalOpen = useSetIsSettingsModalOpen();
  const { isLoggedIn, userInfo, hasDismissedBanner } = useAuth();
  const [isKbOpen, setIsKbOpen] = useState(false);
  const kbRef = useRef<HTMLLIElement | null>(null);

  // Calculate whether banner is showing
  const showBanner = !hasDismissedBanner && !IS_WORDPRESS;

  useRenderTracker('MobileHeader', {
    isLoggedIn,
    userInfo,
    setIsSettingsModalOpen,
    setIsMobileSidebarOpen,
    showBanner
  });

  // Close KB dropdown on outside click
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (kbRef.current && !kbRef.current.contains(event.target as Node)) {
        setIsKbOpen(false);
      }
    }
    function handleEsc(event: KeyboardEvent) {
      if (event.key === 'Escape') setIsKbOpen(false);
    }
    document.addEventListener('mousedown', handleClickOutside);
    document.addEventListener('keydown', handleEsc);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('keydown', handleEsc);
    };
  }, []);

  return (
    <>
      {/* Main header with menu and profile */}
      <nav className="flex h-12 items-center justify-between border-b px-2 py-5 sm:px-3 sm:py-7 dark:border-gray-800 md:hidden">
        {/* Left side - menu button */}
        <button
          type="button"
          className="flex rounded-md dark:bg-secondary/15 shrink-0 items-center justify-center text-lg"
          aria-label="Open menu"
          onClick={() => setIsMobileSidebarOpen(true)}
        >
          <SlMenu />
        </button>
        
        {/* Right side - navigation links and profile */}
        <div className="flex items-center space-x-4">
          {/* Navigation links */}
          {!IS_WORDPRESS && (
          <ul className="flex space-x-4 items-center">
            <li>
              <a 
                href="https://wpassistant.ai/about" 
                className="relative text-[14px] font-medium text-gray-700 dark:text-gray-200 hover:text-black dark:hover:text-white transition-colors duration-200"
              >
                About
              </a>
            </li>
            <li>
              <a 
                href="https://wpassistant.ai/faq" 
                className="relative text-[14px] font-medium text-gray-700 dark:text-gray-200 hover:text-black dark:hover:text-white transition-colors duration-200"
              >
                FAQ
              </a>
            </li>
            <li className="relative" ref={kbRef}>
              <button
                type="button"
                aria-haspopup="true"
                aria-expanded={isKbOpen}
                onClick={() => setIsKbOpen((v) => !v)}
                className="relative text-[14px] font-medium text-gray-700 dark:text-gray-200 hover:text-black dark:hover:text-white transition-colors duration-200 flex items-center"
              >
                Knowledge Base
                <span className="ml-1">▾</span>
              </button>
              {isKbOpen && (
                <div className="absolute right-0 top-full z-[9000] w-64 bg-background-light dark:bg-background-dark border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg px-3 py-3 max-h-[70vh] overflow-auto">
                  <ul className="space-y-1">
                    <li>
                      <a href="https://wpassistant.ai/knowledge-base/caching/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Caching</a>
                    </li>
                    <li>
                      <a href="https://wpassistant.ai/knowledge-base/content_management/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Content Management</a>
                    </li>
                    <li>
                      <a href="https://wpassistant.ai/knowledge-base/custom_development/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Custom Development</a>
                    </li>
                    <li>
                      <a href="https://wpassistant.ai/knowledge-base/database/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Database</a>
                    </li>
                    <li>
                      <a href="https://wpassistant.ai/knowledge-base/debugging/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Debugging</a>
                    </li>
                    <li>
                      <a href="https://wpassistant.ai/knowledge-base/ecommerce/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Ecommerce</a>
                    </li>
                    <li>
                      <a href="https://wpassistant.ai/knowledge-base/gutenberg_editor/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Gutenberg Editor</a>
                    </li>
                    <li>
                      <a href="https://wpassistant.ai/knowledge-base/hosting/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Hosting</a>
                    </li>
                    <li>
                      <a href="https://wpassistant.ai/knowledge-base/maintenance/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Maintenance</a>
                    </li>
                    <li>
                      <a href="https://wpassistant.ai/knowledge-base/performance/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Performance</a>
                    </li>
                    <li>
                      <a href="https://wpassistant.ai/knowledge-base/plugin_issues/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Plugin Issues</a>
                    </li>
                    <li>
                      <a href="https://wpassistant.ai/knowledge-base/security/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Security</a>
                    </li>
                    <li>
                      <a href="https://wpassistant.ai/knowledge-base/seo_optimization/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">SEO Optimization</a>
                    </li>
                    <li>
                      <a href="https://wpassistant.ai/knowledge-base/theme_customization/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Theme Customization</a>
                    </li>
                    <li>
                      <a href="https://wpassistant.ai/knowledge-base/wordpress_setup/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">WordPress Setup</a>
                    </li>
                  </ul>
                </div>
              )}
            </li>
          </ul>
          )}
          
          {/* Profile logo */}
          {isLoggedIn && userInfo ? (
            <ProfileLogo 
              name={userInfo.name} 
              email={userInfo.email} 
              onClick={() => setIsSettingsModalOpen(true)}
              size={40}
              showLabel={false}
            />
          ) : (
            // Empty spacer to maintain layout
            <div className="w-10"></div>
          )}
        </div>
      </nav>
      
      {/* Banner below the header if showing */}
      {showBanner && (
        <div className="flex py-1 px-1 justify-center bg-blue-50/50 dark:bg-blue-900/20 border-b dark:border-gray-800 md:hidden">
          <SeoConsentBanner />
        </div>
      )}
    </>
  );
};

export default React.memo(MobileHeader);
