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

// Setup: Create screenshots directory if it doesn't exist
const screenshotDir = 'screenshots';
fs.mkdirSync(screenshotDir, { recursive: true });

/**
 * Test Case: Create Zones After Moving Canvas
 */
test('Create zones after moving canvas', async ({ page }) => {
  test.setTimeout(120000); // Increase timeout to 2 minutes

  // 1. Navigate to the application, log in, and set up
  await loginAndSetup(page);

  // 2. Switch to 2D mode
  console.log('Switching to 2D mode...');
  await page.locator('.toggle-option:has-text("2d")').click();

  // 3. Move the canvas to the top position
  await moveCanvas(page);

  // Wait for the canvas to stabilize
  console.log('Waiting for canvas to stabilize...');
  await page.waitForTimeout(5000); // Increased delay to ensure stability

  // Take a screenshot after moving the canvas
  await page.screenshot({ path: `${screenshotDir}/canvas-moved.png` });
  console.log('Canvas moved. Screenshot saved.');

  // 4. Select the zone tool
  console.log('Selecting zone tool...');
  await page.getByTitle('Zone').getByRole('img').click();

  // Define zone paths (start and end points)
  const zonePaths = [
    { start: { x: 172, y: 220 }, end: { x: 292, y: 339 } },
    { start: { x: 328, y: 220 }, end: { x: 441, y: 340 } },
    { start: { x: 470, y: 220 }, end: { x: 593, y: 342 } },
    { start: { x: 174, y: 378 }, end: { x: 289, y: 517 } },
    { start: { x: 327, y: 378 }, end: { x: 442, y: 519 } },
    { start: { x: 468, y: 378 }, end: { x: 593, y: 521 } },
    { start: { x: 699, y: 197 }, end: { x: 801, y: 359 } },
    { start: { x: 913, y: 516 }, end: { x: 1040, y: 644 } },
    { start: { x: 1079, y: 518 }, end: { x: 1205, y: 647 } },
    { start: { x: 912, y: 355 }, end: { x: 1036, y: 473 } },
    { start: { x: 1082, y: 357 }, end: { x: 1203, y: 476 } },
    { start: { x: 916, y: 190 }, end: { x: 1193, y: 333 } },
  ];

  // Create zones using reusable function with increased delays
  await createZones(page, zonePaths);

  // Take a final screenshot after creating zones
  const zonesAfterPath = `${screenshotDir}/zones-created-after-moving-canvas.png`;
  await page.screenshot({ path: zonesAfterPath });
  console.log(`Final screenshot saved at: ${zonesAfterPath}`);
});

/**
 * Test Case: Delete Zones After Moving Canvas
 */
test('Delete zones after moving canvas', async ({ page }) => {
  test.setTimeout(120000); // Increase timeout to 2 minutes

  // 1. Navigate to the application, log in, and set up
  await loginAndSetup(page);

  // 2. Switch to 2D mode
  console.log('Switching to 2D mode...');
  await page.locator('.toggle-option:has-text("2d")').click();

  // 3. Move the canvas to the top position
  await moveCanvas(page);

  // Wait for the canvas to stabilize
  console.log('Waiting for canvas to stabilize...');
  await page.waitForTimeout(5000); // Increased delay to ensure stability

  // Open the "3 dots" menu and select the delete tool
  console.log('Opening three-dot menu...');
  await page.locator('.drop-down-option-button > svg').click();
  console.log('Selecting Delete option...');
  await page.locator('div').filter({ hasText: /^Delete$/ }).first().click();

  // Wait for the delete tool to be active
  await page.waitForTimeout(2000); // Adjust timeout if necessary

  // Define zone paths (same as creation)
  const zonePaths = [
    { start: { x: 172, y: 220 }, end: { x: 292, y: 339 } },
    { start: { x: 328, y: 220 }, end: { x: 441, y: 340 } },
    { start: { x: 470, y: 220 }, end: { x: 593, y: 342 } },
    { start: { x: 174, y: 378 }, end: { x: 289, y: 517 } },
    { start: { x: 327, y: 378 }, end: { x: 442, y: 519 } },
    { start: { x: 468, y: 378 }, end: { x: 593, y: 521 } },
    { start: { x: 699, y: 197 }, end: { x: 801, y: 359 } },
    { start: { x: 913, y: 516 }, end: { x: 1040, y: 644 } },
    { start: { x: 1079, y: 518 }, end: { x: 1205, y: 647 } },
    { start: { x: 912, y: 355 }, end: { x: 1036, y: 473 } },
    { start: { x: 1082, y: 357 }, end: { x: 1203, y: 476 } },
    { start: { x: 916, y: 190 }, end: { x: 1193, y: 333 } },
  ];

  // Delete zones using reusable function with increased delays
  await deleteZones(page, zonePaths);

  // Take a final screenshot after deleting zones
  const afterPath = `${screenshotDir}/zones-deleted-after-moving-canvas.png`;
  await page.screenshot({ path: afterPath });
  console.log(`Final screenshot saved at: ${afterPath}`);
});

/**
 * Reusable function for creating zones.
 * @param {Object} page - Playwright page object
 * @param {Array} zonePaths - Array of {start, end} objects representing zone points
 */
async function createZones(page, zonePaths) {
  console.log('Creating zones...');
  for (const { start, end } of zonePaths) {
    console.log(`Creating zone from (${start.x}, ${start.y}) to (${end.x}, ${end.y})`);
    
    // First click (start point)
    await simulatePointerClick(page, start.x, start.y);
    await page.waitForTimeout(500); // Increased delay after the first click

    // Second click (end point)
    await simulatePointerClick(page, end.x, end.y);
    await page.waitForTimeout(500); // Increased delay after the second click
  }
}

/**
 * Reusable function for deleting zones.
 * @param {Object} page - Playwright page object
 * @param {Array} zonePaths - Array of {start, end} objects representing zone points
 */
async function deleteZones(page, zonePaths) {
  console.log('Deleting zones...');
  for (const { start, end } of zonePaths) {
    console.log(`Deleting zone from (${start.x}, ${start.y}) to (${end.x}, ${end.y})`);
    
    // First click (start point)
    await simulatePointerClick(page, start.x, start.y);
    await page.waitForTimeout(500); // Increased delay after the first click

    // Second click (end point)
    await simulatePointerClick(page, end.x, end.y);
    await page.waitForTimeout(500); // Increased delay after the second click
  }
}

/**
 * Simulates a pointer click at specific coordinates.
 */
async function simulatePointerClick(page, x, y, button = 'left') {
  // Move to the desired position
  await page.mouse.move(x, y);

  // Simulate mouse down and up to mimic a real click
  await page.mouse.down({ button });
  await page.mouse.up({ button });
}

/**
 * Common setup function for logging in and switching to full-screen mode.
 */
async function loginAndSetup(page) {
  // Navigate to the application
  await page.goto('http://185.100.212.76:8200');

  // Log in
  await page.getByPlaceholder('Email').fill('ramkumar@tester.local');
  await page.getByPlaceholder('Password').fill('123456');
  await page.getByRole('button', { name: 'Continue', exact: true }).click();

  // Switch to full-screen mode
  console.log('Switching to full-screen mode...');
  await page.keyboard.press('F11'); // Simulate pressing F11 to enter full-screen mode
}

/**
 * Common function to move the canvas.
 */
async function moveCanvas(page) {
  console.log('Moving canvas to the top position...');
  const canvas = page.locator('canvas').first();
  const canvasBox = await canvas.boundingBox();

  if (!canvasBox) {
    throw new Error('Canvas bounding box not found. Ensure the canvas is visible.');
  }

  // Start position (center of canvas)
  const startX = canvasBox.x + canvasBox.width / 2;
  const startY = canvasBox.y + canvasBox.height / 2;

  // Simulate a drag action to move the canvas
  await page.mouse.move(startX, startY);
  await page.mouse.down();

  // Move the mouse down while dragging
  await page.mouse.move(startX, startY + 100, {
    steps: 20, // Smooth movement
  });

  // Simultaneously scroll the page (if needed)
  await page.mouse.wheel(0, 500); // Scroll down 500px

  await page.mouse.up();
}