'use client'

import { type ReactNode } from 'react'
import { cn } from '@/lib/utils'

/**
 * Forge Switch — implements DESIGN.md §4.Switch
 *
 * Tones
 *  - success (default) — green when "enabled/connected"
 *  - primary           — indigo when "selected mode"
 *
 * Sizes
 *  - sm : 32x18 track, 14 knob
 *  - md : 40x22 track, 18 knob (default)
 */

export type SwitchTone = 'success' | 'primary'
export type SwitchSize = 'sm' | 'md'

export interface SwitchProps {
  checked: boolean
  onChange: (next: boolean) => void
  disabled?: boolean
  tone?: SwitchTone
  size?: SwitchSize
  /** Optional label rendered to the left of the switch. */
  label?: ReactNode
  /** Optional helper rendered under the label. */
  helper?: ReactNode
  /** Reverse the layout: switch on the right side. */
  align?: 'left' | 'right'
  className?: string
  'aria-label'?: string
  /** Native title tooltip (e.g. used to explain why the switch is disabled). */
  title?: string
}

export function Switch({
  checked,
  onChange,
  disabled = false,
  tone = 'success',
  size = 'md',
  label,
  helper,
  align = 'right',
  className,
  'aria-label': ariaLabel,
  title,
}: SwitchProps) {
  const trackSize = size === 'sm' ? 'w-8 h-[18px]' : 'w-10 h-[22px]'
  const knobSize = size === 'sm' ? 'w-[14px] h-[14px]' : 'w-[18px] h-[18px]'
  const knobTranslate = size === 'sm' ? 'translate-x-[14px]' : 'translate-x-[18px]'
  const onBg = tone === 'primary' ? 'bg-brand-primary' : 'bg-green'

  const switchEl = (
    <button
      type="button"
      role="switch"
      aria-checked={checked}
      aria-label={ariaLabel}
      title={title}
      disabled={disabled}
      onClick={() => onChange(!checked)}
      className={cn(
        'rounded-full p-0.5 transition-colors cursor-pointer shrink-0',
        'focus:outline-none focus-visible:shadow-focus-ring',
        'disabled:opacity-50 disabled:cursor-not-allowed',
        trackSize,
        checked ? onBg : 'bg-surface-4',
      )}
    >
      <div
        className={cn(
          'rounded-full bg-white shadow-sm transition-transform duration-200',
          knobSize,
          checked ? knobTranslate : 'translate-x-0',
        )}
      />
    </button>
  )

  if (!label && !helper) {
    return <span className={className}>{switchEl}</span>
  }

  return (
    <label
      className={cn(
        'flex items-center justify-between gap-3 select-none',
        align === 'left' && 'flex-row-reverse justify-end',
        className,
      )}
    >
      <span className="min-w-0">
        {label && <span className="block text-[13px] font-medium text-ink">{label}</span>}
        {helper && <span className="block text-[11px] text-ink-muted mt-0.5">{helper}</span>}
      </span>
      {switchEl}
    </label>
  )
}
