// @design-system: layout/HamburgerDrawer
'use client';

/**
 * HamburgerDrawer - mobile slide-out navigation drawer.
 *
 * Triggered by a hamburger button placed in TopBar's startSlot.
 * Contains all customer nav links + auth-aware items (login/logout,
 * vendor dashboard, admin link).
 *
 * Desktop: hidden (lg:hidden on the trigger).
 * Mobile: slides in from the logical-start side (right in RTL Hebrew).
 */

import { useState, useSyncExternalStore, useRef } from 'react';
import { createPortal } from 'react-dom';
import { cn } from '@/lib/cn';
import { formatPhoneHintLabel } from '@/lib/phone.js';
import { useT } from '@/lib/i18n/react';
import { Button } from '@/components/ui/primitives/Button';
import { Icon } from '@/components/ui/icons/Icon';
import { LogoutButton } from '@/components/ui/primitives/LogoutButton';
import { MDLogo } from '@/components/ui/icons/MDLogo';
import { Drawer, DrawerContent, DrawerTitle } from '@/components/ui/overlays/Drawer';
import { LanguageToggle } from '@/components/ui/i18n/LanguageToggle';
import { useBrowserBody } from '@/lib/hooks/useHydrated';

export interface HamburgerDrawerProps {
  /** True when no session exists — shows Login, hides Logout/profile. */
  isGuest: boolean;
  /** True when user has an active vendor account. */
  isVendor?: boolean;
  /** True = show affiliate dashboard section. */
  isAffiliate?: boolean;
  /** True when user has admin privileges. */
  isAdmin?: boolean;
  /** Current page path for active link highlighting. */
  currentPath?: string;
  /** User display name — shown next to Menu icon when logged in. */
  displayName?: string;
  /** Last 3 digits of phone — fallback label when no displayName. */
  phoneHint?: string;
}

// ─── Nav link ─────────────────────────────────────────────────────────────────

interface NavLinkProps {
  href: string;
  active?: boolean;
  children: React.ReactNode;
  iconName?: React.ComponentProps<typeof Icon>['name'];
  reloadPage?: boolean;
}

function NavLink({ href, active, children, iconName, reloadPage }: NavLinkProps) {
  return (
    <a
      href={href}
      data-astro-reload={reloadPage || undefined}
      className={cn(
        'flex h-10 items-center gap-2 rounded-md px-3',
        'text-sm font-medium no-underline',
        'text-text-primary transition-colors',
        active ? 'bg-brand-primary-100' : 'hover:bg-surface-hover',
        'focus-visible:outline-brand-primary-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2',
      )}
      aria-current={active ? 'page' : undefined}
    >
      {iconName && <Icon name={iconName} size="sm" aria-hidden />}
      {children}
    </a>
  );
}

// ─── Section heading ──────────────────────────────────────────────────────────

function SectionHeading({ children }: { children: React.ReactNode }) {
  return (
    <p className="text-text-secondary px-3 pt-2 pb-1 text-xs font-semibold tracking-wider uppercase">
      {children}
    </p>
  );
}

// ─── Separator ────────────────────────────────────────────────────────────────

function Separator() {
  return <hr className="border-border my-2 border-t" />;
}

// ─── HamburgerDrawer ──────────────────────────────────────────────────────────

export function HamburgerDrawer({
  isGuest,
  isVendor = false,
  isAffiliate = false,
  isAdmin = false,
  currentPath = '/',
  displayName,
  phoneHint,
}: HamburgerDrawerProps) {
  const tNav = useT('nav');
  const tCommon = useT('common');
  const [open, setOpen] = useState(false);
  const burgerRef = useRef<HTMLButtonElement>(null);
  // useSyncExternalStore: server snapshot=false, client snapshot=true — avoids useEffect+setState cascade
  const mounted = useSyncExternalStore(
    () => () => {},
    () => true,
    () => false,
  );
  const portalTarget = useBrowserBody();

  // User label: displayName if set; else masked phone (05*-***-* + last 3); else nothing.
  const userLabel =
    !isGuest && (displayName || phoneHint)
      ? displayName || (phoneHint ? formatPhoneHintLabel(phoneHint) : '')
      : undefined;

  return (
    <Drawer open={open} onOpenChange={setOpen} side="start">
      {/* Inline burger lives in TopBar startSlot — flex-centers with CartNavButton in endSlot.
          Hidden on lg+ where DesktopTopBar takes over. */}
      <Button
        ref={burgerRef}
        variant="ghost"
        size="sm"
        className="lg:hidden"
        data-hamburger-toggle="true"
        aria-label={tNav('menu_open')}
        aria-expanded={open}
        aria-controls="hamburger-drawer-content"
        onClick={() => setOpen((o) => !o)}
      >
        <Icon name="Menu" size="md" aria-hidden />
        {userLabel && (
          <span
            className="text-text-primary max-w-28 truncate text-sm font-medium"
            aria-hidden="true"
          >
            {userLabel}
          </span>
        )}
      </Button>

      {/* Close (X) button portaled to document.body — escapes TopBar stacking context (z-sticky=1100)
          so it floats above the drawer overlay (z-overlay=1200) and panel (z-modal=1300).
          Only mounted while the drawer is open, so the closed state keeps the inline burger
          horizontally aligned with the cart icon on the opposite edge. */}
      {mounted &&
        portalTarget &&
        open &&
        createPortal(
          <button
            type="button"
            data-hamburger-toggle="true"
            style={{
              position: 'fixed',
              insetBlockStart: 'calc(var(--safe-area-top, 0rem) + var(--spacing-3))',
              insetInlineStart: 'calc(var(--safe-area-start, 0rem) + var(--spacing-3))',
              zIndex: 'calc(var(--z-modal) + 2)',
              // Radix Dialog modal sets body { pointer-events: none } while open.
              pointerEvents: 'auto',
            }}
            className="text-text-primary hover:bg-surface-hover focus-visible:outline-brand-primary-600 inline-flex h-9 w-9 items-center justify-center rounded-md focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2"
            aria-label={tNav('menu_close')}
            aria-controls="hamburger-drawer-content"
            onClick={() => setOpen(false)}
          >
            <Icon name="X" size="md" aria-hidden />
          </button>,
          portalTarget,
        )}

      <DrawerContent
        id="hamburger-drawer-content"
        side="start"
        onPointerDownOutside={(e) => {
          // Prevent Radix auto-dismiss when clicking either the inline burger (start slot)
          // or the portaled X button — both are outside the dialog DOM so Radix would treat
          // them as outside clicks and race with their own onClick handlers.
          const target = (e as CustomEvent<{ originalEvent: PointerEvent }>).detail.originalEvent
            .target as Element | null;
          if (target?.closest?.('[data-hamburger-toggle="true"]')) {
            e.preventDefault();
          }
        }}
        className={cn(
          'text-text-primary flex w-[52vw] flex-col border-none bg-[var(--color-surface-app)] ease-in-out',
          'pt-[var(--safe-area-top)]',
          'pb-[var(--safe-area-bottom)]',
          'ps-[var(--safe-area-start)]',
          'pe-[var(--safe-area-end)]',
        )}
        aria-label={tNav('menu_title')}
      >
        {/* Header — logo only. ps-12 clears the floating burger X on the start side. */}
        <div className="flex items-center px-4 ps-12 pt-2 pb-4">
          <a
            href="/"
            className="focus-visible:outline-brand-primary-600 flex items-center gap-2 rounded-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2"
            tabIndex={0}
          >
            <MDLogo size={32} />
            <span className="text-text-primary text-lg font-bold">{tCommon('app_name')}</span>
          </a>
        </div>

        {/* Visually hidden title for screen readers */}
        <DrawerTitle className="sr-only">{tNav('menu_title')}</DrawerTitle>

        {/* ── Nav content ── */}
        <nav
          aria-label={tNav('menu_title')}
          className="flex flex-1 flex-col gap-1 overflow-y-auto px-3 pb-6"
        >
          {/* Customer nav */}
          <NavLink href="/" active={currentPath === '/'} iconName="ShoppingBag">
            {tNav('home')}
          </NavLink>
          <NavLink href="/search" active={currentPath === '/search'} iconName="Search">
            {tNav('search')}
          </NavLink>
          <NavLink href="/stores" active={currentPath === '/stores'} iconName="Store">
            {tNav('stores')}
          </NavLink>
          <NavLink href="/club" active={currentPath === '/club'} iconName="Star">
            {tNav('club')}
          </NavLink>

          {/* Authenticated-only: favorites, purchases, profile */}
          {!isGuest && (
            <>
              <NavLink href="/favorites" active={currentPath === '/favorites'} iconName="Heart">
                {tNav('favorites')}
              </NavLink>
              <NavLink
                href="/purchases"
                active={currentPath === '/purchases'}
                iconName="ShoppingBag"
              >
                {tNav('purchases')}
              </NavLink>
              <NavLink href="/profile" active={currentPath === '/profile'} iconName="User">
                {tNav('profile')}
              </NavLink>
              <NavLink href="/settings" active={currentPath === '/settings'} iconName="Settings">
                {tNav('settings')}
              </NavLink>
              <NavLink href="/wishlist" active={currentPath === '/wishlist'} iconName="Heart">
                {tNav('wishlist')}
              </NavLink>
              <NavLink href="/cases" active={currentPath?.startsWith('/cases')} iconName="FileText">
                {tNav('cases')}
              </NavLink>
              <NavLink href="/whats-left" active={currentPath === '/whats-left'} iconName="Clock">
                {tNav('whats_left')}
              </NavLink>
              <NavLink
                href="/threads"
                active={currentPath?.startsWith('/threads')}
                iconName="MessageCircle"
              >
                {tNav('messages')}
              </NavLink>
              <NavLink
                href="/support/tickets"
                active={currentPath?.startsWith('/support/tickets')}
                iconName="Headphones"
              >
                {tNav('support_center')}
              </NavLink>
            </>
          )}

          {/* ── Vendor section ── */}
          {isVendor && (
            <>
              <Separator />
              <SectionHeading>{tNav('vendor_dashboard')}</SectionHeading>
              <NavLink href="/vendor" active={currentPath?.startsWith('/vendor')} iconName="Store">
                {tNav('vendor_dashboard')}
              </NavLink>
            </>
          )}

          {/* ── Affiliate section ── */}
          {isAffiliate && !isAdmin && (
            <>
              <Separator />
              <SectionHeading>{tNav('affiliate_dashboard')}</SectionHeading>
              <NavLink
                href="/affiliate"
                active={currentPath?.startsWith('/affiliate')}
                iconName="Users"
              >
                {tNav('affiliate_dashboard')}
              </NavLink>
            </>
          )}

          {/* ── Admin section ── */}
          {isAdmin && (
            <>
              <Separator />
              <SectionHeading>{tNav('admin')}</SectionHeading>
              <NavLink
                href="/admin"
                active={currentPath?.startsWith('/admin')}
                iconName="Settings"
                reloadPage
              >
                {tNav('admin')}
              </NavLink>
            </>
          )}

          {/* ── Auth section ── */}
          <Separator />
          {isGuest ? (
            <NavLink
              href={
                currentPath && currentPath !== '/login'
                  ? `/login?redirect=${encodeURIComponent(currentPath)}`
                  : '/login'
              }
              active={currentPath === '/login'}
              iconName="User"
            >
              {tCommon('login')}
            </NavLink>
          ) : (
            <div className="px-0">
              <LogoutButton variant="ghost" className="w-full justify-start" />
            </div>
          )}
        </nav>

        {/* ── Language toggle ── */}
        <div className="border-border flex justify-center border-t px-4 py-3">
          <LanguageToggle />
        </div>
      </DrawerContent>
    </Drawer>
  );
}
