"use client";

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

import { useDesktopEditorSupported } from "@/lib/editor-device";

const links = [
  { href: "/", label: "Cruscotto" },
  { href: "/reservations", label: "Prenotazioni" },
  { href: "/tables", label: "Editor" },
  { href: "/floor-plan", label: "Piantina" },
  { href: "/whatsapp", label: "WhatsApp" }
];

type NavigationProps = {
  variant?: "default" | "sidebar";
};

export function Navigation({ variant = "default" }: NavigationProps) {
  const pathname = usePathname();
  const desktopEditorSupported = useDesktopEditorSupported();
  const [portalHomeHref, setPortalHomeHref] = useState<string | null>(null);
  const normalizedPathname = (pathname || "").replace(/\/+$/, "") || "/";
  const modulePath = normalizedPathname.startsWith("/prenotazioni")
    ? normalizedPathname.slice("/prenotazioni".length) || "/"
    : normalizedPathname;
  const visibleLinks = desktopEditorSupported === true
    ? links
    : links.filter((link) => link.href !== "/tables");

  useEffect(() => {
    if (typeof document !== "undefined") {
      const referrer = document.referrer.trim();
      if (referrer) {
        try {
          const referrerUrl = new URL(referrer, window.location.origin);
          referrerUrl.pathname = "/home";
          referrerUrl.search = "";
          referrerUrl.hash = "";
          setPortalHomeHref(referrerUrl.toString());
          return;
        } catch {
          // Fall through to local path fallback.
        }
      }
    }

    if (normalizedPathname === "/prenotazioni" || normalizedPathname.startsWith("/prenotazioni/")) {
      setPortalHomeHref("/home");
      return;
    }

    setPortalHomeHref(null);
  }, [normalizedPathname]);

  return (
    <nav className={`app-nav${variant === "sidebar" ? " is-sidebar" : ""}`}>
      <div className={`app-nav-inner${variant === "sidebar" ? " is-sidebar" : ""}`}>
        {portalHomeHref ? (
          <a href={portalHomeHref} className={`app-nav-link${variant === "sidebar" ? " is-sidebar" : ""}`}>
            Home
          </a>
        ) : null}
        {visibleLinks.map((link) => {
          const active =
            link.href === "/"
              ? modulePath === "/"
              : modulePath === link.href || modulePath.startsWith(`${link.href}/`);
          return (
            <Link
              key={link.href}
              href={link.href}
              className={`app-nav-link${variant === "sidebar" ? " is-sidebar" : ""}${active ? " is-active" : ""}`}
            >
              {link.label}
            </Link>
          );
        })}
      </div>
    </nav>
  );
}
