"use client"

import { useState, useEffect } from "react"
import { usePathname } from "next/navigation"
import Image from "next/image"
import Link from "next/link"
import { motion, AnimatePresence } from "framer-motion"
import { Menu, X, Phone, Home, Briefcase, Users, Calculator, Mail, LogIn } from "lucide-react"
import { createPortal } from "react-dom"

const navLinks = [
  { href: "/", label: "Ana Sayfa", icon: Home },
  { href: "/#hizmetler", label: "Hizmetlerimiz", icon: Briefcase },
  { href: "/hakkimizda", label: "Hakkımızda", icon: Users },
  { href: "/sure-hesaplama", label: "Süre Hesaplama", icon: Calculator },
  { href: "/#basvuru", label: "İletişim", icon: Mail },
]

function SidebarMenu({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) {
  const [mounted, setMounted] = useState(false)
  const pathname = usePathname()

  useEffect(() => {
    setMounted(true)
  }, [])

  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = "hidden"
    } else {
      document.body.style.overflow = ""
    }
    return () => {
      document.body.style.overflow = ""
    }
  }, [isOpen])

  if (!mounted) return null

  return createPortal(
    <AnimatePresence>
      {isOpen && (
        <>
          {/* Overlay - sağ taraf */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.2 }}
            onClick={onClose}
            className="fixed inset-0 bg-black/40 z-[9998]"
          />
          
          {/* Sidebar - Soldan açılan */}
          <motion.div 
            initial={{ x: "-100%" }}
            animate={{ x: 0 }}
            exit={{ x: "-100%" }}
            transition={{ duration: 0.25, ease: "easeOut" }}
            className="fixed top-0 left-0 bottom-0 w-[280px] bg-white z-[9999] shadow-2xl flex flex-col"
          >
            {/* Header - Logo ve Kapat */}
            <div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
              <Link href="/" onClick={onClose}>
                <Image
                  src="/analitiklogo.png"
                  alt="Analitik İSG"
                  width={120}
                  height={40}
                  className="h-8 w-auto"
                />
              </Link>
              <button
                onClick={onClose}
                className="p-2 text-gray-500 hover:text-black hover:bg-gray-100 rounded-lg transition-colors"
              >
                <X size={22} />
              </button>
            </div>

            {/* Menu Items */}
            <div className="flex-1 py-4 px-3 overflow-y-auto">
              <div className="space-y-1">
                {navLinks.map((link) => {
                  const Icon = link.icon
                  const isActive = pathname === link.href || 
                    (link.href !== "/" && pathname.startsWith(link.href.split("#")[0]))
                  
                  return (
                    <Link
                      key={link.href}
                      href={link.href}
                      onClick={onClose}
                      className={`flex items-center gap-3 py-3 px-4 text-[15px] font-medium rounded-lg transition-colors ${
                        isActive 
                          ? "bg-[#0F2A44] text-white" 
                          : "text-gray-700 hover:bg-gray-100"
                      }`}
                    >
                      <Icon className="w-5 h-5" />
                      {link.label}
                    </Link>
                  )
                })}
              </div>
            </div>

            {/* Bottom CTA Buttons */}
            <div className="p-4 border-t border-gray-100 space-y-2">
              <Link
                href="/giris"
                onClick={onClose}
                className="flex items-center justify-center gap-2 w-full px-4 py-3 rounded-lg bg-gray-100 text-gray-800 font-medium hover:bg-gray-200 transition-all text-sm"
              >
                <LogIn className="w-4 h-4" />
                Giriş Yap
              </Link>
              <a
                href="tel:+905551234567"
                className="flex items-center justify-center gap-2 w-full px-4 py-3 rounded-lg bg-[#0F2A44] text-white font-medium hover:bg-[#1a3a5c] transition-all text-sm"
              >
                <Phone className="w-4 h-4" />
                Hemen Arayın
              </a>
            </div>

            {/* Footer */}
            <div className="px-4 py-3 text-center border-t border-gray-50">
              <p className="text-xs text-gray-400">© 2026 Analitik İSG</p>
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>,
    document.body
  )
}

export default function Navbar() {
  const [isScrolled, setIsScrolled] = useState(false)
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false)
  const [hasVisited, setHasVisited] = useState(true)
  const pathname = usePathname()
  
  const isHomePage = pathname === "/"
  const shouldShowBg = !isHomePage || isScrolled
  
  useEffect(() => {
    const visited = sessionStorage.getItem("analitik_visited")
    if (!visited) {
      setHasVisited(false)
      sessionStorage.setItem("analitik_visited", "true")
    }
  }, [])

  const shouldAnimate = isHomePage && !hasVisited

  useEffect(() => {
    const handleScroll = () => setIsScrolled(window.scrollY > 50)
    window.addEventListener("scroll", handleScroll)
    return () => window.removeEventListener("scroll", handleScroll)
  }, [])

  return (
    <>
      <nav 
        className={`fixed top-0 left-0 right-0 z-[100] transition-all duration-500 ${
          shouldShowBg 
            ? "bg-white/95 backdrop-blur-md shadow-lg border-b border-gray-200/50" 
            : "bg-transparent"
        }`}
      >
        <div className="max-w-7xl mx-auto px-4 sm:px-6">
          <div className="flex justify-between items-center h-16 sm:h-18">
            {/* Hamburger Menu Button - Sol */}
            <motion.button
              initial={shouldAnimate ? { opacity: 0 } : { opacity: 1 }}
              animate={{ opacity: 1 }}
              transition={{ delay: shouldAnimate ? 1.5 : 0, duration: shouldAnimate ? 0.6 : 0 }}
              onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
              className="p-2 rounded-lg transition-colors text-[#0F2A44] hover:bg-gray-100"
              whileTap={{ scale: 0.95 }}
              aria-label="Menüyü aç"
            >
              <Menu size={24} />
            </motion.button>

            {/* Logo - Orta */}
            <motion.div
              initial={shouldAnimate ? { 
                scale: 1.2,
                opacity: 0 
              } : { scale: 1, opacity: 1 }}
              animate={{ 
                scale: 1,
                opacity: 1 
              }}
              transition={{ 
                duration: shouldAnimate ? 1.2 : 0,
                ease: [0.22, 1, 0.36, 1],
                delay: shouldAnimate ? 0.3 : 0
              }}
              className="absolute left-1/2 -translate-x-1/2"
            >
              <Link href="/" onClick={() => setIsMobileMenuOpen(false)}>
                <motion.div
                  whileHover={{ scale: 1.02 }}
                  whileTap={{ scale: 0.98 }}
                >
                  <Image
                    src="/analitiklogo.png"
                    alt="Analitik İSG"
                    width={200}
                    height={60}
                    className="h-10 sm:h-14 w-auto transition-all duration-300"
                    priority
                  />
                </motion.div>
              </Link>
            </motion.div>

            {/* Giriş Yap Butonu - Sağ */}
            <motion.div
              initial={shouldAnimate ? { opacity: 0, x: 20 } : { opacity: 1, x: 0 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ 
                duration: shouldAnimate ? 0.8 : 0,
                delay: shouldAnimate ? 1.8 : 0,
                ease: [0.22, 1, 0.36, 1]
              }}
            >
              <Link
                href="/giris"
                className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-[#0F2A44] hover:bg-gray-100 transition-all"
              >
                <LogIn className="w-4 h-4" />
                <span className="hidden sm:inline">Giriş Yap</span>
              </Link>
            </motion.div>
          </div>
        </div>
      </nav>

      {/* Sidebar Menu */}
      <SidebarMenu 
        isOpen={isMobileMenuOpen} 
        onClose={() => setIsMobileMenuOpen(false)} 
      />
    </>
  )
}
