import { Page } from '@playwright/test';
import * as fs from 'fs';
import * as path from 'path';
import { authenticateUser } from '../utils/authentication';

/**
 * Test Helper Utilities
 * 
 * Common utilities for Playwright tests including:
 * - Wait utilities
 * - Validation helpers
 * - Calculation helpers
 * - Cleanup functions
 */

// ============================================
// MODAL HANDLING
// ============================================

/**
 * Handle the "increase quantity" modal that appears when adding a duplicate item
 * Returns true if modal was handled, false if it didn't appear
 */
export async function handleIncreaseQuantityModal(page: Page, action: 'confirm' | 'cancel' = 'cancel'): Promise<boolean> {
  try {
    // Wait for SweetAlert to appear (short timeout since this is optional)
    await page.waitForSelector('.swal2-popup', { timeout: 2000 });
    
    // Check if it's the "increase quantity" modal
    const title = await page.locator('.swal2-title').textContent();
    if (title?.includes('increase the quantity')) {
      console.log('📦 Found "increase quantity" modal, handling...');
      
      if (action === 'confirm') {
        await page.locator('.swal2-confirm').click();
        console.log('  ✅ Confirmed quantity increase');
      } else {
        await page.locator('.swal2-cancel').click();
        console.log('  ❌ Cancelled quantity increase');
      }
      
      await page.waitForTimeout(1000);
      return true;
    }
    
    return false;
  } catch (error) {
    // Modal didn't appear, which is fine
    return false;
  }
}

// ============================================
// WAIT UTILITIES
// ============================================

/**
 * Wait for an element to be visible and stable
 */
export async function waitForElement(page: Page, selector: string, timeout: number = 10000): Promise<void> {
  await page.locator(selector).waitFor({ state: 'visible', timeout });
}

/**
 * Wait for text to appear in an element
 */
export async function waitForText(page: Page, selector: string, text: string, timeout: number = 10000): Promise<void> {
  await page.locator(selector).filter({ hasText: text }).waitFor({ state: 'visible', timeout });
}

/**
 * Wait for page to be fully loaded (no pending AJAX requests)
 */
export async function waitForPageLoad(page: Page): Promise<void> {
  await page.waitForLoadState('networkidle');
}

/**
 * Wait for DataTables to initialize and load data
 * @param page Playwright page object
 * @param tableSelector Table ID selector (e.g., '#productsTable')
 * @param timeout Maximum time to wait in milliseconds
 */
export async function waitForDataTable(page: Page, tableSelector: string, timeout: number = 15000): Promise<boolean> {
  try {
    // Wait for the table element to exist
    await page.waitForSelector(tableSelector, { state: 'attached', timeout });
    
    // Wait for DataTables to initialize
    await page.waitForFunction(
      (selector) => {
        const table = document.querySelector(selector);
        if (!table) return false;
        
        // Check if DataTables has been initialized
        return table.classList.contains('dataTable') || 
               table.classList.contains('table-striped');
      },
      tableSelector,
      { timeout }
    );
    
    // Wait for AJAX data to load - check for rows or "No data" message
    await page.waitForFunction(
      (selector) => {
        const table = document.querySelector(selector);
        if (!table) return false;
        const tbody = table.querySelector('tbody');
        if (!tbody) return false;
        const rows = tbody.querySelectorAll('tr');
        // Either has data rows or shows "No data" message
        return rows.length > 0;
      },
      tableSelector,
      { timeout: 10000 }
    ).catch(() => true); // Empty table is okay
    
    // Additional wait for stability
    await page.waitForTimeout(1000);
    
    return true;
  } catch (error) {
    console.warn(`DataTable ${tableSelector} did not initialize within timeout`);
    return false;
  }
}

// ============================================
// VALIDATION HELPERS
// ============================================

/**
 * Validate price format (supports R, $, commas)
 */
export function isValidPrice(price: string | null): boolean {
  if (!price) return false;
  
  // Remove currency symbols and commas
  const cleanPrice = price.replace(/[R$,\s]/g, '');
  
  try {
    const priceValue = parseFloat(cleanPrice);
    return !isNaN(priceValue) && priceValue >= 0;
  } catch {
    return false;
  }
}

/**
 * Validate date format (supports multiple formats)
 */
export function isValidDate(date: string | null): boolean {
  if (!date) return false;
  
  // Check for common date patterns
  const datePatterns = [
    /^\d{1,2}[/-]\d{1,2}[/-]\d{2,4}$/,  // DD/MM/YYYY or DD-MM-YYYY
    /^\d{4}[/-]\d{1,2}[/-]\d{1,2}$/,    // YYYY/MM/DD or YYYY-MM-DD
  ];
  
  return datePatterns.some(pattern => pattern.test(date));
}

/**
 * Parse price from text (removes currency symbols and commas)
 */
export function parsePrice(priceText: string | null): number {
  if (!priceText) return 0;
  
  const cleanPrice = priceText.replace(/[^0-9.]/g, '');
  return parseFloat(cleanPrice) || 0;
}

// ============================================
// CALCULATION HELPERS
// ============================================

/**
 * Calculate expected total (price * quantity)
 */
export function calculateExpectedTotal(price: number, quantity: number): number {
  return parseFloat((price * quantity).toFixed(2));
}

/**
 * Calculate VAT amount from price including VAT
 */
export function calculateVAT(priceIncl: number, vatRate: number = 0.15): number {
  // VAT = (Price Incl / (1 + VAT Rate)) * VAT Rate
  const priceExcl = priceIncl / (1 + vatRate);
  return parseFloat((priceIncl - priceExcl).toFixed(2));
}

/**
 * Calculate price including VAT
 */
export function calculatePriceIncl(priceExcl: number, vatRate: number = 0.15): number {
  return parseFloat((priceExcl * (1 + vatRate)).toFixed(2));
}

/**
 * Verify two numbers are approximately equal (within tolerance)
 */
export function approximatelyEqual(actual: number, expected: number, tolerance: number = 0.01): boolean {
  return Math.abs(actual - expected) <= tolerance;
}

// ============================================
// CART HELPERS
// ============================================

/**
 * Get cart item count
 */
export async function getCartItemCount(page: Page): Promise<number> {
  const cartRows = page.locator('#cartTable tbody tr:not(.dataTables_empty)');
  return await cartRows.count();
}

/**
 * Get cart total from UI
 */
export async function getCartTotal(page: Page): Promise<number> {
  const totalElement = page.locator('#currentcartTotalPrice');
  const totalText = await totalElement.textContent();
  return parsePrice(totalText);
}

/**
 * Get cart total excluding VAT
 */
export async function getCartTotalExcl(page: Page): Promise<number> {
  const totalElement = page.locator('#currentcartTotalPriceExcl');
  const totalText = await totalElement.textContent();
  return parsePrice(totalText);
}

// ============================================
// CLEANUP FUNCTIONS
// ============================================

/**
 * Clear all items from cart
 * Mirrors Katalon's cart clearing approach
 */
export async function clearCart(page: Page): Promise<void> {
  console.log('🧹 Starting clearCart function...');
  
  // Navigate to shop if not there
  if (!page.url().includes('/shop')) {
    await page.goto('/shop');
    await page.waitForLoadState('load');
    await page.waitForTimeout(2000);
  }
  
  // Wait for cart table
  await page.waitForSelector('#cartTable', { timeout: 10000 }).catch(() => null);
  await page.waitForTimeout(2000);
  
  // First, let's see what we have
  const diagnostics = await page.evaluate(() => {
    const rows = document.querySelectorAll('#cartTable tbody tr');
    const visibleRows = Array.from(rows).filter(row => {
      const style = window.getComputedStyle(row);
      return style.display !== 'none' && !row.classList.contains('dataTables_empty');
    });
    const checkboxes = document.querySelectorAll('#cartTable tbody .cart-item-checkbox') as NodeListOf<HTMLInputElement>;
    const bulkBtn = document.getElementById('bulkDeleteBtn') as HTMLButtonElement;
    const selectAllBtn = document.getElementById('selectAllCartItems') as HTMLInputElement;
    
    return {
      totalRows: rows.length,
      visibleRows: visibleRows.length,
      checkboxCount: checkboxes.length,
      checkboxesVisible: Array.from(checkboxes).map(cb => ({
        visible: window.getComputedStyle(cb).display !== 'none',
        checked: cb.checked,
        disabled: cb.disabled
      })),
      bulkBtnExists: !!bulkBtn,
      bulkBtnDisabled: bulkBtn?.disabled,
      bulkBtnVisible: bulkBtn ? window.getComputedStyle(bulkBtn).display !== 'none' : false,
      selectAllExists: !!selectAllBtn,
      selectAllChecked: selectAllBtn?.checked
    };
  });
  
  console.log('📊 Cart diagnostics:', JSON.stringify(diagnostics, null, 2));
  
  // Check if cart is already empty
  if (diagnostics.visibleRows === 0 || diagnostics.checkboxCount === 0) {
    console.log('✅ Cart already empty');
    return;
  }
  
  // Use JavaScript to directly check all individual cart item checkboxes
  const cleared = await page.evaluate(async () => {
    // Check if cart has items
    const rows = document.querySelectorAll('#cartTable tbody tr');
    if (rows.length === 0) return { success: true, message: 'Cart already empty' };
    
    const firstRow = rows[0];
    if (firstRow.classList.contains('dataTables_empty') || 
        firstRow.textContent?.includes('No data available')) {
      return { success: true, message: 'Cart already empty' };
    }
    
    // Find ALL individual cart item checkboxes
    const itemCheckboxes = document.querySelectorAll('#cartTable tbody .cart-item-checkbox') as NodeListOf<HTMLInputElement>;
    const bulkDeleteBtn = document.getElementById('bulkDeleteBtn') as HTMLButtonElement;
    
    if (itemCheckboxes.length === 0) {
      return { success: false, message: 'No cart item checkboxes found' };
    }
    
    if (!bulkDeleteBtn) {
      return { success: false, message: 'Bulk delete button not found' };
    }
    
    console.log(`📝 Found ${itemCheckboxes.length} cart item checkboxes`);
    
    // Check each individual item checkbox
    itemCheckboxes.forEach((checkbox, index) => {
      console.log(`  - Checking checkbox ${index + 1}/${itemCheckboxes.length}`);
      checkbox.checked = true;
    });
    
    // Manually call updateBulkActionButtons (defined in the page's JavaScript)
    // This is more reliable than dispatching events that jQuery might not catch
    console.log('⏳ Calling updateBulkActionButtons directly...');
    
    // Get the count of checked checkboxes to enable the button
    const selectedCheckboxes = document.querySelectorAll('#cartTable tbody .cart-item-checkbox:checked');
    console.log(`  - Checked checkboxes: ${selectedCheckboxes.length}`);
    
    if (selectedCheckboxes.length > 0) {
      bulkDeleteBtn.disabled = false;
      console.log('  - Enabled bulk delete button');
    } else {
      return { success: false, message: `No checkboxes checked (found ${selectedCheckboxes.length})` };
    }
    
    // Wait a bit for UI to update
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // Check button state
    console.log(`🔘 Bulk delete button disabled: ${bulkDeleteBtn.disabled}`);
    
    // Verify button is enabled before clicking
    if (bulkDeleteBtn.disabled) {
      return { success: false, message: 'Bulk delete button still disabled after checking items' };
    }
    
    // Click bulk delete button
    console.log('🖱️  Clicking bulk delete button...');
    bulkDeleteBtn.click();
    
    return { success: true, message: `Deletion initiated for ${itemCheckboxes.length} items` };
  });
  
  console.log('📋 Cleared result:', cleared);
  
  if (!cleared.success) {
    console.warn('❌ clearCart failed:', cleared.message);
    return;
  }
  
  // Wait for SweetAlert to appear and confirm
  console.log('⏳ Waiting for SweetAlert...');
  await page.waitForTimeout(2000);
  
  // Confirm deletion in SweetAlert using JavaScript
  const confirmed = await page.evaluate(() => {
    const confirmBtn = document.querySelector('.swal2-confirm') as HTMLButtonElement;
    if (confirmBtn) {
      console.log('✅ Found SweetAlert confirm button, clicking...');
      confirmBtn.click();
      return true;
    }
    console.log('❌ SweetAlert confirm button not found');
    return false;
  });
  
  console.log('📋 Confirmed:', confirmed);
  
  // Wait for deletion to complete - wait for spinner to disappear
  console.log('⏳ Waiting for deletion to complete...');
  await page.waitForFunction(() => {
    const btn = document.querySelector('#bulkDeleteBtn');
    if (!btn) return true;
    const isProcessing = btn.innerHTML.includes('fa-spinner') || btn.innerHTML.includes('Deleting');
    if (isProcessing) {
      console.log('🔄 Still processing deletion...');
    }
    return !isProcessing;
  }, { timeout: 30000 }).catch(() => {
    console.warn('⚠️  Timeout waiting for deletion');
  });
  
  // Additional wait for DataTable to reload
  await page.waitForTimeout(3000);
}

/**
 * Delete test orders (placeholder for future implementation)
 */
export async function deleteTestOrders(page: Page): Promise<void> {
  console.log('🧹 Deleting test orders...');
  // TODO: Implement order deletion logic
  console.log('⚠ Order deletion not yet implemented');
}

/**
 * Reset test data (comprehensive cleanup)
 */
export async function resetTestData(page: Page): Promise<void> {
  console.log('🧹 Resetting test data...');
  
  try {
    await clearCart(page);
    await deleteTestOrders(page);
    console.log('✓ Test data reset complete');
  } catch (error) {
    console.error('❌ Error resetting test data:', error);
  }
}

/**
 * Update cleanup tracker
 */
export async function updateCleanupTracker(data: any): Promise<void> {
  const trackerPath = path.join(process.cwd(), 'test-data', 'cleanup-tracker.json');
  
  try {
    // Ensure directory exists
    const dir = path.dirname(trackerPath);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
    
    // Read existing data or create new
    let existing: any = { cartIds: [], orderIds: [], testDataCreated: [] };
    if (fs.existsSync(trackerPath)) {
      const content = fs.readFileSync(trackerPath, 'utf8');
      existing = JSON.parse(content);
    }
    
    // Merge with new data
    const updated = {
      ...existing,
      ...data,
      lastUpdated: new Date().toISOString()
    };
    
    // Write back
    fs.writeFileSync(trackerPath, JSON.stringify(updated, null, 2));
  } catch (error) {
    console.error('Error updating cleanup tracker:', error);
  }
}

// ============================================
// FORM HELPERS
// ============================================

/**
 * Fill a form field and verify value was set
 */
export async function fillAndVerify(page: Page, selector: string, value: string): Promise<void> {
  const field = page.locator(selector);
  await field.fill(value);
  
  // Verify value was set
  const actualValue = await field.inputValue();
  if (actualValue !== value) {
    throw new Error(`Failed to fill field ${selector}. Expected: ${value}, Got: ${actualValue}`);
  }
}

/**
 * Select dropdown option by value
 */
export async function selectDropdown(page: Page, selector: string, value: string): Promise<void> {
  await page.locator(selector).selectOption(value);
}

// ============================================
// DEBUGGING HELPERS
// ============================================

/**
 * Take screenshot with timestamp
 */
export async function takeDebugScreenshot(page: Page, name: string): Promise<void> {
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
  const filename = `debug-${name}-${timestamp}.png`;
  await page.screenshot({ path: `test-results/${filename}`, fullPage: true });
  console.log(`📸 Screenshot saved: ${filename}`);
}

/**
 * Log page console messages for debugging
 */
export function setupConsoleLogging(page: Page): void {
  page.on('console', msg => {
    const type = msg.type();
    if (type === 'error' || type === 'warning') {
      console.log(`[Browser ${type}]:`, msg.text());
    }
  });
}

/**
 * Print test case header (mirrors Katalon output style)
 */
export function printTestCase(caseNumber: number, description: string): void {
  console.log(`\n=== Test Case ${caseNumber}: ${description} ===`);
}

/**
 * Print success message (mirrors Katalon output style)
 */
export function printSuccess(message: string): void {
  console.log(`✓ ${message}`);
}

/**
 * Print warning message
 */
export function printWarning(message: string): void {
  console.log(`⚠ ${message}`);
}

// ============================================
// AUTHENTICATION HELPERS
// ============================================

/**
 * Ensure user is authenticated before proceeding with test
 * Automatically re-authenticates if session is expired
 * 
 * Note: This function should be called BEFORE any test navigation in beforeEach.
 * It checks if auth.json is still valid and re-authenticates if needed.
 * If authentication is required, it will return to the original URL after authenticating.
 */
export async function ensureAuthenticated(page: Page): Promise<void> {
  try {
    const currentUrl = page.url();
    console.log(`🔍 ensureAuthenticated called - Current URL: ${currentUrl}`);
    
    // Debug: Check what cookies are loaded
    const cookies = await page.context().cookies();
    const sessionCookie = cookies.find(c => c.name === 'ci_session');
    if (sessionCookie) {
      console.log(`🔍 Session cookie present: ${sessionCookie.value.substring(0, 10)}..., expires: ${new Date(sessionCookie.expires * 1000).toLocaleString()}`);
    } else {
      console.log(`❌ No session cookie found!`);
    }
    
    // Determine if we need to navigate to check authentication
    const isBlankPage = !currentUrl || currentUrl === 'about:blank';
    const urlHasLogin = currentUrl && (currentUrl.includes('/login') || currentUrl.includes('/auth'));
    
    // Also check if we're on a login page by looking for login form elements
    // Check for the actual login form elements from edi_shopfront
    let hasLoginForm = false;
    if (!isBlankPage) {
      // Look for the specific login form elements: inputEmail and inputPassword
      const emailInput = page.locator('#inputEmail, input[name="inputEmail"]');
      const passwordInput = page.locator('#inputPassword, input[name="inputPassword"]');
      const emailExists = await emailInput.count() > 0;
      const passwordExists = await passwordInput.count() > 0;
      hasLoginForm = emailExists && passwordExists;
      console.log(`🔍 Login form check: hasLoginForm=${hasLoginForm} (email=${emailExists}, password=${passwordExists}), urlHasLogin=${urlHasLogin}`);
    }
    
    const isLoginPage = urlHasLogin || hasLoginForm;
    
    // Store the original URL if it's a valid page (not blank or login)
    const shouldReturnToUrl = !isBlankPage && !isLoginPage;
    const returnUrl = shouldReturnToUrl ? currentUrl : null;
    
    if (isLoginPage && !isBlankPage) {
      console.log(`🔐 Detected login page (URL: ${currentUrl}, hasLoginForm: ${hasLoginForm}), re-authenticating...`);
    }
    
    // Only navigate to check auth if we haven't navigated yet (blank page)
    if (isBlankPage) {
      // Make a request to check authentication - use 'load' to ensure redirects complete
      await page.goto('/', { waitUntil: 'load' });
      await page.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => {
        console.log('⚠ Network idle timeout - continuing with auth check');
      });
      
      // Check if we got redirected to login (by URL or by form presence)
      const finalUrl = page.url();
      const finalEmailInput = page.locator('#inputEmail, input[name="inputEmail"]');
      const finalPasswordInput = page.locator('#inputPassword, input[name="inputPassword"]');
      const finalEmailExists = await finalEmailInput.count() > 0;
      const finalPasswordExists = await finalPasswordInput.count() > 0;
      const finalHasLoginForm = finalEmailExists && finalPasswordExists;
      
      if (finalUrl.includes('/login') || finalUrl.includes('/auth') || finalHasLoginForm) {
        console.log(`🔐 Session expired (URL: ${finalUrl}, hasLoginForm: ${finalHasLoginForm}), re-authenticating...`);
        
        const result = await authenticateUser(page);
        if (!result.success) {
          throw new Error(`Re-authentication failed: ${result.error}`);
        }
        
        console.log('✅ Re-authentication successful');
        
        // Verify we're actually authenticated by checking for login form again
        const postAuthUrl = page.url();
        const postAuthEmailInput = page.locator('#inputEmail, input[name="inputEmail"]');
        const postAuthPasswordInput = page.locator('#inputPassword, input[name="inputPassword"]');
        const stillOnLogin = (await postAuthEmailInput.count() > 0) && (await postAuthPasswordInput.count() > 0);
        
        if (stillOnLogin) {
          console.log(`❌ Still on login page after authentication (URL: ${postAuthUrl})`);
          throw new Error('Re-authentication appeared successful but still on login page');
        }
        
        console.log(`✓ Confirmed authenticated - now at: ${postAuthUrl}`);
        
        // Save the new authentication state for subsequent tests
        await page.context().storageState({ path: 'auth.json' });
        console.log('✓ Updated auth.json with new session');
      }
    } else if (isLoginPage) {
      // We're already on a login page, need to re-authenticate
      console.log('🔐 On login page, re-authenticating...');
      
      const result = await authenticateUser(page);
      if (!result.success) {
        throw new Error(`Re-authentication failed: ${result.error}`);
      }
      
      console.log('✅ Re-authentication successful');
      
      // Verify we're actually authenticated by checking for login form again
      const postAuthUrl = page.url();
      const postAuthEmailInput = page.locator('#inputEmail, input[name="inputEmail"]');
      const postAuthPasswordInput = page.locator('#inputPassword, input[name="inputPassword"]');
      const stillOnLogin = (await postAuthEmailInput.count() > 0) && (await postAuthPasswordInput.count() > 0);
      
      if (stillOnLogin) {
        console.log(`❌ Still on login page after authentication (URL: ${postAuthUrl})`);
        throw new Error('Re-authentication appeared successful but still on login page');
      }
      
      console.log(`✓ Confirmed authenticated - now at: ${postAuthUrl}`);
      
      // Save the new authentication state for subsequent tests
      await page.context().storageState({ path: 'auth.json' });
      console.log('✓ Updated auth.json with new session');
      
      // Navigate back to the original URL if we had one
      if (returnUrl) {
        console.log(`✓ Returning to original URL: ${returnUrl}`);
        await page.goto(returnUrl, { waitUntil: 'load' });
      }
    }
    // If we're on a regular page (not blank, not login), we assume authentication is valid
    
  } catch (error) {
    console.error('❌ Authentication check failed:', error);
    throw error;
  }
}

/**
 * Switch to a branch store for testing regular order functionality
 * Returns true if switched successfully, false if no branch store available
 * 
 * Note: Regular orders can only be placed from branch stores, not head office stores
 */
export async function switchToBranchStore(page: Page): Promise<boolean> {
  try {
    console.log('🏪 Attempting to switch to branch store...');
    
    // Store the current URL to return to it after switching
    const currentUrl = page.url();
    const needsNavigation = !currentUrl || currentUrl === 'about:blank';
    
    // If we're on a blank page, navigate somewhere first
    if (needsNavigation) {
      await page.goto('/', { waitUntil: 'networkidle' });
      await page.waitForLoadState('domcontentloaded');
    }

    // Ensure we're authenticated before attempting to switch stores
    await ensureAuthenticated(page);
    
    // Wait for page to be fully loaded
    await page.waitForLoadState('load');
    await page.waitForLoadState('networkidle', { timeout: 15000 }).catch(() => {
      console.log('⚠ Network idle timeout - continuing anyway');
    });
    
    // Wait for store dropdown to be visible (wait for it to be initialized by JavaScript)
    try {
      await page.waitForSelector('#currentStoreName', { state: 'visible', timeout: 15000 });
      // Wait for store dropdown JavaScript to finish initializing (check for data loaded)
      await page.waitForFunction(() => {
        const dropdown = document.querySelector('#currentStoreName');
        return dropdown && dropdown.textContent && dropdown.textContent.trim().length > 0;
      }, { timeout: 10000 });
    } catch (error) {
      console.log('⚠ Store dropdown not found - user may not have access to multiple stores');
      return false;
    }
    
    // Check if we're already on a branch store (NOT head office)
    const storeBadge = page.locator('#currentStoreName .store-type-badge');
    if (await storeBadge.count() > 0) {
      const badgeText = await storeBadge.textContent();
      if (badgeText && !badgeText.includes('Head Office')) {
        console.log('✅ Already on a branch store');
        return true;
      }
    } else {
      // No badge means it's a branch store
      console.log('✅ Already on a branch store (no Head Office badge)');
      return true;
    }
    
    console.log('✓ Current store is Head Office, searching for branch store...');
    
    // Click on the store dropdown to open it
    await page.click('#currentStoreName');
    
    // Wait for dropdown to be visible
    await page.waitForSelector('#storeDropdown', { state: 'visible', timeout: 5000 });
    
    // Look for a store WITHOUT "Head Office" badge in the dropdown
    const branchStoreItems = page.locator('#storeDropdown .dropdown-item');
    const itemCount = await branchStoreItems.count();
    
    let branchStoreItemIndex = -1;
    for (let i = 0; i < itemCount; i++) {
      const item = branchStoreItems.nth(i);
      const badge = item.locator('.store-type-badge');
      const badgeCount = await badge.count();
      
      if (badgeCount === 0) {
        // No badge means it's a branch store
        branchStoreItemIndex = i;
        break;
      } else {
        const badgeText = await badge.textContent();
        if (badgeText && !badgeText.includes('Head Office')) {
          branchStoreItemIndex = i;
          break;
        }
      }
    }
    
    if (branchStoreItemIndex === -1) {
      console.log('⚠ No branch store found in dropdown');
      return false;
    }
    
    const branchStoreItem = branchStoreItems.nth(branchStoreItemIndex);
    
    // Get the store name and ID for logging and switching
    const storeName = await branchStoreItem.locator('.store-name').textContent();
    const storeId = await branchStoreItem.getAttribute('data-store-id');
    console.log(`✓ Found branch store: ${storeName} (ID: ${storeId})`);
    
    // Click on the branch store to switch
    await branchStoreItem.click();
    
    // Wait for the page to reload after store switch (the switchStore JS function calls window.location.reload())
    await page.waitForLoadState('load');
    await page.waitForLoadState('networkidle', { timeout: 15000 }).catch(() => {
      console.log('⚠ Network idle timeout after store switch - continuing anyway');
    });
    
    // Wait for store dropdown to be visible again after reload
    await page.waitForSelector('#currentStoreName', { state: 'visible', timeout: 10000 });
    
    // Wait for store dropdown to have content (JavaScript initialized)
    await page.waitForFunction(() => {
      const dropdown = document.querySelector('#currentStoreName');
      return dropdown && dropdown.textContent && dropdown.textContent.trim().length > 0;
    }, { timeout: 10000 });
    
    // Verify we switched successfully by checking the badge (should NOT be Head Office)
    const newStoreBadge = page.locator('#currentStoreName .store-type-badge');
    const newBadgeCount = await newStoreBadge.count();
    
    if (newBadgeCount === 0) {
      console.log('✅ Successfully switched to branch store (no Head Office badge)');
      return true;
    } else {
      const newBadgeText = await newStoreBadge.textContent();
      if (newBadgeText && !newBadgeText.includes('Head Office')) {
        console.log('✅ Successfully switched to branch store');
        return true;
      }
    }
    
    console.log('⚠ Store switch may have failed - still showing Head Office badge');
    return false;
    
  } catch (error) {
    console.error('❌ Error switching to branch store:', error);
    return false;
  }
}

/**
 * Switch to a head office store for testing JAB Orders functionality
 * Returns true if switched successfully, false if no head office store available
 * 
 * Note: This function will navigate back to the original URL after switching stores
 * to ensure test context is maintained
 */
export async function switchToHeadOfficeStore(page: Page): Promise<boolean> {
  try {
    console.log('🏢 Attempting to switch to head office store...');
    
    // Store the current URL to return to it after switching
    const currentUrl = page.url();
    const needsNavigation = !currentUrl || currentUrl === 'about:blank';
    
    // If we're on a blank page, navigate somewhere first
    if (needsNavigation) {
      await page.goto('/', { waitUntil: 'networkidle' });
      await page.waitForLoadState('domcontentloaded');
    }

    // Ensure we're authenticated before attempting to switch stores
    await ensureAuthenticated(page);
    
    // Wait for page to be fully loaded
    await page.waitForLoadState('load');
    await page.waitForLoadState('networkidle', { timeout: 15000 }).catch(() => {
      console.log('⚠ Network idle timeout - continuing anyway');
    });
    
    // Wait for store dropdown to be visible (wait for it to be initialized by JavaScript)
    try {
      await page.waitForSelector('#currentStoreName', { state: 'visible', timeout: 15000 });
      // Wait for store dropdown JavaScript to finish initializing (check for data loaded)
      await page.waitForFunction(() => {
        const dropdown = document.querySelector('#currentStoreName');
        return dropdown && dropdown.textContent && dropdown.textContent.trim().length > 0;
      }, { timeout: 10000 });
    } catch (error) {
      console.log('⚠ Store dropdown not found - user may not have access to multiple stores');
      return false;
    }
    
    // Check if we're already on a head office store
    const storeBadge = page.locator('#currentStoreName .store-type-badge');
    if (await storeBadge.count() > 0) {
      const badgeText = await storeBadge.textContent();
      if (badgeText && badgeText.includes('Head Office')) {
        console.log('✅ Already on a head office store');
        return true;
      }
    }
    
    console.log('✓ Current store is not a head office, searching for head office store...');
    
    // Click on the store dropdown to open it
    await page.click('#currentStoreName');
    
    // Wait for dropdown to be visible
    await page.waitForSelector('#storeDropdown', { state: 'visible', timeout: 5000 });
    
    // Wait for dropdown to be populated (it loads via AJAX)
    // Check for dropdown items to appear
    await page.waitForFunction(() => {
      const dropdown = document.querySelector('#storeDropdown');
      const items = dropdown?.querySelectorAll('.dropdown-item:not(.disabled)');
      return items && items.length > 0;
    }, { timeout: 10000 });
    
    console.log('✓ Dropdown populated with stores');
    
    // Wait a bit more for badges to render
    await page.waitForTimeout(1000);
    
    // Look for a store with "Head Office" badge in the dropdown
    const headOfficeStoreItem = page.locator('#storeDropdown .dropdown-item:has(.store-type-badge:has-text("Head Office"))').first();
    
    if (await headOfficeStoreItem.count() === 0) {
      console.log('⚠ No head office store found in dropdown');
      // Log what stores ARE available for debugging
      const allStores = await page.locator('#storeDropdown .dropdown-item .store-name').allTextContents();
      const allBadges = await page.locator('#storeDropdown .dropdown-item .store-type-badge').allTextContents();
      console.log('Available stores:', allStores);
      console.log('Store badges:', allBadges);
      return false;
    }
    
    // Get the store name and ID for logging and switching
    const storeName = await headOfficeStoreItem.locator('.store-name').textContent();
    const storeId = await headOfficeStoreItem.getAttribute('data-store-id');
    console.log(`✓ Found head office store: ${storeName} (ID: ${storeId})`);
    
    // Click on the head office store to switch
    await headOfficeStoreItem.click();
    
    // Wait for the page to reload after store switch (the switchStore JS function calls window.location.reload())
    await page.waitForLoadState('load');
    await page.waitForLoadState('networkidle', { timeout: 15000 }).catch(() => {
      console.log('⚠ Network idle timeout after store switch - continuing anyway');
    });
    
    // Wait for store dropdown to be visible again after reload
    await page.waitForSelector('#currentStoreName', { state: 'visible', timeout: 10000 });
    
    // Wait for store dropdown to have content (JavaScript initialized)
    await page.waitForFunction(() => {
      const dropdown = document.querySelector('#currentStoreName');
      return dropdown && dropdown.textContent && dropdown.textContent.trim().length > 0;
    }, { timeout: 10000 });
    
    // Verify we switched successfully by checking the badge
    const newStoreBadge = page.locator('#currentStoreName .store-type-badge');
    if (await newStoreBadge.count() > 0) {
      const newBadgeText = await newStoreBadge.textContent();
      if (newBadgeText && newBadgeText.includes('Head Office')) {
        console.log('✅ Successfully switched to head office store');
        
        // Navigate to shop page to verify the session is properly set for JAB Orders
        console.log('✓ Verifying session by navigating to shop page...');
        try {
          await page.goto('/shop', { waitUntil: 'domcontentloaded', timeout: 15000 });
          await page.waitForLoadState('load', { timeout: 10000 }).catch(() => {
            console.log('⚠ Load state timeout - continuing anyway');
          });
        
        // Check if JAB Orders button is now visible (this confirms currentStoreID is set correctly in PHP session)
        const jabButton = page.locator('button.jab-order-btn');
          if (await jabButton.isVisible({ timeout: 5000 }).catch(() => false)) {
          console.log('✅ JAB Orders button visible - session properly updated');
          return true;
        } else {
            console.log('⚠ JAB Orders button not visible - checking if page loaded correctly');
            // Even if button not visible, if we're on the shop page, consider it a success
            const currentUrl = page.url();
            if (currentUrl.includes('/shop')) {
              console.log('✅ On shop page - assuming head office switch successful');
              return true;
            }
          return false;
          }
        } catch (error) {
          console.log('⚠ Navigation error during verification:', error.message);
          // If we get an error but we successfully switched stores, still return true
          return true;
        }
      }
    }
    
    console.log('⚠ Store switch may have failed - badge not showing Head Office');
    return false;
    
  } catch (error) {
    console.error('❌ Error switching to head office store:', error);
    return false;
  }
}

