import { useState, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Menu, X, ChevronDown, ArrowRight, Sparkles } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Link, useLocation } from "wouter";
import { useTranslation } from "@/lib/use-translation";
import type { Language } from "@/lib/translations";

const languageFlags: Record<Language, string> = {
  en: "🇬🇧",
  tr: "🇹🇷",
  es: "🇪🇸",
};

const languageLabels: Record<Language, string> = {
  en: "English",
  tr: "Türkçe",
  es: "Español",
};

export default function Navigation() {
  const [isOpen, setIsOpen] = useState(false);
  const [scrollY, setScrollY] = useState(0);
  const [isHovered, setIsHovered] = useState(false);
  const [langOpen, setLangOpen] = useState(false);
  const [location] = useLocation();
  const isHomePage = location === '/';
  const { t, language, setLanguage } = useTranslation();
  const langRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleScroll = () => setScrollY(window.scrollY);
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => { document.body.style.overflow = ''; };
  }, [isOpen]);

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (langRef.current && !langRef.current.contains(e.target as Node)) {
        setLangOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const scrollToSection = (sectionId: string) => {
    setIsOpen(false);
    setTimeout(() => {
      const element = document.getElementById(sectionId);
      if (element) {
        const navHeight = 64;
        const elementPosition = element.offsetTop - navHeight;
        window.scrollTo({
          top: elementPosition,
          behavior: 'smooth'
        });
      }
    }, 100);
  };

  const navItems = [
    { label: t.navItems[7] || "Products", href: "/products", badge: "NEW" as const },
    { label: t.navItems[0], href: "/human-development" },
    { label: t.navItems[1], href: "/decision-intelligence" },
    { label: t.navItems[2], action: isHomePage ? () => scrollToSection("enterprise") : () => { window.location.href = "/#enterprise"; } },
    { label: t.navItems[3], href: "/ai-consulting-services-pricing" },
    { label: t.navItems[4], href: "/ai-events-trainings" },
    { label: t.navItems[5], href: "/about" },
  ];

  return (
    <>
    <nav className="fixed top-0 left-0 right-0 z-50 backdrop-blur-lg bg-gradient-to-r from-black/20 via-purple-900/10 to-black/20">
      <div className="max-w-7xl mx-auto px-6 lg:px-8">
        <div className="relative flex items-center justify-between h-16">
          <Link 
            href="/" 
            className="flex items-center space-x-2 cursor-pointer group"
            onMouseEnter={() => setIsHovered(true)}
            onMouseLeave={() => setIsHovered(false)}
          >
            <motion.div 
              className="flex items-center justify-center"
              animate={{
                width: scrollY > 100 ? "32px" : "40px",
                height: scrollY > 100 ? "32px" : "40px"
              }}
              transition={{ duration: 0.3, ease: "easeInOut" }}
            >
              <img 
                src="/images/oktogon-logo.svg" 
                alt="OktoPeople Logo" 
                className="w-full h-full filter brightness-0 invert"
              />
            </motion.div>
            <motion.div 
              className="text-white font-semibold tracking-tight"
              style={{ fontFamily: 'Poppins, sans-serif' }}
              animate={{
                fontSize: scrollY > 100 ? "18px" : "20px"
              }}
              transition={{ duration: 0.3, ease: "easeInOut" }}
            >
              OktoPeople
            </motion.div>
          </Link>

          <div className="hidden md:flex absolute left-1/2 -translate-x-1/2 items-center space-x-5 lg:space-x-7">
            {navItems.map((item) => (
              item.action ? (
                <button
                  key={item.label}
                  onClick={item.action}
                  className="text-white/80 hover:text-white transition-colors duration-200 text-[13px] font-medium"
                  style={{ fontFamily: 'Poppins, sans-serif' }}
                >
                  {item.label}
                </button>
              ) : (
                <Link key={item.label} href={item.href!}>
                  <span
                    className={`inline-flex items-center gap-1.5 text-[13px] font-medium transition-colors duration-200 cursor-pointer ${
                      location === item.href 
                        ? "text-white" 
                        : "text-white/80 hover:text-white"
                    }`}
                    style={{ fontFamily: 'Poppins, sans-serif' }}
                  >
                    {item.label}
                    {item.badge && (
                      <motion.span
                        animate={{ rotate: [0, -8, 7, -6, 5, -3, 2, 0] }}
                        transition={{ duration: 0.9, ease: "easeInOut", repeat: Infinity, repeatDelay: 2.6 }}
                        whileHover={{ scale: 1.1, rotate: 0 }}
                        style={{ transformOrigin: "50% 50%" }}
                        className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wider bg-gradient-to-r from-violet-500 to-emerald-500 text-white shadow-[0_0_10px_rgba(139,92,246,0.5)]"
                      >
                        <Sparkles className="w-2.5 h-2.5" />
                        {item.badge}
                      </motion.span>
                    )}
                  </span>
                </Link>
              )
            ))}
          </div>

          <div className="hidden md:flex items-center gap-4">
            <div className="relative" ref={langRef}>
              <button
                onClick={() => setLangOpen(!langOpen)}
                className="flex items-center gap-1 px-2 py-1 rounded-lg text-white/80 hover:text-white hover:bg-white/10 transition-all duration-200 text-sm"
              >
                <span className="text-base">{languageFlags[language]}</span>
                <ChevronDown className="w-3 h-3" />
              </button>
              {langOpen && (
                <div className="absolute right-0 top-full mt-1 bg-black/90 backdrop-blur-lg border border-white/10 rounded-lg overflow-hidden min-w-[120px] shadow-xl">
                  {(Object.keys(languageFlags) as Language[]).map((lang) => (
                    <button
                      key={lang}
                      onClick={() => { setLanguage(lang); setLangOpen(false); }}
                      className={`flex items-center gap-2 w-full px-3 py-2 text-sm transition-colors duration-200 ${
                        language === lang ? "text-white bg-white/10" : "text-white/70 hover:text-white hover:bg-white/5"
                      }`}
                      style={{ fontFamily: 'Poppins, sans-serif' }}
                    >
                      <span>{languageFlags[lang]}</span>
                      <span>{languageLabels[lang]}</span>
                    </button>
                  ))}
                </div>
              )}
            </div>

            <motion.button
              className="relative px-6 py-2 rounded-xl text-white font-medium overflow-hidden group bg-transparent border-2"
              style={{
                borderImage: `conic-gradient(
                  from var(--border-angle, 0deg),
                  transparent 0deg,
                  transparent 270deg,
                  rgba(139, 92, 246, 0.8) 300deg,
                  rgba(16, 185, 129, 0.8) 330deg,
                  rgba(59, 130, 246, 0.8) 360deg,
                  transparent 390deg,
                  transparent 720deg
                ) 1`,
                '--border-angle': '0deg'
              } as any}
              onClick={() => window.location.href = "/contact"}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              animate={{
                '--border-angle': ['0deg', '360deg']
              } as any}
              transition={{
                duration: 3,
                repeat: Infinity,
                ease: "linear"
              }}
            >
              <span className="relative z-10">
                Get Started
              </span>
            </motion.button>
          </div>

          <button
            className="md:hidden relative w-10 h-10 flex items-center justify-center text-white rounded-xl touch-manipulation"
            onClick={() => setIsOpen(!isOpen)}
            aria-label="Toggle menu"
          >
            <AnimatePresence mode="wait">
              {isOpen ? (
                <motion.div key="close" initial={{ rotate: -90, opacity: 0 }} animate={{ rotate: 0, opacity: 1 }} exit={{ rotate: 90, opacity: 0 }} transition={{ duration: 0.15 }}>
                  <X className="w-6 h-6" />
                </motion.div>
              ) : (
                <motion.div key="open" initial={{ rotate: 90, opacity: 0 }} animate={{ rotate: 0, opacity: 1 }} exit={{ rotate: -90, opacity: 0 }} transition={{ duration: 0.15 }}>
                  <Menu className="w-6 h-6" />
                </motion.div>
              )}
            </AnimatePresence>
          </button>
        </div>
      </div>

    </nav>

    {/* Mobile full-screen drawer — rendered outside <nav> to avoid backdrop-filter stacking context clipping */}
    <AnimatePresence>
        {isOpen && (
          <>
            {/* Backdrop */}
            <motion.div
              key="backdrop"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.2 }}
              className="fixed inset-0 z-40 bg-black/60 backdrop-blur-sm md:hidden"
              onClick={() => setIsOpen(false)}
            />

            {/* Drawer panel — slides in from right */}
            <motion.div
              key="drawer"
              initial={{ x: "100%" }}
              animate={{ x: 0 }}
              exit={{ x: "100%" }}
              transition={{ type: "spring", stiffness: 380, damping: 38, mass: 0.8 }}
              className="fixed top-0 right-0 bottom-0 z-50 w-full max-w-sm md:hidden flex flex-col"
              style={{ background: "linear-gradient(160deg, #0a0a12 0%, #0d0820 50%, #080d18 100%)" }}
            >
              {/* Header row */}
              <div className="flex items-center justify-between px-6 py-5 border-b border-white/8">
                <Link href="/" onClick={() => setIsOpen(false)} className="flex items-center gap-2.5">
                  <img src="/images/oktogon-logo.svg" alt="OktoPeople" className="w-7 h-7 filter brightness-0 invert" />
                  <span className="text-white font-semibold text-lg" style={{ fontFamily: 'Poppins, sans-serif' }}>OktoPeople</span>
                </Link>
                <button
                  onClick={() => setIsOpen(false)}
                  className="w-10 h-10 flex items-center justify-center rounded-xl bg-white/8 text-white/70 hover:text-white hover:bg-white/12 transition-all touch-manipulation"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              {/* Nav links — scrollable middle area */}
              <div className="flex-1 overflow-y-auto px-4 py-4">
                {/* Home */}
                <motion.div
                  initial={{ opacity: 0, x: 24 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: 0.05 }}
                >
                  {isHomePage ? (
                    <button
                      onClick={() => { scrollToSection("hero"); setIsOpen(false); }}
                      className={`flex items-center justify-between w-full px-4 py-4 rounded-2xl text-left transition-all duration-200 touch-manipulation group ${
                        location === '/' ? 'bg-white/10 text-white' : 'text-white/70 hover:text-white hover:bg-white/6'
                      }`}
                      style={{ fontFamily: 'Poppins, sans-serif' }}
                    >
                      <span className="text-[17px] font-medium">Home</span>
                      {location === '/' && <div className="w-1.5 h-1.5 rounded-full bg-violet-400" />}
                    </button>
                  ) : (
                    <Link href="/">
                      <button
                        onClick={() => setIsOpen(false)}
                        className="flex items-center justify-between w-full px-4 py-4 rounded-2xl text-left text-white/70 hover:text-white hover:bg-white/6 transition-all duration-200 touch-manipulation"
                        style={{ fontFamily: 'Poppins, sans-serif' }}
                      >
                        <span className="text-[17px] font-medium">Home</span>
                      </button>
                    </Link>
                  )}
                </motion.div>

                {navItems.map((item, i) => (
                  <motion.div
                    key={item.label}
                    initial={{ opacity: 0, x: 24 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: 0.07 + i * 0.04 }}
                  >
                    {item.action ? (
                      <button
                        onClick={() => { item.action!(); setIsOpen(false); }}
                        className={`flex items-center justify-between w-full px-4 py-4 rounded-2xl text-left transition-all duration-200 touch-manipulation ${
                          'text-white/70 hover:text-white hover:bg-white/6'
                        }`}
                        style={{ fontFamily: 'Poppins, sans-serif' }}
                      >
                        <span className="text-[17px] font-medium">{item.label}</span>
                      </button>
                    ) : (
                      <Link href={item.href!}>
                        <button
                          onClick={() => setIsOpen(false)}
                          className={`flex items-center justify-between w-full px-4 py-4 rounded-2xl text-left transition-all duration-200 touch-manipulation ${
                            location === item.href
                              ? 'bg-white/10 text-white'
                              : 'text-white/70 hover:text-white hover:bg-white/6'
                          }`}
                          style={{ fontFamily: 'Poppins, sans-serif' }}
                        >
                          <span className="inline-flex items-center gap-2 text-[17px] font-medium">
                            {item.label}
                            {item.badge && (
                              <motion.span
                                animate={{ rotate: [0, -8, 7, -6, 5, -3, 2, 0] }}
                                transition={{ duration: 0.9, ease: "easeInOut", repeat: Infinity, repeatDelay: 2.6 }}
                                style={{ transformOrigin: "50% 50%" }}
                                className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-gradient-to-r from-violet-500 to-emerald-500 text-white shadow-[0_0_10px_rgba(139,92,246,0.5)]"
                              >
                                <Sparkles className="w-3 h-3" />
                                {item.badge}
                              </motion.span>
                            )}
                          </span>
                          {location === item.href && <div className="w-1.5 h-1.5 rounded-full bg-violet-400" />}
                        </button>
                      </Link>
                    )}
                  </motion.div>
                ))}

                {/* Language section */}
                <motion.div
                  initial={{ opacity: 0, x: 24 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: 0.38 }}
                  className="mt-4 pt-4 border-t border-white/8"
                >
                  <p className="px-4 pb-3 text-xs font-semibold uppercase tracking-widest text-white/30" style={{ fontFamily: 'Poppins, sans-serif' }}>Language</p>
                  <div className="flex flex-col gap-1">
                    {(Object.keys(languageFlags) as Language[]).map((lang) => (
                      <button
                        key={lang}
                        onClick={() => { setLanguage(lang); setIsOpen(false); }}
                        className={`flex items-center gap-3 w-full px-4 py-3.5 rounded-2xl transition-all duration-200 touch-manipulation ${
                          language === lang
                            ? 'bg-violet-500/15 text-white border border-violet-500/25'
                            : 'text-white/50 hover:text-white/80 hover:bg-white/5'
                        }`}
                        style={{ fontFamily: 'Poppins, sans-serif' }}
                      >
                        <span className="text-xl leading-none">{languageFlags[lang]}</span>
                        <span className="text-[15px] font-medium">{languageLabels[lang]}</span>
                        {language === lang && (
                          <div className="ml-auto w-2 h-2 rounded-full bg-violet-400" />
                        )}
                      </button>
                    ))}
                  </div>
                </motion.div>
              </div>

              {/* Pinned bottom CTA */}
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.28 }}
                className="px-5 py-5 border-t border-white/8"
                style={{ paddingBottom: 'calc(1.25rem + env(safe-area-inset-bottom, 0px))' }}
              >
                <button
                  onClick={() => { window.location.href = "/contact"; setIsOpen(false); }}
                  className="flex items-center justify-center gap-2 w-full py-4 rounded-2xl font-semibold text-[15px] text-white transition-all duration-200 active:scale-[0.97] touch-manipulation"
                  style={{
                    fontFamily: 'Poppins, sans-serif',
                    background: 'linear-gradient(135deg, #7c3aed 0%, #6d28d9 40%, #059669 100%)',
                    boxShadow: '0 4px 24px rgba(124, 58, 237, 0.35)',
                  }}
                >
                  Get Started
                  <ArrowRight className="w-4 h-4" />
                </button>
              </motion.div>
            </motion.div>
          </>
        )}
    </AnimatePresence>
    </>
  );
}