'use client';

import { useRouter } from 'next/navigation';
import { AnimatePresence, motion } from 'framer-motion';
import { ChevronUp, Menu } from 'lucide-react';
import Image from 'next/image';
import { useEffect, useRef, useState } from 'react';
import { UILink } from '../ui';

const navigation = [
  {
    label: 'Home',
    href: '/',
  },
  {
    label: 'Modelos',
    href: '/modelos',
  },
];

const Header = () => {
  const router = useRouter();

  const [menuVisible, setMenuVisible] = useState(false);

  const mobileMenuRef = useRef<HTMLDivElement>(null);
  const menuButtonRef = useRef<HTMLButtonElement>(null);

  const closeMenu = () => setMenuVisible(false);
  const toggleMenu = () => setMenuVisible((prev) => !prev);

  useEffect(() => {
    if (!menuVisible) return;

    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Node;

      if (
        mobileMenuRef.current &&
        !mobileMenuRef.current.contains(target) &&
        !menuButtonRef.current?.contains(target)
      ) {
        closeMenu();
      }
    };

    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        closeMenu();
      }
    };

    document.addEventListener('pointerdown', handleClickOutside);
    document.addEventListener('keydown', handleEscape);

    return () => {
      document.removeEventListener('pointerdown', handleClickOutside);
      document.removeEventListener('keydown', handleEscape);
    };
  }, [menuVisible]);

  const handleContactClick = () => {
    const registerSection = document.getElementById('register');

    if (window.location.pathname === '/') {
      // Ya estamos en home, scroll directo
      registerSection?.scrollIntoView({ behavior: 'smooth' });
    } else {
      // Navegar al home con query param
      router.push('/?scroll=register');
    }
    closeMenu();
  };

  return (
    <>
      {/* DESKTOP */}
      <header className="show-on-desktop bg-foreground sticky top-0 z-50 shadow-2xl">
        <nav
          aria-label="Main navigation"
          className="malek-containter flex w-full items-center justify-between px-48 py-4"
        >
          <UILink href={'/'}>
            <Image
              src="/logo.png"
              alt="Company logo"
              width={1206}
              height={425}
              priority
              className="max-h-15 w-auto"
            />
          </UILink>

          <ul className="flex items-center gap-9 text-xs font-bold uppercase">
            {navigation.map((item) => (
              <li key={item.href}>
                <UILink href={item.href}>{item.label}</UILink>
              </li>
            ))}
            <li>
              <button
                className="text-text-primary text-xs font-bold transition-opacity duration-200 hover:opacity-70 focus-visible:ring-2 focus-visible:outline-none lg:text-sm"
                onClick={handleContactClick}
              >
                CONTACTO
              </button>
            </li>
          </ul>
        </nav>
      </header>
      {/* MOBILE */}
      <header className="show-on-mobile bg-background sticky top-0 z-50 w-full shadow-2xl">
        <nav
          aria-label="Mobile navigation"
          className="relative flex items-center justify-between px-6 py-5 shadow-2xl"
        >
          <Image
            src="/logo.png"
            alt="Company logo"
            width={1206}
            height={425}
            priority
            className="max-h-10 w-auto"
          />

          <button
            ref={menuButtonRef}
            type="button"
            aria-label={menuVisible ? 'Close menu' : 'Open menu'}
            aria-expanded={menuVisible}
            aria-controls="mobile-menu"
            onClick={toggleMenu}
            className="flex items-center justify-center"
          >
            <Menu className="h-8 w-8 stroke-[1.5]" />
          </button>
        </nav>

        <AnimatePresence initial={false}>
          {menuVisible && (
            <motion.div
              ref={mobileMenuRef}
              id="mobile-menu"
              initial={{ height: 0, opacity: 0 }}
              animate={{ height: 'auto', opacity: 1 }}
              exit={{ height: 0, opacity: 0 }}
              transition={{
                duration: 0.2,
                ease: [0.22, 1, 0.36, 1],
              }}
              className="bg-background absolute w-full overflow-hidden"
            >
              <motion.ul
                initial="closed"
                animate="open"
                exit="closed"
                variants={{
                  open: {
                    transition: {
                      staggerChildren: 0.06,
                      delayChildren: 0.05,
                    },
                  },
                  closed: {
                    transition: {
                      staggerChildren: 0.04,
                      staggerDirection: -1,
                    },
                  },
                }}
                className="flex flex-col px-8 pt-10 pb-6"
              >
                {navigation.map((item) => (
                  <motion.li
                    key={item.href}
                    variants={{
                      open: {
                        opacity: 1,
                        y: 0,
                      },
                      closed: {
                        opacity: 0,
                        y: -8,
                      },
                    }}
                    transition={{
                      duration: 0.2,
                    }}
                  >
                    <UILink
                      href={item.href}
                      onClick={closeMenu}
                      className="block py-5 text-base font-light uppercase"
                    >
                      {item.label}
                    </UILink>
                  </motion.li>
                ))}

                <motion.li
                  variants={{
                    open: {
                      opacity: 1,
                      y: 0,
                    },
                    closed: {
                      opacity: 0,
                      y: -8,
                    },
                  }}
                  transition={{
                    duration: 0.2,
                  }}
                >
                  <button
                    className="text-text-primary block py-5 text-base font-light uppercase transition-opacity duration-200 hover:opacity-70 focus-visible:ring-2 focus-visible:outline-none lg:text-sm"
                    onClick={handleContactClick}
                  >
                    CONTACTO
                  </button>
                </motion.li>
                <motion.li
                  variants={{
                    open: {
                      opacity: 1,
                      y: 0,
                    },
                    closed: {
                      opacity: 0,
                      y: -8,
                    },
                  }}
                  transition={{
                    duration: 0.2,
                  }}
                  className="mt-8 flex justify-center"
                >
                  <button
                    type="button"
                    onClick={closeMenu}
                    aria-label="Close menu"
                    className="py-2"
                  >
                    <ChevronUp className="text-text-primary h-10 w-10 stroke-[1.25]" />
                  </button>
                </motion.li>
              </motion.ul>
            </motion.div>
          )}
        </AnimatePresence>
      </header>
    </>
  );
};

export default Header;
