export interface GroupAutocompleteOpts {
  sendMessage: (msg: { type: 'list_groups' }) => Promise<{ ok: boolean; data?: { groups: string[] }; error?: string }>;
}

const DATALIST_ID = 'groups-datalist';

export async function wireGroupAutocomplete(form: HTMLElement, opts: GroupAutocompleteOpts): Promise<void> {
  const input = form.querySelector<HTMLInputElement>('#f-group');
  if (!input) return;
  let resp: Awaited<ReturnType<typeof opts.sendMessage>>;
  try {
    resp = await opts.sendMessage({ type: 'list_groups' });
  } catch {
    return;
  }
  if (!resp?.ok || !resp.data?.groups) return;

  // Datalists must live in the document, not nested inside an input. Reuse if
  // we've already mounted one this session.
  let list = document.getElementById(DATALIST_ID) as HTMLDataListElement | null;
  if (!list) {
    list = document.createElement('datalist');
    list.id = DATALIST_ID;
    document.body.appendChild(list);
  }
  list.innerHTML = resp.data.groups.map((g) => `<option value="${g.replace(/"/g, '&quot;')}"></option>`).join('');
  input.setAttribute('list', DATALIST_ID);
}
