// src/components/frontend/layout/MobileMenu.tsx

'use client'

import { useState } from 'react'
import * as motion from 'framer-motion/m'
import { AnimatePresence } from 'framer-motion'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { ChevronDown, ChevronUp } from 'lucide-react'

// ─── Types ────────────────────────────────────────────────────────────────────

interface MenuItem {
  id: string;
  parent_id: string | null;
  type: 'page' | 'category' | 'product' | 'custom' | 'post';
  reference_id: string | null;
  url: string | null;
  target: '_self' | '_blank';
  icon: string | null;
  css_class: string | null;
  display_type: 'default' | 'dropdown' | 'mega';
  mega_columns: number | null;
  mega_style: 'default' | 'cards' | 'grid' | 'list';
  label: string;
  title_attr: string | null;
  description: string | null;
  children: MenuItem[];
  sort_order?: number;
}

interface MobileMenuProps {
  isOpen: boolean
  onClose: () => void
  menuItems?: MenuItem[]
}

export default function MobileMenu({ isOpen, onClose, menuItems = [] }: MobileMenuProps) {
  const pathname = usePathname()
  const [openDropdown, setOpenDropdown] = useState<string | null>(null)

  const toggleDropdown = (id: string) => {
    setOpenDropdown(openDropdown === id ? null : id)
  }

  const isActive = (path: string) => pathname === path

  // ─── Build URL from menu item ──────────────────────────────────────────────
  const getItemUrl = (item: MenuItem): string => {
    if (item.type === 'custom' && item.url) {
      return item.url
    }
    if (item.reference_id) {
      if (item.type === 'page') return `/page/${item.reference_id}`
      if (item.type === 'post') return `/post/${item.reference_id}`
      if (item.type === 'category') return `/category/${item.reference_id}`
      if (item.type === 'product') return `/product/${item.reference_id}`
    }
    return '#'
  }

  // ─── Render menu items recursively ─────────────────────────────────────────
  const renderMenuItem = (item: MenuItem, depth: number = 0) => {
    const hasChildren = item.children && item.children.length > 0
    const isExpanded = openDropdown === item.id
    const url = getItemUrl(item)

    return (
      <div key={item.id} className="relative">
        {hasChildren ? (
          // ─── Dropdown Item ────────────────────────────────────────────────────
          <div>
            <button
              onClick={() => toggleDropdown(item.id)}
              className={`w-full flex justify-between items-center py-3 px-4 rounded-lg font-semibold transition ${
                pathname.startsWith(url) ? 'bg-primary/10 text-primary' : 'text-dark hover:bg-gray-50'
              }`}
              style={{ paddingLeft: `${depth * 12 + 16}px` }}
            >
              <span>
                {item.icon && <span className={`${item.icon} mr-2`} />}
                {item.label}
              </span>
              {isExpanded ? <ChevronUp size={18} /> : <ChevronDown size={18} />}
            </button>
            {isExpanded && (
              <div className="ml-4 mt-1 space-y-1 border-l-2 border-gray-200 pl-3">
                {item.children.map((child) => renderMenuItem(child, depth + 1))}
              </div>
            )}
          </div>
        ) : (
          // ─── Simple Link ──────────────────────────────────────────────────────
          <Link
            href={url}
            target={item.target || '_self'}
            onClick={onClose}
            className={`block py-3 px-4 rounded-lg font-semibold transition ${
              isActive(url) ? 'bg-primary/10 text-primary' : 'text-dark hover:bg-gray-50'
            }`}
            style={{ paddingLeft: `${depth * 12 + 16}px` }}
          >
            {item.icon && <span className={`${item.icon} mr-2`} />}
            {item.label}
          </Link>
        )}
      </div>
    )
  }

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/50 z-50"
            onClick={onClose}
          />
          <motion.div
            initial={{ x: '-100%' }}
            animate={{ x: 0 }}
            exit={{ x: '-100%' }}
            transition={{ type: 'tween' }}
            className="fixed top-0 left-0 w-4/5 h-full bg-white z-50 shadow-xl p-4 overflow-y-auto"
          >
            <button 
              onClick={onClose} 
              className="absolute top-4 right-4 text-2xl p-2 hover:bg-gray-100 rounded-full"
            >
              &times;
            </button>
            
            <nav className="mt-16 flex flex-col gap-1">
              {menuItems.length > 0 ? (
                // ─── Dynamic Menu ──────────────────────────────────────────────
                menuItems.map((item) => renderMenuItem(item))
              ) : (
                // ─── Fallback Static Menu ──────────────────────────────────────
                <>
                  <Link href="/" onClick={onClose} className="py-3 px-4 rounded-lg font-semibold text-dark hover:bg-gray-50">
                    Home
                  </Link>
                  <Link href="/products" onClick={onClose} className="py-3 px-4 rounded-lg font-semibold text-dark hover:bg-gray-50">
                    Shop
                  </Link>
                  <Link href="/about" onClick={onClose} className="py-3 px-4 rounded-lg font-semibold text-dark hover:bg-gray-50">
                    About
                  </Link>
                  <Link href="/contact" onClick={onClose} className="py-3 px-4 rounded-lg font-semibold text-dark hover:bg-gray-50">
                    Contact
                  </Link>
                </>
              )}

              {/* Account Section */}
              <div className="border-t border-gray-200 my-4 pt-4">
                <Link href="/account" onClick={onClose} className="block py-3 px-4 text-dark hover:bg-gray-50 rounded-lg transition">
                  👤 My Account
                </Link>
                <Link href="/account/orders" onClick={onClose} className="block py-3 px-4 text-dark hover:bg-gray-50 rounded-lg transition">
                  📦 My Orders
                </Link>
                <Link href="/account/wishlist" onClick={onClose} className="block py-3 px-4 text-dark hover:bg-gray-50 rounded-lg transition">
                  ❤️ Wishlist
                </Link>
                <Link href="/account/addresses" onClick={onClose} className="block py-3 px-4 text-dark hover:bg-gray-50 rounded-lg transition">
                  📍 Addresses
                </Link>
                <Link href="/account/referrals" onClick={onClose} className="block py-3 px-4 text-dark hover:bg-gray-50 rounded-lg transition">
                  🔗 My Referrals
                </Link>
                <Link href="/account/earnings" onClick={onClose} className="block py-3 px-4 text-dark hover:bg-gray-50 rounded-lg transition">
                  💰 My Earnings
                </Link>
              </div>

              {/* Auth Links */}
              <div className="border-t border-gray-200 pt-4">
                <Link href="/login" onClick={onClose} className="block py-3 px-4 text-center bg-gradient-primary text-white rounded-lg font-semibold">
                  Sign In
                </Link>
                <Link href="/register" onClick={onClose} className="block py-3 px-4 text-center text-primary border border-primary rounded-lg font-semibold mt-2">
                  Create Account
                </Link>
              </div>
            </nav>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  )
}