const { chromium } = require("playwright");
const { randomUUID } = require("crypto");

(async () => {
  console.log("🎭 Starting Live UI Testing Demo\n");

  const testEmail = `testcompany${randomUUID().slice(0, 8)}@test.com`;
  const testPassword = "TestPass123!";
  const testCompanyName = `Test Company ${randomUUID().slice(0, 6)}`;
  const firstName = "John";
  const lastName = "Doe";

  console.log("📧 Test Email:", testEmail);
  console.log("👤 Name:", firstName, lastName);
  console.log("🏢 Company Name:", testCompanyName);
  console.log("\n🚀 Launching Chromium browser...\n");

  const browser = await chromium.launch({
    headless: false,
    slowMo: 600,
    args: ["--window-size=1400,900"],
  });

  const context = await browser.newContext({
    viewport: { width: 1400, height: 900 },
  });

  const page = await context.newPage();

  try {
    // Step 1: Navigate to signup
    console.log("📍 Step 1: Opening signup page...");
    await page.goto("http://localhost:3001/signup?intent=company");
    await page.waitForTimeout(3000);

    // Step 2: Fill ALL required fields using correct selectors
    console.log("✍️  Step 2: Filling ALL required fields...\n");

    // First Name (id="first-name")
    console.log("   → First Name...");
    await page.fill("#first-name", firstName);
    await page.waitForTimeout(300);

    // Last Name (id="last-name")
    console.log("   → Last Name...");
    await page.fill("#last-name", lastName);
    await page.waitForTimeout(300);

    // Email (id="email")
    console.log("   → Email...");
    await page.fill("#email", testEmail);
    await page.waitForTimeout(300);

    // Password (id="password")
    console.log("   → Password...");
    await page.fill("#password", testPassword);
    await page.waitForTimeout(300);

    // Confirm Password (id="confirm-password")
    console.log("   → Confirm Password...");
    await page.fill("#confirm-password", testPassword);
    await page.waitForTimeout(300);

    // CAPTCHA (id="captcha") - Need to read from canvas
    console.log("   → CAPTCHA...");
    // For demo purposes, we'll need to manually handle this or skip
    // The captcha is drawn on a canvas, we can't easily read it
    // Let's fill a placeholder and see what happens
    await page.fill("#captcha", "TEST12");
    console.log("   ⚠️  Note: CAPTCHA filled with placeholder");
    await page.waitForTimeout(300);

    // Terms Checkbox
    console.log("   → Terms & Conditions...");
    await page.check(".auth-checkbox");
    console.log("   ✅ Terms checked");
    await page.waitForTimeout(300);

    console.log("\n✅ All fields filled!");
    await page.waitForTimeout(1500);

    // Take screenshot before submit
    await page.screenshot({ path: "./test-results/02-signup-filled.png", fullPage: true });

    // Step 3: Check if button is enabled
    console.log("\n📤 Step 3: Checking Sign Up button...");
    const submitBtn = await page.locator(".auth-submit-btn");
    const isDisabled = await submitBtn.isDisabled();

    if (isDisabled) {
      console.log("⚠️  Button is still disabled - CAPTCHA may be invalid");
      console.log("   📝 In real usage, user would need to:");
      console.log("      1. Read the CAPTCHA from the canvas image");
      console.log("      2. Enter the correct CAPTCHA code");
      console.log("      3. Then click Sign Up");

      // For demo, let's try refreshing the captcha and entering a new one
      console.log("   🔄 Refreshing CAPTCHA...");
      await page.click(".auth-captcha-refresh");
      await page.waitForTimeout(1000);

      // Note: We still can't read the canvas captcha programmatically
      // This is where manual intervention is needed in real testing
    }

    console.log("\n⏸️  PAUSED: Manual CAPTCHA entry required");
    console.log("   Please manually:");
    console.log("   1. Look at the CAPTCHA image in the browser");
    console.log("   2. Clear the CAPTCHA field");
    console.log("   3. Enter the correct CAPTCHA code");
    console.log("   4. Click the Sign Up button");
    console.log("   5. Complete the email verification");
    console.log("\n   Browser will stay open for 60 seconds...");
    console.log("   (Take your time to complete the flow manually)");

    // Keep browser open for manual interaction
    await new Promise((resolve) => setTimeout(resolve, 60000));

    // After manual completion, check current URL
    const currentUrl = page.url();
    console.log("\n📍 Current URL after manual flow:", currentUrl);

    // If we reached the dashboard or verification page
    if (currentUrl.includes("dashboard") || currentUrl.includes("verify")) {
      console.log("✅ Signup flow completed!");
      await page.screenshot({ path: "./test-results/03-after-signup.png", fullPage: true });

      // Now check admin panel
      console.log("\n🔐 Opening Admin Panel to check verification...");
      const adminPage = await context.newPage();
      await adminPage.goto("http://localhost:3000/login");
      await adminPage.waitForTimeout(2000);

      // Admin login
      await adminPage.fill('input[type="email"]', "admin@nxtgauge.com");
      await adminPage.fill('input[type="password"]', "admin123");
      await adminPage.click('button[type="submit"]');
      await adminPage.waitForTimeout(3000);

      // Go to verification
      await adminPage.goto("http://localhost:3000/admin/verification");
      await adminPage.waitForTimeout(3000);

      // Search for company
      const searchInput = await adminPage.locator('input[type="search"]').first();
      if (searchInput) {
        await searchInput.fill(testEmail);
        await adminPage.waitForTimeout(2000);
      }

      await adminPage.screenshot({
        path: "./test-results/04-admin-verification.png",
        fullPage: true,
      });
      console.log("📸 Admin screenshot saved");

      const companyFound = await adminPage
        .locator(`text=${testEmail}`)
        .isVisible()
        .catch(() => false);
      if (companyFound) {
        console.log("✅ SUCCESS! Company found in verification queue!");
      } else {
        console.log("⚠️  Company not found - may still be processing");
      }
    }
  } catch (error) {
    console.error("\n❌ Error:", error.message);
    await page.screenshot({ path: "./test-results/error.png", fullPage: true });
  } finally {
    await context.close();
    await browser.close();
    console.log("\n✅ Test completed");
    console.log("📸 Screenshots in ./test-results/");
  }
})();
