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

const BASE = 'http://localhost:5000';

/**
 * ═══════════════════════════════════════════════════════════
 * Product Description (Ultra Description) E2E Tests
 * ═══════════════════════════════════════════════════════════
 *
 * Tests:
 *  1. Page load & UI
 *  2. Stats row rendering
 *  3. Tab switching (Products / Fields / Clean Data)
 *  4. Filters & search
 *  5. Product table rendering
 *  6. API health checks
 */

test.describe('Product Description — Page Load & UI', () => {

  test('1.1 — Page loads without JS errors', async ({ page }) => {
    const errors: string[] = [];
    page.on('pageerror', err => errors.push(err.message));

    await page.goto(`${BASE}/static/main.html?page=product-desc%2Fproduct-desc.html&p=1`);
    // removed networkidle

    // Ignore non-critical errors (CORS, etc.)
    const criticalErrors = errors.filter(e =>
      !e.includes('CORS') &&
      !e.includes('ResizeObserver') &&
      !e.includes('Script error')
    );
    expect(criticalErrors).toHaveLength(0);
  });

  test('1.2 — Page loads via iframe (main.html wrapper)', async ({ page }) => {
    await page.goto(`${BASE}/static/main.html?page=product-desc%2Fproduct-desc.html&p=1`);
    // removed networkidle

    // The page is loaded inside an iframe in main.html
    // Look for iframe with content
    const iframe = page.frameLocator('#contentFrame, iframe').first();

    // Check that the product desc page title is visible inside iframe
    const title = iframe.locator('h1');
    await expect(title).toContainText('Ultra Description', { timeout: 15000 });
  });

  test('1.3 — Direct page load (no iframe)', async ({ page }) => {
    await page.goto(`${BASE}/static/product-desc/product-desc.html`);
    // removed networkidle

    // Title
    const title = page.locator('h1');
    await expect(title).toContainText('Ultra Description');

    // Refresh button
    const refreshBtn = page.locator('button:has-text("Refresh")');
    await expect(refreshBtn).toBeVisible();
  });
});


test.describe('Product Description — Stats Row', () => {

  test('2.1 — Stats cards render with data', async ({ page }) => {
    await page.goto(`${BASE}/static/product-desc/product-desc.html`);
    // removed networkidle

    // Wait for stats to load (replace "—" with actual numbers)
    await page.waitForFunction(() => {
      const el = document.querySelector('#statTotal');
      return el && el.textContent !== '—';
    }, null, { timeout: 15000 });

    // Check key stat elements
    const statTotal = page.locator('#statTotal');
    const statDone = page.locator('#statDone');
    const statApproved = page.locator('#statApproved');
    const statPending = page.locator('#statPending');
    const statMissing = page.locator('#statMissing');

    // Each should have a numeric value (not "—")
    for (const stat of [statTotal, statDone, statApproved, statPending, statMissing]) {
      const text = await stat.textContent();
      expect(text).not.toBe('—');
    }
  });

  test('2.2 — Progress bar renders', async ({ page }) => {
    await page.goto(`${BASE}/static/product-desc/product-desc.html`);
    // removed networkidle

    await page.waitForFunction(() => {
      const el = document.querySelector('#statProgress');
      return el && el.textContent !== '—';
    }, null, { timeout: 15000 });

    const progressFill = page.locator('#progressFill');
    await expect(progressFill).toBeVisible();
  });
});


test.describe('Product Description — Tab Navigation', () => {

  test('3.1 — Switch to Fields tab', async ({ page }) => {
    await page.goto(`${BASE}/static/product-desc/product-desc.html`);
    // removed networkidle

    // Click Fields tab
    const fieldsTab = page.locator('#tabFields');
    await fieldsTab.click();

    // Products section hidden, Fields section visible
    await expect(page.locator('#sectionProducts')).toBeHidden();
    await expect(page.locator('#sectionFields')).toBeVisible();

    // Fields table should be visible
    const fieldsTable = page.locator('#fieldsTable');
    await expect(fieldsTable).toBeVisible();
  });

  test('3.2 — Switch to Clean Data tab', async ({ page }) => {
    await page.goto(`${BASE}/static/product-desc/product-desc.html`);
    // removed networkidle

    // Click Clean Data tab
    const cleanTab = page.locator('#tabCleanData');
    await cleanTab.click();

    // Clean Data section visible
    await expect(page.locator('#sectionCleanData')).toBeVisible();
    await expect(page.locator('#sectionProducts')).toBeHidden();

    // Search input for product code
    const searchInput = page.locator('#cleanDataSearch');
    await expect(searchInput).toBeVisible();
  });

  test('3.3 — Switch back to Products tab', async ({ page }) => {
    await page.goto(`${BASE}/static/product-desc/product-desc.html`);
    // removed networkidle

    // Go to Fields, then back to Products
    await page.locator('#tabFields').click();
    await page.locator('#tabProducts').click();

    await expect(page.locator('#sectionProducts')).toBeVisible();
    await expect(page.locator('#sectionFields')).toBeHidden();
  });
});


test.describe('Product Description — Product Table', () => {

  test('4.1 — Product table loads with rows', async ({ page }) => {
    await page.goto(`${BASE}/static/product-desc/product-desc.html`);
    // removed networkidle

    // Wait for table rows to appear (not the "Đang tải..." placeholder)
    await page.waitForFunction(() => {
      const tbody = document.querySelector('#tableBody');
      if (!tbody) return false;
      const rows = tbody.querySelectorAll('tr');
      return rows.length > 0 && !rows[0].textContent?.includes('Đang tải');
    }, null, { timeout: 15000 });

    const rows = page.locator('#tableBody tr');
    const count = await rows.count();
    expect(count).toBeGreaterThan(0);
  });

  test('4.2 — Filter by status works', async ({ page }) => {
    await page.goto(`${BASE}/static/product-desc/product-desc.html`);
    // removed networkidle

    // Wait for table to load first
    await page.waitForFunction(() => {
      const el = document.querySelector('#statTotal');
      return el && el.textContent !== '—';
    }, null, { timeout: 15000 });

    // Select "Đã duyệt" filter
    await page.locator('#statusFilter').selectOption('approved');
    await page.locator('button:has-text("Lọc")').click();

    // Wait for table refresh
    await page.waitForTimeout(2000);

    // Table should still render (no crash)
    const tbody = page.locator('#tableBody');
    await expect(tbody).toBeVisible();
  });

  test('4.3 — Search by product code', async ({ page }) => {
    await page.goto(`${BASE}/static/product-desc/product-desc.html`);
    // removed networkidle

    await page.waitForFunction(() => {
      const el = document.querySelector('#statTotal');
      return el && el.textContent !== '—';
    }, null, { timeout: 15000 });

    // Type a search term
    const searchInput = page.locator('#searchInput');
    await searchInput.fill('polo');
    await page.locator('button:has-text("Lọc")').click();

    await page.waitForTimeout(2000);

    // Table should still work
    const tbody = page.locator('#tableBody');
    await expect(tbody).toBeVisible();
  });

  test('4.4 — Pagination renders', async ({ page }) => {
    await page.goto(`${BASE}/static/product-desc/product-desc.html`);
    // removed networkidle

    await page.waitForFunction(() => {
      const el = document.querySelector('#statTotal');
      return el && el.textContent !== '—';
    }, null, { timeout: 15000 });

    // Pagination element should exist
    const pagination = page.locator('#pagination');
    await expect(pagination).toBeVisible();
  });

  test('4.5 — Reset filters button works', async ({ page }) => {
    await page.goto(`${BASE}/static/product-desc/product-desc.html`);
    // removed networkidle

    await page.waitForFunction(() => {
      const el = document.querySelector('#statTotal');
      return el && el.textContent !== '—';
    }, null, { timeout: 15000 });

    // Apply a filter first
    await page.locator('#statusFilter').selectOption('approved');
    await page.locator('button:has-text("Lọc")').click();
    await page.waitForTimeout(1000);

    // Reset
    await page.locator('button:has-text("Reset")').click();
    await page.waitForTimeout(1000);

    // Status filter should be back to default
    const val = await page.locator('#statusFilter').inputValue();
    expect(val).toBe('');
  });
});


test.describe('Product Description — API Health', () => {

  test('5.1 — GET /api/product-desc/overview returns 200', async ({ request }) => {
    const resp = await request.get(`${BASE}/api/product-desc/overview`);
    expect(resp.status()).toBe(200);

    const body = await resp.json();
    expect(body).toHaveProperty('total');
  });

  test('5.2 — GET /api/product-desc/list returns 200', async ({ request }) => {
    const resp = await request.get(`${BASE}/api/product-desc/list?page=1&limit=5`);
    expect(resp.status()).toBe(200);

    const body = await resp.json();
    expect(body).toHaveProperty('products');
  });

  test('5.3 — GET /api/bulk/fields returns 200', async ({ request }) => {
    const resp = await request.get(`${BASE}/api/bulk/fields`);
    expect(resp.status()).toBe(200);
  });
});


test.describe('Product Description — Network Integrity', () => {

  test('6.1 — No 404/500 on page load resources', async ({ page }) => {
    const failedRequests: string[] = [];

    page.on('response', resp => {
      if (resp.status() >= 400 && resp.url().includes('localhost')) {
        failedRequests.push(`${resp.status()} ${resp.url()}`);
      }
    });

    await page.goto(`${BASE}/static/product-desc/product-desc.html`);
    // removed networkidle

    expect(failedRequests).toHaveLength(0);
  });
});
