/**
 * Reusable toggle switch — accessible checkbox styled as a sliding toggle.
 */

import { useId } from "react";
import styles from "./ToggleSwitch.module.css";

export interface ToggleSwitchProps {
  checked: boolean;
  onChange: (checked: boolean) => void;
  label: string;
  disabled?: boolean;
  id?: string;
}

export function ToggleSwitch({
  checked,
  onChange,
  label,
  disabled = false,
  id,
}: ToggleSwitchProps) {
  const autoId = useId();
  const inputId = id ?? autoId;

  return (
    <label className={styles.wrapper} htmlFor={inputId} data-disabled={disabled || undefined}>
      <span className={styles.label}>{label}</span>
      <span className={styles.track} data-checked={checked || undefined}>
        <input
          id={inputId}
          type="checkbox"
          role="switch"
          className={styles.input}
          checked={checked}
          disabled={disabled}
          aria-label={label}
          onChange={(e) => onChange(e.target.checked)}
        />
        <span className={styles.thumb} />
      </span>
    </label>
  );
}
