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

const summary = {
  id: 9001,
  slug: 'release-lms-course',
  title: 'Release LMS Course',
  shortDescription: 'A release fixture for the Learnitive LMS.',
  coverMediaId: null,
  coverUrl: null,
  projectModeId: 'python',
  level: 'beginner',
  status: 'published',
  visibility: 'public',
  accessTier: 'free',
  featured: true,
  sequentialLearning: true,
  estimatedMinutes: 45,
  outcomes: ['Use the learner player'],
  requirements: [],
  notice: {},
  itemCount: 2,
  completedCount: 0,
  progressPercent: 0,
  updatedAt: new Date(0).toISOString(),
  publishedAt: new Date(0).toISOString(),
};

const course = {
  ...summary,
  locked: false,
  prerequisites: [],
  description: { text: 'Release fixture course description.' },
  faqs: [],
  pageSettings: { layout: 'classic', showOutcomes: true, showRequirements: true, showFaq: true, showMaterials: false },
  customFields: [],
  certificateEnabled: false,
  sections: [{
    id: 7001,
    title: 'Start here',
    description: '',
    position: 0,
    items: [
      { id: 7101, sectionId: 7001, type: 'lesson', title: 'Lists and layout', slug: 'lists-and-layout', position: 0, status: 'published', accessTier: 'free', estimatedMinutes: 20, locked: false, completed: false, progressPercent: 0 },
      { id: 7102, sectionId: 7001, type: 'lesson', title: 'Locked next lesson', slug: 'locked-next', position: 1, status: 'published', accessTier: 'free', estimatedMinutes: 25, locked: true, completed: false, progressPercent: 0 },
    ],
  }],
};

const lesson = {
  course: summary,
  id: 7101,
  slug: 'lists-and-layout',
  title: 'Lists and layout',
  type: 'lesson',
  accessTier: 'free',
  estimatedMinutes: 20,
  locked: false,
  completed: false,
  progressPercent: 0,
  projectModeId: 'python',
  completionMode: 'manual',
  settings: {},
  blockProgress: {},
  document: {
    schemaVersion: 1,
    time: 0,
    blocks: [
      { id: 'intro', type: 'paragraph', data: { text: 'A learner paragraph that must stay inside the mobile reading column.' } },
      { id: 'bullets', type: 'list', data: { style: 'unordered', items: [{ content: 'Bullet one', items: [] }, { content: 'Bullet two', items: [] }] } },
      { id: 'numbers', type: 'list', data: { style: 'ordered', items: [{ content: 'Number one', items: [] }, { content: 'Number two', items: [] }] } },
    ],
  },
};

async function installLearnMocks(page: Page, lessonFixture: unknown = lesson) {
  await page.route('**/api/config/public', (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify({ enabled: true }) }));
  await page.route('**/api/auth/me', (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify({ authenticated: false }) }));
  await page.route('**/api/learn/courses/release-lms-course/lessons/lists-and-layout', (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify({ lesson: lessonFixture }) }));
  await page.route('**/api/learn/courses/release-lms-course', (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify({ course }) }));
  await page.route(/\/api\/learn\/courses(?:\?.*)?$/u, (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify({ courses: [summary] }) }));
}

test('LMS catalog renders public item counts independently of learner authentication', async ({ page }) => {
  await installLearnMocks(page);
  await page.goto('/learn');
  await expect(page.getByRole('heading', { level: 1, name: /Learn by building/u })).toBeVisible();
  await expect(page.getByRole('heading', { name: 'Release LMS Course' }).first()).toBeVisible();
  await expect(page.getByText('2 lessons').first()).toBeVisible();
});

test('learner lesson keeps semantic lists, locked curriculum semantics and bounded mobile width', async ({ page }) => {
  await installLearnMocks(page);
  await page.goto('/learn/release-lms-course/lists-and-layout');
  await expect(page.getByRole('heading', { level: 1, name: 'Lists and layout' })).toBeVisible();
  const unordered = page.locator('.interactive-learn-block-list ul').first();
  const ordered = page.locator('.interactive-learn-block-list ol').first();
  await expect(unordered).toBeVisible();
  await expect(ordered).toBeVisible();
  expect(await unordered.evaluate((node) => getComputedStyle(node).listStyleType)).not.toBe('none');
  expect(await ordered.evaluate((node) => getComputedStyle(node).listStyleType)).not.toBe('none');

  const locked = page.getByText('Locked next lesson', { exact: true }).locator('xpath=ancestor::*[@aria-disabled="true"][1]');
  await expect(locked).toBeVisible();
  await expect(locked).not.toHaveAttribute('href');
  await expect(page.getByText('Next', { exact: true })).toBeVisible();

  const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
  expect(overflow).toBeLessThanOrEqual(1);
});


test('learner Wistia video uses Aurora web component assets instead of the legacy iframe host', async ({ page }) => {
  const wistiaLesson = {
    ...lesson,
    document: {
      schemaVersion: 1,
      time: 0,
      blocks: [{ id: 'wistia-video', type: 'video', data: { source: 'wistia', externalId: 'c322lh6ifl', title: 'Wistia release fixture' } }],
    },
  };
  const wistiaRequests: string[] = [];
  page.on('request', (request) => {
    if (request.url().includes('wistia')) wistiaRequests.push(request.url());
  });
  await page.route('https://fast.wistia.com/player.js', (route) => route.fulfill({
    contentType: 'application/javascript',
    body: `class TestWistiaPlayer extends HTMLElement { constructor(){ super(); this.currentTime=0; this.duration=120; } connectedCallback(){ queueMicrotask(()=>this.dispatchEvent(new Event('api-ready'))); } } customElements.define('wistia-player', TestWistiaPlayer);`,
  }));
  await page.route('https://fast.wistia.com/embed/c322lh6ifl.js', (route) => route.fulfill({ contentType: 'application/javascript', body: 'export {};' }));
  await installLearnMocks(page, wistiaLesson);
  await page.goto('/learn/release-lms-course/lists-and-layout');

  const player = page.locator("wistia-player[media-id='c322lh6ifl']");
  await expect(player).toBeVisible();
  await expect(player).toHaveAttribute('aspect', '1.7777777777777777');
  expect(wistiaRequests.some((url) => url === 'https://fast.wistia.com/player.js')).toBe(true);
  expect(wistiaRequests.some((url) => url === 'https://fast.wistia.com/embed/c322lh6ifl.js')).toBe(true);
  expect(wistiaRequests.some((url) => url.includes('fast.wistia.net/embed/iframe'))).toBe(false);
});
