/* ====================================================
 * Header Component - Sticky Navigation
 * Responsive with mobile hamburger menu
 * ==================================================== */

'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import { HiOutlineMenu, HiOutlineX, HiOutlinePhone, HiOutlineMail, HiChevronDown } from 'react-icons/hi';
import { FaFacebookF, FaYoutube } from 'react-icons/fa';
import { SiZalo } from 'react-icons/si';
import { useScrollPosition } from '@/hooks';
import { mainMenu, contactInfo as mockContactInfo } from '@/data/mock-data';
import { coreService } from '@/services/coreService';
import { productService } from '@/services/productService';
import { SiteSetting, Category } from '@/types/api';

export default function Header() {
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [activeDropdown, setActiveDropdown] = useState<number | null>(null);
  const [settings, setSettings] = useState<SiteSetting | null>(null);
  const [menuItems, setMenuItems] = useState(mainMenu);
  const { isScrolled } = useScrollPosition();
  const pathname = usePathname();

  useEffect(() => {
    coreService.getSettings().then(setSettings).catch(console.error);
    
    // Fetch categories and update product menu
    productService.getCategories().then((res) => {
      if (res && res.results) {
        setMenuItems(prev => prev.map(item => {
          if (item.href === '/san-pham') {
            return {
              ...item,
              children: [
                {
                  id: 299,
                  label: 'Tất cả sản phẩm',
                  href: '/san-pham',
                  isVisible: true,
                  order: 0
                },
                ...res.results.map((cat: Category, index: number) => ({
                  id: 300 + index,
                  label: cat.name,
                  href: `/san-pham?category=${cat.slug}`,
                  isVisible: true,
                  order: index + 1
                }))
              ]
            };
          }
          return item;
        }));
      }
    }).catch(console.error);
  }, []);

  const contactData = settings || mockContactInfo;

  /* Close mobile menu on route change */
  useEffect(() => {
    setMobileMenuOpen(false);
    setActiveDropdown(null);
  }, [pathname]);

  /* Prevent scroll when mobile menu is open */
  useEffect(() => {
    document.body.style.overflow = mobileMenuOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [mobileMenuOpen]);

  const isActive = (href: string) => {
    if (href === '/') return pathname === '/';
    return pathname.startsWith(href);
  };

  return (
    <>
      {/* === Top Bar === */}
      <div className="bg-primary-700 text-white text-sm hidden lg:block">
        <div className="container-custom flex items-center justify-between py-2">
          <div className="flex items-center gap-6">
            <a href={`tel:${contactData.hotline}`} className="flex items-center gap-1.5 hover:text-secondary-300 transition-colors">
              <HiOutlinePhone className="w-4 h-4" />
              <span>Hotline: {contactData.hotline}</span>
            </a>
            <a href={`mailto:${contactData.email}`} className="flex items-center gap-1.5 hover:text-secondary-300 transition-colors">
              <HiOutlineMail className="w-4 h-4" />
              <span>{contactData.email}</span>
            </a>
          </div>
          <div className="flex items-center gap-3">
            {contactData.facebook && (
              <a href={contactData.facebook} target="_blank" rel="noopener noreferrer"
                className="w-7 h-7 rounded-full bg-white/10 flex items-center justify-center hover:bg-white/20 transition-colors">
                <FaFacebookF className="w-3.5 h-3.5" />
              </a>
            )}
            {contactData.youtube && (
              <a href={contactData.youtube} target="_blank" rel="noopener noreferrer"
                className="w-7 h-7 rounded-full bg-white/10 flex items-center justify-center hover:bg-white/20 transition-colors">
                <FaYoutube className="w-3.5 h-3.5" />
              </a>
            )}
            {contactData.zalo && (
              <a href={contactData.zalo} target="_blank" rel="noopener noreferrer"
                className="w-7 h-7 rounded-full bg-white/10 flex items-center justify-center hover:bg-white/20 transition-colors">
                <SiZalo className="w-3.5 h-3.5" />
              </a>
            )}
          </div>
        </div>
      </div>

      {/* === Main Header === */}
      <header
        className={`sticky top-0 z-50 transition-all duration-300 ${isScrolled
          ? 'bg-white/95 backdrop-blur-md shadow-nav'
          : 'bg-white'
          }`}
      >
        <div className="container-custom">
          <div className="flex items-center justify-between h-24 lg:h-28">
            {/* Logo */}
            <Link href="/" className="flex items-center gap-2.5 shrink-0">
              {settings?.logo ? (
                <img src={settings.logo} alt="Logo" className="h-24 lg:h-26 object-contain" />
              ) : (
                <>
                  <div className="w-10 h-10 lg:w-11 lg:h-11 rounded-xl bg-gradient-primary flex items-center justify-center">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M12 2L14 6H18L15 9L16 13L12 10.5L8 13L9 9L6 6H10L12 2Z" fill="white" />
                      <circle cx="12" cy="18" r="4" fill="white" opacity="0.8" />
                    </svg>
                  </div>
                  <div>
                    <span className="text-xl lg:text-2xl font-bold text-primary-600 font-heading block leading-tight">
                      {settings?.site_name || 'Vitalist Pharma'}
                    </span>
                    <span className="text-[10px] text-dark-300 tracking-wider uppercase hidden sm:block">
                      Pharmaceutical
                    </span>
                  </div>
                </>
              )}
            </Link>

            {/* Desktop Navigation */}
            <nav className="hidden lg:flex items-center gap-1">
              {menuItems.filter(m => m.isVisible).map((item) => (
                <div
                  key={item.id}
                  className="relative"
                  onMouseEnter={() => item.children && setActiveDropdown(item.id)}
                  onMouseLeave={() => setActiveDropdown(null)}
                >
                  <Link
                    href={item.href}
                    className={`flex items-center gap-1 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 ${isActive(item.href)
                      ? 'text-primary-600 bg-primary-50'
                      : 'text-dark-600 hover:text-primary-600 hover:bg-primary-50/50'
                      }`}
                  >
                    {item.label}
                    {item.children && <HiChevronDown className={`w-4 h-4 transition-transform ${activeDropdown === item.id ? 'rotate-180' : ''}`} />}
                  </Link>

                  {/* Dropdown Menu */}
                  <AnimatePresence>
                    {item.children && activeDropdown === item.id && (
                      <motion.div
                        initial={{ opacity: 0, y: 8 }}
                        animate={{ opacity: 1, y: 0 }}
                        exit={{ opacity: 0, y: 8 }}
                        transition={{ duration: 0.2 }}
                        className="absolute top-full left-0 w-56 bg-white rounded-xl shadow-xl border border-surface-200 py-2 mt-1"
                      >
                        {item.children.map((child) => (
                          <Link
                            key={child.id}
                            href={child.href}
                            className="block px-4 py-2.5 text-sm text-dark-500 hover:text-primary-600 hover:bg-primary-50 transition-colors"
                          >
                            {child.label}
                          </Link>
                        ))}
                      </motion.div>
                    )}
                  </AnimatePresence>
                </div>
              ))}
            </nav>

            {/* CTA + Mobile Toggle */}
            <div className="flex items-center gap-3">
              <Link
                href="/lien-he"
                className="hidden md:inline-flex items-center gap-2 px-5 py-2.5 bg-gradient-primary text-white text-sm font-semibold rounded-button hover:shadow-lg hover:shadow-primary-500/25 transition-all duration-300 hover:-translate-y-0.5"
              >
                <HiOutlinePhone className="w-4 h-4" />
                Liên hệ
              </Link>

              {/* Mobile Menu Toggle */}
              <button
                onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
                className="lg:hidden w-10 h-10 flex items-center justify-center rounded-lg text-dark-600 hover:bg-surface-100 transition-colors"
                aria-label="Toggle menu"
              >
                {mobileMenuOpen ? <HiOutlineX className="w-6 h-6" /> : <HiOutlineMenu className="w-6 h-6" />}
              </button>
            </div>
          </div>
        </div>
      </header>

      {/* === Mobile Menu Overlay === */}
      <AnimatePresence>
        {mobileMenuOpen && (
          <>
            {/* Backdrop */}
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="fixed inset-0 bg-black/40 z-40 lg:hidden"
              onClick={() => setMobileMenuOpen(false)}
            />

            {/* Menu Panel */}
            <motion.div
              initial={{ x: '100%' }}
              animate={{ x: 0 }}
              exit={{ x: '100%' }}
              transition={{ type: 'spring', damping: 25, stiffness: 200 }}
              className="fixed right-0 top-0 bottom-0 w-[85%] max-w-sm bg-white z-50 lg:hidden overflow-y-auto"
            >
              {/* Mobile Menu Header */}
              <div className="flex items-center justify-between p-4 border-b border-surface-200">
                <Link href="/" className="flex items-center gap-2" onClick={() => setMobileMenuOpen(false)}>
                  <div className="w-9 h-9 rounded-lg bg-gradient-primary flex items-center justify-center">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                      <path d="M12 2L14 6H18L15 9L16 13L12 10.5L8 13L9 9L6 6H10L12 2Z" fill="white" />
                      <circle cx="12" cy="18" r="4" fill="white" opacity="0.8" />
                    </svg>
                  </div>
                  <span className="text-lg font-bold text-primary-600">{settings?.site_name || 'Vitalist Pharma'}</span>
                </Link>
                <button
                  onClick={() => setMobileMenuOpen(false)}
                  className="w-9 h-9 flex items-center justify-center rounded-lg hover:bg-surface-100"
                >
                  <HiOutlineX className="w-5 h-5" />
                </button>
              </div>

              {/* Mobile Nav Links */}
              <nav className="p-4 space-y-1">
                {menuItems.filter(m => m.isVisible).map((item) => (
                  <div key={item.id}>
                    <Link
                      href={item.href}
                      onClick={() => !item.children && setMobileMenuOpen(false)}
                      className={`flex items-center justify-between px-4 py-3 rounded-lg text-base font-medium transition-colors ${isActive(item.href)
                        ? 'text-primary-600 bg-primary-50'
                        : 'text-dark-600 hover:bg-surface-50'
                        }`}
                    >
                      {item.label}
                      {item.children && (
                        <button onClick={(e) => {
                          e.preventDefault();
                          e.stopPropagation();
                          setActiveDropdown(activeDropdown === item.id ? null : item.id);
                        }}>
                          <HiChevronDown className={`w-5 h-5 transition-transform ${activeDropdown === item.id ? 'rotate-180' : ''}`} />
                        </button>
                      )}
                    </Link>

                    {/* Mobile Submenu */}
                    <AnimatePresence>
                      {item.children && activeDropdown === item.id && (
                        <motion.div
                          initial={{ height: 0, opacity: 0 }}
                          animate={{ height: 'auto', opacity: 1 }}
                          exit={{ height: 0, opacity: 0 }}
                          className="overflow-hidden ml-4"
                        >
                          {item.children.map((child) => (
                            <Link
                              key={child.id}
                              href={child.href}
                              onClick={() => setMobileMenuOpen(false)}
                              className="block px-4 py-2.5 text-sm text-dark-400 hover:text-primary-600 transition-colors"
                            >
                              {child.label}
                            </Link>
                          ))}
                        </motion.div>
                      )}
                    </AnimatePresence>
                  </div>
                ))}
              </nav>

              {/* Mobile Contact */}
              <div className="p-4 border-t border-surface-200 mt-4">
                <a href={`tel:${contactData.hotline}`}
                  className="flex items-center gap-3 px-4 py-3 bg-primary-50 rounded-lg text-primary-600 font-medium mb-3">
                  <HiOutlinePhone className="w-5 h-5" />
                  {contactData.hotline}
                </a>
                <div className="flex items-center gap-3 px-4">
                  {contactData.facebook && (
                    <a href={contactData.facebook} target="_blank" rel="noopener noreferrer"
                      className="w-10 h-10 rounded-full bg-surface-100 flex items-center justify-center hover:bg-primary-50 hover:text-primary-600 transition-colors">
                      <FaFacebookF className="w-4 h-4" />
                    </a>
                  )}
                  {contactData.youtube && (
                    <a href={contactData.youtube} target="_blank" rel="noopener noreferrer"
                      className="w-10 h-10 rounded-full bg-surface-100 flex items-center justify-center hover:bg-primary-50 hover:text-primary-600 transition-colors">
                      <FaYoutube className="w-4 h-4" />
                    </a>
                  )}
                  {contactData.zalo && (
                    <a href={contactData.zalo} target="_blank" rel="noopener noreferrer"
                      className="w-10 h-10 rounded-full bg-surface-100 flex items-center justify-center hover:bg-primary-50 hover:text-primary-600 transition-colors">
                      <SiZalo className="w-4 h-4" />
                    </a>
                  )}
                </div>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </>
  );
}
