import { describe, it, expect, vi, beforeEach } from 'vitest';
import { wireGroupAutocomplete } from '../group-autocomplete';

describe('wireGroupAutocomplete', () => {
  let form: HTMLElement;

  beforeEach(() => {
    // Clean up any datalist from a prior test
    document.getElementById('groups-datalist')?.remove();
    form = document.createElement('div');
    form.innerHTML = `<input id="f-group" type="text" />`;
    document.body.appendChild(form);
  });

  it('attaches datalist with all groups', async () => {
    const sendMessage = vi.fn().mockResolvedValue({
      ok: true,
      data: { groups: ['personal', 'work', 'finance'] },
    });
    await wireGroupAutocomplete(form, { sendMessage });
    const list = document.getElementById('groups-datalist') as HTMLDataListElement | null;
    expect(list).not.toBeNull();
    const opts = Array.from(list!.querySelectorAll('option')).map((o) => o.value);
    expect(opts).toEqual(['personal', 'work', 'finance']);
    const input = form.querySelector('#f-group') as HTMLInputElement;
    expect(input.getAttribute('list')).toBe('groups-datalist');
  });

  it('is a no-op if SW returns error', async () => {
    const sendMessage = vi.fn().mockResolvedValue({ ok: false, error: 'vault_locked' });
    await wireGroupAutocomplete(form, { sendMessage });
    const input = form.querySelector('#f-group') as HTMLInputElement;
    expect(input.getAttribute('list')).toBeNull();
  });
});
