---
import type { HTMLAttributes } from 'astro/types'
import IconCheck from '../icons/default/IconCheck.astro'
import IconX from '../icons/default/IconX.astro'
import '../../dist/components/Switch/styles.css'

export type SwitchTextDirection = 'left' | 'right'

/**
 * Differences from React: the native checkbox is uncontrolled, so there is no
 * `checked`/`defaultChecked` pair: `checked` is the initial state. No
 * `onChange`: listen to the input's native `change` event (it bubbles to the
 * root `<label>`) and read `event.target.checked`. `id`, `name`, `value` and
 * `aria-label` go to the input; every other attribute (`class`, `data-*`…)
 * goes to the root.
 */
export type Props = Omit<HTMLAttributes<'label'>, 'aria-label'> & {
  /** Texto do switch (Show Text / Edit Text no Figma). Sem `label`, passe `aria-label`. */
  label?: string
  /** Texto de apoio abaixo do label, em até duas linhas (Description no Figma). */
  description?: string
  /** Lado do texto em relação ao switch (Text Direction no Figma). */
  textDirection?: SwitchTextDirection
  /** Ocupa a largura do container: o texto cresce e o switch vai para a borda oposta. Sem ela, o switch fica a 8px do texto. */
  fullWidth?: boolean
  /** Initial state of the switch. */
  checked?: boolean
  disabled?: boolean
  name?: string
  value?: string
  'aria-label'?: string
}

const {
  label,
  description,
  textDirection = 'left',
  fullWidth = false,
  checked = false,
  disabled = false,
  id,
  name,
  value,
  'aria-label': ariaLabel,
  class: className,
  ...rest
} = Astro.props
---

<label
  class:list={[
    'au-switch-field',
    textDirection === 'left' && 'au-switch-field--direction-left',
    textDirection === 'right' && 'au-switch-field--direction-right',
    description && 'au-switch-field--with-description',
    fullWidth && 'au-switch-field--full-width',
    disabled && 'au-switch-field--disabled',
    className,
  ]}
  {...rest}>
  {label && (
    <span class="au-switch-field__text">
      <span class="au-switch-field__label">{label}</span>
      {description && <span class="au-switch-field__description">{description}</span>}
    </span>
  )}
  <span class="au-switch-field__control">
    <input
      class="au-switch-field__input"
      type="checkbox"
      role="switch"
      id={id}
      name={name}
      value={value}
      checked={checked}
      disabled={disabled}
      aria-label={ariaLabel}
    />
    <span class="au-switch-field__track" aria-hidden="true">
      <span class="au-switch-field__thumb">
        <IconCheck class="au-switch-field__icon au-switch-field__icon--on" />
        <IconX class="au-switch-field__icon au-switch-field__icon--off" />
      </span>
    </span>
  </span>
</label>
