import { beforeEach, describe, expect, it, vi } from 'vitest';
import { renderSettings } from '../settings';

vi.mock('../../../shared/state', () => ({
  setState: vi.fn(),
  sendMessage: vi.fn(),
  navigate: vi.fn(),
  escapeHtml: (s: string) => s,
  popOutToTab: vi.fn(),
  isInTab: vi.fn(() => false),
  openVaultTab: vi.fn(),
}));

import { sendMessage } from '../../../shared/state';

function settingsResponses() {
  // Two parallel calls in renderSettings: get_settings + get_blacklist.
  (sendMessage as ReturnType<typeof vi.fn>)
    .mockResolvedValueOnce({ ok: true, data: { settings: { captureEnabled: false, captureStyle: 'bar' } } })
    .mockResolvedValueOnce({ ok: true, data: { blacklist: [] } });
}

describe('settings view', () => {
  let app: HTMLElement;

  beforeEach(() => {
    document.body.innerHTML = '<div id="app"></div>';
    app = document.getElementById('app')!;
    (sendMessage as ReturnType<typeof vi.fn>).mockReset();
  });

  it('renders a Sync now button', async () => {
    settingsResponses();

    await renderSettings(app);

    expect(app.querySelector('#sync-now-btn')).not.toBeNull();
  });

  it('clicking Sync now sends a sync message and shows feedback on success', async () => {
    settingsResponses();
    (sendMessage as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ ok: true });

    await renderSettings(app);
    app.querySelector<HTMLButtonElement>('#sync-now-btn')!.click();
    await new Promise((r) => setTimeout(r, 0));
    await new Promise((r) => setTimeout(r, 0));

    expect(sendMessage).toHaveBeenCalledWith({ type: 'sync' });
    const status = app.querySelector('#sync-status')!;
    expect(status.textContent).toMatch(/synced/i);
  });

  it('shows the error when sync fails', async () => {
    settingsResponses();
    (sendMessage as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ ok: false, error: 'remote_unreachable' });

    await renderSettings(app);
    app.querySelector<HTMLButtonElement>('#sync-now-btn')!.click();
    await new Promise((r) => setTimeout(r, 0));
    await new Promise((r) => setTimeout(r, 0));

    const status = app.querySelector('#sync-status')!;
    expect(status.textContent).toMatch(/remote_unreachable/);
  });
});
