/**
 * Switch — 开关切换
 * @prop {'brand'|'black'} [variant='brand'] — 变体样式
 * @prop {'sm'|'md'} [size='md'] — 尺寸，`sm` 高度固定 16px，`md` 为默认 24px
 * @prop {boolean} checked — 是否开启（受控，无默认）
 * @prop {boolean} [defaultChecked=false] — 非受控初始开启
 * @prop {function} [onChange=null] — 状态切换回调
 * @prop {boolean} [disabled=false] — 是否禁用
 * @prop {string} [className=''] — 根节点类名
 */

import { useState, useCallback } from 'react';

/* ── 按钮根节点（可聚焦、可键盘操作） ── */
const BASE = [
  'group inline-flex items-center justify-center shrink-0',
  'rounded-full border-none p-0 m-0',
  'bg-transparent cursor-pointer',
  'transition-colors tfds-motion-ui-normal',
  '[outline:2px_solid_transparent] outline-offset-2',
  'disabled:opacity-50 disabled:cursor-not-allowed disabled:pointer-events-none',
].join(' ');

/* ── 轨道：关闭态（两 variant 共用） ── */
const TRACK_OFF = [
  'bg-fill',
  'group-hover:bg-blueGrey-300',
].join(' ');

/* ── 轨道：开启态 ── */
const TRACK_ON = {
  brand: [
    'bg-brand-500',
    'group-hover:bg-brand-600',
  ].join(' '),
  black: [
    'bg-grey-950',
    'group-hover:bg-grey-900',
  ].join(' '),
};

const FOCUS_CLASS = {
  brand: 'focus-visible:outline-brand-200',
  black: 'focus-visible:outline-grey-400',
};

/* ── 尺寸：SM 以 MD 高度等比缩小到 16px，使用整数/半像素保证视觉稳定 ── */
const SIZE_CLASS = {
  sm: {
    track: 'w-[30px] h-[16px] p-[1.5px]',
    thumb: 'size-[13px]',
    thumbOn: 'translate-x-[14px]',
  },
  md: {
    track: 'w-[44px] h-[24px] p-[2px]',
    thumb: 'size-[20px]',
    thumbOn: 'translate-x-[20px]',
  },
};

const THUMB_BASE = [
  'block rounded-full bg-white',
  'shadow-[0_1px_2px_rgba(16,24,40,0.08)]',
  'transition-transform tfds-motion-ui-normal',
  'pointer-events-none',
].join(' ');

export default function Switch({
  variant = 'brand',
  size = 'md',
  checked,
  defaultChecked = false,
  onChange,
  disabled = false,
  className = '',
  ...rest
}) {
  const isControlled = checked !== undefined;
  const [innerChecked, setInnerChecked] = useState(defaultChecked);
  const isOn = isControlled ? Boolean(checked) : innerChecked;

  const sz = SIZE_CLASS[size] || SIZE_CLASS.md;

  const setNext = useCallback((next, e) => {
    if (!isControlled) setInnerChecked(next);
    onChange?.(next, e);
  }, [isControlled, onChange]);

  const toggle = useCallback((e) => {
    if (disabled) return;
    setNext(!isOn, e);
  }, [disabled, isOn, setNext]);

  const onKeyDown = useCallback((e) => {
    if (disabled) return;
    if (e.key === ' ' || e.key === 'Enter') {
      e.preventDefault();
      setNext(!isOn, e);
    }
  }, [disabled, isOn, setNext]);

  const trackCls = [
    'flex items-center rounded-full',
    sz.track,
    isOn ? TRACK_ON[variant] : TRACK_OFF,
  ].join(' ');

  const thumbCls = [
    THUMB_BASE,
    sz.thumb,
    isOn ? sz.thumbOn : 'translate-x-0',
  ].join(' ');

  const rootCls = [BASE, FOCUS_CLASS[variant], className].filter(Boolean).join(' ');

  return (
    <button
      type="button"
      role="switch"
      aria-checked={isOn}
      disabled={disabled}
      className={[`tfds-switch`, rootCls].filter(Boolean).join(' ')}
      onClick={toggle}
      onKeyDown={onKeyDown}
      {...rest}
     data-tfds-component="Switch">
      <span className={trackCls} aria-hidden>
        <span className={thumbCls} />
      </span>
    </button>
  );
}
