import { useState, useEffect } from '@wordpress/element';
import * as React from 'react';

/**
 * ProRank Toggle Slider — emits canonical .prorank-toggle markup.
 * See styles/components/_toggle.css for the design system.
 *
 * Legacy size names ('small' | 'medium') map to canonical sizes ('sm' | 'md').
 */

interface ProrankToggleSliderProps {
  checked?: boolean;
  onChange?: (checked: boolean) => void;
  disabled?: boolean;
  className?: string;
  size?: 'small' | 'medium' | 'sm' | 'md' | 'lg';
}

const SIZE_MAP: Record<string, 'sm' | 'md' | 'lg'> = {
  small: 'sm',
  sm: 'sm',
  medium: 'md',
  md: 'md',
  lg: 'lg',
};

const ProrankToggleSlider: React.FC<ProrankToggleSliderProps> = ({
  checked = false,
  onChange,
  disabled = false,
  className = '',
  size = 'medium',
}) => {
  const [isChecked, setIsChecked] = useState(checked);

  useEffect(() => {
    setIsChecked(checked);
  }, [checked]);

  const handleToggle = () => {
    if (!disabled) {
      const newValue = !isChecked;
      setIsChecked(newValue);
      onChange?.(newValue);
    }
  };

  const canonicalSize = SIZE_MAP[size] || 'md';

  const classes = [
    'prorank-toggle',
    `prorank-toggle--${canonicalSize}`,
    isChecked ? 'prorank-toggle--checked' : '',
    disabled ? 'prorank-toggle--disabled' : '',
    className,
  ]
    .filter(Boolean)
    .join(' ');

  return (
    <button
      type="button"
      role="switch"
      aria-checked={isChecked}
      className={classes}
      onClick={handleToggle}
      disabled={disabled}
    >
      <span className="prorank-toggle__track" />
      <span className="prorank-toggle__thumb" />
    </button>
  );
};

export default ProrankToggleSlider;
