// @design-system: layout/Tabs
/**
 * Tabs - Radix UI Tabs wrapper with Multideal styling.
 *
 * Active tab is indicated by a bottom border in the brand color (customer)
 * or vendor accent (vendor mode).
 *
 * @example
 * <Tabs
 *   items={[
 *     { value: 'for-you', label: t('for_you'), count: 12 },
 *     { value: 'hot', label: t('hot'), count: 5, warnAt: 3, dangerAt: 10 },
 *     { value: 'closed', label: t('closed'), tooltip: t('closed_hint') },
 *   ]}
 *   defaultValue="for-you"
 *   mode="customer"
 * />
 */

import * as RadixTabs from '@radix-ui/react-tabs';
import { cn } from '@/lib/cn';
import { useLocale, useT } from '@/lib/i18n/react';
import { dirForLocale } from '@/lib/i18n';
import { tabBadgeTone, tabBadgeToneClasses } from '@/lib/ui/tab-badge-tone';

export interface TabItem {
  value: string;
  label: string;
  /** Optional badge count rendered beside the label. */
  count?: number;
  /** With `count`, count above this uses warning tone (strict `>`). */
  warnAt?: number;
  /** With `count`, count above this uses danger tone (strict `>`). */
  dangerAt?: number;
  /** Native tooltip (`title`) on the tab trigger. */
  tooltip?: string;
  /** When true, renders a stale/attention dot after the label. */
  indicator?: boolean;
  /** Per-tab accessible name when richer than visible label. */
  ariaLabel?: string;
  /** Disables this tab trigger. */
  disabled?: boolean;
  /** `data-testid` on the tab trigger. */
  testId?: string;
}

export interface TabsProps {
  items: TabItem[];
  defaultValue?: string;
  value?: string;
  onValueChange?: (value: string) => void;
  mode?: 'customer' | 'vendor';
  /** Content to render inside each panel. Keyed by tab value. */
  panels?: Record<string, React.ReactNode>;
  className?: string;
  /** Optional className on the tab list element. */
  listClassName?: string;
  /** Optional className on each tab panel (`Tabs.Content`). */
  panelClassName?: string;
  /** Accessible label for the tab list. Defaults to i18n a11y.tabs_label. */
  ariaLabel?: string;
}

function hasBadgeToneThresholds(item: TabItem): boolean {
  return item.count !== undefined && (item.warnAt !== undefined || item.dangerAt !== undefined);
}

function badgeToneForItem(item: TabItem) {
  const warnAt = item.warnAt ?? 0;
  const dangerAt = item.dangerAt ?? warnAt;
  return tabBadgeTone(item.count!, warnAt, dangerAt);
}

export function Tabs({
  items,
  defaultValue,
  value,
  onValueChange,
  mode = 'customer',
  panels,
  className,
  listClassName,
  panelClassName,
  ariaLabel,
}: TabsProps) {
  const isVendor = mode === 'vendor';
  const { locale } = useLocale();
  const dir = dirForLocale(locale);
  const t = useT('a11y');

  return (
    <RadixTabs.Root
      defaultValue={defaultValue ?? items[0]?.value}
      value={value}
      onValueChange={onValueChange}
      dir={dir}
      className={cn('flex flex-col', className)}
    >
      <RadixTabs.List
        className={cn(
          'border-border-default flex items-end border-b',
          'bg-surface-base',
          'scrollbar-none overflow-x-auto',
          listClassName,
        )}
        aria-label={ariaLabel ?? t('tabs_label')}
      >
        {items.map((item) => (
          <RadixTabs.Trigger
            key={item.value}
            value={item.value}
            disabled={item.disabled}
            title={item.tooltip}
            aria-label={item.ariaLabel}
            data-testid={item.testId}
            className={cn(
              'group relative z-0 flex min-h-[var(--touch-target-min)] shrink-0 items-center gap-1.5',
              'px-4 py-3',
              'text-sm font-medium',
              'text-text-muted',
              'transition-colors duration-[var(--duration-fast)] ease-[var(--ease-out)]',
              'hover:text-text-primary',
              'data-[state=active]:text-text-primary',
              'focus-visible:z-[var(--z-raised)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-[-2px]',
              // Active indicator - pseudo-element via after: utility
              'after:absolute after:inset-x-0 after:bottom-0 after:h-(--size-hairline-indicator) after:rounded-t-sm',
              'after:scale-x-0 after:transition-transform after:duration-[var(--duration-fast)]',
              isVendor
                ? 'data-[state=active]:after:bg-mode-vendor-600 data-[state=active]:after:scale-x-100'
                : 'data-[state=active]:after:bg-brand-primary-600 data-[state=active]:after:scale-x-100',
              item.disabled && 'pointer-events-none opacity-50',
            )}
          >
            <span>{item.label}</span>
            {item.indicator && (
              <span className="text-warning-600 ms-1" aria-hidden="true">
                ●
              </span>
            )}
            {item.count !== undefined && (
              <span
                className={cn(
                  'inline-flex items-center justify-center',
                  'min-w-[var(--spacing-5)] rounded-full px-1.5',
                  'text-xs font-bold',
                  hasBadgeToneThresholds(item)
                    ? tabBadgeToneClasses[badgeToneForItem(item)]
                    : cn(
                        'text-text-muted bg-neutral-100',
                        isVendor
                          ? 'group-data-[state=active]:bg-mode-vendor-100 group-data-[state=active]:text-mode-vendor-700'
                          : 'group-data-[state=active]:bg-brand-primary-100 group-data-[state=active]:text-brand-primary-700',
                      ),
                )}
              >
                {item.count}
              </span>
            )}
          </RadixTabs.Trigger>
        ))}
      </RadixTabs.List>

      {panels &&
        items.map((item) => (
          <RadixTabs.Content key={item.value} value={item.value} className={panelClassName}>
            {panels[item.value]}
          </RadixTabs.Content>
        ))}
    </RadixTabs.Root>
  );
}
