'use client';

import { useState, useEffect, useMemo } from 'react';
import { motion } from 'framer-motion';
import {
  ChevronDown,
  Cloud,
  Globe,
  HardDrive,
  Leaf,
  Mail,
  Menu,
  Moon,
  Network,
  Home,
  Server,
  Settings,
  ShieldCheck,
  Sun,
  X,
  Zap,
} from 'lucide-react';
import { useTheme } from 'next-themes';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { useI18n } from '../../i18n/provider';

export default function Header() {
  const [isScrolled, setIsScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const { locale, t } = useI18n();
  const dir = locale === 'en' ? 'ltr' : 'rtl';
  const { theme, setTheme } = useTheme();
  const router = useRouter();
  const pathname = usePathname();

  type NavChild = {
    id: string;
    label: string;
    href: string;
    icon: typeof Globe;
    bg: string;
    ring: string;
  };

  type NavItem =
    | { id: string; type: 'link'; primary: string; secondary: string; href: string }
    | { id: string; type: 'dropdown'; primary: string; secondary: string; children: NavChild[] };

  const navItems = useMemo<NavItem[]>(() => {
    const isFa = locale === 'fa';
    const pick = (fa: string, en: string) => (isFa ? { primary: fa, secondary: en } : { primary: en, secondary: fa });

    const mkChild = (child: Omit<NavChild, 'bg' | 'ring'> & Partial<Pick<NavChild, 'bg' | 'ring'>>): NavChild => ({
      bg: child.bg ?? 'from-slate-500/20 to-slate-500/10',
      ring: child.ring ?? 'ring-slate-400/20',
      ...child,
    });

    return [
      { id: 'home', type: 'link', ...pick('خانه', 'Home'), href: `/${locale}` },
      {
        id: 'hosting',
        type: 'dropdown',
        ...pick('میزبانی', 'Hosting'),
        children: [
          mkChild({
            id: 'eco-hosting',
            label: isFa ? 'هاست اقتصادی' : 'Budget Hosting',
            href: `/${locale}/eco-hosting`,
            icon: Leaf,
            bg: 'from-emerald-500/25 to-teal-500/10',
            ring: 'ring-emerald-400/20',
          }),
          mkChild({
            id: 'high-traffic-hosting',
            label: isFa ? 'هاست پربازدید' : 'High-traffic Hosting',
            href: `/${locale}/high-traffic-hosting`,
            icon: Zap,
            bg: 'from-fuchsia-500/20 to-indigo-500/10',
            ring: 'ring-fuchsia-400/20',
          }),
          mkChild({
            id: 'wordpress-hosting',
            label: isFa ? 'هاست وردپرس' : 'WordPress Hosting',
            href: `/${locale}/wordpress-hosting`,
            icon: Cloud,
            bg: 'from-sky-500/25 to-blue-500/10',
            ring: 'ring-sky-400/20',
          }),
          mkChild({
            id: 'woocommerce-hosting',
            label: isFa ? 'هاست ووکامرس' : 'WooCommerce Hosting',
            href: `/${locale}/woocommerce-hosting`,
            icon: Cloud,
            bg: 'from-rose-500/20 to-orange-500/10',
            ring: 'ring-rose-400/20',
          }),
        ],
      },
      {
        id: 'server',
        type: 'dropdown',
        ...pick('سرور', 'Servers'),
        children: [
          mkChild({
            id: 'vps',
            label: isFa ? 'سرور مجازی' : 'VPS',
            href: `/${locale}/vps`,
            icon: Server,
            bg: 'from-cyan-500/20 to-sky-500/10',
            ring: 'ring-cyan-400/20',
          }),
          mkChild({
            id: 'dedicated-server',
            label: isFa ? 'سرور اختصاصی' : 'Dedicated Server',
            href: `/${locale}/dedicated-server`,
            icon: Server,
            bg: 'from-violet-500/20 to-purple-500/10',
            ring: 'ring-violet-400/20',
          }),
          mkChild({
            id: 'managed-vps',
            label: isFa ? 'سرور مجازی مدیریت‌شده' : 'Managed VPS',
            href: `/${locale}/managed-vps`,
            icon: Settings,
            bg: 'from-amber-500/20 to-orange-500/10',
            ring: 'ring-amber-400/20',
          }),
          mkChild({
            id: 'managed-dedicated',
            label: isFa ? 'سرور اختصاصی مدیریت‌شده' : 'Managed Dedicated',
            href: `/${locale}/managed-dedicated`,
            icon: Settings,
            bg: 'from-lime-500/20 to-emerald-500/10',
            ring: 'ring-lime-400/20',
          }),
        ],
      },
      { id: 'domain', type: 'link', ...pick('دامین', 'Domain'), href: `/${locale}/domain` },
      {
        id: 'org-email',
        type: 'dropdown',
        ...pick('ایمیل سازمانی', 'Business Email'),
        children: [
          mkChild({
            id: 'org-email-iran',
            label: isFa ? 'ایمیل سازمانی ایران' : 'Business Email (Iran)',
            href: `/${locale}/org-email-iran`,
            icon: Mail,
            bg: 'from-rose-500/20 to-pink-500/10',
            ring: 'ring-rose-400/20',
          }),
          mkChild({
            id: 'org-email-international',
            label: isFa ? 'ایمیل سازمانی بین‌الملل' : 'Business Email (International)',
            href: `/${locale}/org-email-international`,
            icon: Mail,
            bg: 'from-sky-500/20 to-indigo-500/10',
            ring: 'ring-sky-400/20',
          }),
        ],
      },
      {
        id: 'other-products',
        type: 'dropdown',
        ...pick('سایر محصولات', 'Other Products'),
        children: [
          mkChild({
            id: 'ssl',
            label: 'SSL',
            href: `/${locale}/ssl`,
            icon: ShieldCheck,
            bg: 'from-violet-500/20 to-purple-500/10',
            ring: 'ring-violet-400/20',
          }),
          mkChild({
            id: 'storage',
            label: isFa ? 'فضای ذخیره‌سازی' : 'Storage',
            href: `/${locale}/storage`,
            icon: HardDrive,
            bg: 'from-slate-500/25 to-zinc-500/10',
            ring: 'ring-slate-400/20',
          }),
          mkChild({
            id: 'cdn',
            label: 'CDN',
            href: `/${locale}/cdn`,
            icon: Network,
            bg: 'from-cyan-500/20 to-blue-500/10',
            ring: 'ring-cyan-400/20',
          }),
          mkChild({
            id: 'geodns',
            label: 'GeoDns',
            href: `/${locale}/geodns`,
            icon: Globe,
            bg: 'from-emerald-500/20 to-teal-500/10',
            ring: 'ring-emerald-400/20',
          }),
        ],
      },
    ];
  }, [locale]);

  const [mobileSections, setMobileSections] = useState<Record<string, boolean>>({});
  useEffect(() => {
    const initial: Record<string, boolean> = {};
    for (const item of navItems) {
      if (item.type === 'dropdown') initial[item.id] = false;
    }
    setMobileSections((prev) => (Object.keys(prev).length ? prev : initial));
  }, [navItems]);

  useEffect(() => {
    const handleScroll = () => {
      // حساسیت اسکرول تنظیم شده تا تغییرات به موقع انجام شود
      if (window.scrollY > 40) {
        setIsScrolled(true);
      } else {
        setIsScrolled(false);
      }
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  useEffect(() => {
    setMobileOpen(false);
    setMobileSections((prev) => {
      const next: Record<string, boolean> = { ...prev };
      for (const key of Object.keys(next)) next[key] = false;
      return next;
    });
  }, [pathname]);

  return (
    // حذف پدینگ ثابت از بالا تا هدر بتواند به سقف بچسبد
    <div className="fixed top-0 left-0 right-0 z-50 flex flex-col items-center transition-all duration-500 px-4 sm:px-6">
      <motion.header
        initial={{ y: -50, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        transition={{ duration: 0.8, ease: "easeOut" }}
        className={`flex items-center justify-between text-[color:var(--text-primary)] transition-all duration-700 ease-in-out w-full ${
          isScrolled
            ? 'mt-4 max-w-5xl px-6 py-3 bg-[color:var(--glass-05)] backdrop-blur-lg border border-[color:var(--border-10)] rounded-full ' // حالت اسکرول شده: کپسول شناور
            : 'mt-0 max-w-7xl px-8 py-5 bg-[color:var(--glass-05)] backdrop-blur-md border-b border-x border-[color:var(--border-10)] rounded-t-none rounded-b-[2.5rem] ' // حالت بالای صفحه: چسبیده به سقف با پایین گرد
        }`}
        dir={dir}
      >
        {/* بخش لوگو */}
        <div className="flex items-center gap-2 cursor-pointer">
          <div className="w-8 h-8 rounded-full bg-[color:var(--glass-10)] flex items-center justify-center transition-transform hover:scale-110 duration-300">
             <Cloud className="w-5 h-5 text-blue-400" />
          </div>
          <span className="font-bold text-lg tracking-wide">MugCloud</span>
        </div>

        {/* منوی دسکتاپ */}
        <nav className={`hidden md:flex items-center transition-all duration-500 ${isScrolled ? 'gap-6' : 'gap-10'}`}>
          {navItems.map((item) => {
            if (item.type === 'link') {
              return (
                <Link
                  key={item.id}
                  href={item.href}
                  className="inline-flex items-center gap-1.5 text-[color:var(--text-muted)] hover:text-[color:var(--text-primary)] transition-colors text-sm font-medium"
                >
                  {item.id === 'home' ? <Home className="w-4 h-4 opacity-80" /> : null}
                  <span className="flex flex-col leading-tight">
                    <span>{item.primary}</span>
                    <span className="text-[11px] font-semibold tracking-wide text-[color:var(--text-muted-3)]">
                      {item.secondary}
                    </span>
                  </span>
                </Link>
              );
            }

            return (
              <div key={item.id} className="relative group">
                <button
                  type="button"
                  className="inline-flex items-center gap-1.5 text-[color:var(--text-muted)] hover:text-[color:var(--text-primary)] transition-colors text-sm font-medium"
                >
                  <span className="flex flex-col leading-tight text-start">
                    <span>{item.primary}</span>
                    <span className="text-[11px] font-semibold tracking-wide text-[color:var(--text-muted-3)]">
                      {item.secondary}
                    </span>
                  </span>
                  <ChevronDown className="w-4 h-4 text-[color:var(--text-muted-3)] transition-transform duration-200 group-hover:rotate-180" />
                </button>

                <div className="absolute top-full pt-3 right-0 left-auto hidden group-hover:block">
                  <div className="glass-rotating-border min-w-[19.5rem] rounded-3xl border border-[color:var(--border-10)] bg-[color:var(--global-surface-bg-80)] backdrop-blur-2xl shadow-[0_20px_90px_rgba(0,0,0,0.42)] overflow-hidden">
                    <div className="relative p-2.5">
                      <div className="pointer-events-none absolute inset-0 bg-gradient-to-br from-white/10 via-[color:var(--global-surface-bg-80)] to-blue-500/10 opacity-80" />
                      {item.children.map((child) => (
                        <Link
                          key={child.id}
                          href={child.href}
                          className="relative group/item flex items-center gap-3 px-3 py-2.5 rounded-2xl text-sm text-[color:var(--text-muted)] hover:text-[color:var(--text-primary)] hover:bg-[color:var(--glass-10)] transition-colors"
                        >
                          <span
                            className={`w-9 h-9 rounded-2xl bg-gradient-to-br ${child.bg} ring-1 ${child.ring} border border-[color:var(--border-10)] flex items-center justify-center`}
                          >
                            <child.icon className="w-4 h-4 text-[color:var(--text-primary)] opacity-90" />
                          </span>
                          <span className="flex-1">{child.label}</span>
                          <span className="w-1.5 h-1.5 rounded-full bg-blue-500/0 group-hover/item:bg-blue-400/70 transition-colors" />
                        </Link>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </nav>

        {/* بخش اکشن‌ها */}
        <div className="flex items-center gap-3">
          {/* منوی موبایل */}
          <button
            type="button"
            onClick={() => setMobileOpen((v) => !v)}
            className="md:hidden p-2 rounded-full bg-[color:var(--glass-05)] hover:bg-[color:var(--glass-10)] border border-[color:var(--border-10)] transition-colors flex items-center justify-center"
            aria-label="Toggle menu"
            aria-expanded={mobileOpen}
          >
            {mobileOpen ? (
              <X className="w-4 h-4 text-[color:var(--text-muted)]" />
            ) : (
              <Menu className="w-4 h-4 text-[color:var(--text-muted)]" />
            )}
          </button>

          {/* دکمه انتخاب زبان (در حالت کپسولی پنهان می‌شود) */}
          <div className={`overflow-hidden transition-all duration-500 `}>
            <button
              type="button"
              onClick={() => {
                const target = locale === 'fa' ? 'en' : 'fa';
                const next = pathname.replace(/^\/(fa|en)(\/|$)/, `/${target}$2`);
                router.push(next === pathname ? `/${target}` : next);
              }}
              className="flex items-center gap-2 px-3 py-1.5 rounded-full bg-[color:var(--glass-05)] hover:bg-[color:var(--glass-10)] border border-[color:var(--border-10)] text-sm text-[color:var(--text-muted)] transition-colors whitespace-nowrap"
            >
              <span>{locale === 'fa' ? t('nav_lang_en') : t('nav_lang_fa')}</span>
              <span className="text-[color:var(--text-muted-3)]">{locale === 'fa' ? t('nav_lang_fa') : t('nav_lang_en')}</span>
            </button>
          </div>

          {/* دکمه تغییر تم */}
          <button
            type="button"
            onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
            className="p-2 rounded-full bg-[color:var(--glass-05)] hover:bg-[color:var(--glass-10)] border border-[color:var(--border-10)] transition-colors flex items-center justify-center"
          >
            {theme === 'light' ? (
              <Sun className="w-4 h-4 text-[color:var(--text-muted)]" />
            ) : (
              <Moon className="w-4 h-4 text-[color:var(--text-muted)]" />
            )}
          </button>

          {/* دکمه شروع کنید */}
          {/* <button className="px-5 py-2 rounded-full bg-blue-600 hover:bg-blue-500 text-white text-sm font-semibold transition-all hover:shadow-[0_0_15px_rgba(37,99,235,0.5)]">
            {t('nav_start')}
          </button> */}
        </div>
      </motion.header>

      {/* پنل منوی موبایل */}
      {mobileOpen ? (
        <div
          className={`md:hidden w-full max-w-7xl mt-3 rounded-2xl bg-[color:var(--glass-05)] backdrop-blur-lg border border-[color:var(--border-10)] shadow-2xl overflow-hidden`}
          dir={dir}
        >
          <div className="p-3 flex flex-col gap-2">
            {navItems.map((item) => {
              if (item.type === 'link') {
                return (
                  <Link
                    key={item.id}
                    href={item.href}
                    className="px-3 py-2 rounded-xl text-sm font-medium text-[color:var(--text-muted)] hover:text-[color:var(--text-primary)] hover:bg-[color:var(--glass-10)] transition-colors"
                  >
                    <span className="flex flex-col leading-tight">
                      <span>{item.primary}</span>
                      <span className="text-[11px] font-semibold tracking-wide text-[color:var(--text-muted-3)]">
                        {item.secondary}
                      </span>
                    </span>
                  </Link>
                );
              }

              const isOpen = Boolean(mobileSections[item.id]);
              return (
                <div key={item.id} className="rounded-xl overflow-hidden border border-[color:var(--border-10)] bg-[color:var(--glass-02)]">
                  <button
                    type="button"
                    onClick={() => setMobileSections((prev) => ({ ...prev, [item.id]: !Boolean(prev[item.id]) }))}
                    className="w-full flex items-center justify-between px-3 py-2 text-sm font-medium text-[color:var(--text-muted)] hover:text-[color:var(--text-primary)] hover:bg-[color:var(--glass-10)] transition-colors"
                    aria-expanded={isOpen}
                  >
                    <span className="flex flex-col leading-tight text-start">
                      <span>{item.primary}</span>
                      <span className="text-[11px] font-semibold tracking-wide text-[color:var(--text-muted-3)]">
                        {item.secondary}
                      </span>
                    </span>
                    <ChevronDown
                      className={`w-4 h-4 text-[color:var(--text-muted-3)] transition-transform ${isOpen ? 'rotate-180' : ''}`}
                    />
                  </button>

                  {isOpen ? (
                    <div className="px-2 pb-2">
                      <div className="grid grid-cols-1 gap-1">
                        {item.children.map((child) => (
                          <Link
                            key={child.id}
                            href={child.href}
                            className="flex items-center gap-3 px-3 py-2 rounded-2xl text-sm text-[color:var(--text-muted)] hover:text-[color:var(--text-primary)] hover:bg-[color:var(--glass-10)] transition-colors"
                          >
                            <span
                              className={`w-9 h-9 rounded-2xl bg-gradient-to-br ${child.bg} ring-1 ${child.ring} border border-[color:var(--border-10)] flex items-center justify-center`}
                            >
                              <child.icon className="w-4 h-4 text-[color:var(--text-primary)] opacity-90" />
                            </span>
                            <span className="flex-1">{child.label}</span>
                          </Link>
                        ))}
                      </div>
                    </div>
                  ) : null}
                </div>
              );
            })}
          </div>
        </div>
      ) : null}
    </div>
  );
}
