---
/* ---------------------------------------------------------------------------
 * MultiSelectAsyncField — checkbox grid for picking multiple options.
 *
 * Submits as repeated form values under field.key[] (browser default for
 * multiple checkboxes with the same name). The route handler in step 7
 * normalises the array form via getAll().
 * ------------------------------------------------------------------------- */

import type { MultiSelectAsyncField } from '../../resource-types';

interface Props {
  field: MultiSelectAsyncField;
  value: unknown;
}

const { field, value } = Astro.props;
const options = await field.loadOptions();

const selected = new Set<string>();
if (Array.isArray(value)) {
  for (const v of value) selected.add(String(v));
}
---

<fieldset class="bs-multiselect" disabled={field.readOnly}>
  <legend class="bs-visually-hidden">{field.label}</legend>
  {options.length === 0 && (
    <p class="bs-multiselect-empty">No options available.</p>
  )}
  {options.map(opt => {
    const id = `f-${field.key}-${opt.value}`;
    const isChecked = selected.has(String(opt.value));
    return (
      <label class="bs-multiselect-row" for={id}>
        <input
          type="checkbox"
          id={id}
          name={field.key}
          value={String(opt.value)}
          checked={isChecked}
        />
        <span>{opt.label}</span>
      </label>
    );
  })}
</fieldset>
