const { chromium } = require("C:/Users/ramez/AppData/Roaming/npm/node_modules/playwright");
const path = require("path");
const outDir = process.argv[2] || process.cwd();

(async () => {
  const browser = await chromium.launch({ headless: true });
  const page = await browser.newPage({ viewport: { width: 1600, height: 1000 } });

  const snap = async (name) => {
    const p = path.join(outDir, name);
    await page.screenshot({ path: p, fullPage: false });
    console.log("saved", p);
  };

  try {
    await page.goto("http://localhost:3006", { waitUntil: "networkidle", timeout: 20000 });
    await page.waitForTimeout(2500);
    await snap("01-home-empty.png");

    await page.getByRole("button", { name: "Bibliothèque" }).first().click();
    await page.waitForTimeout(1000);
    await snap("02-library-tab.png");

    // Find example select near "Load" button
    const select = page.locator("select").filter({ hasText: /Chiller/ }).first();
    if (await select.count() > 0) {
      await select.selectOption("chiller_flooded_4port_watercooled.json");
      await page.waitForTimeout(2500);
      await snap("03-example-loaded.png");
    } else {
      console.log("example select not found");
    }

    await page.getByRole("button", { name: /Solve/i }).first().click();
    await page.waitForTimeout(3000);
    await snap("04-after-solve.png");

    // Click an evaporator node label
    try {
      const evap = page.locator("text=evap_1").first();
      await evap.click({ timeout: 3000 });
      await page.waitForTimeout(600);
      await snap("05-properties-panel.png");
    } catch (e) { console.log("evap label click failed:", e.message); }

    await page.getByRole("button", { name: /Guide/i }).first().click();
    await page.waitForTimeout(800);
    await snap("06-guide-modal.png");

    // Click + Nouveau Modèle in library panel
    await page.getByRole("button", { name: /Nouveau Modèle/i }).first().click();
    await page.waitForTimeout(800);
    await snap("07-new-model-modal.png");
  } catch (e) {
    console.error("Error:", e.message);
    await snap("zz-error.png");
  } finally {
    await browser.close();
  }
})();
