"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useRef, useState } from "react";

import { SulsysLogo } from "./brand/SulsysMark";

import { LOCALE_LABEL, LOCALE_NAME, LOCALES, type Locale } from "@/lib/locales";
import { rememberLocale } from "@/lib/remember-locale";
import { href, resolveRoute } from "@/lib/routes";

import styles from "./Header.module.css";

export type NavItem = { key: string; label: string; href: string };
export type NavModule = { id: string; code: string; brandName: string; name: string; href: string };

export type NavStrings = {
  navAria: string;
  companyName: string;
  companyDescriptor: string;
  modules: string;
  menuOpen: string;
  menuClose: string;
  menuTitle: string;
  langAria: string;
  callAria: string;
  facebookHref: string;
  facebookAria: string;
  demo: string;
  phoneHref: string;
  phoneDisplay: string;
  demoHref: string;
};

/**
 * The navigation, as one client component.
 *
 * It is a client component for two reasons, both of which need the live URL:
 * the current item carries `aria-current="page"`, and the language switch
 * resolves the *exact counterpart URL* of the page being viewed rather than
 * dropping the visitor on the other home page. Because the route registry is
 * pure, `resolveRoute` works here as well as on the server.
 *
 * Desktop: three words, the languages, the phone. Phone and tablet: the phone
 * and a menu; the sheet lists the four products first, then the site.
 */
export function SiteNav({
  locale,
  items,
  more,
  modules,
  strings,
}: {
  locale: Locale;
  items: NavItem[];
  more: NavItem[];
  modules: NavModule[];
  strings: NavStrings;
}) {
  const pathname = usePathname() ?? "";
  const dialogRef = useRef<HTMLDialogElement | null>(null);

  const isCurrent = (target: string) => pathname === target;

  /* ---- Mobile sheet ----------------------------------------------------- */

  const [sheetOpen, setSheetOpen] = useState(false);

  function openSheet() {
    setSheetOpen(true);
    dialogRef.current?.showModal();
  }

  function closeSheet() {
    setSheetOpen(false);
    dialogRef.current?.close();
  }

  /* ---- Language switch -------------------------------------------------- */

  /**
   * Resolve the counterpart URL from the live path. A path that does not
   * resolve (the 404 page, say) falls back to that language's home page,
   * which is the only case where the switch changes subject.
   */
  function counterpart(other: Locale): string {
    const segments = pathname.split("/").filter(Boolean);
    const [first, ...rest] = segments;
    if (first === locale) {
      const target = resolveRoute(locale, rest);
      if (target) return href(target, other);
    }
    return href({ key: "home" }, other);
  }

  const langSwitch = (
    <div className={styles.lang} role="group" aria-label={strings.langAria}>
      {LOCALES.map((other) => {
        const current = other === locale;
        return (
          <Link
            key={other}
            href={current ? counterpart(locale) : counterpart(other)}
            hrefLang={other}
            lang={other}
            aria-label={LOCALE_NAME[other]}
            aria-current={current ? "true" : undefined}
            className={[styles.langItem, current ? styles.langCurrent : null]
              .filter(Boolean)
              .join(" ")}
            onClick={() => {
              rememberLocale(other);
              closeSheet();
            }}
          >
            {LOCALE_LABEL[other]}
          </Link>
        );
      })}
    </div>
  );

  return (
    <>
      {/* Desktop */}
      <nav className={`${styles.nav} ${styles.desktopOnly}`} aria-label={strings.navAria}>
        <ul className={styles.list}>
          {items.map((item) => (
            <li key={item.key}>
              <Link
                href={item.href}
                className={styles.link}
                aria-current={isCurrent(item.href) ? "page" : undefined}
              >
                {item.label}
              </Link>
            </li>
          ))}
        </ul>
        {langSwitch}
        <a
          href={strings.phoneHref}
          className={styles.phone}
          aria-label={strings.callAria}
          data-event="call_click"
        >
          <PhoneIcon />
          <span>{strings.phoneDisplay}</span>
        </a>
      </nav>

      {/* Phone and tablet: tap-to-call plus the sheet */}
      <div className={styles.mobileOnly}>
        <a
          href={strings.phoneHref}
          className={styles.iconButton}
          aria-label={strings.callAria}
          data-event="call_click"
        >
          <PhoneIcon />
        </a>
        <button
          type="button"
          className={styles.iconButton}
          aria-label={strings.menuOpen}
          aria-expanded={sheetOpen}
          onClick={openSheet}
        >
          <MenuIcon />
        </button>
      </div>

      <dialog
        ref={dialogRef}
        className={styles.sheet}
        aria-label={strings.menuTitle}
        onClose={() => setSheetOpen(false)}
        onCancel={() => setSheetOpen(false)}
      >
        <div className={styles.sheetInner}>
          <div className={styles.sheetTop}>
            {/*
              The sheet opens over the page, so it restates whose site this is
              with the mark itself. The descriptor stays: in the sheet there is
              room for it, and it is the one place a visitor meets "software,
              Gostivar" without having to read a paragraph.
            */}
            <span className={styles.sheetBrand}>
              <SulsysLogo tone="ink" tier="compact" />
              <span className="visually-hidden">{strings.companyName}</span>
              <span className={styles.sheetBrandTag}>{strings.companyDescriptor}</span>
            </span>
            <button
              type="button"
              className={styles.iconButton}
              aria-label={strings.menuClose}
              onClick={closeSheet}
            >
              <CloseIcon />
            </button>
          </div>

          {/* The products first: the thing most people opened the menu for. */}
          <p className={styles.sheetLabel}>{strings.modules}</p>
          <ul className={styles.sheetSub}>
            {modules.map((module) => (
              <li key={module.id}>
                <Link
                  href={module.href}
                  className={styles.sheetSubLink}
                  aria-current={isCurrent(module.href) ? "page" : undefined}
                  onClick={closeSheet}
                >
                  <span className={styles.panelCode}>{module.code}</span>
                  <span>
                    <span className={styles.panelBrand}>{module.brandName}</span>
                    <span className={styles.panelName}>{module.name}</span>
                  </span>
                </Link>
              </li>
            ))}
          </ul>

          <ul className={styles.sheetList}>
            {[...items, ...more].map((item) => (
              <li key={item.key} className={styles.sheetItem}>
                <Link
                  href={item.href}
                  className={styles.sheetLink}
                  aria-current={isCurrent(item.href) ? "page" : undefined}
                  onClick={closeSheet}
                >
                  {item.label}
                </Link>
              </li>
            ))}
          </ul>

          {langSwitch}

          <div className={styles.sheetFoot}>
            <a
              href={strings.facebookHref}
              className={styles.sheetChannel}
              target="_blank"
              rel="noopener noreferrer"
              onClick={closeSheet}
              data-event="facebook_click"
            >
              <FacebookIcon />
              {strings.facebookAria}
            </a>
            <a href={strings.phoneHref} className={styles.slimCall} data-event="call_click">
              <PhoneIcon />
              {strings.phoneDisplay}
            </a>
            <Link href={strings.demoHref} className={styles.slimDemo} onClick={closeSheet}>
              {strings.demo}
            </Link>
          </div>
        </div>
      </dialog>
    </>
  );
}

/* ---- Icons: 1.5 px stroke, 20 px ---------------------------------------- */

function PhoneIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true">
      <path
        d="M5 2.5h3l1.5 3.5-2 1.5a9 9 0 0 0 5 5l1.5-2 3.5 1.5v3c0 .8-.7 1.5-1.5 1.5A14 14 0 0 1 2.5 4C2.5 3.2 3.2 2.5 4 2.5"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function MenuIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true">
      <path d="M3 6h14M3 10h14M3 14h14" stroke="currentColor" strokeWidth="1.5" />
    </svg>
  );
}

/** The channel mark, drawn flat at the same 1.5 px weight as the others. */
function FacebookIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true">
      <path
        d="M11.6 18v-7h2.2l.4-2.6h-2.6V6.8c0-.75.22-1.26 1.3-1.26h1.38V3.2A18 18 0 0 0 12.3 3c-2 0-3.35 1.2-3.35 3.42V8.4H6.7V11h2.25v7"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function CloseIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true">
      <path d="M4 4l12 12M16 4L4 16" stroke="currentColor" strokeWidth="1.5" />
    </svg>
  );
}
