// @vitest-environment jsdom
/**
 * Component tests for PushNotificationsForm (settings → notifications.push.*).
 *
 * Focus: enable checkbox gating, URL/text passthrough (empty → undefined),
 * and numeric serialization for payloadMaxBytes / queueConcurrency.
 */
import '../../test/dom-setup';
import { beforeAll, describe, it, expect, vi } from 'vitest';
import { screen, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderWithProviders } from '../../test/render-helpers';
import i18n from '../../i18n';
import { PushNotificationsForm } from './PushNotificationsForm';

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

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

describe('PushNotificationsForm', () => {
  it('renders with realistic existing push config', () => {
    render({
      notifications: {
        push: { enabled: true, vapidSubject: 'https://maestro.example.com/', queueConcurrency: 8 },
      },
    });
    expect(screen.getByDisplayValue('https://maestro.example.com/')).toBeInTheDocument();
    const enable = screen.getByLabelText('Enable Web Push') as HTMLInputElement;
    expect(enable.checked).toBe(true);
  });

  it('defaults to disabled when push config is absent', () => {
    render({});
    const enable = screen.getByLabelText('Enable Web Push') as HTMLInputElement;
    expect(enable.checked).toBe(false);
  });

  it('toggles the enable switch', async () => {
    const user = userEvent.setup();
    const onChange = render({});
    await user.click(screen.getByLabelText('Enable Web Push'));
    expect(onChange).toHaveBeenCalledWith('notifications.push.enabled', true);
  });

  it('writes vapidSubject text, undefined when cleared', async () => {
    const user = userEvent.setup();
    const onChange = render({ notifications: { push: { vapidSubject: 'mailto:x@y.z' } } });
    const input = screen.getByDisplayValue('mailto:x@y.z');
    await user.clear(input);
    expect(onChange).toHaveBeenLastCalledWith('notifications.push.vapidSubject', undefined);
  });

  it('serializes payloadMaxBytes to a Number', () => {
    const onChange = render({});
    const numberInputs = screen.getAllByRole('spinbutton');
    // first number field is payloadMaxBytes
    fireEvent.change(numberInputs[0], { target: { value: '3072' } });
    expect(onChange).toHaveBeenCalledWith('notifications.push.payloadMaxBytes', 3072);
  });
});
