import { expect, test, type Page } from '@playwright/test';

async function waitForBlazorConnection(page: Page) {
  await page.waitForTimeout(750);
}

test('calendar modal saves and deletes an event with picker ranges', async ({ page }) => {
  const eventTitle = `Smoke ${Date.now()}`;

  await page.setViewportSize({ width: 1440, height: 960 });
  await page.goto('/calendar-event/2026-04-22', { waitUntil: 'networkidle' });
  await waitForBlazorConnection(page);

  const startDateInput = page.getByTestId('calendar-event-start-date-input');
  const endDateInput = page.getByTestId('calendar-event-end-date-input');
  await expect(startDateInput).toBeVisible();
  await expect(endDateInput).toBeVisible();

  await endDateInput.click();
  await page.getByTestId('calendar-event-end-date-day-2026-04-23').click();
  await expect(endDateInput).toHaveValue('23/04/2026');

  const editorTimeInputs = page.locator('input[type="time"]');
  await expect(editorTimeInputs).toHaveCount(2);
  await editorTimeInputs.nth(0).fill('09:00');
  await editorTimeInputs.nth(1).fill('12:00');

  await page.locator('input[placeholder="Optional"]').fill(eventTitle);
  await page.getByRole('button', { name: 'Save' }).click();

  await waitForBlazorConnection(page);
  await expect(page).toHaveURL(/\/calendar\/2026-04$/);

  const savedEventEntries = page.locator('.calendar-item-event', { hasText: eventTitle });
  await expect(savedEventEntries).toHaveCount(2);
  await expect(savedEventEntries.first()).toContainText('09:00');

  await savedEventEntries.first().click();
  page.once('dialog', dialog => dialog.accept());
  await page.getByRole('button', { name: 'Delete' }).click();

  await expect(page.getByText(eventTitle)).toHaveCount(0);
});