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

const PLAYGROUND = '/admin/flowdrop/workflows/e2e_calculator_user/playground';

test('e2e_calculator_user playground: sums [3,1] to 4 and accepts confirmation', async ({
  page,
}) => {
  await page.goto(PLAYGROUND);

  await expect(
    page.getByRole('heading', { name: /Playground.*E2E Calculator User/ }),
  ).toBeVisible();

  // globalSetup() deletes any pre-existing sessions for this workflow, so
  // the playground renders the first-visit state with a standalone
  // "New session" button (no dropdown).
  await page.getByRole('button', { name: 'New session' }).click();

  const input = page.getByRole('textbox', { name: /Type your message/ });
  await expect(input).toBeEnabled({ timeout: 10_000 });
  await input.fill('[3,1]');
  await page.getByRole('button', { name: 'Send message' }).click();

  // Confirm the message actually posted — the user's [3,1] bubble in the
  // execution log is the cheapest signal that the backend accepted Send.
  const userBubble = page.locator('.message-bubble--user').last();
  await expect(userBubble).toContainText('[3,1]', { timeout: 10_000 });

  // The workflow runs synchronously and pauses on a HITL confirmation. The
  // playground's real-time log subscription is unreliable in headless
  // Chromium for sessions created mid-page, so poll the page state until
  // either it shows up or a reload brings it in. See tests/e2e/README.md
  // ("Known quirks") for the underlying UX bug this papers over.
  const confirmation = page.getByRole('group', { name: 'Confirmation Required' });
  await expect
    .poll(
      async () => {
        if (await confirmation.isVisible().catch(() => false)) return true;
        await page.reload();
        return confirmation.isVisible().catch(() => false);
      },
      { timeout: 20_000, intervals: [1500, 2000, 3000] },
    )
    .toBe(true);

  // The assistant bubble carries the calculator's result. Targeting the
  // bubble class (rather than the whole log) avoids false matches like
  // "247ms" in timing entries.
  const assistantBubble = page.locator('.message-bubble--assistant').last();
  await expect(assistantBubble).toContainText(/\b4\b/);

  await confirmation.last().getByRole('button', { name: 'Yes' }).click();

  await expect(page.getByText('Confirmation Submitted').last()).toBeVisible({
    timeout: 10_000,
  });
});
