"use client";
import { useState } from "react";
import Link from "next/link";
import type { Locale } from "@/i18n/routes";
import { switchLocale } from "@/i18n/routes";

type Item = { href: string; label: string };

export function MobileNav({
  locale,
  items,
  menuLabel,
  switchLabel,
}: {
  locale: Locale;
  items: Item[];
  menuLabel: string;
  switchLabel: string;
}) {
  const [open, setOpen] = useState(false);
  const target: Locale = locale === "de" ? "en" : "de";
  return (
    <div className="md:hidden">
      <button
        type="button"
        aria-expanded={open}
        aria-controls="mobile-nav"
        onClick={() => setOpen((v) => !v)}
        className="font-mono text-sm text-muted hover:text-accent"
      >
        [{open ? "x" : menuLabel}]
      </button>
      {open ? (
        <nav id="mobile-nav" className="absolute left-0 right-0 z-10 mt-2 border-b border-hairline bg-[var(--bg-deep)]">
          <ul className="mx-auto flex max-w-5xl flex-col gap-3 px-4 py-4">
            {items.map((i) => (
              <li key={i.href}>
                <Link
                  href={i.href}
                  className="block font-mono text-sm text-[var(--fg)] hover:text-accent"
                  onClick={() => setOpen(false)}
                >
                  {i.label}
                </Link>
              </li>
            ))}
            <li>
              <Link
                href="#"
                className="block font-mono text-xs uppercase text-muted hover:text-accent"
                onClick={(e) => {
                  e.preventDefault();
                  if (typeof window === "undefined") return;
                  const next = switchLocale(window.location.pathname, target) ?? (target === "en" ? "/en" : "/");
                  window.location.href = next;
                }}
              >
                {switchLabel}
              </Link>
            </li>
          </ul>
        </nav>
      ) : null}
    </div>
  );
}
