'use client';

/**
 * MobileMenu Component
 *
 * Reverted & enhanced rich mobile menu drawer with category discovery accordion,
 * category icons, "How it works", "Become a Partner (Pros)", "Find a service" CTA,
 * Language & Theme preferences, and smooth non-cutting scroll architecture.
 *
 * DATA: `categories` prop contains live API data passed from layout RSC via Header.
 * VISUAL: Zero changes to markup, classes, animations, or layout.
 */

import React, { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import Link from 'next/link';
import { useTranslations } from 'next-intl';
import { LanguageSwitcher } from './LanguageSwitcher';
import { ThemeToggle } from '@/components/ui/theme-toggle';
import { useAuthStore } from '@/lib/stores/useAuthStore';
import {
  Menu,
  X,
  ChevronDown,
  Sparkles,
  Scissors,
  Heart,
  Smile,
  Feather,
  Eye,
  Sparkle,
  Flame,
  HelpCircle,
  Briefcase,
  User,
  ArrowRight,
} from 'lucide-react';
import type { Category } from '@shinecode/api-client/types';
import { ImageWithFallback } from '@/components/ui/ImageWithFallback';

import { useIsMounted } from '@/hooks/useIsMounted';

/** Same icon map as ServicesMegaMenu — visual only, not data */
const ICON_MAP: Record<string, React.ComponentType<{ className?: string }>> = {
  hair: Scissors,
  nails: Sparkles,
  massage: Heart,
  spa: Smile,
  facial: Sparkle,
  lashes: Eye,
  brows: Feather,
  waxing: Flame,
};

function getIconForCat(slug: string): React.ComponentType<{ className?: string }> {
  const clean = slug.toLowerCase();
  for (const [key, val] of Object.entries(ICON_MAP)) {
    if (clean.includes(key)) return val;
  }
  return Sparkles;
}

interface MobileMenuProps {
  locale: string;
  /** Live API categories from layout RSC — empty array means API unavailable */
  categories?: Category[];
}

export function MobileMenu({ locale, categories = [] }: MobileMenuProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [isServicesExpanded, setIsServicesExpanded] = useState(true);
  const mounted = useIsMounted();
  const { isAuthenticated, user, openAuthModal } = useAuthStore();

  const isAr = locale === 'ar';
  const tNav = useTranslations('navigation');

  /** Map API categories to display items with icon and image */
  const displayCategories = categories.map((cat) => {
    const icon = getIconForCat(cat.slug);
    return { slug: cat.slug, name: cat.name, icon, image: cat.category_image };
  });

  // Lock background scroll when drawer is open and support ESC key
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
      const handleKeyDown = (e: KeyboardEvent) => {
        if (e.key === 'Escape') setIsOpen(false);
      };
      document.addEventListener('keydown', handleKeyDown);
      return () => {
        document.body.style.overflow = '';
        document.removeEventListener('keydown', handleKeyDown);
      };
    } else {
      document.body.style.overflow = '';
    }
  }, [isOpen]);

  const handleLoginClick = () => {
    setIsOpen(false);
    openAuthModal('login');
  };

  // No local categories array — use API prop

  const drawerContent = isOpen && mounted ? (
    <div
      className="fixed inset-0 z-[120] flex justify-end md:hidden"
      role="dialog"
      aria-modal="true"
      aria-label="Mobile navigation"
    >
      {/* 1. Backdrop Overlay */}
      <div
        className="fixed inset-0 bg-slate-950/60 backdrop-blur-xs transition-opacity animate-in fade-in duration-200"
        onClick={() => setIsOpen(false)}
        aria-hidden="true"
      />

      {/* 2. Drawer Menu Panel (Full 100dvh with proper flexbox scroll containment) */}
      <aside className="relative z-50 w-full max-w-sm h-[100dvh] bg-white dark:bg-zinc-950 border-s border-slate-200 dark:border-zinc-800 shadow-2xl flex flex-col justify-between overflow-hidden animate-in slide-in-from-end duration-300">
        
        {/* Drawer Header (Fixed top) */}
        <div className="shrink-0 p-4 border-b border-slate-100 dark:border-zinc-850 flex items-center justify-between bg-white dark:bg-zinc-950">
          <Link
            href={`/${locale}`}
            onClick={() => setIsOpen(false)}
            className="flex items-center gap-0.5 text-xl font-black text-slate-950 dark:text-white"
          >
            <span>Shine</span>
            <span className="text-brand-500">code</span>
          </Link>

          {/* Close Button */}
          <button
            type="button"
            onClick={() => setIsOpen(false)}
            className="w-10 h-10 inline-flex items-center justify-center rounded-xl text-slate-500 dark:text-zinc-400 hover:text-slate-900 dark:hover:text-white hover:bg-slate-100 dark:hover:bg-zinc-850 transition-colors cursor-pointer"
            aria-label="Close navigation menu"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Scrollable Navigation Body */}
        <div className="flex-1 overflow-y-auto min-h-0 overscroll-contain p-4 space-y-3">
          
          {/* Services Accordion */}
          <div className="border border-slate-200/80 dark:border-zinc-800 rounded-2xl overflow-hidden bg-slate-50/50 dark:bg-zinc-900/50">
            <button
              type="button"
              onClick={() => setIsServicesExpanded((prev) => !prev)}
              className="w-full px-4 py-3.5 flex items-center justify-between text-start text-sm font-bold text-slate-900 dark:text-white hover:bg-slate-100/60 dark:hover:bg-zinc-850 transition-colors cursor-pointer"
            >
              <span className="flex items-center gap-2.5">
                <Sparkles className="w-4 h-4 text-brand-500" />
                <span>{tNav('services')}</span>
              </span>
              <ChevronDown
                className={`w-4 h-4 text-slate-400 transition-transform duration-200 ${
                  isServicesExpanded ? 'rotate-180 text-brand-500' : ''
                }`}
              />
            </button>

            {isServicesExpanded && (
              <div className="p-2 pt-0 grid grid-cols-2 gap-1.5 border-t border-slate-200/60 dark:border-zinc-800">
                {displayCategories.map((cat) => {
                  const Icon = cat.icon;
                  return (
                    <Link
                      key={cat.slug}
                      href={`/${locale}/categories/${cat.slug}`}
                      onClick={() => setIsOpen(false)}
                      className="px-3 py-2.5 rounded-xl text-xs font-semibold text-slate-800 dark:text-zinc-200 hover:bg-white dark:hover:bg-zinc-800 hover:shadow-xs transition-all flex items-center gap-2 border border-transparent hover:border-slate-200 dark:hover:border-zinc-700"
                    >
                      <div className="w-6 h-6 flex items-center justify-center shrink-0 overflow-hidden relative rounded-md">
                        {cat.image ? (
                          <ImageWithFallback
                            src={cat.image}
                            alt={cat.name}
                            width={24}
                            height={24}
                            className="w-full h-full object-cover rounded-md"
                          />
                        ) : (
                          <Icon className="w-4 h-4 text-zinc-700 dark:text-zinc-300" />
                        )}
                      </div>
                      <span className="truncate">{cat.name}</span>
                    </Link>
                  );
                })}
                <div className="col-span-2 pt-1">
                  <Link
                    href={`/${locale}/services`}
                    onClick={() => setIsOpen(false)}
                    className="w-full py-2.5 text-center text-xs font-bold text-brand-500 hover:text-brand-600 block transition-colors bg-white dark:bg-zinc-900 rounded-xl border border-slate-200 dark:border-zinc-800"
                  >
                    {tNav('viewAllServices')} →
                  </Link>
                </div>
              </div>
            )}
          </div>

          {/* How it works */}
          <Link
            href={`/${locale}#how-it-works`}
            onClick={() => setIsOpen(false)}
            className="w-full px-4 py-3.5 flex items-center gap-3 text-sm font-semibold text-slate-800 dark:text-zinc-200 hover:bg-slate-50 dark:hover:bg-zinc-900 rounded-2xl transition-colors min-h-[46px] border border-slate-100 dark:border-zinc-850"
          >
            <HelpCircle className="w-4 h-4 text-slate-500" />
            <span>{tNav('howItWorks')}</span>
          </Link>

          {/* Become a Partner */}
          <Link
            href={`/${locale}/partner`}
            onClick={() => setIsOpen(false)}
            className="w-full px-4 py-3.5 flex items-center justify-between text-sm font-bold text-brand-700 dark:text-brand-400 bg-brand-50 dark:bg-brand-950/40 hover:bg-brand-100/80 rounded-2xl transition-colors min-h-[46px] border border-brand-100 dark:border-brand-900/50"
          >
            <span className="flex items-center gap-3">
              <Briefcase className="w-4 h-4 text-brand-600 dark:text-brand-400" />
              <span>{tNav('becomePartner')}</span>
            </span>
            <span className="text-[10px] font-extrabold bg-brand-500 text-white px-2 py-0.5 rounded-full">
              Pros
            </span>
          </Link>
        </div>

        {/* Bottom Utilities & CTA (Fixed bottom) */}
        <div className="shrink-0 p-4 border-t border-slate-100 dark:border-zinc-850 bg-slate-50/90 dark:bg-zinc-900/90 space-y-3 pb-safe">
          {/* User Auth Section */}
          {isAuthenticated && user ? (
            <div className="p-3 bg-white dark:bg-zinc-800 rounded-xl border border-slate-200 dark:border-zinc-700 space-y-2">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2 min-w-0">
                  <div className="w-8 h-8 rounded-full bg-zinc-100 dark:bg-zinc-700 font-bold text-xs flex items-center justify-center text-zinc-900 dark:text-white shrink-0">
                    {(user.first_name?.charAt(0) || 'U').toUpperCase()}
                  </div>
                  <div className="min-w-0">
                    <div className="text-xs font-bold text-zinc-900 dark:text-white truncate">
                      {user.first_name} {user.last_name}
                    </div>
                    <div className="text-[10px] text-zinc-400 truncate">
                      {user.email}
                    </div>
                  </div>
                </div>
                <button
                  type="button"
                  onClick={() => {
                    setIsOpen(false);
                    useAuthStore.getState().logout();
                  }}
                  className="text-[11px] font-semibold text-rose-500 hover:underline shrink-0"
                >
                  {isAr ? 'خروج' : 'Logout'}
                </button>
              </div>
              <Link
                href={`/${locale}/dashboard`}
                onClick={() => setIsOpen(false)}
                className="w-full py-2 bg-zinc-900 dark:bg-white text-white dark:text-zinc-950 font-bold text-xs rounded-lg flex items-center justify-center gap-1.5 transition-colors"
              >
                <span>{isAr ? 'لوحة التحكم وحجوزاتي' : 'My Bookings & Dashboard'}</span>
              </Link>
            </div>
          ) : (
            <button
              type="button"
              onClick={handleLoginClick}
              className="w-full py-3 px-4 rounded-xl border border-slate-200 dark:border-zinc-800 text-sm font-bold text-slate-900 dark:text-white bg-white dark:bg-zinc-850 hover:bg-slate-50 dark:hover:bg-zinc-800 shadow-xs transition-colors flex items-center justify-center gap-2 min-h-[46px] cursor-pointer"
            >
              <User className="w-4 h-4 text-slate-500" />
              <span>{tNav('login')}</span>
            </button>
          )}

          {/* Language Switcher & Theme Toggle */}
          <div className="flex items-center justify-between px-2">
            <span className="text-xs font-semibold text-slate-500 dark:text-zinc-400">
              {isAr ? 'التفضيلات' : 'Preferences'}
            </span>
            <div className="flex items-center gap-2">
              <LanguageSwitcher currentLocale={locale} />
              <ThemeToggle />
            </div>
          </div>

          {/* Primary Full-width CTA */}
          <Link
            href={`/${locale}/search`}
            onClick={() => setIsOpen(false)}
            className="w-full py-3.5 px-4 bg-brand-500 hover:bg-brand-600 active:bg-brand-700 text-white font-bold text-sm rounded-xl shadow-brand text-center flex items-center justify-center gap-2 transition-transform active:scale-98 min-h-[46px]"
          >
            <span>{tNav('findService')}</span>
            <ArrowRight className="w-4 h-4 rtl:rotate-180" />
          </Link>
        </div>

      </aside>
    </div>
  ) : null;

  return (
    <>
      {/* Mobile Controls (Header Right) */}
      <div className="flex items-center gap-2">
        {/* Quick Book CTA button */}
        <Link
          href={`/${locale}/search`}
          className="px-4 py-2 bg-brand-500 hover:bg-brand-600 active:bg-brand-700 text-white font-bold text-xs rounded-full shadow-sm transition-transform active:scale-95 flex items-center justify-center min-h-[38px]"
        >
          {tNav('book')}
        </Link>

        {/* Hamburger Toggle Button */}
        <button
          type="button"
          onClick={() => setIsOpen(true)}
          className="w-10 h-10 inline-flex items-center justify-center rounded-xl text-slate-800 dark:text-white hover:bg-slate-100 dark:hover:bg-zinc-800 active:bg-slate-200 transition-colors focus:outline-none cursor-pointer"
          aria-expanded={isOpen}
          aria-label="Open navigation menu"
        >
          <Menu className="w-6 h-6" />
        </button>
      </div>

      {/* Render Drawer into Portal */}
      {mounted && typeof document !== 'undefined' ? createPortal(drawerContent, document.body) : null}
    </>
  );
}

export default MobileMenu;
