'use client';

import * as React from 'react';
import { usePathname } from 'next/navigation';
import { TransitionLink } from '@/components/ui/TransitionLink';
import { Home, Briefcase, Users, Mail } from 'lucide-react';
import { motion } from 'framer-motion';

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

interface MobileBottomNavProps {
  navLinks: NavLink[];
  currentLocale: string;
}

export function MobileBottomNav({ navLinks, currentLocale }: MobileBottomNavProps) {
  const pathname = usePathname() || '/';
  const [isFlyoutOpen, setIsFlyoutOpen] = React.useState(false);

  // We need to gather all links that should go into the flyout.
  // The user wants 'alle navigationspunkte daraus' (from the old burger menu).
  // Old menu had: Kompetenzen, Über uns (Firma, Team, Zertifikate, Standorte), Referenzen, Karriere, Messen.
  
  // Construct our bottom nav items
  const items = React.useMemo(() => {
    const homeUrl = `/${currentLocale}`;
    const competenciesUrl = navLinks[0]?.url || `/${currentLocale}/kompetenzen`;
    const referencesUrl = navLinks[2]?.url || `/${currentLocale}/referenzen`;
    const contactUrl = `/${currentLocale}/${currentLocale === 'de' ? 'kontakt' : 'contact'}`;

    return [
      {
        id: 'home',
        label: currentLocale === 'de' ? 'Start' : 'Home',
        url: homeUrl,
        icon: <Home className="w-5 h-5 md:w-6 md:h-6" strokeWidth={2.5} />,
        exactMatch: true
      },
      {
        id: 'kompetenzen',
        label: navLinks[0]?.label || (currentLocale === 'de' ? 'Kompetenzen' : 'Competencies'),
        url: competenciesUrl,
        icon: <Briefcase className="w-5 h-5 md:w-6 md:h-6" strokeWidth={2.5} />
      },
      {
        id: 'referenzen',
        label: navLinks[2]?.label || (currentLocale === 'de' ? 'Referenzen' : 'References'),
        url: referencesUrl,
        icon: <Users className="w-5 h-5 md:w-6 md:h-6" strokeWidth={2.5} /> // Using Users for now, wait we need an image or star icon?
      },
      {
        id: 'menu',
        label: navLinks[1]?.label || (currentLocale === 'de' ? 'Über uns' : 'About Us'),
        url: '#', // Triggers flyout
        icon: <svg className="w-5 h-5 md:w-6 md:h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}><path strokeLinecap="round" strokeLinejoin="round" d="M4 6h16M4 12h16m-7 6h7" /></svg>,
        isFlyoutTrigger: true
      },
      {
        id: 'kontakt',
        label: currentLocale === 'de' ? 'Kontakt' : 'Contact',
        url: contactUrl,
        icon: <Mail className="w-5 h-5 md:w-6 md:h-6" strokeWidth={2.5} />
      }
    ];
  }, [currentLocale, navLinks]);

  // Use a star or folder for references? Let's use standard Briefcase for Kompetenzen, and maybe a Layers or Image icon for Referenzen.
  // We'll replace the Users icon with something better if possible, but Users is fine for now, wait, Users is Über uns!
  // I will fix the icon in the render.

  // Gather flyout links:
  const flyoutLinks = React.useMemo(() => {
    // We want to put Über uns children, Karriere, and Messen in here.
    const aboutNode = navLinks[1];
    const karriereNode = navLinks[3];
    const messenNode = navLinks[4];
    
    let links: {label: string, url: string}[] = [];
    if (aboutNode?.children) {
      links.push(...aboutNode.children.map(c => ({ label: c.label, url: c.url })));
    }
    if (karriereNode) links.push({ label: karriereNode.label, url: karriereNode.url });
    if (messenNode) links.push({ label: messenNode.label, url: messenNode.url });
    return links;
  }, [navLinks]);

  return (
    <>
      <div className="md:hidden fixed bottom-0 left-0 right-0 z-[9999] px-4 pb-[calc(env(safe-area-inset-bottom)+1rem)] pt-4 pointer-events-none flex justify-center">
        <nav className="flex justify-between items-center bg-white/80 backdrop-blur-3xl border border-white/60 shadow-[0_8px_32px_rgba(0,0,0,0.12)] rounded-3xl p-1.5 pointer-events-auto w-full max-w-[400px]">
          {items.map((item) => {
            // Determine if active
            const mappedUrl = item.url.startsWith('/') && !item.url.match(/^\/(en|de)/) 
              ? `/${currentLocale}${item.url}` 
              : item.url;
              
            let isActive = false;
            if (item.isFlyoutTrigger) {
              isActive = isFlyoutOpen;
            } else {
              isActive = item.exactMatch 
                ? pathname === mappedUrl 
                : (pathname === mappedUrl || (mappedUrl !== `/${currentLocale}` && pathname?.startsWith(`${mappedUrl}/`)));
            }

            // Fix icon for referenzen
            let ItemIcon = item.icon;
            if (item.id === 'referenzen') {
              ItemIcon = <svg className="w-5 h-5 md:w-6 md:h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}><path strokeLinecap="round" strokeLinejoin="round" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" /></svg>;
            }

            const LinkWrapper = item.isFlyoutTrigger ? 'button' : TransitionLink;
            const linkProps = item.isFlyoutTrigger 
              ? { onClick: () => setIsFlyoutOpen(!isFlyoutOpen), className: "w-full focus:outline-none" } 
              : { href: mappedUrl };

            return (
              <LinkWrapper 
                key={item.label}
                {...linkProps}
                className={`relative flex flex-col items-center justify-center flex-1 h-[60px] transition-colors duration-300 select-none ${
                  isActive ? 'text-white' : 'text-neutral-500 hover:text-neutral-900'
                } ${item.isFlyoutTrigger ? 'focus:outline-none' : ''}`}
                style={{ WebkitTapHighlightColor: 'transparent', touchAction: 'manipulation' }}
              >
                {isActive && (
                  <motion.div
                    layoutId="mobile-nav-active-bg"
                    className="absolute inset-0 bg-primary rounded-2xl shadow-md"
                    transition={{ type: 'spring', stiffness: 400, damping: 25 }}
                  />
                )}
                
                <div className="relative flex flex-col items-center justify-center z-10 w-full h-full">
                  <motion.div 
                    whileTap={{ scale: 0.8 }}
                    animate={{ y: isActive ? -2 : 0 }}
                    transition={{ type: 'spring', stiffness: 400, damping: 17 }}
                  >
                    {ItemIcon}
                  </motion.div>
                  <motion.span 
                    animate={{ opacity: isActive ? 1 : 0.7, y: isActive ? 0 : 2 }}
                    className="text-[10px] font-bold mt-1 tracking-wide"
                  >
                    {item.label}
                  </motion.span>
                </div>
              </LinkWrapper>
            );
          })}
        </nav>
      </div>

      {/* Flyout Menu (Bottom Sheet) */}
      <AnimatePresence>
        {isFlyoutOpen && (
          <>
            <motion.div 
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.3 }}
              className="fixed inset-0 bg-black/40 backdrop-blur-sm z-[9997] md:hidden"
              onClick={() => setIsFlyoutOpen(false)}
            />
            <motion.div
              initial={{ y: '100%', opacity: 0 }}
              animate={{ y: 0, opacity: 1 }}
              exit={{ y: '100%', opacity: 0 }}
              transition={{ type: 'spring', stiffness: 300, damping: 30 }}
              className="fixed bottom-0 left-0 right-0 z-[9998] bg-white rounded-t-3xl pt-6 pb-[calc(env(safe-area-inset-bottom)+6rem)] px-6 md:hidden shadow-[0_-20px_40px_rgba(0,0,0,0.1)] border-t border-neutral-100"
            >
              <div className="w-12 h-1.5 bg-neutral-200 rounded-full mx-auto mb-6" />
              <h3 className="text-sm font-bold uppercase tracking-widest text-neutral-400 mb-4 px-2">{currentLocale === 'de' ? 'Über uns & Mehr' : 'About us & More'}</h3>
              <div className="flex flex-col gap-1">
                {flyoutLinks.map((link, i) => {
                  const childUrl = link.url.startsWith('/') && !link.url.match(/^\/(en|de)/) 
                    ? `/${currentLocale}${link.url}` 
                    : link.url;
                  const isChildActive = pathname === childUrl;
                  
                  return (
                    <TransitionLink
                      key={i}
                      href={childUrl}
                      onClick={() => setIsFlyoutOpen(false)}
                      className={`px-4 py-3.5 rounded-2xl text-base font-medium transition-all flex items-center justify-between ${
                        isChildActive ? 'bg-primary/10 text-primary' : 'text-neutral-700 hover:bg-neutral-50'
                      }`}
                    >
                      {link.label}
                      <svg className={`w-4 h-4 ${isChildActive ? 'text-primary' : 'text-neutral-400'}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M9 5l7 7-7 7" />
                      </svg>
                    </TransitionLink>
                  );
                })}
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </>
  );
}
