// @design-system: layout/VendorShell
/**
 * VendorShell - layout shell for vendor screens.
 *
 * variant="centered" — full-screen centered layout (registration, welcome, pending,
 *   rejected, frozen, banned screens). Equivalent to the former VendorCenteredShell.
 *
 * variant="dashboard" — full vendor console layout:
 *   ≥1024px: sidebar (left/right per dir) + topbar + scrollable main content.
 *   <1024px: topbar + scrollable main content + bottom-nav (fixed).
 *
 * Auth gate: dashboard variant shows children only (caller is responsible for
 * server-side auth redirect). Shell itself is layout-only, no auth logic.
 *
 * @example
 * ```tsx
 * <VendorShell variant="centered" textCenter>
 *   <main id="main" aria-labelledby="title">...</main>
 * </VendorShell>
 *
 * <VendorShell variant="dashboard" currentPath="/vendor/dashboard">
 *   <main id="main">...</main>
 * </VendorShell>
 * ```
 */

'use client';

import type { ReactNode } from 'react';
import { cn } from '@/lib/cn';
import { findVendorNavContext } from '@/lib/vendor-nav';
import { pickLocalized } from '@/lib/i18n';
import { useLocale, useT } from '@/lib/i18n/react';
import { VendorSidebar } from '@/features/vendor-navigation/VendorSidebar';
import { VendorBottomNav } from '@/components/ui/layout/VendorBottomNav';
import {
  PublicChromeInner,
  usePublicCommandPalette,
} from '@/components/ui/layout/PublicChromeIsland/PublicChromeIsland';
import { VendorModeToggle } from '@/features/vendor-mode-toggle';

export interface VendorShellProps {
  /** Layout variant. Default: 'centered'. */
  variant?: 'centered' | 'dashboard';
  /** Page content - typically a <main> element with id="main". */
  children: ReactNode;
  /** Centers text inside the shell (centered variant). Default: false. */
  textCenter?: boolean;
  /** Extra Tailwind classes to pass through. */
  className?: string;
  /**
   * Render site navbar above centered content. Use on dashboard-context screens
   * (pending, rejected, frozen, banned, welcome). Do NOT set on onboarding/registration screens.
   */
  showTopbar?: boolean;
  // ─── Dashboard variant props / centered + showTopbar props ───────────────
  /** Current pathname — used by sidebar + bottom-nav for active highlighting. */
  currentPath?: string;
  /** Render dashboard chrome without loading vendor-specific data. */
  demo?: boolean;
  /**
   * Override the page h1 title (dashboard variant).
   * When omitted, title is derived from vendor-nav via currentPath.
   * Use for dynamic titles: entity names, create/edit context, etc.
   */
  pageTitle?: string;
}

/**
 * VendorShell
 *
 * Tokens used: `--color-surface-base`, `--color-surface-raised`, `--color-border`.
 *
 * centered variant: `bg-surface-base flex min-h-dvh flex-col items-center justify-center`
 * dashboard variant: sidebar + topbar + main + bottom-nav composition.
 */
export function VendorShell({
  variant = 'centered',
  children,
  textCenter = false,
  className,
  showTopbar = false,
  currentPath = '/',
  demo = false,
  pageTitle,
}: VendorShellProps) {
  const { commandPaletteOpen, onCommandPaletteOpenChange, onCommandPaletteOpen } =
    usePublicCommandPalette();
  const { locale } = useLocale();
  const t = useT('vendor_sidebar');
  const navCtx = findVendorNavContext(currentPath);
  const tabs = navCtx?.page.tabs ?? [];

  const tab = navCtx?.tabPath ? navCtx.page.tabs.find((tb) => tb.path === navCtx.tabPath) : null;
  const derivedTitle = tab
    ? pickLocalized(tab, locale, 'title')
    : navCtx?.page
      ? pickLocalized(navCtx.page, locale, 'title')
      : null;
  const effectiveTitle = pageTitle ?? derivedTitle;

  if (variant === 'centered') {
    if (showTopbar) {
      return (
        <div className={cn('bg-surface-base flex min-h-dvh flex-col', className)}>
          <PublicChromeInner
            currentPath={currentPath}
            endExtra={<VendorModeToggle currentMode="vendor" />}
            commandPaletteOpen={commandPaletteOpen}
            onCommandPaletteOpenChange={onCommandPaletteOpenChange}
            onCommandPaletteOpen={onCommandPaletteOpen}
          />
          <div
            className={cn(
              'flex flex-1 flex-col items-center justify-center px-6 py-10',
              textCenter && 'text-center',
            )}
          >
            {children}
          </div>
        </div>
      );
    }
    return (
      <div
        className={cn(
          'bg-surface-base flex min-h-dvh flex-col items-center justify-center px-6 py-10',
          textCenter && 'text-center',
          className,
        )}
      >
        {children}
      </div>
    );
  }

  // variant === 'dashboard'
  return (
    <div className={cn('bg-surface-base flex min-h-dvh flex-col', className)}>
      {/* Full-width topbar spans above sidebar + content */}
      <PublicChromeInner
        currentPath={currentPath}
        endExtra={<VendorModeToggle currentMode="vendor" />}
        commandPaletteOpen={commandPaletteOpen}
        onCommandPaletteOpenChange={onCommandPaletteOpenChange}
        onCommandPaletteOpen={onCommandPaletteOpen}
      />

      {/* Body row: sidebar + content */}
      <div className="flex min-w-0 flex-1">
        {/* Desktop sidebar */}
        <VendorSidebar currentPath={currentPath} demo={demo} />

        {/* Page content */}
        <div className="min-w-0 flex-1 pb-[calc(var(--bottom-nav-height)+var(--safe-area-bottom))] lg:pb-0">
          {/* Tab strip — auto-rendered when active page has tabs */}
          {tabs.length > 0 && (
            <nav
              aria-label={t('tabs_aria')}
              className="border-b border-[var(--color-neutral-200)] bg-[var(--color-surface-base)] px-4"
            >
              <ul className="flex gap-0 overflow-x-auto">
                {tabs.map((tab) => {
                  const isTabActive = currentPath === tab.path;
                  const label = pickLocalized(tab, locale, 'title');
                  return (
                    <li key={tab.path}>
                      <a
                        href={tab.path}
                        aria-current={isTabActive ? 'page' : undefined}
                        className={cn(
                          'inline-flex items-center border-b-2 px-4 py-3 text-sm font-medium whitespace-nowrap transition-colors',
                          'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-[-2px]',
                          isTabActive
                            ? 'border-[var(--color-mode-vendor-600)] text-[var(--color-text-primary)]'
                            : 'border-transparent text-[var(--color-text-secondary)] hover:border-[var(--color-neutral-300)] hover:text-[var(--color-text-primary)]',
                        )}
                      >
                        {label}
                      </a>
                    </li>
                  );
                })}
              </ul>
            </nav>
          )}
          {effectiveTitle && (
            <h1 className="text-text-primary px-4 pt-4 pb-2 text-xl font-semibold lg:px-6">
              {effectiveTitle}
            </h1>
          )}
          {children}
        </div>
      </div>

      {/* Mobile bottom nav */}
      <VendorBottomNav currentPath={currentPath} demo={demo} />
    </div>
  );
}
