'use client';

import * as React from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { usePathname } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import { LanguageSwitcher } from './LanguageSwitcher';
import { Button } from '@/components/ui/Button';

export interface NavLink {
  label: string;
  url: string;
}

interface HeaderProps {
  navLinks: NavLink[];
}

export function Header({ navLinks }: HeaderProps) {
  const [isScrolled, setIsScrolled] = React.useState(false);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = React.useState(false);
  const [forceSolid, setForceSolid] = React.useState(false);
  const pathname = usePathname() || '/';

  // Determine current locale from pathname
  const currentLocale = pathname.startsWith('/en') ? 'en' : 'de';

  // Helper to switch languages
  const getSwitchedUrl = (newLocale: string) => {
    if (!pathname) return `/${newLocale}`;
    const pathWithoutLocale = pathname.replace(/^\/(en|de)/, '');
    return `/${newLocale}${pathWithoutLocale === '' ? '' : pathWithoutLocale}`;
  };

  React.useEffect(() => {
    const handleScroll = () => {
      setIsScrolled(window.scrollY > 20);
    };
    window.addEventListener('scroll', handleScroll);
    
    // Check for forced solid header (used by error pages, legal pages without hero, etc.)
    const checkSolid = () => {
      setForceSolid(document.body.getAttribute('data-force-solid-header') === 'true');
    };
    checkSolid();
    
    // Set up observer for client-side navigation changes
    const observer = new MutationObserver(checkSolid);
    observer.observe(document.body, { attributes: true, attributeFilter: ['data-force-solid-header'] });
    
    // Re-check when pathname changes
    checkSolid();
    
    return () => {
      window.removeEventListener('scroll', handleScroll);
      observer.disconnect();
    };
  }, [pathname]);

  // Close mobile menu on route change
  React.useEffect(() => {
    setIsMobileMenuOpen(false);
  }, [pathname]);

  const isSolidMode = isScrolled || forceSolid;


  return (
    <>
      <header
        className={`fixed top-0 left-0 right-0 z-50 flex justify-center transition-all duration-700 ease-[cubic-bezier(0.16,1,0.3,1)] ${
          isSolidMode ? 'pt-4 px-4' : 'pt-0 px-0'
        }`}
      >
        <div
          className={`relative overflow-hidden w-full max-w-[1400px] mx-auto transition-all duration-700 ease-[cubic-bezier(0.16,1,0.3,1)] flex items-center justify-between ${
            isSolidMode
              ? 'rounded-full bg-white/50 backdrop-blur-xl shadow-[0_8px_32px_rgba(0,0,0,0.08)] border border-white/40 py-2.5 px-6 md:px-8'
              : 'rounded-none bg-transparent py-6 px-4 md:px-8 border border-transparent'
          }`}
        >
          {/* Scroll triggered shine effect */}
          {isScrolled && (
            <div className="absolute inset-0 z-0 pointer-events-none overflow-hidden rounded-full">
              <motion.div 
                initial={{ x: '-100%' }}
                animate={{ x: '100%' }}
                transition={{ duration: 1.5, ease: [0.16, 1, 0.3, 1], delay: 0.3 }}
                className="absolute top-0 h-[200%] w-[150%] bg-gradient-to-r from-transparent via-white to-transparent skew-x-[-20deg] mix-blend-overlay"
              />
            </div>
          )}

          <Link href={`/${currentLocale}`} className={`relative flex items-center transition-all duration-500 ease-out z-50 group ${isSolidMode ? 'h-9 w-36' : 'h-12 w-48'}`}>
            <Image
              src={(isSolidMode || isMobileMenuOpen) ? "/assets/logo.png" : "/assets/logo-white.png"}
              alt="E-TIB Gruppe"
              fill
              className="object-contain object-left group-hover:scale-105 transition-transform duration-500 origin-left"
              priority
              sizes="192px"
            />
          </Link>
          
          <nav className="relative z-10 hidden md:flex items-center gap-8 lg:gap-10">
            {navLinks && navLinks.length > 0 && navLinks.map((link) => {
              const mappedUrl = link.url.startsWith('/') && !link.url.match(/^\/(en|de)/) 
                ? `/${currentLocale}${link.url}` 
                : link.url;
                
              const isActive = pathname === mappedUrl || (mappedUrl !== `/${currentLocale}` && pathname?.startsWith(`${mappedUrl}/`));
                
              return (
                <Link 
                  key={link.url}
                  href={mappedUrl} 
                  className={`relative font-bold text-xs lg:text-sm uppercase tracking-widest transition-colors duration-300 group py-2 ${
                    isSolidMode 
                      ? (isActive ? 'text-primary' : 'text-text-primary hover:text-primary')
                      : (isActive ? 'text-white' : 'text-white/80 hover:text-white')
                  }`}
                >
                  {link.label}
                  
                  {/* Framer Motion Active Indicator */}
                  {isActive && (
                    <motion.div 
                      layoutId="header-active-indicator"
                      className={`absolute -bottom-1 left-0 right-0 h-0.5 rounded-full ${isSolidMode ? 'bg-primary' : 'bg-white'}`}
                      transition={{ type: 'spring', stiffness: 400, damping: 30 }}
                    />
                  )}
                  
                  {/* Subtle hover underline */}
                  <span className={`absolute -bottom-1 left-1/2 w-0 h-0.5 -translate-x-1/2 rounded-full transition-all duration-300 ease-out group-hover:w-full ${isSolidMode ? 'bg-primary/30' : 'bg-white/30'} ${isActive ? 'opacity-0' : 'opacity-100'}`} />
                </Link>
              );
            })}
            
            <div className={`h-5 w-px transition-colors duration-300 ${isSolidMode ? 'bg-neutral-200' : 'bg-white/20'}`} />
            
            <LanguageSwitcher isSolidMode={isSolidMode} />
            
            <Link
              href={`/${currentLocale}/${currentLocale === 'de' ? 'kontakt' : 'contact'}`}
              className={`relative ml-2 px-7 py-2.5 rounded-full font-bold text-xs lg:text-sm uppercase tracking-widest transition-all duration-500 overflow-hidden group/cta isolate ${
                isSolidMode
                  ? 'bg-primary text-white shadow-lg shadow-primary/20 hover:shadow-primary/40 hover:-translate-y-0.5 border border-transparent'
                  : 'bg-white/10 text-white backdrop-blur-md border border-white/30 hover:bg-white/20 hover:-translate-y-0.5 hover:shadow-[0_0_20px_rgba(255,255,255,0.2)]'
              }`}
            >
              <span className="relative z-10 transition-transform duration-300 group-hover/cta:scale-105 inline-block">{currentLocale === 'de' ? 'Kontakt' : 'Contact'}</span>
              {/* Sleek shine sweep effect */}
              <span className="absolute top-0 -left-[150%] h-[200%] w-[150%] bg-gradient-to-r from-transparent via-white/30 to-transparent skew-x-[-20deg] group-hover/cta:left-[100%] transition-all duration-1000 ease-[cubic-bezier(0.16,1,0.3,1)] z-30 pointer-events-none" />
            </Link>
          </nav>

          {/* Mobile Nav Button */}
          <button 
            className="md:hidden z-50 p-2 relative group"
            onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
            aria-label="Toggle menu"
          >
            <div className={`absolute inset-0 rounded-full transition-all duration-300 ${isSolidMode ? 'bg-neutral-100 group-hover:bg-neutral-200' : 'bg-white/10 group-hover:bg-white/20'}`} />
            <svg className="relative z-10 transition-transform duration-300 group-hover:scale-110" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke={(isSolidMode || isMobileMenuOpen) ? "currentColor" : "white"} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              {isMobileMenuOpen ? (
                <>
                  <line x1="18" y1="6" x2="6" y2="18" className="origin-center animate-in fade-in zoom-in duration-300" />
                  <line x1="6" y1="6" x2="18" y2="18" className="origin-center animate-in fade-in zoom-in duration-300" />
                </>
              ) : (
                <>
                  <line x1="3" x2="21" y1="6" y2="6" className="transition-all duration-300 group-hover:translate-x-1" />
                  <line x1="3" x2="21" y1="12" y2="12" />
                  <line x1="3" x2="21" y1="18" y2="18" className="transition-all duration-300 group-hover:-translate-x-1" />
                </>
              )}
            </svg>
          </button>
        </div>
      </header>

      {/* Mobile Menu Overlay */}
      <AnimatePresence>
        {isMobileMenuOpen && (
          <motion.div
            initial={{ opacity: 0, y: -20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            transition={{ duration: 0.2 }}
            className="fixed inset-0 z-40 bg-white md:hidden pt-32 pb-8 px-6 overflow-y-auto"
          >
            <nav className="flex flex-col gap-6">
              {navLinks && navLinks.length > 0 && navLinks.map((link) => {
                const mappedUrl = link.url.startsWith('/') && !link.url.match(/^\/(en|de)/) 
                  ? `/${currentLocale}${link.url}` 
                  : link.url;
                  
                return (
                  <Link 
                    key={link.url}
                    href={mappedUrl} 
                    className="text-2xl font-heading font-bold text-neutral-dark border-b border-neutral-100 pb-4"
                  >
                    {link.label}
                  </Link>
                );
              })}
              
              <Link 
                href={`/${currentLocale}/${currentLocale === 'de' ? 'kontakt' : 'contact'}`} 
                className="text-2xl font-heading font-bold text-primary border-b border-neutral-100 pb-4"
              >
                {currentLocale === 'de' ? 'Kontakt' : 'Contact'}
              </Link>
              
              <div className="mt-8 pt-6">
                <p className="text-text-secondary text-sm font-bold uppercase tracking-widest mb-4">Sprache wählen</p>
                <LanguageSwitcher mobile={true} />
              </div>
            </nav>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}

