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

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

/**
 * ═══════════════════════════════════════════════════════════
 * Lead Flow E2E Tests — Canifa AI Stylist
 * ═══════════════════════════════════════════════════════════
 * 
 * Tests:
 *  1. Page load & UI elements
 *  2. Stage bar rendering (5 stages)
 *  3. Chat input & AI response
 *  4. Pipeline debug panel
 *  5. Conversation history dropdown
 *  6. API health checks
 */

test.describe('Lead Flow — Page Load & UI', () => {

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

    await page.goto(`${BASE}/static/main.html?page=lead_flow%2Flead-flow.html`);
    // removed networkidle

    // No JS errors
    expect(errors.join(', ')).toBe('');
    
    // Title correct
    await expect(page).toHaveTitle(/Canifa AI Platform/);
  });

  test('1.2 — Stage bar renders 5 stages', async ({ page }) => {
    await page.goto(`${BASE}/static/main.html?page=lead_flow%2Flead-flow.html`);
    // removed networkidle

    // Check all 5 stage nodes are visible
    for (let i = 1; i <= 5; i++) {
      const dot = page.frameLocator('iframe').locator(`#stageDot${i}`);
      await expect(dot).toBeVisible();
      await expect(dot).toHaveText(String(i));
    }

    // Check stage labels
    await expect(page.frameLocator('iframe').locator('#stageLabel1')).toHaveText('Awareness');
    await expect(page.frameLocator('iframe').locator('#stageLabel2')).toHaveText('Interest');
    await expect(page.frameLocator('iframe').locator('#stageLabel3')).toHaveText('Consideration');
    await expect(page.frameLocator('iframe').locator('#stageLabel4')).toHaveText('Decision');
    await expect(page.frameLocator('iframe').locator('#stageLabel5')).toHaveText('Retention');
  });

  test('1.3 — Chat input & send button exist', async ({ page }) => {
    await page.goto(`${BASE}/static/main.html?page=lead_flow%2Flead-flow.html`);
    // removed networkidle

    // Chat input
    const input = page.frameLocator('iframe').locator('#chatInput');
    await expect(input).toBeVisible();

    // Send button
    const sendBtn = page.frameLocator('iframe').locator('#sendBtn');
    await expect(sendBtn).toBeVisible();
  });

  test('1.4 — Empty state / quick prompts shown on fresh load', async ({ page }) => {
    await page.goto(`${BASE}/static/main.html?page=lead_flow%2Flead-flow.html`);
    // removed networkidle

    // Empty state text
    const emptyState = page.frameLocator('iframe').locator('#emptyState');
    await expect(emptyState).toBeVisible();
    await expect(emptyState).toContainText('Lead Stage AI');

    // Quick prompt buttons
    const quickPrompts = page.frameLocator('iframe').locator('.quick-prompt');
    const count = await quickPrompts.count();
    expect(count).toBeGreaterThanOrEqual(3);
  });

  test('1.5 — Device ID input exists', async ({ page }) => {
    await page.goto(`${BASE}/static/main.html?page=lead_flow%2Flead-flow.html`);
    // removed networkidle

    const deviceInput = page.frameLocator('iframe').locator('#deviceIdInput');
    await expect(deviceInput).toBeVisible();
    // Should have a generated value
    const val = await deviceInput.inputValue();
    expect(val.length).toBeGreaterThan(5);
  });

  test('1.6 — Debug panel visible', async ({ page }) => {
    await page.goto(`${BASE}/static/main.html?page=lead_flow%2Flead-flow.html`);
    // removed networkidle

    // Debug panel should exist (may be on right side)
    const debugPanel = page.frameLocator('iframe').locator('.debug-panel, #debugPanel, .pipeline-panel');
    await expect(debugPanel.first()).toBeVisible();
  });
});


test.describe('Lead Flow — Chat Interaction', () => {

  test('2.1 — Send message and receive AI response', async ({ page }) => {
    await page.goto(`${BASE}/static/main.html?page=lead_flow%2Flead-flow.html`);
    // removed networkidle

    // Type message
    const input = page.frameLocator('iframe').locator('#chatInput');
    await input.fill('Tôi muốn tìm áo polo nam');

    // Send
    const sendBtn = page.frameLocator('iframe').locator('#sendBtn');
    await sendBtn.click();

    // Wait for AI response (bot bubble to appear)
    const botMsg = page.frameLocator('iframe').locator('.msg.ai, .chat-bubble.bot, .bot-message').first();
    await expect(botMsg).toBeVisible({ timeout: 30000 });

    // Response should have some content
    const text = await botMsg.textContent();
    expect(text!.length).toBeGreaterThan(10);
  });

  test('2.2 — Quick prompt button sends message', async ({ page }) => {
    await page.goto(`${BASE}/static/main.html?page=lead_flow%2Flead-flow.html`);
    // removed networkidle

    // Click first quick prompt
    const quickBtn = page.frameLocator('iframe').locator('.quick-prompt').first();
    await quickBtn.click();

    // User message should appear
    const userMsg = page.frameLocator('iframe').locator('.msg.human, .chat-bubble.user, .user-message').first();
    await expect(userMsg).toBeVisible({ timeout: 10000 });

    // Bot response should follow
    const botMsg = page.frameLocator('iframe').locator('.msg.ai, .chat-bubble.bot, .bot-message').first();
    await expect(botMsg).toBeVisible({ timeout: 30000 });
  });

  test('2.3 — Stage progresses after chat interactions', async ({ page }) => {
    await page.goto(`${BASE}/static/main.html?page=lead_flow%2Flead-flow.html`);
    // removed networkidle

    // Send a message to trigger stage classification
    const input = page.frameLocator('iframe').locator('#chatInput');
    await input.fill('Tìm áo khoác nam mùa đông');
    await page.frameLocator('iframe').locator('#sendBtn').click();

    // Wait for response
    const botMsg = page.frameLocator('iframe').locator('.msg.ai, .chat-bubble.bot, .bot-message').first();
    await expect(botMsg).toBeVisible({ timeout: 30000 });

    // Check that at least stage 1 or 2 is active (has 'active' or similar class)
    const activeDots = page.frameLocator('iframe').locator('.stage-dot.active, .stage-dot.current, .stage-node.active');
    // At minimum, stage 1 should be highlighted
    const cnt = await activeDots.count();
    expect(cnt).toBeGreaterThanOrEqual(1);
  });
});


test.describe('Lead Flow — API Health', () => {

  test('3.1 — POST /api/agent/chat-lead-flow returns 200', async ({ request }) => {
    const resp = await request.post(`${BASE}/api/agent/chat-lead-flow`, {
      data: {
        user_query: 'Xin chào',
        device_id: 'e2e-test-device-001',
      },
    });
    expect(resp.status()).toBe(200);

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

  test('3.2 — GET /api/lead/conversations returns 200', async ({ request }) => {
    const resp = await request.get(`${BASE}/api/lead/conversations`, {
      headers: { 'device_id': 'e2e-test-device-001' }
    });
    expect(resp.status()).toBe(200);

    const body = await resp.json();
    expect(body.status).toBe('success');
    expect(body).toHaveProperty('data');
  });

  test('3.3 — GET /api/lead/dashboard returns 200', async ({ request }) => {
    const resp = await request.get(`${BASE}/api/lead/dashboard?limit=5`);
    expect(resp.status()).toBe(200);

    const body = await resp.json();
    expect(body.status).toBe('success');
    expect(body).toHaveProperty('data');
    expect(body).toHaveProperty('count');
  });

  test('3.4 — POST /api/agent/lead-stage (classifier debug) returns 200', async ({ request }) => {
    const resp = await request.post(`${BASE}/api/agent/lead-stage`, {
      data: {
        user_query: 'Tôi muốn mua áo khoác',
      },
    });
    expect(resp.status()).toBe(200);

    const body = await resp.json();
    expect(body.status).toBe('success');
    // Should have classification fields
    expect(body).toHaveProperty('stage');
  });
});


test.describe('Lead Flow — Network Integrity', () => {

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

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

    await page.goto(`${BASE}/static/main.html?page=lead_flow%2Flead-flow.html`);
    // removed networkidle

    // Filter out known CDN/external failures
    const localFailures = failedRequests.filter(r => r.includes('localhost'));
    expect(localFailures).toHaveLength(0);
  });
});

