'use client';

import { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { usePathname } from 'next/navigation';
import { useTranslations, useLocale } from 'next-intl';
import { useRouter } from 'next/navigation';
import { locales } from '@/config';

export default function MobileHeader() {
  const [isLanguageOpen, setIsLanguageOpen] = useState(false);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const languageDropdownRef = useRef<HTMLDivElement>(null);
  const pathname = usePathname();
  const t = useTranslations('Navigation');
  const tLang = useTranslations('LanguageSwitcher');
  const tCommon = useTranslations('Common');
  const locale = useLocale();
  const router = useRouter();

  // Обработчик клика вне языкового переключателя
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (languageDropdownRef.current && !languageDropdownRef.current.contains(event.target as Node)) {
        setIsLanguageOpen(false);
      }
    };

    if (isLanguageOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isLanguageOpen]);

  const handleLocaleChange = (newLocale: string) => {
    const newPath = `/${newLocale}${pathname.startsWith(`/${locale}`) ? pathname.substring(locale.length + 1) : pathname}`;
    router.replace(newPath);
    setIsLanguageOpen(false);
  };

  const handleContactClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
    e.preventDefault();
    const footer = document.getElementById('footer-section');
    if (footer) {
      footer.scrollIntoView({ behavior: 'smooth' });
    }
  };

  const navItems = [
    { key: 'home', path: '/' },
    { key: 'about', path: '/about' },
    { key: 'location', path: '/location' },
    { key: 'team', path: '/team' },
    { key: 'investors', path: '/investors' },
    { key: 'media', path: '/media' },
    { key: 'contact', path: '#footer-section' },
  ];

  const moreItems = [
    { key: 'characteristics', path: '/characteristics' },
    { key: 'villas_layout', path: '/villas-layout' },
    { key: 'safety_resilience', path: '/safety-resilience' },
    { key: 'environmental_sustainability', path: '/environmental-sustainability' },
    { key: 'reasons_to_invest', path: '/reasons-to-invest' },
  ];

  const getLocalizedPath = (path: string) => {
    if (path === '/') {
        return `/${locale}`;
    }
    return `/${locale}${path}`;
  }

  const isActive = (path: string) => {
    const localizedPath = getLocalizedPath(path);
    if (path === '/') {
      return pathname === `/${locale}` || pathname === `/${locale}/` || pathname === '/';
    }
    return pathname === localizedPath || pathname.startsWith(localizedPath + '/');
  }

  return (
    <>
      <header className="w-full bg-white flex items-center justify-between py-[5px] pl-3 pr-0">
        {/* Left: Logo */}
        <div className="w-[55px] h-[55px] flex-shrink-0">
          <Link href={getLocalizedPath('/')} className="w-full h-full relative block">
            <Image
              src="/images/logo/logotype.svg"
              alt="LAKE Resort Residence"
              fill
              sizes="55px"
              className="object-contain"
              style={{ color: "#2C2C2C" }}
              priority
            />
          </Link>
        </div>

        {/* Right: Frame 1584 */}
        <div className="flex justify-end items-center flex-shrink-0">
          {/* Language Switcher */}
          <div className="relative" ref={languageDropdownRef}>
            <button
              onClick={() => setIsLanguageOpen(!isLanguageOpen)}
              className="w-[77px] h-[43px] flex justify-center items-center flex-shrink-0 rounded-lg"
            >
              <div className="flex py-2 px-4 items-start gap-2 rounded-lg bg-white">
                <span className="text-[#666] font-inter text-lg font-medium leading-[150%]">
                  {locale === 'ru' ? 'РУС' : locale === 'en' ? 'ENG' : locale === 'ar' ? 'العربية' : locale === 'zh' ? '中文' : locale.toUpperCase()}
                </span>
                <div className="flex w-4 py-1 px-0.5 flex-col justify-center items-center gap-2 self-stretch">
                  <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                  </svg>
                </div>
              </div>
            </button>
            {isLanguageOpen && (
              <div className="absolute right-0 mt-2 w-40 bg-white rounded-lg shadow-lg py-2 z-[9999] animate-slideDownFadeInMenu">
                {locales.map((lng: string) => (
                  <button
                    key={lng}
                    onClick={() => handleLocaleChange(lng)}
                    className={`w-full px-4 py-2 text-left font-roboto text-lg hover:bg-gray-50 ${
                      locale === lng ? 'font-medium text-[#2C2C2C]' : 'font-light text-[#666]'
                    }`}
                  >
                    {lng === 'ru' ? 'РУС' : lng === 'en' ? 'ENG' : lng === 'ar' ? 'العربية' : lng === 'zh' ? '中文' : lng.toUpperCase()}
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Mobile Menu Button */}
          <button
            onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
            className="w-[56px] h-[48px] flex justify-center items-center flex-shrink-0 rounded-lg"
          >
            <div className="flex py-2 px-3 justify-center items-center gap-2 rounded-lg">
              <div className="w-8 h-8 relative">
                <svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                </svg>
              </div>
            </div>
          </button>
        </div>
      </header>

      {/* Mobile Menu Overlay */}
      {isMobileMenuOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-50 z-[9998] transition-all duration-300 ease-out animate-slideDownFadeInMenu" onClick={() => setIsMobileMenuOpen(false)}>
          <div className="bg-white w-full max-w-sm h-full p-6 transition-all duration-300 ease-out animate-slideDownFadeInMenu">
            <div className="flex flex-col gap-4">
              {navItems.map((item) => (
                <div key={item.path} className="flex flex-col">
                  <Link
                    href={item.path.startsWith('#') ? item.path : getLocalizedPath(item.path)}
                    onClick={(e) => {
                      if (item.path.startsWith('#')) {
                        handleContactClick(e);
                      }
                      setIsMobileMenuOpen(false);
                    }}
                    className={`px-4 py-3 font-roboto text-lg font-medium leading-[150%] transition-colors ${
                      isActive(item.path) && !item.path.startsWith('#') ? 'text-[#2C2C2C]' : 'text-[#666] hover:text-[#2C2C2C]'
                    }`}
                  >
                    {t(item.key)}
                  </Link>
                  {isActive(item.path) && !item.path.startsWith('#') && (
                    <div className="ml-4 w-[51px] h-[1px] bg-[#2C2C2C]" />
                  )}
                </div>
              ))}
              
              <div className="border-t pt-4">
                <h3 className="text-[#666] font-roboto text-sm font-medium mb-2">{t('more')}</h3>
                {moreItems.map((item) => (
                  <div key={item.path} className="flex flex-col">
                    <Link
                      href={getLocalizedPath(item.path)}
                      className={`block px-4 py-2 font-roboto text-lg font-light transition-colors ${
                        isActive(item.path) ? 'text-[#2C2C2C]' : 'text-[#666] hover:text-[#2C2C2C] hover:bg-gray-50'
                      }`}
                      onClick={() => setIsMobileMenuOpen(false)}
                    >
                      {t(item.key)}
                    </Link>
                    {isActive(item.path) && (
                      <div className="ml-4 w-[51px] h-[1px] bg-[#2C2C2C]" />
                    )}
                  </div>
                ))}
              </div>

              <div className="border-t pt-4">
                <div className="flex flex-col">
                  <Link
                    href={getLocalizedPath('/lake-token')}
                    className={`flex items-center gap-2 px-4 py-3 transition-colors ${
                      isActive('/lake-token') ? 'text-[#002F5E]' : 'text-[#002F5E]'
                    }`}
                    onClick={() => setIsMobileMenuOpen(false)}
                  >
                    <div className="w-7 h-7 relative">
                      <Image
                        src="/images/logo/icon.png"
                        alt="LAKE TOKEN"
                        fill
                        sizes="28px"
                        className="object-contain"
                      />
                    </div>
                    <span className="font-roboto text-lg font-semibold leading-[150%]">
                      {tCommon('lake_token')}
                    </span>
                  </Link>
                  {isActive('/lake-token') && (
                    <div className="ml-4 w-8 h-[1px] bg-[#002F5E]" />
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
} 