/**
 * Seller Portal Dashboard Test
 * 
 * Tags: @seller @p1 @dashboard
 * 
 * Tests seller dashboard functionality:
 * - Navigate to seller dashboard
 * - View dashboard statistics
 * - Switch between seller companies
 * - View recent orders
 * - Verify dashboard widgets
 */

import { test, expect } from '@playwright/test';
import { 
  printTestCase, 
  printSuccess, 
  printWarning, 
  ensureAuthenticated 
} from '../../helpers/test-helpers';

test.describe('06_Seller_Portal - Dashboard', () => {
  test.use({ storageState: 'auth.json' });
  
  test.beforeEach(async ({ page }) => {
    await ensureAuthenticated(page);
  });
  
  test('Test Case 1: Navigate to seller dashboard', async ({ page }) => {
    printTestCase(1, 'Navigate to Seller Dashboard');
    
    await page.goto('/seller/dashboard');
    await page.waitForLoadState('networkidle');
    
    // Verify dashboard header
    const dashboardHeader = page.locator('.dashboard-header, h1:has-text("Dashboard"), h2:has-text("Dashboard")');
    const headerVisible = await dashboardHeader.isVisible({ timeout: 5000 }).catch(() => false);
    
    if (headerVisible) {
      printSuccess('Seller dashboard loaded');
    } else {
      printWarning('Dashboard header not found - may not have seller access');
    }
    
    // Verify URL is correct
    const currentUrl = page.url();
    if (currentUrl.includes('/seller')) {
      printSuccess('On seller portal');
    }
  });
  
  test('Test Case 2: View dashboard statistics', async ({ page }) => {
    printTestCase(2, 'View Dashboard Statistics');
    
    await page.goto('/seller/dashboard');
    await page.waitForLoadState('networkidle');
    
    // Wait for stats to load
    await page.waitForFunction(() => {
      const statsCards = document.querySelectorAll('.stats-card, .stat-card, [class*="stat"]');
      return statsCards && statsCards.length > 0;
    }, { timeout: 10000 }).catch(() => {});
    
    // Check for statistics cards
    const statsCards = page.locator('.stats-card, .card:has(.stats-number), .card:has([class*="stat"])');
    const statsCount = await statsCards.count();
    
    if (statsCount > 0) {
      printSuccess(`Found ${statsCount} statistics card(s)`);
      
      // Verify common stat types
      const statsTypes = [
        { name: 'Total Products', selector: '.stats-card:has-text("Product"), .card:has-text("Product")' },
        { name: 'Active Orders', selector: '.stats-card:has-text("Order"), .card:has-text("Order")' },
        { name: 'Total Sales', selector: '.stats-card:has-text("Sales"), .card:has-text("Sales")' }
      ];
      
      for (const stat of statsTypes) {
        const statCard = page.locator(stat.selector).first();
        if (await statCard.isVisible().catch(() => false)) {
          printSuccess(`${stat.name} statistic visible`);
        }
      }
    } else {
      printWarning('No statistics cards found');
    }
  });
  
  test('Test Case 3: View recent orders widget', async ({ page }) => {
    printTestCase(3, 'View Recent Orders Widget');
    
    await page.goto('/seller/dashboard');
    await page.waitForLoadState('networkidle');
    
    // Look for recent orders section
    const recentOrdersSection = page.locator('.recent-orders-card, .card:has-text("Recent Orders"), [class*="recent"]:has-text("Order")');
    const recentOrdersVisible = await recentOrdersSection.first().isVisible({ timeout: 5000 }).catch(() => false);
    
    if (recentOrdersVisible) {
      printSuccess('Recent orders widget visible');
      
      // Check for order table or list
      const orderTable = page.locator('.recent-orders-card table, table.table-modern');
      if (await orderTable.isVisible().catch(() => false)) {
        const orderRows = orderTable.locator('tbody tr');
        const rowCount = await orderRows.count();
        
        if (rowCount > 0) {
          printSuccess(`Found ${rowCount} recent order(s)`);
          
          // Verify table columns
          const headers = orderTable.locator('thead th');
          const headerCount = await headers.count();
          printSuccess(`Table has ${headerCount} columns`);
        } else {
          printSuccess('No recent orders (empty state)');
        }
      }
    } else {
      printWarning('Recent orders widget not found');
    }
  });
  
  test('Test Case 4: View seller selector dropdown', async ({ page }) => {
    printTestCase(4, 'View Seller Selector Dropdown');
    
    await page.goto('/seller/dashboard');
    await page.waitForLoadState('networkidle');
    
    // Look for seller selector dropdown
    const sellerDropdown = page.locator('#currentSellerName, [id*="seller"], button:has-text("Select Seller"), .dropdown:has-text("Seller")');
    const dropdownVisible = await sellerDropdown.first().isVisible({ timeout: 5000 }).catch(() => false);
    
    if (dropdownVisible) {
      printSuccess('Seller selector dropdown found');
      
      // Try to click the dropdown
      await sellerDropdown.first().click().catch(() => {});
      await page.waitForTimeout(1000);
      
      // Check for dropdown menu
      const dropdownMenu = page.locator('#sellerDropdown, .dropdown-menu:visible, [class*="dropdown"]:visible');
      if (await dropdownMenu.first().isVisible({ timeout: 2000 }).catch(() => false)) {
        printSuccess('Seller dropdown menu opened');
        
        // Count sellers
        const sellerItems = dropdownMenu.locator('.dropdown-item, [class*="seller-item"]');
        const sellerCount = await sellerItems.count();
        
        if (sellerCount > 0) {
          printSuccess(`Found ${sellerCount} seller(s)`);
        }
        
        // Close dropdown by clicking elsewhere
        await page.keyboard.press('Escape');
      }
    } else {
      printWarning('Seller selector not found - may have only one seller');
    }
  });
  
  test('Test Case 5: Switch seller company', async ({ page }) => {
    printTestCase(5, 'Switch Seller Company');
    
    await page.goto('/seller/dashboard');
    await page.waitForLoadState('networkidle');
    
    // Look for seller selector
    const sellerDropdown = page.locator('#currentSellerName, [id*="seller"], button:has-text("Select Seller")');
    const dropdownVisible = await sellerDropdown.first().isVisible({ timeout: 5000 }).catch(() => false);
    
    if (dropdownVisible) {
      // Get current seller name
      const currentSellerBefore = await sellerDropdown.first().textContent();
      
      // Click dropdown
      await sellerDropdown.first().click();
      await page.waitForTimeout(1000);
      
      // Get seller items
      const dropdownMenu = page.locator('#sellerDropdown, .dropdown-menu:visible');
      const sellerItems = dropdownMenu.locator('.dropdown-item, [class*="seller-item"]');
      const sellerCount = await sellerItems.count();
      
      if (sellerCount > 1) {
        printSuccess('Multiple sellers available for switching');
        
        // Click the second seller
        await sellerItems.nth(1).click();
        
        // Wait for page reload/update
        await page.waitForLoadState('networkidle');
        await page.waitForTimeout(2000);
        
        // Verify switch occurred
        const currentSellerAfter = await sellerDropdown.first().textContent();
        
        if (currentSellerBefore !== currentSellerAfter) {
          printSuccess('Successfully switched to different seller');
        } else {
          printWarning('Seller may have switched but name unchanged');
        }
      } else {
        printWarning('Only one seller available - cannot test switching');
      }
    } else {
      printWarning('Seller selector not found - cannot test switching');
    }
  });
  
  test('Test Case 6: Verify quick action links', async ({ page }) => {
    printTestCase(6, 'Verify Quick Action Links');
    
    await page.goto('/seller/dashboard');
    await page.waitForLoadState('networkidle');
    
    // Look for quick action links/buttons
    const quickActions = [
      { name: 'View Orders', selector: 'a[href*="/seller/orders"], button:has-text("View Orders")' },
      { name: 'Manage Products', selector: 'a[href*="/seller/products"], button:has-text("Manage Products"), button:has-text("Products")' },
      { name: 'View Analytics', selector: 'a[href*="/seller/analytics"], button:has-text("Analytics")' }
    ];
    
    let foundActions = 0;
    for (const action of quickActions) {
      const actionLink = page.locator(action.selector).first();
      if (await actionLink.isVisible({ timeout: 2000 }).catch(() => false)) {
        printSuccess(`${action.name} link found`);
        foundActions++;
      }
    }
    
    if (foundActions > 0) {
      printSuccess(`Found ${foundActions} quick action link(s)`);
    } else {
      printWarning('No quick action links found');
    }
  });
  
  test('Test Case 7: Verify performance metrics', async ({ page }) => {
    printTestCase(7, 'Verify Performance Metrics');
    
    await page.goto('/seller/dashboard');
    await page.waitForLoadState('networkidle');
    
    // Look for performance indicators
    const performanceIndicators = page.locator('[class*="performance"], [class*="metric"], .badge:has-text("%")');
    const indicatorCount = await performanceIndicators.count();
    
    if (indicatorCount > 0) {
      printSuccess(`Found ${indicatorCount} performance indicator(s)`);
      
      // Check for growth percentage
      const growthIndicator = page.locator('[class*="growth"], :has-text("growth")').first();
      if (await growthIndicator.isVisible().catch(() => false)) {
        printSuccess('Growth indicator visible');
      }
    } else {
      printWarning('No performance metrics found');
    }
  });
  
  test('Test Case 8: Test dashboard refresh', async ({ page }) => {
    printTestCase(8, 'Test Dashboard Refresh');
    
    await page.goto('/seller/dashboard');
    await page.waitForLoadState('networkidle');
    
    // Get initial stats
    const statsCard = page.locator('.stats-card, .stat-card').first();
    const initialContent = await statsCard.textContent().catch(() => '');
    
    // Look for refresh button
    const refreshBtn = page.locator('button:has-text("Refresh"), button[title*="Refresh"], i.fa-sync').first();
    const refreshBtnVisible = await refreshBtn.isVisible({ timeout: 2000 }).catch(() => false);
    
    if (refreshBtnVisible) {
      await refreshBtn.click();
      await page.waitForLoadState('networkidle');
      printSuccess('Dashboard refreshed');
    } else {
      // Refresh the page manually
      await page.reload();
      await page.waitForLoadState('networkidle');
      printSuccess('Dashboard reloaded');
    }
    
    // Verify content is still present
    if (await statsCard.isVisible().catch(() => false)) {
      printSuccess('Dashboard content reloaded successfully');
    }
  });
});

