// @vitest-environment jsdom
/**
 * Component tests for SearchFilterForm (settings → searchFilter.*).
 *
 * Focus: blocked-patterns StringArrayEditor add, and the four auto-block
 * checkboxes mapping to searchFilter.autoBlock.<key>.
 */
import '../../test/dom-setup';
import { beforeAll, describe, it, expect, vi } from 'vitest';
import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderWithProviders } from '../../test/render-helpers';
import i18n from '../../i18n';
import { SearchFilterForm } from './SearchFilterForm';

beforeAll(async () => {
  await i18n.changeLanguage('en');
});

function render(config: any, onChange = vi.fn()) {
  renderWithProviders(
    <SearchFilterForm config={config} onChange={onChange} overriddenByEnv={{}} />,
  );
  return onChange;
}

describe('SearchFilterForm', () => {
  it('renders existing blocked patterns and auto-block state', () => {
    render({
      searchFilter: {
        blockedPatterns: ['secret\\.internal'],
        autoBlock: { privateIp: true, email: false },
      },
    });
    expect(screen.getByText('secret\\.internal')).toBeInTheDocument();
    const privateIp = screen.getByLabelText('Private IP') as HTMLInputElement;
    expect(privateIp.checked).toBe(true);
    const email = screen.getByLabelText('Email address') as HTMLInputElement;
    expect(email.checked).toBe(false);
  });

  it('adds a blocked pattern via the StringArrayEditor', async () => {
    const user = userEvent.setup();
    const onChange = render({ searchFilter: { blockedPatterns: ['a'] } });
    const input = screen.getByPlaceholderText('regex pattern');
    await user.type(input, 'b\\.c');
    await user.keyboard('{Enter}');
    expect(onChange).toHaveBeenCalledWith('searchFilter.blockedPatterns', ['a', 'b\\.c']);
  });

  it('toggles each auto-block checkbox to the correct nested path', async () => {
    const user = userEvent.setup();
    const onChange = render({ searchFilter: {} });
    await user.click(screen.getByLabelText('Phone number'));
    expect(onChange).toHaveBeenCalledWith('searchFilter.autoBlock.phone', true);
    await user.click(screen.getByLabelText('Internal domain'));
    expect(onChange).toHaveBeenCalledWith('searchFilter.autoBlock.internalDomain', true);
  });
});
