'use client';

import React, { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Menu, X, Sun, Moon } from 'lucide-react';
import { Button } from './ui/Button';
import { motion, AnimatePresence } from 'framer-motion';
import type { BackgroundMode } from '../types/theme';

// framer-motion v10 types can get confused in this repo setup and treat DOM props as `unknown`.
// These casts keep the runtime behavior identical while unblocking TS on `className`, etc.
const MotionHeader = motion.header as unknown as React.ComponentType<any>;
const MotionDiv = motion.div as unknown as React.ComponentType<any>;

interface HeaderProps {
  darkMode: boolean;
  backgroundMode: BackgroundMode;
  setBackgroundMode: (mode: BackgroundMode) => void;
  toggleTheme: () => void;
}

const navItems = [
  // { label: 'Home', href: '/' },
  { label: 'Solutions', href: '/solutions/b2b-qerp-crm' },

  { label: 'Pricing', href: '/pricing/b2b-qerp-crm' },
  { label: 'Contact', href: '/contact' },
];

export const Header: React.FC<HeaderProps> = ({ darkMode, backgroundMode, setBackgroundMode, toggleTheme }) => {
  const [isScrolled, setIsScrolled] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [clickCount, setClickCount] = useState(0);
  const clickTimerRef = useRef<NodeJS.Timeout | null>(null);
  const pathname = usePathname();

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

  // Smooth scroll to top helper
  const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
  };

  const handleMobileNavClick = () => {
    setMobileMenuOpen(false);
    scrollToTop();
  };

  const handleDesktopNavClick = () => {
    scrollToTop();
  };

  // Handle rapid clicks on logo to cycle background modes:
  // 0-4 => classic, 5-7 => blackMagic, 8 => living, then wrap (next click returns to classic)
  const handleLogoClick = () => {
    // Clear existing timer
    if (clickTimerRef.current) {
      clearTimeout(clickTimerRef.current);
    }

    setClickCount(prev => {
      const next = prev + 1;

      if (next >= 8) {
        setBackgroundMode('living');
        console.log('🌊 Living Background Activated!');
        return 0; // wrap the counter after 8
      }

      if (next >= 5) {
        if (backgroundMode !== 'blackMagic') {
          setBackgroundMode('blackMagic');
          console.log('🪄 Black Magic Mode Activated!');
        }
        return next;
      }

      if (backgroundMode !== 'classic') {
        setBackgroundMode('classic');
      }
      return next;
    });

    // Reset counter after 800ms of no clicks (does not change the active mode)
    clickTimerRef.current = setTimeout(() => {
      setClickCount(0);
    }, 800);

    // Scroll to top when logo is clicked
    scrollToTop();
  };

  return (
    <>
      <MotionHeader
        initial={{ y: -10 }}
        animate={{ y: 0 }}
        transition={{ type: "spring", stiffness: 100, damping: 20, duration: 6 }}
        className={`fixed top-0 left-0 right-0 z-50 flex justify-center transition-all duration-300 ${isScrolled ? 'pt-4' : 'pt-6'}`}
      >
        <div className={`
          relative flex items-center justify-between 
          ${isScrolled
            ? `w-[95%] sm:w-[90%] md:w-[85%] lg:w-[80%] max-w-6xl bg-white/40 dark:bg-slate-900/80 backdrop-blur-xl shadow-glass border border-white/40 dark:border-slate-700/50 rounded-2xl px-3 sm:px-5 py-1 md:py-2`
            : 'w-[95%] sm:w-full max-w-7xl px-3 sm:px-5 lg:px-8 py-2 md:py-3 bg-white/80 dark:bg-slate-900/80 backdrop-blur-xl shadow-glass border border-white/40 dark:border-slate-700/50 rounded-2xl'}
          transition-all duration-500 ease-[cubic-bezier(0.23,1,0.32,1)]
        `}>

          {/* Logo */}
          <div className="flex-shrink-0 flex items-center" onClick={handleLogoClick}>
            <Link href="/" className="flex items-center gap-2 group">
              <img
                src="https://knowbuildwebsiteassets.s3.ap-south-1.amazonaws.com/logo.svg"
                alt="knowbuild"
                className={`h-6 md:h-8 w-auto transition-transform duration-300 group-hover:scale-105 ${darkMode ? '' : ''}`}
              />
            </Link>
          </div>

          {/* Desktop Nav */}
          <nav className="hidden md:flex items-center gap-8 ml-2">
            {navItems.map((item) => (
              <Link
                key={item.label}
                href={item.href}
                onClick={handleDesktopNavClick}
                className={`text-md font-bold transition-colors relative group ${pathname === item.href
                  ? 'text-brand-blue'
                  : 'text-slate-600 dark:text-slate-300 hover:text-brand-blue dark:hover:text-brand-blue'
                  }`}
              >
                {item.label}
                <span className="absolute -bottom-1 left-0 w-0 h-0.5 bg-brand-orange transition-all duration-300 group-hover:w-full rounded-full"></span>
              </Link>
            ))}
          </nav>

          {/* Desktop CTA */}
          <div className="hidden md:flex items-center gap-4">
            <button
              onClick={toggleTheme}
              className="p-2 rounded-full text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
            >
              {darkMode ? <Sun size={20} /> : <Moon size={20} />}
            </button>

            <Link href="/book-demo">
              <Button size="sm" variant="primary" className="shadow-lg shadow-brand-orange/20">Book a Demo</Button>
            </Link>
            <Link href="/contact">
              <Button size="sm" variant="outline" className="border-slate-300 dark:border-white/20">Contact Sales</Button>
            </Link>
          </div>

          {/* Mobile Controls */}
          <div className="flex items-center md:hidden gap-4">
            <button
              onClick={toggleTheme}
              className="p-2 rounded-full text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
            >
              {darkMode ? <Sun size={18} /> : <Moon size={18} />}
            </button>

            <Link href="/book-demo">
              <Button size="sm" className="text-xs px-3 py-2">Book Demo</Button>
            </Link>
            <button
              onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
              className="text-slate-600 dark:text-slate-300 hover:text-brand-navy dark:hover:text-white p-1"
            >
              {mobileMenuOpen ? <X size={24} /> : <Menu size={24} />}
            </button>
          </div>
        </div>
      </MotionHeader>

      {/* Mobile Menu Overlay */}
      <AnimatePresence>
        {mobileMenuOpen && (
          <MotionDiv
            initial={{ opacity: 0, y: -20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            className="md:hidden fixed inset-0 z-40 pt-28 px-6 backdrop-blur-xl bg-white/95 dark:bg-slate-900/95"
          >
            <div className="flex flex-col gap-6">
              {navItems.map((item) => (
                <Link
                  key={item.label}
                  href={item.href}
                  onClick={handleMobileNavClick}
                  className={`text-2xl font-bold hover:text-brand-blue ${pathname === item.href
                    ? 'text-brand-blue'
                    : 'text-slate-800 dark:text-white'
                    }`}
                >
                  {item.label}
                </Link>
              ))}
              <Link href="/contact" onClick={handleMobileNavClick}>
                <Button variant="primary" size="lg" fullWidth className="mt-4">Contact Sales</Button>
              </Link>
            </div>
          </MotionDiv>
        )}
      </AnimatePresence>
    </>
  );
};
