"use client";

import React, { useState } from "react";
import Link from "next/link";
import { generateSlug } from "@/utils/slugHelper";

type Category = {
  name: string;
  category_id: string;
};

type Subcategory = {
  name: string;
  subcategory_id: string;
  category_id: string;
};

type MobileNavProps = {
  categories: Category[];
  subcatsByCatId: Record<string, Subcategory[]>;
};

export default function MobileNav({ categories, subcatsByCatId }: MobileNavProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [expanded, setExpanded] = useState<string | null>(null);

  const toggle = () => setIsOpen((p) => !p);
  const close = () => { setIsOpen(false); setExpanded(null); };

  const toggleCat = (id: string) => setExpanded((prev) => (prev === id ? null : id));

  return (
    <>
      {/* Hamburger button — visible below lg */}
      <button
        onClick={toggle}
        aria-label={isOpen ? "Close menu" : "Open menu"}
        className="lg:hidden flex flex-col justify-center items-center w-10 h-10 rounded-xl hover:bg-surface transition-colors gap-1.5"
      >
        <span className={`w-5 h-0.5 bg-foreground rounded-full transition-all duration-200 origin-center ${isOpen ? "rotate-45 translate-y-2" : ""}`} />
        <span className={`w-5 h-0.5 bg-foreground rounded-full transition-all duration-200 ${isOpen ? "opacity-0" : ""}`} />
        <span className={`w-5 h-0.5 bg-foreground rounded-full transition-all duration-200 origin-center ${isOpen ? "-rotate-45 -translate-y-2" : ""}`} />
      </button>

      {/* Drawer backdrop */}
      {isOpen && (
        <div
          className="fixed inset-0 bg-black/40 z-[120] lg:hidden backdrop-blur-sm animate-fade-in"
          onClick={close}
        />
      )}

      {/* Drawer panel */}
      <div
        className={`fixed top-0 left-0 h-full w-80 max-w-[85vw] bg-white z-[130] lg:hidden flex flex-col shadow-[var(--shadow-modal)] transition-transform duration-300 ease-out ${isOpen ? "translate-x-0" : "-translate-x-full"
          }`}
      >
        {/* Drawer header */}
        <div className="flex items-center justify-between px-5 py-5 border-b border-border">
          <Link href="/" onClick={close}>
            <img
              src="/classic.avif"
              alt="Classic Helmets"
              className="h-9 w-auto object-contain"
            />
          </Link>
          <button
            onClick={close}
            className="w-9 h-9 rounded-xl flex items-center justify-center text-muted hover:bg-surface hover:text-foreground transition-colors"
          >
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        {/* Nav items */}
        <nav className="flex-1 overflow-y-auto py-4 px-3 custom-scrollbar space-y-1">
          {(() => {
            const links: { name: string; href: string }[] = [];

            // 1. Add subcategories first for categories that have them
            categories.forEach((cat) => {
              const subs = subcatsByCatId[cat.category_id] || [];
              subs.forEach((sub) => {
                links.push({
                  name: sub.name,
                  href: `/category/${generateSlug(cat.name)}/${generateSlug(sub.name)}`,
                });
              });
            });

            // 2. Add the categories themselves (only if they don't have subcategories)
            categories.forEach((cat) => {
              const subs = subcatsByCatId[cat.category_id] || [];
              if (subs.length === 0) {
                links.push({
                  name: cat.name,
                  href: `/category/${generateSlug(cat.name)}`,
                });
              }
            });

            return links.map((link, idx) => (
              <Link
                key={idx}
                href={link.href}
                onClick={close}
                className="block px-4 py-3 text-[14px] font-semibold text-foreground hover:bg-primary-light hover:text-primary rounded-xl transition-colors"
              >
                {link.name}
              </Link>
            ));
          })()}
        </nav>

        {/* Drawer footer */}
        <div className="px-5 py-5 border-t border-border flex flex-col gap-2">
          <Link
            href="/login"
            onClick={close}
            className="w-full inline-flex items-center justify-center gap-2 rounded-xl border border-border bg-transparent text-foreground hover:border-primary/40 hover:bg-primary-light font-semibold px-5 py-2.5 text-sm transition-all duration-200 cursor-pointer select-none focus:outline-none active:scale-[.97]"
          >
            Dealer Log In
          </Link>
        </div>
      </div>
    </>
  );
}
