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). Thin
    wrapper over the CIBG Huisstijl `.form-check.styled` checkbox CSS; native
    input for full keyboard + screen-reader support. */
@Component({
  selector: 'app-checkbox',
  template: `
    <div class="form-check styled">
      <input
        class="form-check-input"
        type="checkbox"
        [id]="checkboxId()"
        [checked]="value"
        [disabled]="disabled"
        (change)="onToggle($event)"
        (blur)="onTouched()"
      />
      <label class="form-check-label" [for]="checkboxId()">{{ label() }}</label>
    </div>
  `,
  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;
  }
}
