"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { clearCart } from "../../lib/cart";
import { dispatchAuthChanged } from "../../lib/auth";

// Persistent account navigation — a fixed sidebar (sm+) / horizontal tab
// bar (below sm) shown on every logged-in /konto/* page via KontoShell.
// Replaces the "Profil & Adresse / Weiter einkaufen / Abmelden" links that
// used to live at the bottom of the orders page's content — those became
// unreachable without scrolling past an arbitrarily long order list. Being
// part of the shell now (not page content), reachability no longer depends
// on how much is above it.
//
// No Merkliste entry — the Navbar's own wishlist heart icon already covers
// that (visible at every width, on every page, not just inside /konto/*),
// so a second entry here would just be a redundant path to the same page.
const NAV_ITEMS = [
  { href: "/konto/bestellungen", label: "Bestellungen" },
  { href: "/konto/profil", label: "Profil" },
] as const;

export function AccountNav() {
  const pathname = usePathname();
  const router = useRouter();

  // Same sequence as the old LogoutButton (now folded in here, its one
  // call site): clear the local cart (already mirrored server-side by
  // CartSync, so safe to drop — the next login's mergeServerCartIntoLocal()
  // restores it), tell already-mounted Client Components (Navbar's
  // AccountLink) the auth state changed, leave the account area, then
  // force a fresh Server Component render.
  async function handleLogout() {
    await fetch("/api/account/logout", { method: "POST" });
    clearCart();
    dispatchAuthChanged();
    router.push("/");
    router.refresh();
  }

  return (
    <>
      {/* Desktop/tablet — sidebar, sm+ (640px). Sits to the left of the
          page content inside KontoShell's flex row. */}
      <nav className="hidden sm:flex sm:flex-col sm:w-48 shrink-0 gap-1">
        <p className="text-label font-bold text-text-muted uppercase tracking-wide px-3 pb-2">Mein Konto</p>
        {NAV_ITEMS.map((item) => (
          <Link
            key={item.href}
            href={item.href}
            className={`px-3 py-2 rounded-sm text-body-sm font-semibold transition-colors ${
              pathname.startsWith(item.href) ? "bg-bg-muted text-text-primary" : "text-text-muted hover:text-text-primary"
            }`}
          >
            {item.label}
          </Link>
        ))}
        <button
          type="button"
          onClick={handleLogout}
          className="mt-4 px-3 py-2 text-left rounded-sm text-body-sm font-semibold text-red-600 hover:bg-red-50 transition-colors"
        >
          Abmelden
        </button>
      </nav>

      {/* Mobile — horizontal tab bar, below sm. overflow-x-auto rather
          than wrapping: 3 items at once already fits most phones, and a
          scrollable single row reads clearly as "more tabs this way"
          rather than a wrapped second line competing for attention with
          the page content right below it. */}
      <nav className="sm:hidden flex items-center gap-2 overflow-x-auto pb-1 -mx-[var(--layout-padding-x)] px-[var(--layout-padding-x)]">
        {NAV_ITEMS.map((item) => (
          <Link
            key={item.href}
            href={item.href}
            className={`shrink-0 px-4 py-2 rounded-full text-body-sm font-bold whitespace-nowrap transition-colors ${
              pathname.startsWith(item.href) ? "bg-brand text-text-primary" : "text-text-muted"
            }`}
          >
            {item.label}
          </Link>
        ))}
        <button
          type="button"
          onClick={handleLogout}
          className="shrink-0 px-4 py-2 rounded-full text-body-sm font-bold whitespace-nowrap text-red-600"
        >
          Abmelden
        </button>
      </nav>
    </>
  );
}
