import { test, expect } from '@playwright/test';
import { BASE_URL, ensureLoggedIn } from './helpers/auth';

// ─────────────────────────────────────────────────────────────────────────────
// 8. DOCUMENTS — Quản lý tài liệu (Upload, Preview, List)
// ─────────────────────────────────────────────────────────────────────────────
test.describe('8. Documents — Quản lý tài liệu', () => {
  test.beforeEach(async ({ page }) => {
    await ensureLoggedIn(page);
  });

  test('8.1 Điều hướng tới Documents qua sidebar', async ({ page }) => {
    // Navigation.tsx renders documents with id="header-documents"
    const docsLink = page.locator('#header-documents');
    await docsLink.waitFor({ state: 'visible', timeout: 12000 });
    await docsLink.click();
    await expect(page).toHaveURL(/\/app\/documents/, { timeout: 12000 });
  });

  test('8.2 Documents page render không bị lỗi (heading + tabs hiện)', async ({ page }) => {
    await page.goto(`${BASE_URL}/app/documents`, { waitUntil: 'domcontentloaded' });

    // Page should not crash
    await expect(page.locator('body')).not.toContainText(/500 internal server error/i, { timeout: 8000 });

    // Should see heading (FileText icon + title)
    const heading = page.getByRole('heading').first();
    await expect(heading).toBeVisible({ timeout: 15000 });

    // Should see tabs: "List" and "Upload"
    const tabList = page.getByRole('tablist');
    await expect(tabList).toBeVisible({ timeout: 8000 });
  });

  test('8.3 Chuyển Tab List → Upload', async ({ page }) => {
    await page.goto(`${BASE_URL}/app/documents`, { waitUntil: 'domcontentloaded' });

    const tabList = page.getByRole('tablist');
    await tabList.waitFor({ state: 'visible', timeout: 12000 });

    // Click "Upload" tab
    const uploadTab = page.getByRole('tab').filter({ hasText: /upload/i });
    await uploadTab.click();

    // Upload area should now be visible
    const uploadContent = page.getByText(/supported formats|docx|pdf|txt/i).first();
    await expect(uploadContent).toBeVisible({ timeout: 8000 });

    // Click "List" tab to go back
    const listTab = page.getByRole('tab').filter({ hasText: /list/i });
    await listTab.click();

    // List content area should be visible
    await page.waitForTimeout(500);
    console.log('[8.3] Tab switching OK');
  });

  test('8.4 Upload button triggers file input', async ({ page }) => {
    await page.goto(`${BASE_URL}/app/documents`, { waitUntil: 'domcontentloaded' });

    // Find the Upload button in the header
    const uploadBtn = page.getByRole('button').filter({ hasText: /upload/i }).first();
    await uploadBtn.waitFor({ state: 'visible', timeout: 10000 });

    // Hidden file input should exist
    const fileInput = page.locator('#doc-upload-input');
    await expect(fileInput).toBeAttached({ timeout: 5000 });

    // Simulate file upload with a test .txt file
    await fileInput.setInputFiles({
      name: 'e2e-test-doc.txt',
      mimeType: 'text/plain',
      buffer: Buffer.from('This is a test document for E2E testing.'),
    });

    // Wait for upload to process
    await page.waitForTimeout(2000);

    // Should not show an unhandled error
    await expect(page.locator('body')).not.toContainText(/unhandled|crash/i);
    console.log('[8.4] Document upload triggered OK');
  });

  test('8.5 Upload tab hiển thị supported formats', async ({ page }) => {
    await page.goto(`${BASE_URL}/app/documents`, { waitUntil: 'domcontentloaded' });

    // Switch to Upload tab
    const uploadTab = page.getByRole('tab').filter({ hasText: /upload/i });
    await uploadTab.waitFor({ state: 'visible', timeout: 10000 });
    await uploadTab.click();

    // Should show supported format list
    await expect(page.getByText('DOCX (.docx)')).toBeVisible({ timeout: 8000 });
    await expect(page.getByText('PDF (.pdf)')).toBeVisible({ timeout: 3000 });
    await expect(page.getByText('TXT (.txt)')).toBeVisible({ timeout: 3000 });
  });
});
