'use client';

import * as React from 'react';
import * as SwitchPrimitive from '@radix-ui/react-switch';

import { cn } from '../../shared/utils';

/**
 * Immediate binary state toggle (On/Off).
 *
 * @description
 * Differs from `<Checkbox>` in that it implies an immediate setting change
 * without requiring form submission (e.g., enabling/disabling a feature).
 * Supports the standard size scale (`sm`, `md`, `lg`).
 *
 * @ai-rules
 * 1. Always pair with a sibling `<Label>` component linked via `id` and `htmlFor`.
 * 2. Use `checked`/`onCheckedChange` (not `value`/`onChange`) to control state.
 * 3. Use the `size` prop to match surrounding form element sizing.
 */
const Switch = React.forwardRef<
  React.ElementRef<typeof SwitchPrimitive.Root>,
  React.ComponentPropsWithoutRef<typeof SwitchPrimitive.Root> & {
    /**
     * Size variant — matches the form component sizing scale.
     * - `sm`: 28×14px track, 12px thumb
     * - `md`: 32×18px track, 16px thumb — **default**
     * - `lg`: 40×22px track, 20px thumb
     */
    size?: 'sm' | 'md' | 'lg';
  }
>(({ className, size = 'md', ...props }, ref) => {
  const trackClasses = {
    sm: 'h-3.5 w-7',
    md: 'h-[1.15rem] w-8',
    lg: 'h-[1.375rem] w-10',
  };
  const thumbClasses = {
    sm: 'size-3',
    md: 'size-4',
    lg: 'size-5',
  };

  return (
    <SwitchPrimitive.Root
      className={cn(
        'peer inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none disabled:cursor-not-allowed disabled:opacity-50',
        'data-[state=checked]:bg-button-primary',
        'data-[state=unchecked]:bg-muted',
        'focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]',
        trackClasses[size],
        className
      )}
      {...props}
      ref={ref}
    >
      <SwitchPrimitive.Thumb
        className={cn(
          'pointer-events-none block rounded-full ring-0 transition-transform shadow-sm',
          'bg-background',
          'data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0',
          thumbClasses[size]
        )}
      />
    </SwitchPrimitive.Root>
  );
});
Switch.displayName = SwitchPrimitive.Root.displayName;

export { Switch };
