import { Component, forwardRef, input } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

/** Atom: a labelled checkbox wired as a form control (ngModel/reactive). Native
    input for full keyboard + screen-reader support; the label is the click target. */
@Component({
  selector: 'app-checkbox',
  styles: [`
    :host{display:block}
    label{display:inline-flex;align-items:center;gap:var(--rhc-space-max-md);cursor:pointer}
    /* form-check-input floats/margins for the .form-check layout; here it's flex-aligned. */
    .form-check-input{margin:0;float:none;inline-size:1.1rem;block-size:1.1rem}
  `],
  template: `
    <label class="form-check-label">
      <input class="form-check-input" type="checkbox" [id]="checkboxId()" [checked]="value" [disabled]="disabled"
        (change)="onToggle($event)" (blur)="onTouched()" />
      <span>{{ label() }}</span>
    </label>
  `,
  providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => CheckboxComponent), multi: true }],
})
export class CheckboxComponent implements ControlValueAccessor {
  checkboxId = input<string>();
  label = input('');

  value = false;
  disabled = false;
  onChange: (v: boolean) => void = () => {};
  onTouched: () => void = () => {};

  onToggle(e: Event) {
    this.value = (e.target as HTMLInputElement).checked;
    this.onChange(this.value);
  }
  writeValue(v: boolean) { this.value = !!v; }
  registerOnChange(fn: (v: boolean) => void) { this.onChange = fn; }
  registerOnTouched(fn: () => void) { this.onTouched = fn; }
  setDisabledState(d: boolean) { this.disabled = d; }
}
