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

/**
 * Opens public signup from the login page (for local stacks on non-default ports).
 * Set PLAYWRIGHT_BASE_URL (e.g. http://localhost:8890) when the UI is not on port 3000.
 *
 * If this fails with "Could not start signup", check `runtime-config.js` on the UI host:
 * `apiBaseUrl` must be reachable from the browser (often `localhost` + API port), and if the API
 * has `TURNSTILE_SECRET_KEY`, the UI needs `TURNSTILE_SITE_KEY` / `VITE_TURNSTILE_SITE_KEY`.
 */
test('signup dialog loads welcome or Turnstile step', async ({ page }) => {
  const signupResponses: { status: number; body: string }[] = [];
  page.on('response', async res => {
    if (!res.url().includes('/api/v1/signup/chat')) return;
    let body = '';
    try {
      body = (await res.text()).slice(0, 500);
    } catch {
      body = '(could not read body)';
    }
    signupResponses.push({ status: res.status(), body });
  });

  await page.goto('/login');
  await expect(page.getByRole('heading', { name: 'Sign in' })).toBeVisible({ timeout: 20_000 });

  await page.getByRole('button', { name: 'Sign up' }).click();
  await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible({ timeout: 20_000 });

  const welcome = page.getByText('Welcome to Silicon Support');
  const turnstileHint = page.getByText('Complete the security check below');
  const startError = page.getByText('Could not start signup');

  await expect(welcome.or(turnstileHint).or(startError)).toBeVisible({ timeout: 45_000 });

  if (await startError.isVisible()) {
    await test.info().attach('signup-chat-responses', {
      body: JSON.stringify(signupResponses, null, 2),
      contentType: 'application/json',
    });
  }

  await expect(startError).not.toBeVisible();
});
