import { expect } from '@playwright/test';
import { createBdd } from 'playwright-bdd';
import { TestContext } from '../support/testContext';
import { LoginPage } from '../pages/LoginPage';
import { DashboardPage } from '../pages/DashboardPage';
import { QuestsPage } from '../pages/QuestsPage';
import { MapPage } from '../pages/MapPage';
import { ChatPanel } from '../pages/ChatPanel';
import { BargainingPanel } from '../pages/BargainingPanel';
import { FixtureUtils } from '../utils/fixtureUtils';

/**
 * Declare global fixtures for type safety
 */
declare global {
  namespace NodeJS {
    interface Global {
      fixtures: {
        testContext: TestContext | null;
        loginPage: LoginPage | null;
        dashboardPage: DashboardPage | null;
        questsPage: QuestsPage | null;
        mapPage: MapPage | null;
        chatPanel: ChatPanel | null;
        bargainingPanel: BargainingPanel | null;
        fixtureUtils: typeof FixtureUtils;
        baseUrl: string;
      };
    }
  }
}

/**
 * Initialize global fixtures object
 */
(global as any).fixtures = {
  testContext: null,
  loginPage: null,
  dashboardPage: null,
  questsPage: null,
  mapPage: null,
  chatPanel: null,
  bargainingPanel: null,
  fixtureUtils: FixtureUtils,
  baseUrl: process.env.SUT_URL || 'http://localhost',
};

/**
 * Export BDD step definitions with playwright-bdd
 */
export const { Given, When, Then, Before, After } = createBdd();

/**
 * Initialize page objects before each scenario
 */
Before(async ({ page, context }) => {
  const baseUrl = process.env.SUT_URL || 'http://localhost';
  
  // Create test context
  const testContext = new TestContext(baseUrl);
  testContext.setPage(page);
  testContext.setContext(context);
  
  // Create page objects
  const loginPage = new LoginPage(page, baseUrl);
  const dashboardPage = new DashboardPage(page, baseUrl);
  const questsPage = new QuestsPage(page, baseUrl);
  const mapPage = new MapPage(page, baseUrl);
  const chatPanel = new ChatPanel(page, baseUrl);
  const bargainingPanel = new BargainingPanel(page, baseUrl);
  
  // Store in global fixtures for use in steps
  (global as any).fixtures = {
    testContext,
    loginPage,
    dashboardPage,
    questsPage,
    mapPage,
    chatPanel,
    bargainingPanel,
    fixtureUtils: FixtureUtils,
    baseUrl,
  };
});

/**
 * Clean up after each scenario
 */
After(async () => {
  const fixtures = (global as any).fixtures;
  if (fixtures?.testContext) {
    fixtures.testContext.reset();
  }
});

export { expect };
