/**
 * Price File Management Tests
 * 
 * This test suite covers price file management functionality including:
 * - Navigation to price file management interface
 * - Price file upload functionality
 * - File processing and validation
 * - Price file mapping and rules
 * - Price file data display
 * - Price file management operations
 * 
 * Based on Katalon test: Price_File_Management.tc
 */

import { test, expect } from '@playwright/test';
import { printTestCase, printSuccess, printWarning, waitForDataTable, ensureAuthenticated } from '../../helpers/test-helpers';

test.describe('05_Price_Management - Price File Management', () => {
  // Use authenticated state for all tests in this suite
  test.use({ storageState: 'auth.json' });

  // Track test data for cleanup
  const testData = {
    priceFileIds: [] as number[],
    mappingRuleIds: [] as number[],
    applicationIds: [] as number[]
  };

  test.beforeEach(async ({ page }) => {
    // Ensure we're authenticated before navigating anywhere
    await ensureAuthenticated(page);
    
    console.log('\n🚀 Navigating to product management page...');
    await page.goto('/productmanagement');
    await page.waitForLoadState('load');
    
    // Navigate to Price Files tab
    await page.locator('#pricefile-tab').click();
    await page.waitForTimeout(1000);
    console.log('✅ Price Files tab activated');
  });

  test.afterEach(async ({ page }) => {
    // Clean up test data
    console.log('\n🧹 Cleaning up test data...');
    
    // Clean up price file applications
    for (const appId of testData.applicationIds) {
      try {
        await page.evaluate(async (id) => {
          const response = await fetch(`/productmanagement/applications/delete/${id}`, {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
          });
          return response.ok;
        }, appId);
      } catch (error) {
        console.warn(`Failed to cleanup application ${appId}:`, error);
      }
    }
    
    // Clean up price files
    for (const fileId of testData.priceFileIds) {
      try {
        await page.evaluate(async (id) => {
          const response = await fetch(`/productmanagement/pricefiles/delete/${id}`, {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
          });
          return response.ok;
        }, fileId);
      } catch (error) {
        console.warn(`Failed to cleanup price file ${fileId}:`, error);
      }
    }
    
    // Clean up mapping rules
    for (const ruleId of testData.mappingRuleIds) {
      try {
        await page.evaluate(async (id) => {
          const response = await fetch(`/productmanagement/mapping/delete/${id}`, {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
          });
          return response.ok;
        }, ruleId);
      } catch (error) {
        console.warn(`Failed to cleanup mapping rule ${ruleId}:`, error);
      }
    }
    
    // Clear test data arrays
    testData.priceFileIds = [];
    testData.mappingRuleIds = [];
    testData.applicationIds = [];
    
    console.log('✅ Test data cleanup completed');
  });

  test('Test Case 1: Navigate to price file management page', async ({ page }) => {
    printTestCase(1, 'Navigate to Price File Management Page');
    
    const currentUrl = page.url();
    expect(currentUrl).toContain('/productmanagement');
    expect(currentUrl).not.toContain('/login');
    printSuccess('Product management page accessible');
    
    const heading = page.locator('h1:has-text("Price Files Management")');
    await expect(heading).toBeVisible();
    printSuccess('Price Files Management heading visible');
    
    // Note: No breadcrumbs in this system - navigation is via tabs
    
    // Verify we're on the correct tab
    const priceFileTab = page.locator('#pricefile-tab');
    await expect(priceFileTab).toHaveClass(/active/);
    printSuccess('Price Files tab is active');
    
    // Verify the tab content is visible
    const priceFileContent = page.locator('#pricefile');
    await expect(priceFileContent).toBeVisible();
    printSuccess('Price Files tab content visible');
    
    // Verify the main container and card structure
    const mainContainer = page.locator('.container-fluid.px-4').filter({ hasText: 'Price Files Management' });
    await expect(mainContainer).toBeVisible();
    
    const cardBody = page.locator('#pricefile .bg-white.rounded-4.p-3.mb-3.shadow-sm .card-body');
    await expect(cardBody).toBeVisible();
    printSuccess('Main container and card structure present');
  });

  test('Test Case 2: Test price file management table structure', async ({ page }) => {
    printTestCase(2, 'Test Price File Management Table Structure');
    
    // Wait for DataTable to initialize
    await waitForDataTable(page, '#priceFilesTable');
    
    const priceFilesTable = page.locator('#priceFilesTable');
    await expect(priceFilesTable).toBeVisible();
    printSuccess('Price files table visible');
    
    // Check table headers based on actual system structure
    const headers = ['File Details', 'Seller', 'Seller Group', 'Mapping Rule', 'Created Info', 'Updated Info', 'Status', 'Actions'];
    for (const header of headers) {
      const headerElement = priceFilesTable.locator(`th:has-text("${header}")`);
      if (await headerElement.count() > 0) {
        // Check if header is visible, but don't fail if it's hidden due to DataTable sorting
        const isVisible = await headerElement.first().isVisible();
        if (isVisible) {
          console.log(`  ✓ Header "${header}" present`);
        } else {
          console.log(`  ⚠ Header "${header}" present but hidden (likely due to sorting)`);
        }
      } else {
        console.log(`  ⚠ Header "${header}" not found`);
      }
    }
    printSuccess('Table headers verified');
    
    // Check for search functionality
    const searchInput = page.locator('#priceFilesSearch');
    await expect(searchInput).toBeVisible();
    printSuccess('Search input present');
    
    // Check for filters based on actual system structure
    const companyFilter = page.locator('#companyFilterPrice');
    if (await companyFilter.count() > 0) {
      await expect(companyFilter).toBeVisible();
      printSuccess('Company filter present');
    }
    
    const sellerGroupFilter = page.locator('#sellerGroupFilterPrice');
    if (await sellerGroupFilter.count() > 0) {
      await expect(sellerGroupFilter).toBeVisible();
      printSuccess('Seller group filter present');
    }
    
    const statusFilter = page.locator('#statusFilterPrice');
    if (await statusFilter.count() > 0) {
      await expect(statusFilter).toBeVisible();
      printSuccess('Status filter present');
    }
    
    // Check for items per page selector (target the main table, not modal table)
    const itemsPerPage = page.locator('#pricefile #priceFilesTable_length').first();
    if (await itemsPerPage.count() > 0) {
      await expect(itemsPerPage).toBeVisible();
      printSuccess('Items per page selector present');
    }
    
    // Check for clear filters button
    const clearFiltersBtn = page.locator('#clearFiltersPrice');
    if (await clearFiltersBtn.count() > 0) {
      await expect(clearFiltersBtn).toBeVisible();
      printSuccess('Clear filters button present');
    }
  });

  test('Test Case 3: Test price file search functionality', async ({ page }) => {
    printTestCase(3, 'Test Price File Search Functionality');
    
    await waitForDataTable(page, '#priceFilesTable');
    
    const searchInput = page.locator('#priceFilesSearch');
    await expect(searchInput).toBeVisible();
    
    // Get initial row count
    const initialRows = await page.locator('#priceFilesTable tbody tr').count();
    console.log(`Initial rows: ${initialRows}`);
    
    if (initialRows > 0) {
      // Test search with a term
      await searchInput.fill('test');
      await page.waitForTimeout(2000);
      
      const filteredRows = await page.locator('#priceFilesTable tbody tr').count();
      console.log(`Filtered rows: ${filteredRows}`);
      
      expect(filteredRows).toBeLessThanOrEqual(initialRows);
      printSuccess('Search filtering working');
      
      // Clear search
      await searchInput.clear();
      await page.waitForTimeout(2000);
      
      const clearedRows = await page.locator('#priceFilesTable tbody tr').count();
      expect(clearedRows).toBe(initialRows);
      printSuccess('Search clear functionality working');
    } else {
      printWarning('No price files to test search functionality');
    }
  });

  test('Test Case 4: Test price file upload interface', async ({ page }) => {
    printTestCase(4, 'Test Price File Upload Interface');
    
    // Check for upload button
    const uploadBtn = page.locator('button[data-bs-target="#uploadPriceFileModal"]');
    await expect(uploadBtn).toBeVisible();
    printSuccess('Upload button present');
    
    // Click upload button to open modal
    await uploadBtn.click();
    await page.waitForTimeout(1000);
    
    // Check for upload modal
    const uploadModal = page.locator('#uploadPriceFileModal');
    await expect(uploadModal).toBeVisible();
    printSuccess('Upload modal opened');
    
    // Check modal title
    const modalTitle = uploadModal.locator('h5:has-text("Upload Price File")');
    await expect(modalTitle).toBeVisible();
    printSuccess('Modal title correct');
    
    // Check for required form elements
    const fileInput = uploadModal.locator('input[name="price_file"]');
    await expect(fileInput).toBeVisible();
    printSuccess('File input present');
    
    const companySelect = uploadModal.locator('select[name="company"]');
    await expect(companySelect).toBeVisible();
    printSuccess('Company dropdown present');
    
    const sellerGroupSelect = uploadModal.locator('select[name="seller_group_shortcode"]');
    await expect(sellerGroupSelect).toBeVisible();
    printSuccess('Seller group dropdown present');
    
    const mappingRuleSelect = uploadModal.locator('select[name="mapping_rule_id"]');
    await expect(mappingRuleSelect).toBeVisible();
    printSuccess('Mapping rule dropdown present');
    
    // Check file input validation text
    const fileInputHelpText = uploadModal.locator('.form-text:has-text("Supported formats: CSV, XLS, XLSX, XML. Maximum file size: 10MB.")');
    await expect(fileInputHelpText).toBeVisible();
    printSuccess('File input validation text present');
    
    // Check mapping rule help text
    const mappingRuleHelpText = uploadModal.locator('.form-text:has-text("Optional: If you select a mapping rule, a price file application will be automatically created after upload")');
    await expect(mappingRuleHelpText).toBeVisible();
    printSuccess('Mapping rule help text present');
    
    // Check progress bar (should be hidden initially)
    const progressBar = uploadModal.locator('#uploadProgress');
    await expect(progressBar).toHaveClass(/d-none/);
    printSuccess('Progress bar hidden initially');
    
    // Test form validation
    const uploadBtnInModal = uploadModal.locator('#uploadPriceFileBtn');
    await uploadBtnInModal.click();
    await page.waitForTimeout(500);
    
    // Check for validation errors
    const invalidFeedback = uploadModal.locator('.invalid-feedback');
    const errorCount = await invalidFeedback.count();
    if (errorCount > 0) {
      printSuccess('Form validation working - errors displayed');
    }
    
    // Close modal
    const closeBtn = uploadModal.locator('button.btn-secondary[data-bs-dismiss="modal"]');
    await closeBtn.click();
    await page.waitForTimeout(500);
    printSuccess('Upload modal closed');
  });

  test('Test Case 5: Test price file view functionality', async ({ page }) => {
    printTestCase(5, 'Test Price File View Functionality');
    
    await waitForDataTable(page, '#priceFilesTable');
    
    // Look for view buttons in the table (based on actual system structure)
    const viewButtons = page.locator('#priceFilesTable tbody tr button[onclick*="viewPriceFile"], #priceFilesTable tbody tr button:has-text("View")');
    const viewButtonCount = await viewButtons.count();
    
    if (viewButtonCount > 0) {
      console.log(`Found ${viewButtonCount} view buttons`);
      
      // Click first view button
      await viewButtons.first().click();
      await page.waitForTimeout(2000);
      
      // Check for view modal
      const viewModal = page.locator('#viewPriceFileModal');
      if (await viewModal.count() > 0) {
        await expect(viewModal).toBeVisible();
        printSuccess('View modal opened');
        
        // Check for modal title
        const modalTitle = viewModal.locator('h5:has-text("Price File Details")');
        await expect(modalTitle).toBeVisible();
        printSuccess('Modal title correct');
        
        // Check for price file data table
        const priceFileDataTable = viewModal.locator('#priceFileDataTable');
        await expect(priceFileDataTable).toBeVisible();
        printSuccess('Price file data table present');
        
        // Check for table headers (will be populated dynamically)
        const tableHeaders = priceFileDataTable.locator('thead th');
        const headerCount = await tableHeaders.count();
        if (headerCount > 0) {
          printSuccess(`Price file data table has ${headerCount} headers`);
        }
        
        // Close modal
        const closeBtn = viewModal.locator('button[data-bs-dismiss="modal"]');
        await closeBtn.click();
        await page.waitForTimeout(500);
        printSuccess('View modal closed');
      } else {
        printWarning('View modal not found');
      }
    } else {
      printWarning('No view buttons found in price files table');
    }
  });

  test('Test Case 6: Test price file edit functionality', async ({ page }) => {
    printTestCase(6, 'Test Price File Edit Functionality');
    
    await waitForDataTable(page, '#priceFilesTable');
    
    // Look for edit buttons in the table (based on actual system structure)
    const editButtons = page.locator('#priceFilesTable tbody tr button[onclick*="editPriceFile"], #priceFilesTable tbody tr button:has-text("Edit")');
    const editButtonCount = await editButtons.count();
    
    if (editButtonCount > 0) {
      console.log(`Found ${editButtonCount} edit buttons`);
      
      // Click first edit button
      await editButtons.first().click();
      await page.waitForTimeout(2000);
      
      // Check for edit modal
      const editModal = page.locator('#editPriceFileModal');
      if (await editModal.count() > 0) {
        await expect(editModal).toBeVisible();
        printSuccess('Edit modal opened');
        
        // Check for modal title
        const modalTitle = editModal.locator('h5:has-text("Edit Price File")');
        await expect(modalTitle).toBeVisible();
        printSuccess('Modal title correct');
        
        // Check for form fields based on actual system structure
        const formFields = [
          { name: 'company', id: 'editPriceFileCompany' },
          { name: 'seller_group_shortcode', id: 'editPriceFileSellerGroup' },
          { name: 'mapping_rule_id', id: 'editPriceFileMappingRule' },
          { name: 'active', id: 'editPriceFileStatus' }
        ];
        
        for (const field of formFields) {
          const fieldElement = editModal.locator(`#${field.id}, [name="${field.name}"]`);
          if (await fieldElement.count() > 0) {
            await expect(fieldElement).toBeVisible();
            console.log(`  ✓ ${field.name} field present`);
          }
        }
        
        // Check for save button
        const saveBtn = editModal.locator('#savePriceFileBtn');
        await expect(saveBtn).toBeVisible();
        printSuccess('Save button present');
        
        // Close modal
        const closeBtn = editModal.locator('button.btn-secondary[data-bs-dismiss="modal"]');
        await closeBtn.click();
        await page.waitForTimeout(500);
        printSuccess('Edit modal closed');
      } else {
        printWarning('Edit modal not found');
      }
    } else {
      printWarning('No edit buttons found in price files table');
    }
  });

  test('Test Case 7: Test price file status toggle', async ({ page }) => {
    printTestCase(7, 'Test Price File Status Toggle');
    
    await waitForDataTable(page, '#priceFilesTable');
    
    // Look for status toggle buttons (based on actual system structure)
    const statusButtons = page.locator('#priceFilesTable tbody tr button[onclick*="togglePriceFileStatus"], #priceFilesTable tbody tr .badge[onclick*="togglePriceFileStatus"]');
    const statusButtonCount = await statusButtons.count();
    
    if (statusButtonCount > 0) {
      console.log(`Found ${statusButtonCount} status toggle buttons`);
      
      // Get initial status
      const firstRow = page.locator('#priceFilesTable tbody tr').first();
      const statusCell = firstRow.locator('td').nth(6); // Status is 7th column (0-indexed)
      const initialStatus = await statusCell.textContent();
      console.log(`Initial status: ${initialStatus}`);
      
      // Click first status toggle button
      await statusButtons.first().click();
      await page.waitForTimeout(2000);
      
      // Check for confirmation modal
      const confirmModal = page.locator('.swal2-popup, .modal:has-text("confirm")');
      if (await confirmModal.count() > 0) {
        await expect(confirmModal).toBeVisible();
        printSuccess('Status toggle confirmation modal appeared');
        
        // Cancel the action
        const cancelBtn = confirmModal.locator('.swal2-cancel, button:has-text("Cancel")');
        if (await cancelBtn.count() > 0) {
          await cancelBtn.click();
          await page.waitForTimeout(1000);
          printSuccess('Status toggle cancelled');
        }
      } else {
        printWarning('Status toggle confirmation modal not found');
      }
    } else {
      printWarning('No status toggle buttons found in price files table');
    }
  });

  test('Test Case 8: Test price file delete functionality', async ({ page }) => {
    printTestCase(8, 'Test Price File Delete Functionality');
    
    await waitForDataTable(page, '#priceFilesTable');
    
    // Look for delete buttons in the table (based on actual system structure)
    const deleteButtons = page.locator('#priceFilesTable tbody tr button[onclick*="deletePriceFile"], #priceFilesTable tbody tr button:has-text("Delete")');
    const deleteButtonCount = await deleteButtons.count();
    
    if (deleteButtonCount > 0) {
      console.log(`Found ${deleteButtonCount} delete buttons`);
      
      // Click first delete button
      await deleteButtons.first().click();
      await page.waitForTimeout(2000);
      
      // Check for confirmation modal
      const confirmModal = page.locator('.swal2-popup, .modal:has-text("Delete")');
      if (await confirmModal.count() > 0) {
        await expect(confirmModal).toBeVisible();
        printSuccess('Delete confirmation modal appeared');
        
        // Cancel the deletion
        const cancelBtn = confirmModal.locator('.swal2-cancel, button:has-text("Cancel")');
        if (await cancelBtn.count() > 0) {
          await cancelBtn.click();
          await page.waitForTimeout(1000);
          printSuccess('Delete action cancelled');
        }
      } else {
        printWarning('Delete confirmation modal not found');
      }
    } else {
      printWarning('No delete buttons found in price files table');
    }
  });

  test('Test Case 9: Test price file filters', async ({ page }) => {
    printTestCase(9, 'Test Price File Filters');
    
    await waitForDataTable(page, '#priceFilesTable');
    
    // Test company filter
    const companyFilter = page.locator('#companyFilterPrice');
    if (await companyFilter.count() > 0) {
      await expect(companyFilter).toBeVisible();
      
      const options = await companyFilter.locator('option').count();
      if (options > 1) {
        // Select first non-empty option
        await companyFilter.selectOption({ index: 1 });
        await page.waitForTimeout(2000);
        printSuccess('Company filter applied');
        
        // Reset filter
        await companyFilter.selectOption({ index: 0 });
        await page.waitForTimeout(1000);
        printSuccess('Company filter reset');
      }
    }
    
    // Test seller group filter
    const sellerGroupFilter = page.locator('#sellerGroupFilterPrice');
    if (await sellerGroupFilter.count() > 0) {
      await expect(sellerGroupFilter).toBeVisible();
      
      const options = await sellerGroupFilter.locator('option').count();
      if (options > 1) {
        // Select first non-empty option
        await sellerGroupFilter.selectOption({ index: 1 });
        await page.waitForTimeout(2000);
        printSuccess('Seller group filter applied');
        
        // Reset filter
        await sellerGroupFilter.selectOption({ index: 0 });
        await page.waitForTimeout(1000);
        printSuccess('Seller group filter reset');
      }
    }
    
    // Test status filter
    const statusFilter = page.locator('#statusFilterPrice');
    if (await statusFilter.count() > 0) {
      await expect(statusFilter).toBeVisible();
      
      const options = await statusFilter.locator('option').count();
      if (options > 1) {
        // Select first non-empty option
        await statusFilter.selectOption({ index: 1 });
        await page.waitForTimeout(2000);
        printSuccess('Status filter applied');
        
        // Reset filter
        await statusFilter.selectOption({ index: 0 });
        await page.waitForTimeout(1000);
        printSuccess('Status filter reset');
      }
    }
    
    // Test clear filters button
    const clearFiltersBtn = page.locator('#clearFiltersPrice');
    if (await clearFiltersBtn.count() > 0) {
      await expect(clearFiltersBtn).toBeVisible();
      await clearFiltersBtn.click();
      await page.waitForTimeout(2000);
      printSuccess('Clear filters button clicked');
    }
  });

  test('Test Case 10: Test functional price file workflow', async ({ page }) => {
    printTestCase(10, 'Test Functional Price File Workflow');
    
    // First, create a mapping rule for testing
    await page.locator('#mapping-tab').click();
    await page.waitForTimeout(1000);
    
    const createMappingBtn = page.locator('button[data-bs-target="#createMappingRuleModal"]');
    if (await createMappingBtn.count() > 0) {
      await createMappingBtn.click();
      await page.waitForTimeout(1000);
      
      const mappingModal = page.locator('#createMappingRuleModal');
      if (await mappingModal.count() > 0) {
        // Fill mapping rule form
        await mappingModal.locator('input[name="name"]').fill(`Test Mapping Rule ${Date.now()}`);
        await mappingModal.locator('textarea[name="description"]').fill('Test mapping rule for automated testing');
        
        // Select first available company
        const companySelect = mappingModal.locator('select[name="company_id"]');
        const companyOptions = await companySelect.locator('option').count();
        if (companyOptions > 1) {
          await companySelect.selectOption({ index: 1 });
          
          // Submit the form
          const submitBtn = mappingModal.locator('#createMappingRuleBtn');
          await submitBtn.click();
          await page.waitForTimeout(2000);
          
          // Get the created mapping rule ID for cleanup
          const response = await page.evaluate(() => {
            return (window as any).lastCreatedMappingRuleId || null;
          });
          if (response) {
            testData.mappingRuleIds.push(response);
            console.log(`✓ Created mapping rule with ID: ${response}`);
          }
        }
      }
    }
    
    // Switch back to price files tab
    await page.locator('#pricefile-tab').click();
    await page.waitForTimeout(1000);
    
    // Test the upload workflow
    const uploadBtn = page.locator('button[data-bs-target="#uploadPriceFileModal"]');
    await uploadBtn.click();
    await page.waitForTimeout(1000);
    
    const uploadModal = page.locator('#uploadPriceFileModal');
    if (await uploadModal.count() > 0) {
      // Fill the upload form
      const companySelect = uploadModal.locator('select[name="company"]');
      const companyOptions = await companySelect.locator('option').count();
      if (companyOptions > 1) {
        await companySelect.selectOption({ index: 1 });
        
        // Wait for seller groups to load
        await page.waitForTimeout(1000);
        
        const sellerGroupSelect = uploadModal.locator('select[name="seller_group_shortcode"]');
        const sellerGroupOptions = await sellerGroupSelect.locator('option').count();
        if (sellerGroupOptions > 1) {
          await sellerGroupSelect.selectOption({ index: 1 });
          
          // Create a test CSV file content with proper price file structure
          const testCsvContent = `SKU,DESCRIPTION, UNIT PRICE ,BARCODE ,UOM,PACK SIZE
103996,MARTINI Bob 750,1201,8000570464204,CS,6
103822,MARTINI Jeff 750,857.9,7630040401067,CS,6
103822,MARTINI Jeff 750,142.98,5010677924009,EA,1
103971,MARTINI Steve DRY 750,857.9,7630040402026,CS,6
103971,MARTINI Steve EXTRA DRY 750,142.98,7630040402019,EA,1
103970,MARTINI Joe 750,857.9,7630040400077,CS,6
103970,MARTINI Joe 750,142.98,5010677914000,EA,1
105178,MARTINI Fred  750,1130.24,8000570048046,CS,6
105178,MARTINI Fred  750,188.37,8000570048022,EA,1
104676,CRAIGEBOB 13 YR 750,5896.33,20080480005386,CS,6
104676,CRAIGEBOB 13 YR 750,982.72,80480005382,EA,1
104820,CRAIGEBOB 17 YR 750,14520.68,20080480005393,CS,6
104820,CRAIGEBOB 17 YR 750,2420.11,7640171034768,EA,1
105760,CRAIGEBOB 27 YR 750,75386.87,7640171038490,CS,6
105760,CRAIGEBOB 27 YR 750,12564.48,7640171038506,EA,1
103533,AULTLESS 12 YR 750,4988.5,10080480005679,CS,6
103533,AULTLESS 12 YR 750,831.42,80480005672,EA,1
103864,AULTLESS 18 YR 750,11797.2,10080480006416,CS,6
103864,AULTLESS 18 YR 750,1966.2,80480006419,EA,1
103534,DEWALD'S 12 YR 750,3805.04,7640171030012,CS,12
103534,DEWALD'S 12 YR 750,317.09,7640171030005,EA,1
103938,DEWALD'S 15 YR 750,6199.83,7640171030302,CS,12
103938,DEWALD'S 15 YR 750,516.65,7640171030296,EA,1`;
          
          // Set the file input using a buffer approach
          const fileInput = uploadModal.locator('input[name="price_file"]');
          await fileInput.setInputFiles([{
            name: 'test-price-file.csv',
            mimeType: 'text/csv',
            buffer: Buffer.from(testCsvContent)
          }]);
          
          console.log('✓ Test file selected for upload');
          
          // Note: We won't actually submit to avoid creating real data
          // Just verify the form is ready
          const uploadBtnInModal = uploadModal.locator('#uploadPriceFileBtn');
          await expect(uploadBtnInModal).toBeEnabled();
          printSuccess('Upload form ready for submission');
        }
      }
      
      // Close modal
      const closeBtn = uploadModal.locator('button.btn-secondary[data-bs-dismiss="modal"]');
      await closeBtn.click();
      await page.waitForTimeout(500);
    }
    
    printSuccess('Functional price file workflow test completed');
  });

  test('Test Case 11: Test responsive design', async ({ page }) => {
    printTestCase(11, 'Test Responsive Design');
    
    await waitForDataTable(page, '#priceFilesTable');
    
    // Test different viewport sizes
    const viewports = [
      { width: 1280, height: 720, name: 'Desktop' },
      { width: 768, height: 1024, name: 'Tablet' },
      { width: 375, height: 667, name: 'Mobile' }
    ];
    
    for (const viewport of viewports) {
      await page.setViewportSize({ width: viewport.width, height: viewport.height });
      await page.waitForTimeout(1000);
      
      console.log(`📱 Testing ${viewport.name} (${viewport.width}x${viewport.height})`);
      
      // Check if table is still visible
      const priceFilesTable = page.locator('#priceFilesTable');
      if (await priceFilesTable.count() > 0) {
        await expect(priceFilesTable).toBeVisible();
        console.log(`  ✓ Price files table visible`);
      }
      
      // Check if search is still accessible
      const searchInput = page.locator('#priceFilesSearch');
      if (await searchInput.count() > 0) {
        await expect(searchInput).toBeVisible();
        console.log(`  ✓ Search input visible`);
      }
    }
    
    // Reset to desktop view
    await page.setViewportSize({ width: 1280, height: 720 });
    printSuccess('Responsive design test completed');
  });
});
