/**
 * Complete E2E Test for Staff Careers Dashboard
 * Validates entire workflow with Playwright
 */

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

const STAFF_USERNAME = 'asim';
const STAFF_PASSWORD = 'AsimMawidi2025!';
const BASE_URL = 'http://localhost:9000';

test.describe('Staff Careers Dashboard - Complete E2E', () => {
  test.beforeEach(async ({ page }) => {
    // Login as staff before each test
    await page.goto(`${BASE_URL}/staff/login`);
    await page.getByRole('textbox', { name: 'Username' }).fill(STAFF_USERNAME);
    await page.getByRole('textbox', { name: 'Password' }).fill(STAFF_PASSWORD);
    await page.getByRole('button', { name: 'Sign In' }).click();
    await page.waitForURL(`${BASE_URL}/staff/dashboard`);
  });

  test('should load careers dashboard without errors', async ({ page }) => {
    // Navigate to careers dashboard
    await page.getByRole('link', { name: 'Careers' }).click();
    await page.waitForURL(`${BASE_URL}/staff/dashboard/careers`);

    // Verify page loads
    await expect(page.getByText('Careers Management')).toBeVisible();
    await expect(page.getByRole('button', { name: 'Job Postings' })).toBeVisible();
    await expect(page.getByRole('button', { name: 'Applications' })).toBeVisible();

    // Verify no console errors (specifically no "Briefcase is not defined")
    const errors: string[] = [];
    page.on('console', msg => {
      if (msg.type() === 'error') {
        errors.push(msg.text());
      }
    });

    await page.waitForTimeout(2000);

    // Check for specific error we're preventing
    const hasBriefcaseError = errors.some(err => err.includes('Briefcase is not defined'));
    expect(hasBriefcaseError).toBe(false);
  });

  test('should display jobs list with all data', async ({ page }) => {
    await page.goto(`${BASE_URL}/staff/dashboard/careers`);
    await page.waitForSelector('table');

    // Verify table structure
    await expect(page.getByRole('columnheader', { name: 'Job Title' })).toBeVisible();
    await expect(page.getByRole('columnheader', { name: 'Department' })).toBeVisible();
    await expect(page.getByRole('columnheader', { name: 'Location' })).toBeVisible();
    await expect(page.getByRole('columnheader', { name: 'Status' })).toBeVisible();
    await expect(page.getByRole('columnheader', { name: 'Posted' })).toBeVisible();
    await expect(page.getByRole('columnheader', { name: 'Actions' })).toBeVisible();

    // Verify at least one job row exists
    const rows = page.locator('tbody tr');
    const rowCount = await rows.count();
    expect(rowCount).toBeGreaterThan(0);
  });

  test('should show statistics in Applications tab', async ({ page }) => {
    await page.goto(`${BASE_URL}/staff/dashboard/careers`);

    // Switch to Applications tab
    await page.getByRole('button', { name: 'Applications' }).click();

    // Verify statistics dashboard
    await expect(page.getByText('NEW')).toBeVisible();
    await expect(page.getByText('SHORTLISTED')).toBeVisible();
    await expect(page.getByText('INTERVIEW')).toBeVisible();
    await expect(page.getByText('HIRED')).toBeVisible();
    await expect(page.getByText('REJECTED')).toBeVisible();

    // Verify search and filter controls
    await expect(page.getByPlaceholder('Search by name or email...')).toBeVisible();
    await expect(page.getByRole('button', { name: 'Search' })).toBeVisible();
  });

  test('should open Create Job modal (ADMIN/SUPER_ADMIN only)', async ({ page }) => {
    await page.goto(`${BASE_URL}/staff/dashboard/careers`);

    // Click Create Job button (if visible - depends on role)
    const createButton = page.getByRole('button', { name: 'Create Job' });

    if (await createButton.isVisible()) {
      await createButton.click();

      // Verify modal opens
      await expect(page.getByText('Create New Job Posting')).toBeVisible();
      await expect(page.getByText('Basic Info')).toBeVisible();
      await expect(page.getByText('Job Details')).toBeVisible();
      await expect(page.getByText('Content & Benefits')).toBeVisible();

      // Verify bilingual fields present
      await expect(page.getByText('Job Title (English)')).toBeVisible();
      await expect(page.getByText('العنوان الوظيفي (عربي)')).toBeVisible();
    }
  });

  test('should search and filter jobs', async ({ page }) => {
    await page.goto(`${BASE_URL}/staff/dashboard/careers`);

    // Test search
    await page.getByPlaceholder('Search by job title...').fill('Engineer');
    await page.getByRole('button', { name: 'Search' }).click();
    await page.waitForTimeout(1000);

    // Test status filter
    await page.locator('select').first().selectOption('open');
    await page.getByRole('button', { name: 'Search' }).click();
    await page.waitForTimeout(1000);

    // Verify results (should show only open jobs with "Engineer" in title)
    const rows = page.locator('tbody tr');
    const rowCount = await rows.count();

    if (rowCount > 0) {
      // Verify each visible row has OPEN status
      for (let i = 0; i < rowCount; i++) {
        await expect(rows.nth(i)).toContainText('OPEN');
      }
    }
  });

  test('should handle empty states gracefully', async ({ page }) => {
    await page.goto(`${BASE_URL}/staff/dashboard/careers`);

    // Filter to see only 'draft' jobs (likely none exist)
    await page.locator('select').first().selectOption('draft');
    await page.getByRole('button', { name: 'Search' }).click();
    await page.waitForTimeout(1000);

    // Should show empty state WITHOUT Briefcase error
    // This is the regression test for the original bug
    const pageContent = await page.content();

    // Verify no JavaScript errors in console
    const errors: string[] = [];
    page.on('console', msg => {
      if (msg.type() === 'error') {
        errors.push(msg.text());
      }
    });

    await page.waitForTimeout(1000);

    // No Briefcase error should occur
    const hasBriefcaseError = errors.some(err => err.includes('Briefcase'));
    expect(hasBriefcaseError).toBe(false);
  });

  test('should switch between tabs without errors', async ({ page }) => {
    await page.goto(`${BASE_URL}/staff/dashboard/careers`);

    // Switch to Applications
    await page.getByRole('button', { name: 'Applications' }).click();
    await expect(page.getByText('NEW')).toBeVisible();

    // Switch back to Jobs
    await page.getByRole('button', { name: 'Job Postings' }).click();
    await expect(page.getByRole('columnheader', { name: 'Job Title' })).toBeVisible();

    // No errors should occur during tab switching
    const errors: string[] = [];
    page.on('console', msg => {
      if (msg.type() === 'error' && !msg.text().includes('Download the React DevTools')) {
        errors.push(msg.text());
      }
    });

    await page.waitForTimeout(1000);
    expect(errors.length).toBe(0);
  });
});

test.describe('API Endpoint Validation', () => {
  test('should return proper error for unauthorized access', async ({ request }) => {
    // Test without authentication
    const response = await request.get(`${BASE_URL}/api/staff/jobs`);
    expect(response.status()).toBe(401);

    const data = await response.json();
    expect(data.error).toBe('Unauthorized');
  });

  test('should list jobs for authenticated staff', async ({ page, request }) => {
    // Login first
    await page.goto(`${BASE_URL}/staff/login`);
    await page.getByRole('textbox', { name: 'Username' }).fill(STAFF_USERNAME);
    await page.getByRole('textbox', { name: 'Password' }).fill(STAFF_PASSWORD);
    await page.getByRole('button', { name: 'Sign In' }).click();
    await page.waitForURL(`${BASE_URL}/staff/dashboard`);

    // Get cookies for API call
    const cookies = await page.context().cookies();
    const cookieHeader = cookies.map(c => `${c.name}=${c.value}`).join('; ');

    // Make authenticated API call
    const response = await request.get(`${BASE_URL}/api/staff/jobs`, {
      headers: {
        'Cookie': cookieHeader,
      },
    });

    expect(response.status()).toBe(200);
    const data = await response.json();
    expect(data).toHaveProperty('jobs');
    expect(data).toHaveProperty('pagination');
    expect(Array.isArray(data.jobs)).toBe(true);
  });
});
