// @design-system: primitives/Select
// Registered at /design-system#select-primitive - Phase 3 (Agent 3E) will render the gallery.

import * as RadixSelect from '@radix-ui/react-select';
import type { ReactNode } from 'react';
import { cn } from '@/lib/cn';
import { useLocale } from '@/lib/i18n/react';
import { dirForLocale } from '@/lib/i18n';

// ─── Re-exports of Radix primitives with Multideal styling ────────────────────

/** Root select component - use to wrap trigger + content. */
export function Select({ dir: dirProp, ...props }: SelectRootProps) {
  const { locale } = useLocale();
  return <RadixSelect.Root dir={dirProp ?? dirForLocale(locale)} {...props} />;
}

/** Portal wrapper (auto-used by SelectContent). */
export const SelectPortal = RadixSelect.Portal;

/** Group component for grouping options. */
export const SelectGroup = RadixSelect.Group;

/** Value display inside trigger. */
export const SelectValue = RadixSelect.Value;

// ─── Trigger ──────────────────────────────────────────────────────────────

/** Props for SelectTrigger */
export interface SelectTriggerProps extends React.ComponentPropsWithoutRef<
  typeof RadixSelect.Trigger
> {
  placeholder?: string;
}

/**
 * Multideal-styled Select trigger button.
 *
 * @example
 * ```tsx
 * <SelectTrigger placeholder={t('select_category')} />
 * ```
 */
export function SelectTrigger({ className, children, ...props }: SelectTriggerProps) {
  return (
    <RadixSelect.Trigger
      className={cn(
        'flex w-full items-center justify-between',
        'border-border-default bg-surface-base rounded-md border',
        'py-2 ps-3 pe-3',
        'text-base text-neutral-900',
        'transition-colors',
        'focus-visible:border-brand-primary-500 focus-visible:ring-brand-primary-500/40 focus-visible:ring-2 focus-visible:outline-none',
        'disabled:cursor-not-allowed disabled:bg-neutral-100 disabled:text-neutral-400',
        'data-[placeholder]:text-neutral-500',
        className,
      )}
      {...props}
    >
      <span className="min-w-0 flex-1 truncate text-start">{children}</span>
      <RadixSelect.Icon className="shrink-0 text-neutral-500">
        <ChevronDownIcon />
      </RadixSelect.Icon>
    </RadixSelect.Trigger>
  );
}

// ─── Content ──────────────────────────────────────────────────────────────

/** Props for SelectContent */
export type SelectContentProps = React.ComponentPropsWithoutRef<typeof RadixSelect.Content>;

/**
 * Multideal-styled Select dropdown content.
 */
export function SelectContent({
  className,
  children,
  position = 'popper',
  align = 'start',
  side = 'bottom',
  sideOffset = 4,
  style,
  ...props
}: SelectContentProps) {
  return (
    <RadixSelect.Portal>
      <RadixSelect.Content
        position={position}
        align={align}
        side={side}
        sideOffset={sideOffset}
        style={style}
        className={cn(
          'z-popover relative max-h-64',
          'w-[var(--radix-select-trigger-width)]',
          'border-border-default bg-surface-base rounded-md border',
          'shadow-md',
          'overflow-hidden',
          'data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',
          'data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95',
          className,
        )}
        {...props}
      >
        <RadixSelect.ScrollUpButton className="flex cursor-default items-center justify-center py-1 text-neutral-500">
          <ChevronUpIcon />
        </RadixSelect.ScrollUpButton>
        <RadixSelect.Viewport className="p-1">{children}</RadixSelect.Viewport>
        <RadixSelect.ScrollDownButton className="flex cursor-default items-center justify-center py-1 text-neutral-500">
          <ChevronDownIcon />
        </RadixSelect.ScrollDownButton>
      </RadixSelect.Content>
    </RadixSelect.Portal>
  );
}

// ─── Item ──────────────────────────────────────────────────────────────────

/** Props for SelectItem */
export type SelectItemProps = React.ComponentPropsWithoutRef<typeof RadixSelect.Item>;

/**
 * A single option inside SelectContent.
 */
export function SelectItem({ className, children, ...props }: SelectItemProps) {
  return (
    <RadixSelect.Item
      className={cn(
        'relative flex w-full cursor-pointer items-center select-none',
        'rounded-sm py-2 ps-8 pe-3',
        'text-sm text-neutral-900',
        'outline-none',
        'focus:bg-brand-primary-50 focus:text-brand-primary-900',
        'focus-visible:ring-brand-primary-500 focus-visible:ring-2 focus-visible:ring-inset',
        'data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
        className,
      )}
      {...props}
    >
      <span className="absolute start-2 flex items-center justify-center">
        <RadixSelect.ItemIndicator>
          <CheckIcon />
        </RadixSelect.ItemIndicator>
      </span>
      <RadixSelect.ItemText>{children}</RadixSelect.ItemText>
    </RadixSelect.Item>
  );
}

/** Props for SelectLabel */
export type SelectLabelProps = React.ComponentPropsWithoutRef<typeof RadixSelect.Label>;

/** Label for a select group. */
export function SelectLabel({ className, ...props }: SelectLabelProps) {
  return (
    <RadixSelect.Label
      className={cn('py-1.5 ps-8 pe-2 text-xs font-medium text-neutral-500', className)}
      {...props}
    />
  );
}

/** Separator between select groups. */
export function SelectSeparator({
  className,
  ...props
}: React.ComponentPropsWithoutRef<typeof RadixSelect.Separator>) {
  return <RadixSelect.Separator className={cn('my-1 h-px bg-neutral-200', className)} {...props} />;
}

// ─── Inline icons (no dependency on Icon component to avoid circular deps) ─

function ChevronUpIcon() {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      aria-hidden="true"
    >
      <path d="m18 15-6-6-6 6" />
    </svg>
  );
}

function ChevronDownIcon() {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      aria-hidden="true"
    >
      <path d="m6 9 6 6 6-6" />
    </svg>
  );
}

function CheckIcon() {
  return (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2.5"
      aria-hidden="true"
    >
      <polyline points="20 6 9 17 4 12" />
    </svg>
  );
}

/** All Radix Select props re-exported for convenience */
export type SelectRootProps = React.ComponentPropsWithoutRef<typeof RadixSelect.Root>;
export type SelectValueProps = React.ComponentPropsWithoutRef<typeof RadixSelect.Value>;

/** Convenience type for grouped items data */
export interface SelectOptionData {
  value: string;
  label: ReactNode;
  disabled?: boolean;
}
