// src/App.tsx

import { ChevronDown, Menu, X } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import './i18n';
import About from './pages/About';
import Home from './pages/Home';

type Tab = 'home' | 'about';

// --- DATA ---
const LANGUAGES = [
  { code: 'sv', label: 'SV', name: 'Svenska', flag: '/se.svg' },
  { code: 'en', label: 'EN', name: 'English', flag: '/gb.svg' },
  { code: 'de', label: 'DE', name: 'Deutsch', flag: '/de.svg' }
];

// --- COMPONENTS ---

const Navbar = ({ activeTab, setActiveTab }: { activeTab: Tab, setActiveTab: (t: Tab) => void }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [isLangOpen, setIsLangOpen] = useState(false);
  const [isMobileLangOpen, setIsMobileLangOpen] = useState(false);
  const { t, i18n } = useTranslation();
  const dropdownRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsLangOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const handleNav = (tab: Tab) => {
    setActiveTab(tab);
    setIsOpen(false);
    setIsMobileLangOpen(false);
  };

  const selectLanguage = (code: string) => {
    i18n.changeLanguage(code);
    localStorage.setItem('kullaberg_lang', code);
    setIsLangOpen(false);
    setIsOpen(false);
    setIsMobileLangOpen(false);
  };

  const currentLang = LANGUAGES.find(l => l.code === i18n.language) || LANGUAGES[0];

  return (
    <nav className="bg-ebony text-white shadow-lg sticky top-0 z-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between items-center h-20">

          {/* Logo & Brand */}
          <div className="flex items-center gap-3 cursor-pointer" onClick={() => handleNav('home')}>
            <img src="/favicon-simple.svg" alt="Naturvärdarna Logo" className="h-12 w-12" />
            <span className="text-3xl font-bold tracking-wide hidden sm:block">Naturvärdarna</span>
          </div>

          {/* Desktop Nav */}
          <div className="hidden md:flex items-center space-x-8 font-medium">
            <button
              onClick={() => handleNav('home')}
              className={`hover:text-gold transition-colors cursor-pointer pb-1 ${activeTab === 'home' ? 'border-b-2 border-gold text-gold' : ''}`}
            >
              {t('nav.home')}
            </button>
            <button
              onClick={() => handleNav('about')}
              className={`hover:text-gold transition-colors cursor-pointer pb-1 ${activeTab === 'about' ? 'border-b-2 border-gold text-gold' : ''}`}
            >
              {t('nav.about')}
            </button>

            {/* Desktop Language Dropdown */}
            <div className="relative" ref={dropdownRef}>
              <button
                onClick={() => setIsLangOpen(!isLangOpen)}
                className="flex items-center gap-2 bg-slate-teal hover:bg-seafoam px-4 py-2 rounded-md transition-colors cursor-pointer font-bold select-none"
              >
                <img src={currentLang.flag} alt="Flag" className="w-5 h-auto rounded-xs" />
                <span>{currentLang.label}</span>
                <ChevronDown size={18} className={`transition-transform duration-200 ${isLangOpen ? 'rotate-180' : ''}`} />
              </button>

              {/* Dropdown Menu */}
              {isLangOpen && (
                <div className="absolute right-0 mt-2 w-40 bg-white rounded-lg shadow-xl py-2 border border-gray-100 overflow-hidden z-50 animate-fade-in">
                  {LANGUAGES.map((lang) => (
                    <button
                      key={lang.code}
                      onClick={() => selectLanguage(lang.code)}
                      className={`w-full text-left px-4 py-2.5 flex items-center gap-3 hover:bg-eggshell transition-colors cursor-pointer ${currentLang.code === lang.code ? 'bg-eggshell/50 font-bold text-slate-teal' : 'text-gray-700'}`}
                    >
                      <img src={lang.flag} alt="Flag" className="w-5 h-auto rounded-xs" />
                      {lang.name}
                    </button>
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* Mobile Menu Toggle Button */}
          <div className="md:hidden flex items-center">
            <button onClick={() => setIsOpen(!isOpen)} className="text-eggshell hover:text-gold cursor-pointer p-2">
              {isOpen ? <X size={28} /> : <Menu size={28} />}
            </button>
          </div>
        </div>
      </div>

      {/* Mobile Nav Dropdown (Now using absolute positioning for overlay) */}
      {isOpen && (
        <div className="md:hidden absolute top-full left-0 w-full bg-moss border-t border-ebony shadow-2xl animate-fade-in z-50">
          <div className="px-2 pt-2 pb-4 space-y-1 sm:px-3">
            <button onClick={() => handleNav('home')} className="block w-full text-left px-3 py-4 text-eggshell font-medium border-b border-ebony/30 cursor-pointer">
              {t('nav.home')}
            </button>
            <button onClick={() => handleNav('about')} className="block w-full text-left px-3 py-4 text-eggshell font-medium border-b border-ebony/30 cursor-pointer">
              {t('nav.about')}
            </button>

            {/* Mobile Language Selector (Accordion) */}
            <div className="px-3 py-4">
              <button
                onClick={() => setIsMobileLangOpen(!isMobileLangOpen)}
                className="w-full flex justify-between items-center text-sm text-eggshell/80 uppercase tracking-wider font-bold cursor-pointer transition-colors hover:text-white"
              >
                <span>{t('nav.languageSelector')}</span>
                <ChevronDown size={20} className={`transition-transform duration-200 ${isMobileLangOpen ? 'rotate-180' : ''}`} />
              </button>

              {isMobileLangOpen && (
                <div className="flex flex-col gap-2 mt-4 animate-fade-in">
                  {LANGUAGES.map((lang) => (
                    <button
                      key={lang.code}
                      onClick={() => selectLanguage(lang.code)}
                      className={`flex items-center gap-3 px-4 py-3 rounded-lg transition-colors cursor-pointer ${currentLang.code === lang.code ? 'bg-slate-teal text-white font-bold' : 'bg-ebony/20 text-eggshell hover:bg-ebony/40'}`}
                    >
                      <img src={lang.flag} alt="Flag" className="w-6 h-auto rounded-xs" />
                      {lang.name}
                    </button>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </nav>
  );
};

const Footer = () => {
  const { t } = useTranslation();

  return (
    <footer className="bg-ebony text-white py-5 md:py-8 text-center mt-auto border-t-4 border-goldenrod">
      <div className="max-w-7xl mx-auto px-4 flex flex-col md:flex-row justify-between items-center gap-3 md:gap-4">

        {/* Left side: Logo and Copyright */}
        <div className="flex items-center gap-2 md:gap-3">
          <img src="/favicon-simple.svg" alt="Logo" className="h-6 w-6 md:h-8 md:w-8 opacity-80" />
          <p className="text-sm md:text-base font-medium tracking-wide">
            © {new Date().getFullYear()} {t('footerCore')} <span className="hidden md:inline">{t('footerSlogan')}</span>
          </p>
        </div>

        {/* Right side: Reserve Name */}
        <div className="text-xs md:text-sm text-eggshell/70">
          Kullabergs Naturreservat
        </div>

      </div>
    </footer>
  );
};

export default function App() {
  const [activeTab, setActiveTab] = useState<Tab>(() => {
    const hash = window.location.hash.replace('#', '');
    return hash === 'about' ? 'about' : 'home';
  });

  useEffect(() => {
    window.location.hash = activeTab;
    window.scrollTo(0, 0);
  }, [activeTab]);

  useEffect(() => {
    const handleHashChange = () => {
      const hash = window.location.hash.replace('#', '');
      setActiveTab(hash === 'about' ? 'about' : 'home');
    };

    window.addEventListener('hashchange', handleHashChange);
    return () => window.removeEventListener('hashchange', handleHashChange);
  }, []);

  return (
    <div className="min-h-screen flex flex-col font-sans bg-white selection:bg-gold selection:text-ebony">
      <Navbar activeTab={activeTab} setActiveTab={setActiveTab} />
      <main className="grow">
        {activeTab === 'home' ? <Home /> : <About />}
      </main>
      <Footer />
    </div>
  );
}