import React, { useState, useEffect, Suspense, useCallback } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { Menu, X, Phone, MapPin, Instagram } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

interface LayoutProps {
  children: React.ReactNode;
}

const PageLoader: React.FC = () => (
  <div className="min-h-screen bg-black flex items-center justify-center">
    <div className="text-center">
      <div className="loading-spinner mb-4"></div>
      <p className="text-white text-base">Loading...</p>
    </div>
  </div>
);

const Layout: React.FC<LayoutProps> = ({ children }) => {
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [isScrolled, setIsScrolled] = useState(false);
  const location = useLocation();

  const navigation = [
    { name: 'Home', href: '/' },
    { name: 'About', href: '/about' },
    { name: 'Facilities', href: '/facilities' },
    { name: 'Gallery', href: '/gallery' },
    { name: 'News', href: '/news' },
    { name: 'Testimonials', href: '/testimonials' },
    { name: 'Membership', href: '/membership' },
    { name: 'Champions', href: '/champions' },
    { name: 'Contact', href: '/contact' },
  ];

  const handleScroll = useCallback(() => {
    const scrollY = window.scrollY;
    setIsScrolled(scrollY > 50);
  }, []);

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

  // Close menu when navigating to a new page
  useEffect(() => {
    setIsMenuOpen(false);
  }, [location.pathname]);

  // Lock body scroll while the menu is open
  useEffect(() => {
    document.body.style.overflow = isMenuOpen ? 'hidden' : '';
    return () => {
      document.body.style.overflow = '';
    };
  }, [isMenuOpen]);

  const toggleMenu = useCallback(() => {
    setIsMenuOpen(prev => !prev);
  }, []);

  const closeMenu = useCallback(() => {
    setIsMenuOpen(false);
  }, []);

  return (
    <div className="min-h-screen bg-black">
      {/* Navigation */}
      <nav className={`fixed w-full z-50 transition-all duration-300 ease-in-out safe-area-top ${
        isScrolled ? 'bg-black/95 backdrop-blur-md shadow-lg py-2' : 'bg-black py-4'
      }`}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            {/* Logo */}
            <Link to="/" className="flex items-center hover-lift" onClick={closeMenu}>
              <img
                src="/Top_Bodies-Logo.webp"
                alt="Top Bodies Gym Logo"
                className="h-16 sm:h-20 w-auto transition-transform duration-300 hover:scale-105"
                loading="eager"
                decoding="sync"
                width="auto"
                height="80"
              />
            </Link>

            {/* Desktop Contact Icons and Menu Button */}
            <div className="flex items-center space-x-2">
              <a
                href="tel:01484518311"
                className="text-white hover:text-yellow-500 transition-colors duration-200 p-2 rounded-lg hover:scale-110 min-h-[44px] min-w-[44px] flex items-center justify-center"
                aria-label="Call us"
              >
                <Phone className="h-5 w-5" />
              </a>
              <a
                href="https://maps.app.goo.gl/oBq5QmpsMWKnd8wv6"
                target="_blank"
                rel="noopener noreferrer"
                className="text-white hover:text-yellow-500 transition-colors duration-200 p-2 rounded-lg hover:scale-110 min-h-[44px] min-w-[44px] flex items-center justify-center"
                aria-label="Find us"
              >
                <MapPin className="h-5 w-5" />
              </a>
              <a
                href="https://www.instagram.com/topbodiesgym_huddersfield/"
                target="_blank"
                rel="noopener noreferrer"
                className="hidden md:flex text-white hover:text-yellow-500 transition-colors duration-200 p-2 rounded-lg hover:scale-110 min-h-[44px] min-w-[44px] items-center justify-center"
                aria-label="Follow us on Instagram"
              >
                <Instagram className="h-5 w-5" />
              </a>
              <button
                onClick={toggleMenu}
                className="text-white hover:text-yellow-500 p-2 rounded-lg transition-all duration-200 hover:scale-110 min-h-[44px] min-w-[44px] flex items-center justify-center"
                aria-label="Toggle menu"
                aria-expanded={isMenuOpen}
              >
                {isMenuOpen ? <X className="h-6 w-6" /> : <Menu className="h-6 w-6" />}
              </button>
            </div>
          </div>
        </div>

        {/* Navigation Overlay with Smooth Transitions */}
        <AnimatePresence>
          {isMenuOpen && (
            <>
              {/* Backdrop with fade animation */}
              <motion.div 
                className="fixed inset-0 bg-black/80 backdrop-blur-sm"
                onClick={closeMenu}
                aria-hidden="true"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                transition={{ duration: 0.3, ease: "easeInOut" }}
              />
              
              {/* Menu Panel with slide and fade animation - NOW WITH SCROLLING */}
              <motion.div 
                className="fixed top-0 right-0 h-full w-80 max-w-[85vw] bg-black/95 backdrop-blur-md safe-area-top safe-area-right overflow-y-auto"
                initial={{ x: "100%", opacity: 0 }}
                animate={{ x: 0, opacity: 1 }}
                exit={{ x: "100%", opacity: 0 }}
                transition={{ 
                  duration: 0.4, 
                  ease: [0.25, 0.46, 0.45, 0.94],
                  opacity: { duration: 0.3 }
                }}
              >
                <div className="flex flex-col min-h-full">
                  {/* Header */}
                  <motion.div 
                    className="flex items-center justify-between p-4 border-b border-gray-800 flex-shrink-0"
                    initial={{ y: -20, opacity: 0 }}
                    animate={{ y: 0, opacity: 1 }}
                    transition={{ delay: 0.1, duration: 0.3 }}
                  >
                    <img
                      src="/Top_Bodies-Logo.webp"
                      alt="Top Bodies Gym"
                      className="h-12 w-auto"
                      loading="lazy"
                    />
                    <button
                      onClick={closeMenu}
                      className="text-white hover:text-yellow-500 p-2 rounded-lg transition-colors duration-200 min-h-[44px] min-w-[44px] flex items-center justify-center"
                      aria-label="Close menu"
                    >
                      <X className="h-6 w-6" />
                    </button>
                  </motion.div>

                  {/* Navigation Links - Scrollable area */}
                  <div className="flex-1 py-4">
                    <div className="space-y-1 px-4">
                      {navigation.map((item, index) => (
                        <motion.div
                          key={item.name}
                          initial={{ x: 20, opacity: 0 }}
                          animate={{ x: 0, opacity: 1 }}
                          transition={{ 
                            delay: 0.1 + (index * 0.05), 
                            duration: 0.3,
                            ease: "easeOut"
                          }}
                        >
                          <Link
                            to={item.href}
                            onClick={closeMenu}
                            className={`block px-4 py-4 text-lg font-medium rounded-lg transition-all duration-200 min-h-[48px] flex items-center ${
                              location.pathname === item.href 
                                ? 'text-yellow-500 bg-white/10' 
                                : 'text-white hover:text-yellow-500 hover:bg-white/5'
                            }`}
                          >
                            {item.name}
                          </Link>
                        </motion.div>
                      ))}
                    </div>
                  </div>

                  {/* Contact Info - Fixed at bottom */}
                  <motion.div 
                    className="border-t border-gray-800 p-4 space-y-4 flex-shrink-0"
                    initial={{ y: 20, opacity: 0 }}
                    animate={{ y: 0, opacity: 1 }}
                    transition={{ delay: 0.2, duration: 0.3 }}
                  >
                    <div className="flex items-center space-x-4">
                      <a
                        href="tel:01484518311"
                        className="flex items-center space-x-3 text-white hover:text-yellow-500 transition-colors duration-200 min-h-[44px] flex-1"
                        onClick={closeMenu}
                      >
                        <Phone className="h-5 w-5" />
                        <span className="text-sm">01484 518 311</span>
                      </a>
                      <a
                        href="https://maps.app.goo.gl/oBq5QmpsMWKnd8wv6"
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center space-x-3 text-white hover:text-yellow-500 transition-colors duration-200 min-h-[44px]"
                        onClick={closeMenu}
                      >
                        <MapPin className="h-5 w-5" />
                        <span className="text-sm">Find Us</span>
                      </a>
                    </div>
                  </motion.div>
                </div>
              </motion.div>
            </>
          )}
        </AnimatePresence>
      </nav>

      {/* Main Content */}
      <main className="pt-20 sm:pt-24 relative">
        <Suspense fallback={<PageLoader />}>
          {children}
        </Suspense>
      </main>

      {/* Footer */}
      <footer className="bg-black border-t border-gray-800 py-8 sm:py-12 safe-area-bottom">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
            <div className="col-span-1 md:col-span-2">
              <div className="flex items-center mb-4">
                <img
                  src="/Top_Bodies-Logo.webp"
                  alt="Top Bodies Gym Logo"
                  className="h-12 sm:h-16 w-auto transition-transform duration-300 hover:scale-105"
                  loading="lazy"
                  decoding="async"
                  width="auto"
                  height="64"
                />
              </div>
              <p className="text-gray-400 mb-6 text-sm sm:text-base">
                Elite bodybuilding gym in Huddersfield. Top Bodies Gym since 1986.
              </p>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                <div>
                  <h4 className="text-yellow-500 font-semibold mb-3 text-sm sm:text-base">Address</h4>
                  <a
                    href="https://maps.app.goo.gl/oBq5QmpsMWKnd8wv6"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-gray-400 hover:text-yellow-500 transition-colors duration-200 text-sm leading-relaxed block"
                  >
                    <p>Unit 3</p>
                    <p>29 Saint John's Road</p>
                    <p>Huddersfield</p>
                    <p>HD1 5DX</p>
                  </a>
                </div>

                <div className="space-y-4">
                  <div>
                    <h4 className="text-yellow-500 font-semibold mb-2 text-sm sm:text-base">Phone</h4>
                    <a 
                      href="tel:01484518311"
                      className="text-gray-400 hover:text-yellow-500 transition-colors duration-200 text-sm min-h-[44px] flex items-center"
                    >
                      01484 518 311
                    </a>
                  </div>
                  <div>
                    <h4 className="text-yellow-500 font-semibold mb-2 text-sm sm:text-base">Email</h4>
                    <a 
                      href="mailto:info@topbodiesgym.co.uk"
                      className="text-gray-400 hover:text-yellow-500 transition-colors duration-200 text-sm min-h-[44px] flex items-center break-all"
                    >
                      info@topbodiesgym.co.uk
                    </a>
                  </div>
                </div>
              </div>
            </div>

            <div className="flex flex-col justify-start">
              <div className="mt-0 md:mt-32">
                <h3 className="text-white font-semibold mb-4 text-sm sm:text-base">Quick Links</h3>
                <div className="grid grid-cols-2 gap-x-4 gap-y-2">
                  {navigation.slice(0, 6).map((item) => (
                    <Link
                      key={item.name}
                      to={item.href}
                      className="text-gray-400 hover:text-yellow-500 text-xs sm:text-sm transition-all duration-200 hover:translate-x-1 min-h-[32px] flex items-center"
                    >
                      {item.name}
                    </Link>
                  ))}
                </div>
              </div>
            </div>
          </div>

          <div className="border-t border-gray-800 mt-8 pt-8 text-center text-gray-400 space-y-2">
            <p className="text-xs sm:text-sm">&copy; 2025 Top Bodies Gym. All rights reserved.</p>
            <p className="text-xs sm:text-sm">
              Powered by{' '}
              <a
                href="https://www.webinventor.co.uk"
                target="_blank"
                rel="noopener noreferrer"
                className="text-yellow-500 hover:underline hover:text-yellow-400 transition-all duration-200 min-h-[32px] inline-flex items-center"
              >
                Web Inventor
              </a>
            </p>
          </div>
        </div>
      </footer>
    </div>
  );
};

export default Layout;