"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { navLinks, siteConfig } from "@/lib/site-config";
import { ChevronDownIcon, CloseIcon, InstagramIcon } from "@/components/ui/icons";

const contactPhoneHref = `tel:${siteConfig.contact.phone.replace(/\s/g, "")}`;

export default function MobileMenu({
  open,
  onClose,
}: {
  open: boolean;
  onClose: () => void;
}) {
  const pathname = usePathname();
  const [openAccordion, setOpenAccordion] = useState<string | null>(null);

  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => {
      document.body.style.overflow = "";
    };
  }, [open]);

  // Close accordion when menu closes
  useEffect(() => {
    if (!open) setOpenAccordion(null);
  }, [open]);

  function toggleAccordion(label: string) {
    setOpenAccordion((prev) => (prev === label ? null : label));
  }

  return (
    <div
      className={`fixed inset-0 z-50 md:hidden ${open ? "pointer-events-auto" : "pointer-events-none"}`}
      aria-hidden={!open}
    >
      {/* Overlay */}
      <div
        onClick={onClose}
        className={`absolute inset-0 bg-black transition-opacity duration-base ${
          open ? "opacity-100" : "opacity-0"
        }`}
      />

      {/* Slide-in panel */}
      <nav
        aria-label="Mobile Navigation"
        className={`absolute right-0 top-0 flex h-full w-[78%] max-w-sm flex-col bg-secondary px-8 py-6 shadow-2xl transition-transform duration-base ease-out ${
          open ? "translate-x-0" : "translate-x-full"
        }`}
      >
        <div className="flex items-center justify-end">
          <button
            onClick={onClose}
            aria-label="Menü schliessen"
            className="rounded p-2 text-cream hover:text-primary-light"
          >
            <CloseIcon className="h-6 w-6" />
          </button>
        </div>

        <ul className="mt-10 flex flex-col gap-1">
          {navLinks.map((item) => {
            if (item.children) {
              const isOpen = openAccordion === item.label;
              return (
                <li key={item.label}>
                  {/* Accordion header */}
                  <button
                    onClick={() => toggleAccordion(item.label)}
                    className="flex w-full items-center justify-between border-l-[3px] border-transparent py-3 pl-4 font-display text-2xl tracking-wide text-cream hover:border-primary hover:text-primary-light"
                    aria-expanded={isOpen}
                  >
                    {item.label}
                    <ChevronDownIcon
                      className={`mr-1 h-5 w-5 transition-transform duration-fast ${
                        isOpen ? "rotate-180" : ""
                      }`}
                    />
                  </button>

                  {/* Accordion children — always in DOM, height animated via grid trick */}
                  <div
                    className={`grid transition-[grid-template-rows] duration-300 ease-in-out ${
                      isOpen ? "grid-rows-[1fr]" : "grid-rows-[0fr]"
                    }`}
                  >
                    <ul className="overflow-hidden mb-2 flex flex-col gap-0.5">
                      {item.children.map((child) => (
                        <li key={child.href}>
                          <Link
                            href={child.href}
                            onClick={onClose}
                            className="block border-l-[3px] border-transparent py-2 pl-8 text-lg text-gray-300 hover:border-primary hover:text-primary-light"
                          >
                            {child.label}
                          </Link>
                        </li>
                      ))}
                    </ul>
                  </div>
                </li>
              );
            }

            // Simple flat link
            const active = item.href === "/" ? pathname === "/" : pathname.startsWith(item.href);
            return (
              <li key={item.href}>
                <Link
                  href={item.href}
                  onClick={onClose}
                  className={`block border-l-[3px] py-3 pl-4 font-display text-2xl tracking-wide ${
                    active
                      ? "border-primary text-primary-light"
                      : "border-transparent text-cream hover:border-primary hover:text-primary-light"
                  }`}
                >
                  {item.label}
                </Link>
              </li>
            );
          })}
        </ul>

        <Link
          href="/kontakt#kontakt-formular"
          onClick={onClose}
          className="mt-8 inline-block rounded bg-primary px-6 py-3 text-center font-semibold text-cream transition-colors duration-fast hover:bg-primary-light"
        >
          Probetraining
        </Link>

        {siteConfig.social.instagram ? (
          <a
            href={siteConfig.social.instagram}
            target="_blank"
            rel="noopener noreferrer"
            className="mt-auto flex items-center gap-2 py-6 text-gray-200 hover:text-accent"
            aria-label="Instagram (öffnet in neuem Tab)"
          >
            <InstagramIcon className="h-5 w-5" />
            <span className="text-sm">{siteConfig.instagramHandle}</span>
          </a>
        ) : (
          <a href={contactPhoneHref} className="mt-auto py-6 text-sm text-gray-200 hover:text-accent">
            {siteConfig.contact.phone}
          </a>
        )}
      </nav>
    </div>
  );
}
