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

const adminAuth = {
  authenticated: true,
  csrfToken: 'test-csrf',
  user: { id: 1, email: 'admin@learnitive.test', displayName: 'Template Admin', avatarUrl: null, role: 'admin', status: 'active' },
  entitlement: { tier: 'pro', pro: true, blocked: false, quota: 1000, usage: 0, remaining: 1000 },
} as const;

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

async function mockCategoryApi(page: Page) {
  const categories: Array<Record<string, unknown>> = [];
  let createdBody: Record<string, unknown> | undefined;
  await page.route('**/api/**', async (route) => {
    const request = route.request();
    const url = new URL(request.url());
    if (url.pathname === '/api/config/public') return json(route, 200, { saasEnabled: true, googleAuthEnabled: false, contactEnabled: false, shopUrl: '' });
    if (url.pathname === '/api/auth/me') return json(route, 200, adminAuth);
    if (url.pathname === '/api/user/settings' && request.method() === 'GET') return json(route, 200, { settings: {} });
    if (url.pathname === '/api/admin/template-categories' && request.method() === 'GET') return json(route, 200, { categories, counts: {} });
    if (url.pathname === '/api/admin/template-categories' && request.method() === 'POST') {
      createdBody = request.postDataJSON() as Record<string, unknown>;
      const category = { ...createdBody, createdAt: '2026-08-24T00:00:00.000Z', updatedAt: '2026-08-24T00:00:00.000Z' };
      categories.push(category);
      return json(route, 201, { category });
    }
    return json(route, 404, { error: 'not_mocked' });
  });
  return { createdBody: () => createdBody };
}

test('Admin creates a managed template category with the visual Lucide icon browser', async ({ page }) => {
  const api = await mockCategoryApi(page);
  await page.goto('/admin/template-categories');

  await expect(page.getByRole('heading', { name: 'Template Categories' })).toBeVisible();
  await page.getByRole('button', { name: 'Create category' }).click();
  await page.getByLabel('Name').fill('Scientific Notes');
  await expect(page.getByLabel('Stable ID / slug')).toHaveValue('scientific-notes');
  await page.getByLabel('Description').fill('Scientific notebooks, lab notes and experiment records.');
  await page.getByLabel('Sort order').fill('115');

  await page.getByRole('button', { name: 'Browse icons' }).click();
  const dialog = page.getByRole('dialog', { name: 'Choose Lucide icon' });
  await expect(dialog).toBeVisible();
  await dialog.getByLabel('Search Lucide icons').fill('FlaskConical');
  await dialog.getByRole('option', { name: 'FlaskConical' }).click();
  await expect(dialog).toBeHidden();
  await expect(page.locator('.interactive-admin-category-icon-choice')).toContainText('FlaskConical');

  await page.locator('.interactive-admin-category-editor').getByRole('button', { name: 'Create category' }).click();
  await expect.poll(() => api.createdBody()).toMatchObject({
    id: 'scientific-notes',
    slug: 'scientific-notes',
    name: 'Scientific Notes',
    icon: 'FlaskConical',
    sortOrder: 115,
    status: 'published',
  });
  await expect(page.getByRole('button', { name: 'Edit Scientific Notes' })).toBeVisible();
});
