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

function json(route: Route, status: number, body: unknown) {
  return route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(body) });
}

const publicConfig = {
  saasEnabled: true,
  googleAuthEnabled: true,
  contactEnabled: true,
  shopUrl: '',
  freePlanProjectLimit: 3,
  homeAiBuilder: {
    enabled: true,
    anonymousVisible: true,
    freeUserEnabled: false,
    maxPromptLength: 8000,
    quickStarts: ['research-paper','essay','study-notes','literature-review','latex','report','article','thesis','dissertation','book-chapter','proposal','lab-report','case-study','meeting-notes','summary','study-guide','flashcards','markdown'],
  },
};

async function mockPublicSession(page: Page, authenticated = false) {
  await page.route('**/api/config/public', (route) => json(route, 200, publicConfig));
  await page.route('**/api/auth/me', (route) => json(route, 200, authenticated ? {
    authenticated: true,
    csrfToken: 'home-ai-csrf',
    user: { id: 9, email: 'writer@example.test', displayName: 'Writer', avatarUrl: null, role: 'user', status: 'active' },
    entitlement: { tier: 'free', pro: false, blocked: false, quota: 0, usage: 0, remaining: 0 },
  } : { authenticated: false }));
  await page.route('**/api/user/settings', (route) => json(route, 200, { settings: {} }));
}

test('homepage writing request stays focused on task prompts and explicit output format', async ({ page }) => {
  await mockPublicSession(page, false);
  await page.goto('/');

  await expect(page.getByText('Popular writing tasks')).toBeVisible();
  await expect(page.getByText('Output format')).toBeVisible();
  await expect(page.getByText('Start with a project')).toHaveCount(0);
  await expect(page.locator('.interactive-home-ai-intents')).toHaveCount(0);
});


test('prompt actions populate the composer with editable text without submitting', async ({ page }) => {
  await mockPublicSession(page, false);
  await page.goto('/');

  const prompt = page.getByTestId('home-ai-build-prompt');
  await page.getByTestId('home-ai-prompt-research-abstract').click();
  await expect(prompt).toHaveValue('Draft an abstract for a research paper about renewable energy storage.');
  await expect(page).toHaveURL(/\/$/u);

  await page.getByTestId('home-ai-prompt-literature-review').click();
  await expect(prompt).toHaveValue(/Create a literature review outline/u);
  await expect(page).toHaveURL(/\/$/u);

  await prompt.fill('My own edited research instruction.');
  await page.getByTestId('home-ai-prompt-thesis-outline').click();
  await expect(prompt).toHaveValue('My own edited research instruction.');
});


test('Markdown and LaTeX output choices are visible and survive the anonymous login handoff', async ({ page }) => {
  await mockPublicSession(page, false);
  await page.goto('/');

  const markdown = page.getByTestId('home-ai-format-markdown');
  const latex = page.getByTestId('home-ai-format-latex');
  await expect(markdown).toHaveAttribute('aria-pressed', 'true');
  await expect(latex).toHaveAttribute('aria-pressed', 'false');

  await latex.click();
  await expect(latex).toHaveAttribute('aria-pressed', 'true');
  await expect(markdown).toHaveAttribute('aria-pressed', 'false');

  await page.getByTestId('home-ai-build-prompt').fill('Write a research paper about local-first research workflows.');
  await page.getByTestId('home-ai-build-submit').click();
  await expect(page).toHaveURL(/\/login\?returnTo=.*homeAiBuild/u);
  const pending = await page.evaluate(() => sessionStorage.getItem('learnitive:pending-home-build'));
  expect(pending).toContain('"outputFormat":"latex"');
});

test('anonymous Create preserves the writing idea and routes through login before any project workflow', async ({ page }) => {
  await mockPublicSession(page, false);
  await page.goto('/');
  await page.getByTestId('home-ai-build-prompt').fill('Write a literature review about local-first education software.');
  await page.getByTestId('home-ai-build-submit').click();
  await expect(page).toHaveURL(/\/login\?returnTo=.*homeAiBuild/u);
  const pending = await page.evaluate(() => sessionStorage.getItem('learnitive:pending-home-build'));
  expect(pending).toContain('Write a literature review about local-first education software.');
});

test('anonymous AI Settings remembers settings intent and authenticates first', async ({ page }) => {
  await mockPublicSession(page, false);
  await page.goto('/');
  await page.getByRole('button', { name: 'AI Settings' }).first().click();
  await expect(page).toHaveURL(/\/login\?returnTo=.*homeAiSettings/u);
  const pending = await page.evaluate(() => sessionStorage.getItem('learnitive:pending-home-build'));
  expect(pending).toContain('"action":"settings"');
});

test('authenticated Free users keep Create enabled and get the Pro upgrade dialog', async ({ page }) => {
  await mockPublicSession(page, true);
  await page.goto('/');
  const prompt = page.getByTestId('home-ai-build-prompt');
  const create = page.getByTestId('home-ai-build-submit');
  await prompt.fill('Create structured study notes about photosynthesis.');
  await expect(create).toBeEnabled();
  await create.click();
  const dialog = page.getByTestId('home-ai-pro-upgrade-dialog');
  await expect(dialog).toBeVisible();
  await expect(dialog).toContainText('AI writing with BYOK or supported AI providers is not enabled for your current Free plan.');
  await expect(dialog.getByRole('link', { name: 'Buy Pro' })).toHaveAttribute('href', '/pricing');
});

test('writer AI section is directly below the hero and the Overleaf comparison remains responsive', async ({ page }) => {
  await mockPublicSession(page, false);
  await page.goto('/');
  const writer = page.locator('[data-home-section="ai-writer"]');
  const comparison = page.locator('[data-home-section="comparison"]');
  await expect(writer).toBeVisible();
  await expect(writer.getByRole('heading', { name: 'What will you write today?' })).toBeVisible();
  await expect(comparison).toBeVisible();

  for (const width of [320, 360, 390, 430, 768, 820]) {
    await page.setViewportSize({ width, height: 900 });
    await expect(comparison.locator('.interactive-product-comparison-table')).toBeHidden();
    await expect(comparison.locator('.interactive-product-comparison-mobile')).toBeVisible();
    await expect(comparison.getByText('Learnitive', { exact: true }).first()).toBeVisible();
    await expect(comparison.getByText('Overleaf', { exact: true }).first()).toBeVisible();
    const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
    expect(overflow, `horizontal overflow at ${width}px`).toBeLessThanOrEqual(0);
  }

  await page.setViewportSize({ width: 1200, height: 900 });
  await expect(comparison.locator('.interactive-product-comparison-table')).toBeVisible();
  await expect(comparison.locator('.interactive-product-comparison-mobile')).toBeHidden();
  await expect(comparison.locator('thead th')).toHaveCount(3);
});
