/**
 * 화면 1722, 2089 검증: split-panel-layout2
 */

import { chromium } from "playwright";
import * as path from "path";
import * as fs from "fs";

const BASE_URL = "http://localhost:9771";
const SCREENSHOT_DIR = path.join(__dirname, "../verification-screenshots");

async function loginIfNeeded(page: any) {
  if (page.url().includes("/login")) {
    await page.fill("#userId", "wace");
    await page.fill("#password", "qlalfqjsgh11");
    await page.locator('button[type="submit"]').first().click();
    await page.waitForURL((u: URL) => !u.includes("/login"), { timeout: 15000 }).catch(() => {});
    await page.waitForTimeout(2000);
  }
}

async function verifyScreen(
  page: any,
  screenId: number,
  report: Record<string, any>
) {
  await page.goto(`${BASE_URL}/screens/${screenId}`, { waitUntil: "load", timeout: 30000 });
  await page.waitForTimeout(2000);
  if (page.url().includes("/login")) {
    await loginIfNeeded(page);
    await page.goto(`${BASE_URL}/screens/${screenId}`, { waitUntil: "load", timeout: 30000 });
    await page.waitForTimeout(2000);
  }

  await page.getByText("로딩중", { exact: false }).waitFor({ state: "hidden", timeout: 10000 }).catch(() => {});
  await page.waitForTimeout(2000);

  const info = await page.evaluate(() => {
    const splitPanels = document.querySelectorAll("[class*='split'], [class*='Split'], [data-panel], [class*='panel']");
    const hasSplitLayout = document.querySelector("[class*='split-panel'], [class*='SplitPanel'], [data-split]") !== null;
    const panels = document.querySelectorAll("[class*='panel'], [class*='Panel'], [class*='resize']");
    const leftPanelBorder = document.querySelectorAll("[class*='border-r']");
    const bodyText = document.body.innerText;
    const hasLeftRightPanels = bodyText.includes("왼쪽 목록에서") || bodyText.includes("품목 목록") || bodyText.includes("선택하세요");
    const buttons = document.querySelectorAll("button");
    const main = document.querySelector("main") || document.body;
    const mainHeight = (main as HTMLElement).offsetHeight;

    return {
      pageLoadsWithoutErrors: !document.body.innerText.includes("화면을 찾을 수 없습니다"),
      splitPanelCount: splitPanels.length,
      panelCount: panels.length,
      leftPanelBorderCount: leftPanelBorder.length,
      bothPanelsVisible: panels.length >= 2 || splitPanels.length >= 2 || hasSplitLayout || (leftPanelBorder.length >= 1 && hasLeftRightPanels),
      buttonsVisible: buttons.length > 0,
      layoutFillsHeight: mainHeight >= window.innerHeight * 0.7,
      bodyScrollWidth: document.body.scrollWidth,
      bodyScrollHeight: document.body.scrollHeight,
      viewportWidth: window.innerWidth,
      viewportHeight: window.innerHeight,
      hasHorizontalOverflow: document.body.scrollWidth > window.innerWidth,
      hasVerticalOverflow: document.body.scrollHeight > window.innerHeight,
    };
  });

  report.pageLoadsWithoutErrors = info.pageLoadsWithoutErrors;
  report.splitPanelVisible = info.bothPanelsVisible || info.splitPanelCount > 0 || info.panelCount >= 2 || (info.leftPanelBorderCount >= 1 && info.pageLoadsWithoutErrors);
  report.buttonsVisible = info.buttonsVisible;
  report.layoutFillsHeight = info.layoutFillsHeight;
  report.noContentOverflowsViewport = !info.hasHorizontalOverflow;
  report.details = info;

  await page.screenshot({
    path: path.join(SCREENSHOT_DIR, `screen-${screenId}-snapshot.png`),
    fullPage: true,
  });
  console.log(`screen-${screenId}-snapshot.png saved`);
}

async function main() {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1280, height: 900 } });
  const page = await context.newPage();

  const report: Record<string, any> = { screen1722: {}, screen2089: {} };

  try {
    await page.goto(`${BASE_URL}/login`, { waitUntil: "load", timeout: 30000 });
    await page.waitForTimeout(1000);
    await loginIfNeeded(page);
    await page.waitForTimeout(2000);

    await verifyScreen(page, 1722, report.screen1722);
    await verifyScreen(page, 2089, report.screen2089);

    console.log("\n=== Report ===");
    console.log(JSON.stringify(report, null, 2));

    fs.writeFileSync(
      path.join(SCREENSHOT_DIR, "split-panel-screens-report.json"),
      JSON.stringify(report, null, 2)
    );
  } catch (error: any) {
    console.error("Error:", error.message);
    report.error = error.message;
    await page.screenshot({
      path: path.join(SCREENSHOT_DIR, "split-panel-error.png"),
      fullPage: true,
    }).catch(() => {});
  } finally {
    await browser.close();
  }
}

main();
