"use client";

import { useState, type ReactNode } from "react";

import { useBodyClass } from "@/lib/useBodyClass";

import type { MenuItem } from "@/lib/api";

/**
 * The primary navigation and its mobile toggle.
 *
 * A Client Component only because the burger has state. The list itself is real
 * markup with real links and is present in the server HTML — with JavaScript off
 * the toggle does nothing but the navigation is still there and still usable,
 * which is the whole point of the SSR requirement.
 *
 * `active` is computed here rather than sent by the API: it is a property of the
 * current URL, and /site is shared across every page in the locale, so baking it
 * in would make that response uncacheable for one boolean. Compared on the
 * finished URLs the backend already built — this is still not URL construction.
 */
export default function MobileNav({
  nav,
  canonical,
  labels,
  languages,
}: {
  nav: MenuItem[];
  canonical: string;
  labels: { open: string; navigation: string; contact: string };
  languages: ReactNode;
}) {
  const [open, setOpen] = useState(false);

  // Scroll lock while the mobile menu covers the page.
  useBodyClass("is-locked", open);

  return (
    <>
      <button
        className="menu-toggle"
        type="button"
        aria-expanded={open}
        aria-controls="primary-navigation"
        aria-label={labels.open}
        onClick={() => setOpen((value) => !value)}
      >
        <span />
        <span />
        <span />
      </button>

      <div className={`nav-wrap${open ? " is-open" : ""}`} id="primary-navigation">
        <nav className="main-nav" aria-label={labels.navigation}>
          <ul className="nav-list">
            {nav.map((item, index) => {
              const isActive = item.url !== null && canonical.endsWith(item.url);

              return (
                <li key={`${item.url ?? item.label}-${index}`}>
                  <a
                    href={item.url ?? undefined}
                    target={item.target !== "_self" ? item.target ?? undefined : undefined}
                    rel={item.target !== "_self" ? "noopener" : undefined}
                    aria-current={isActive ? "page" : undefined}
                  >
                    {item.label}
                  </a>
                </li>
              );
            })}
          </ul>
        </nav>

        {languages}

        <button
          className="header-glyph js-open-side-panel"
          type="button"
          aria-label={labels.contact}
          aria-expanded="false"
          aria-controls="desktop-side-panel"
        >
          <svg viewBox="0 0 42 24" aria-hidden="true">
            <path d="M1 24V0" />
            <path d="M9 24V0" />
            <path d="M17 24V0" />
            <path d="M25 24V0" />
            <path d="M33 24V0" />
            <path d="M41 24V0" />
          </svg>
        </button>
      </div>
    </>
  );
}
