'use client';

import { useState, useEffect } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { Menu, X } from 'lucide-react';
import { motion } from 'framer-motion';

export default function Header() {
  const router = useRouter();
  const pathname = usePathname();
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [showHeader, setShowHeader] = useState(true);
  const [lastScrollY, setLastScrollY] = useState(0);

  // Determine current page from pathname
  const getCurrentPage = () => {
    if (pathname === '/' || pathname === '') return 'home';
    if (pathname === '/calculator') return 'calculator';
    if (pathname === '/how-it-works') return 'how-it-works';
    if (pathname === '/about') return 'about';
    if (pathname === '/contact') return 'contact';
    return 'home';
  };

  const currentPage = getCurrentPage();

  useEffect(() => {
    // Hide header on scroll down, show on scroll up
    const handleScroll = () => {
      const currentScrollY = window.scrollY;

      // Always show header at the top of the page
      if (currentScrollY < 10) {
        setShowHeader(true);
      } else if (currentScrollY > lastScrollY) {
        // Scrolling down
        setShowHeader(false);
      } else {
        // Scrolling up
        setShowHeader(true);
      }

      setLastScrollY(currentScrollY);
    };

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

  const handleNavigate = (page: string) => {
    setMobileMenuOpen(false);
    const path = page === 'home' ? '/' : `/${page}`;
    router.push(path);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  return (
    <header
      className="glass-nav shadow-luxury z-50 fixed top-0 left-0 right-0 transition-transform duration-300 ease-in-out"
      style={{
        transform: showHeader ? 'translate3d(0,0,0)' : 'translate3d(0,-100%,0)',
        WebkitTransform: showHeader ? 'translate3d(0,0,0)' : 'translate3d(0,-100%,0)',
        WebkitBackfaceVisibility: 'hidden',
        backfaceVisibility: 'hidden'
      }}
    >
      <div className="max-w-7xl mx-auto px-4 py-3 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between">
          <motion.div
            className="flex items-center space-x-3 cursor-pointer group"
            onClick={() => handleNavigate('home')}
            whileHover={{ scale: 1.02 }}
            transition={{ type: "spring", stiffness: 400, damping: 17 }}
          >
            <motion.img
              src="/puffinOffset.webp"
              alt="Puffin Offset Logo"
              className="h-10 w-auto transition-transform duration-300 group-hover:scale-110"
              initial={{ opacity: 0, rotate: -10 }}
              animate={{ opacity: 1, rotate: 0 }}
              transition={{ duration: 0.6, delay: 0.2 }}
            />
            <motion.h1
              className="text-xl font-bold heading-luxury"
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.6, delay: 0.4 }}
            >
              Puffin Offset
            </motion.h1>
          </motion.div>

          {/* Mobile menu button */}
          <button
            className="sm:hidden p-2 rounded-md text-gray-600 hover:text-gray-900"
            onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
          >
            {mobileMenuOpen ? <X size={24} /> : <Menu size={24} />}
          </button>

          {/* Desktop navigation */}
          <nav className="hidden sm:flex space-x-2">
            {['calculator', 'how-it-works', 'about', 'contact'].map((page, index) => (
              <motion.button
                key={page}
                onClick={() => handleNavigate(page)}
                className={`px-4 py-2 rounded-xl font-medium transition-all duration-300 ${
                  currentPage === page
                    ? 'bg-gradient-to-r from-blue-600 to-blue-700 text-white shadow-lg'
                    : 'text-slate-600 hover:text-slate-900 hover:bg-white/60'
                }`}
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                initial={{ opacity: 0, y: -10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.4, delay: 0.6 + index * 0.1 }}
              >
                {page === 'how-it-works' ? 'How it Works' :
                 page.charAt(0).toUpperCase() + page.slice(1)}
              </motion.button>
            ))}
          </nav>
        </div>

        {/* Mobile navigation */}
        {mobileMenuOpen && (
          <nav className="sm:hidden mt-4 pb-2 space-y-2">
            <button
              onClick={() => handleNavigate('calculator')}
              className={`block w-full text-left px-4 py-2 rounded-lg ${
                currentPage === 'calculator'
                  ? 'bg-blue-50 text-blue-600 font-semibold'
                  : 'text-gray-600 hover:bg-gray-50'
              }`}
            >
              Calculator
            </button>
            <button
              onClick={() => handleNavigate('how-it-works')}
              className={`block w-full text-left px-4 py-2 rounded-lg ${
                currentPage === 'how-it-works'
                  ? 'bg-blue-50 text-blue-600 font-semibold'
                  : 'text-gray-600 hover:bg-gray-50'
              }`}
            >
              How it Works
            </button>
            <button
              onClick={() => handleNavigate('about')}
              className={`block w-full text-left px-4 py-2 rounded-lg ${
                currentPage === 'about'
                  ? 'bg-blue-50 text-blue-600 font-semibold'
                  : 'text-gray-600 hover:bg-gray-50'
              }`}
            >
              About
            </button>
            <button
              onClick={() => handleNavigate('contact')}
              className={`block w-full text-left px-4 py-2 rounded-lg ${
                currentPage === 'contact'
                  ? 'bg-blue-50 text-blue-600 font-semibold'
                  : 'text-gray-600 hover:bg-gray-50'
              }`}
            >
              Contact
            </button>
          </nav>
        )}
      </div>
    </header>
  );
}
