const { chromium } = require("C:/Users/ramez/AppData/Roaming/npm/node_modules/playwright");

(async () => {
  console.log("Testing Save as Module flow with modal close wait...");
  const browser = await chromium.launch({ headless: true });
  const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });

  await page.goto("http://localhost:3008", { waitUntil: "domcontentloaded" });
  await page.waitForTimeout(1500);

  const bibTab = page.locator("button").filter({ hasText: /^Bibliothèque$/ }).first();

  // 1. Open Bibliothèque tab
  console.log("Opening Bibliothèque tab...");
  await bibTab.click();
  await page.waitForTimeout(800);

  // 2. Click + Poser sur canvas on BaseChiller
  console.log("Clicking + Poser sur canvas on BaseChiller...");
  await page.click("button:has-text('+ Poser sur canvas')");
  await page.waitForTimeout(1000);

  // 3. Click Save as Module button in toolbar
  console.log("Clicking Save as Module button...");
  await page.click("button:has-text('Save as Module')");
  await page.waitForTimeout(800);

  // 4. Fill module name: CustomChiller
  console.log("Entering module name CustomChiller...");
  await page.fill("input[placeholder*='DualChillerCircuit']", "CustomChiller");
  await page.waitForTimeout(500);

  // 5. Click "Créer le Module" and wait for modal to close
  console.log("Clicking Créer le Module...");
  await page.click("button:has-text('Créer le Module')");
  await page.waitForTimeout(1000); // Wait for modal 300ms fadeout & close

  // 6. Verify CustomChiller in Bibliothèque list
  console.log("Opening Bibliothèque tab...");
  await bibTab.click();
  await page.waitForTimeout(1000);

  const screenshotPath = "C:/Users/ramez/.gemini/antigravity-ide/brain/e16f5552-47ce-4483-9b25-8266bb395491/custom_chiller_saved.png";
  await page.screenshot({ path: screenshotPath });
  console.log(`Saved screenshot to ${screenshotPath}`);

  await browser.close();
})();
