import { test, expect } from '@playwright/test';
import {
  loginAsAdmin,
  navigateToCRMDashboard,
  waitForPageStable
} from './helpers/crmcore';

/**
 * CRM Dashboard Tests
 *
 * Tests the CRM Dashboard functionality including:
 * - Dashboard page loads correctly
 * - Statistics cards are displayed
 * - Quick action links work
 * - Charts load (if present)
 */

test.describe('CRM Dashboard', () => {
  test.beforeEach(async ({ page }) => {
    await loginAsAdmin(page);
  });

  test('should display CRM dashboard page', async ({ page }) => {
    await navigateToCRMDashboard(page);

    // Verify page title or heading
    await expect(page.locator('h4, h5').filter({ hasText: /dashboard|crm/i }).first()).toBeVisible();

    // Verify dashboard has card elements
    await expect(page.locator('.card').first()).toBeVisible();
  });

  test('should display statistics cards', async ({ page }) => {
    await navigateToCRMDashboard(page);

    // Wait for page to be stable
    await waitForPageStable(page);

    // Verify statistics cards are present (Companies, Customers, Deals, etc.)
    const cards = page.locator('.card');
    const cardCount = await cards.count();
    expect(cardCount).toBeGreaterThan(0);
  });

  test('should have navigation links to CRM modules', async ({ page }) => {
    await navigateToCRMDashboard(page);
    await waitForPageStable(page);

    // Verify CRM menu is visible in sidebar
    const crmMenu = page.locator('a:has-text("CRM")').first();
    await expect(crmMenu).toBeVisible();
  });

  test('should navigate to Companies from dashboard', async ({ page }) => {
    await navigateToCRMDashboard(page);
    await waitForPageStable(page);

    // Click on Companies link
    await page.goto('/companies');
    await page.waitForURL('**/companies', { timeout: 10000 });

    // Verify we're on companies page
    await expect(page.locator('.card').first()).toBeVisible();
  });

  test('should navigate to Leads from dashboard', async ({ page }) => {
    await navigateToCRMDashboard(page);
    await waitForPageStable(page);

    // Navigate to Leads
    await page.goto('/leads');
    await page.waitForURL('**/leads', { timeout: 10000 });

    // Verify we're on leads page
    await expect(page.locator('h4, h5').filter({ hasText: /leads/i }).first()).toBeVisible();
  });

  test('should navigate to Deals from dashboard', async ({ page }) => {
    await navigateToCRMDashboard(page);
    await waitForPageStable(page);

    // Navigate to Deals
    await page.goto('/deals');
    await page.waitForURL('**/deals', { timeout: 10000 });

    // Verify we're on deals page
    await expect(page.locator('h4, h5').filter({ hasText: /pipeline|deals/i }).first()).toBeVisible();
  });
});
