"use client";

import { useTranslations, useLocale } from 'next-intl';
import Link from 'next/link';
import { useState, useEffect, useRef } from 'react';
import { motion, AnimatePresence, useScroll, useSpring } from 'framer-motion';
import { usePathname, useRouter } from 'next/navigation';
import { useModal } from '@/context/ModalContext';
import Image from 'next/image';

export default function Header() {
  const t = useTranslations('navbar');
  const locale = useLocale();
  const pathname = usePathname();
  const router = useRouter();
  const [isScrolled, setIsScrolled] = useState(false);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const { openModal } = useModal();
  
  // Scroll ilerleme çubuğu için
  const { scrollYProgress } = useScroll();
  const scaleX = useSpring(scrollYProgress, {
    stiffness: 100,
    damping: 30,
    restDelta: 0.001
  });

  // Link oluşturma helper'ı (mevcut dil için)
  const createLocalizedHref = (path: string) => `/${locale}${path}`;

  useEffect(() => {
    const handleScroll = () => {
      const position = window.scrollY;
      setIsScrolled(position > 50);
    };

    window.addEventListener('scroll', handleScroll, { passive: true });
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  // Sayfa değiştiğinde mobil menüyü kapat
  useEffect(() => {
    setIsMobileMenuOpen(false);
  }, [pathname]);

  // Sayfa içi bağlantı yardımcı fonksiyonu
  const handleScrollToSection = (e: React.MouseEvent<HTMLAnchorElement>, sectionId: string) => {
    e.preventDefault();
    
    // Ana sayfa dışındaysa ana sayfaya git, sonra o bölüme kaydır
    if (pathname !== `/${locale}`) {
      router.push(`/${locale}/#${sectionId.replace('#', '')}`);
    } else {
      // Aynı sayfadaysa direkt olarak o bölüme kaydır
      const section = document.getElementById(sectionId.replace('#', ''));
      if (section) {
        section.scrollIntoView({ behavior: 'smooth' });
      }
    }
  };

  // Navbar linkleri
  const navLinks = [
    { href: '#about', label: t('about'), section: true },
    { href: '#services', label: t('services'), section: true },
    { href: '#partners', label: t('partners'), section: true },
    { href: '#faq', label: locale === 'tr' ? 'SSS' : 'FAQ', section: true },
    { href: 'https://gencmusiad.org.tr/bize-ulasin/', label: locale === 'tr' ? 'İletişim' : 'Contact', directLink: true, external: true },
  ];

  return (
    <header className={`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${isScrolled ? 'py-2' : 'py-4'}`}>
      {/* Modern ilerleme çubuğu */}
      <motion.div 
        className="absolute bottom-0 left-0 h-1 bg-gradient-to-r from-blue-500 via-indigo-500 to-blue-500 z-10"
        style={{ 
          scaleX, 
          transformOrigin: "left",
          width: "100%"
        }}
      />
      
      {/* Arka plan blur efekti */}
      <div className={`absolute inset-0 backdrop-blur-lg ${isScrolled ? 'bg-slate-900/80' : 'bg-transparent'} transition-colors duration-300`} />
      
      <div className="container mx-auto px-4 sm:px-6 lg:px-8 relative">
        <div className="flex items-center justify-between">
          {/* Logo */}
          <div className="flex items-center gap-2">
            <Link 
              href={createLocalizedHref('/')} 
              className="relative z-10 flex items-center"
            >
              <motion.div
                className="flex items-center"
                initial={false}
                animate={isScrolled ? { scale: 0.9 } : { scale: 1 }}
                transition={{ duration: 0.3 }}
              >
                <div className="relative">
                  <div className="relative w-auto h-16 md:h-20">
                    <Image 
                      src="/logos/logogm2.png" 
                      alt="GM2 Logo" 
                      width={220} 
                      height={110} 
                      className="object-contain h-full w-auto dark:filter dark:brightness-110 drop-shadow-[0_0_3px_rgba(255,255,255,0.3)]"
                      priority
                    />
                  </div>
                  {/* Minimal efekt - sadece hafif bir arka plan ışıması */}
                  <motion.div 
                    className="absolute -inset-1 rounded-lg blur-sm"
                    animate={{ 
                      opacity: [0.1, 0.2, 0.1],
                      background: ['rgba(59, 130, 246, 0.2)', 'rgba(99, 102, 241, 0.2)', 'rgba(59, 130, 246, 0.2)']
                    }}
                    transition={{ duration: 3, repeat: Infinity }}
                  />
                </div>
              </motion.div>
            </Link>
          </div>
          
          {/* Desktop Navigation */}
          <nav className="hidden lg:flex items-center space-x-1">
            {navLinks.map((link) => {
              const isActive = pathname === createLocalizedHref(link.href) || 
                              (link.section && pathname === createLocalizedHref('/') && location.hash === link.href);
              
              if (link.directLink) {
                return (
                  <a 
                    key={link.href} 
                    href={link.href}
                    target={link.external ? "_blank" : undefined}
                    rel={link.external ? "noopener noreferrer" : undefined}
                    className="relative px-4 py-2 text-sm font-medium group"
                  >
                    <span className={`relative z-10 transition-colors duration-300 text-blue-100 hover:text-white`}>
                      {link.label}
                    </span>
                  </a>
                );
              } else if (link.section) {
                return (
                  <a 
                    key={link.href} 
                    href={link.href}
                    onClick={(e) => handleScrollToSection(e, link.href)}
                    className="relative px-4 py-2 text-sm font-medium group"
                  >
                    <span className={`relative z-10 transition-colors duration-300 ${isActive ? 'text-white font-medium' : 'text-blue-100 group-hover:text-white'} text-base`}>
                      {link.label}
                    </span>
                    
                    {isActive && (
                      <motion.div
                        layoutId="navHighlight"
                        className="absolute inset-0 bg-white/10 rounded-full z-0"
                        initial={false}
                        transition={{ type: "spring", bounce: 0.25, duration: 0.5 }}
                      />
                    )}
                  </a>
                );
              } else {
                return (
                  <Link 
                    key={link.href} 
                    href={createLocalizedHref(link.href)}
                    className="relative px-4 py-2 text-sm font-medium group"
                  >
                    <span className={`relative z-10 transition-colors duration-300 ${isActive ? 'text-white font-medium' : 'text-blue-100 group-hover:text-white'} text-base`}>
                      {link.label}
                    </span>
                    
                    {isActive && (
                      <motion.div
                        layoutId="navHighlight"
                        className="absolute inset-0 bg-white/10 rounded-full z-0"
                        initial={false}
                        transition={{ type: "spring", bounce: 0.25, duration: 0.5 }}
                      />
                    )}
                  </Link>
                );
              }
            })}
          </nav>
          
          {/* Desktop Dil Seçimi ve CTA */}
          <div className="flex items-center gap-4">
            {/* Desktop için dil seçimi */}
            <div className="hidden lg:block">
              <LanguageSwitcher locale={locale} />
            </div>
            
            {/* Başvur butonu - Desktop */}
            <div className="hidden lg:block">
              <a 
                href="https://gm2.ifollow.com.tr/register" 
                target="_blank" 
                rel="noopener noreferrer"
              >
                <motion.button
                  className="relative overflow-hidden px-6 py-2.5 rounded-full bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-base font-medium"
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.98 }}
                >
                  <span className="relative z-10">
                    {t('apply')}
                  </span>
                  <motion.div 
                    className="absolute inset-0 bg-gradient-to-r from-indigo-600 to-blue-600"
                    initial={{ x: '100%' }}
                    whileHover={{ x: 0 }}
                    transition={{ duration: 0.4 }}
                  />
                </motion.button>
              </a>
            </div>
            
            {/* Mobil menü butonu */}
            <div className="lg:hidden flex items-center">
              <button 
                aria-label="Mobil Menü"
                onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
                className="p-2 text-white focus:outline-none focus:ring-2 focus:ring-blue-500 rounded-md"
              >
                <span className="sr-only">Menüyü Aç</span>
                <div className="relative w-6 h-5">
                  <motion.span
                    className="absolute h-0.5 w-6 bg-white rounded-full"
                    animate={{ 
                      top: isMobileMenuOpen ? '10px' : '0px', 
                      rotate: isMobileMenuOpen ? '45deg' : '0deg'
                    }}
                    transition={{ duration: 0.3 }}
                  />
                  <motion.span
                    className="absolute h-0.5 w-6 bg-white rounded-full top-[10px]"
                    animate={{ opacity: isMobileMenuOpen ? 0 : 1 }}
                    transition={{ duration: 0.3 }}
                  />
                  <motion.span
                    className="absolute h-0.5 w-6 bg-white rounded-full top-[20px]"
                    animate={{ 
                      top: isMobileMenuOpen ? '10px' : '20px', 
                      rotate: isMobileMenuOpen ? '-45deg' : '0deg'
                    }}
                    transition={{ duration: 0.3 }}
                  />
                </div>
              </button>
            </div>
          </div>
        </div>
      </div>
      
      {/* Mobil Menü */}
      <AnimatePresence>
        {isMobileMenuOpen && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: 'auto' }}
            exit={{ opacity: 0, height: 0 }}
            transition={{ duration: 0.3 }}
            className="lg:hidden relative overflow-hidden"
          >
            <div className="bg-slate-900/95 backdrop-blur-xl">
              <div className="container mx-auto px-4 py-4">
                <nav className="flex flex-col space-y-1">
                  {navLinks.map((link) => {
                    if (link.directLink) {
                      return (
                        <a 
                          key={link.href} 
                          href={link.href}
                          target={link.external ? "_blank" : undefined}
                          rel={link.external ? "noopener noreferrer" : undefined}
                          className="py-3 px-4 text-white hover:bg-white/5 rounded-lg transition-colors duration-200 text-base font-medium"
                        >
                          {link.label}
                        </a>
                      );
                    } else if (link.section) {
                      return (
                        <a 
                          key={link.href} 
                          href={link.href}
                          onClick={(e) => {
                            handleScrollToSection(e, link.href);
                            setIsMobileMenuOpen(false);
                          }}
                          className="py-3 px-4 text-white hover:bg-white/5 rounded-lg transition-colors duration-200 text-base font-medium"
                        >
                          {link.label}
                        </a>
                      );
                    } else {
                      return (
                        <Link 
                          key={link.href} 
                          href={createLocalizedHref(link.href)}
                          className="py-3 px-4 text-white hover:bg-white/5 rounded-lg transition-colors duration-200 text-base font-medium"
                          onClick={() => setIsMobileMenuOpen(false)}
                        >
                          {link.label}
                        </Link>
                      );
                    }
                  })}
                  
                  <div className="pt-4 pb-2">
                    <div className="h-px w-full bg-white/10" />
                  </div>
                  
                  {/* Dil Seçimi - Mobil menüye eklendi */}
                  <div className="py-2">
                    <LanguageSwitcher locale={locale} />
                  </div>
                  
                  <div className="flex justify-end items-center">
                    {/* Başvur butonu */}
                    <a 
                      href="https://gm2.ifollow.com.tr/register" 
                      target="_blank" 
                      rel="noopener noreferrer"
                      className="w-full"
                    >
                      <button 
                        className="w-full px-6 py-2.5 rounded-full bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-base font-medium"
                      >
                        {t('apply')}
                      </button>
                    </a>
                  </div>
                </nav>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </header>
  );
}

// Dil değiştirici bileşeni
function LanguageSwitcher({ locale }: { locale: string }) {
  return (
    <div className="flex items-center space-x-2">
      <a
        href="/tr"
        className={`flex items-center space-x-1 px-3 py-2 rounded-md transition-colors duration-200 text-sm font-medium ${
          locale === 'tr' 
            ? 'bg-gradient-to-r from-red-600 to-red-700 text-white' 
            : 'bg-white/10 text-blue-100 hover:text-white hover:bg-white/20'
        }`}
      >
        <div className="w-6 h-6 flex items-center justify-center overflow-hidden rounded-full border border-white/30 flex-shrink-0">
          <Image src="/flags/tr.svg" alt="Türkçe" width={24} height={24} className="w-full h-full object-cover" />
        </div>
        <span>TR</span>
      </a>
      
      <a
        href="/en"
        className={`flex items-center space-x-1 px-3 py-2 rounded-md transition-colors duration-200 text-sm font-medium ${
          locale === 'en' 
            ? 'bg-gradient-to-r from-blue-600 to-blue-700 text-white' 
            : 'bg-white/10 text-blue-100 hover:text-white hover:bg-white/20'
        }`}
      >
        <div className="w-6 h-6 flex items-center justify-center overflow-hidden rounded-full border border-white/30 flex-shrink-0">
          <Image src="/flags/en.svg" alt="English" width={24} height={24} className="w-full h-full object-cover" />
        </div>
        <span>EN</span>
      </a>
    </div>
  );
}