import { test, expectFixture as expect, dismissConsentBanner } from '../helpers/test-fixtures';

const eventSlug = process.env.E2E_GUEST_EVENT_SLUG;

test.describe('Guest Profile Flow', () => {
  test('should require name setup on first event join and persist it', async ({ page, fetchJoinToken }) => {
    test.skip(!eventSlug, 'Set E2E_GUEST_EVENT_SLUG to point the guest suite at an existing event.');

    const joinToken = await fetchJoinToken({ slug: eventSlug!, ensureActive: true });

    await page.goto('/event');
    await dismissConsentBanner(page);

    // Enter event slug manually
    await page.getByPlaceholder(/Event-Code|event code/i).fill(joinToken.token);
    await page.getByRole('button', { name: /Event beitreten|Join event/i }).click();

    // Should redirect to setup if no name
    await expect(page).toHaveURL(new RegExp(`/e/${joinToken.token}/setup`));

    // Fill name and submit
    await page.getByPlaceholder(/Dein Name|Your name/i).fill('Test User');
    await page.getByRole('button', { name: /Los gehts|Let's go/i }).click();

    // Should navigate to home
    await expect(page).toHaveURL(new RegExp(`/e/${joinToken.token}$`));

    // Check localStorage
    const storedName = await page.evaluate((token) => localStorage.getItem(`guestName_${token}`), joinToken.token);
    expect(storedName).toBe('Test User');

    // Reload to test persistence - should stay on home, not redirect to setup
    await page.reload();
    await expect(page).toHaveURL(new RegExp(`/e/${joinToken.token}$`));

    // Re-nav to landing and join again - should go directly to home
    await page.goto('/event');
    await dismissConsentBanner(page);
    await page.getByPlaceholder(/Event-Code|event code/i).fill(joinToken.token);
    await page.getByRole('button', { name: /Event beitreten|Join event/i }).click();
    await expect(page).toHaveURL(new RegExp(`/e/${joinToken.token}$`));
  });

  test('should go directly to home if name already stored', async ({ page, fetchJoinToken }) => {
    test.skip(!eventSlug, 'Set E2E_GUEST_EVENT_SLUG to point the guest suite at an existing event.');

    const joinToken = await fetchJoinToken({ slug: eventSlug!, ensureActive: true });

    // Pre-set name in localStorage
    await page.addInitScript((token) => {
      localStorage.setItem(`guestName_${token}`, 'Existing User');
    }, joinToken.token);

    await page.goto('/event');
    await dismissConsentBanner(page);

    // Join
    await page.getByPlaceholder(/Event-Code|event code/i).fill(joinToken.token);
    await page.getByRole('button', { name: /Event beitreten|Join event/i }).click();

    // Should go directly to home
    await expect(page).toHaveURL(new RegExp(`/e/${joinToken.token}$`));
  });
});
