/**
 * 화면 1244 새로고침 검증 (2차)
 * - 3초 대기 후 스크린샷
 * - data-screen-runtime, 테이블 관련 div width 확인
 * - 가로 스크롤 가능 여부 확인
 */

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 main() {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1280, height: 900 } });
  const page = await context.newPage();

  try {
    // 로그인
    await page.goto(`${BASE_URL}/login`, { waitUntil: "load", timeout: 30000 });
    await page.waitForTimeout(1000);
    await page.fill("#userId", "wace");
    await page.fill("#password", "qlalfqjsgh11");
    await page.locator('button[type="submit"]').first().click();
    await page.waitForURL((u) => !u.includes("/login"), { timeout: 15000 }).catch(() => {});
    await page.waitForTimeout(2000);

    // /screens/1244 접속
    await page.goto(`${BASE_URL}/screens/1244`, { waitUntil: "load", timeout: 45000 });
    await page.getByText("로딩중", { exact: false }).waitFor({ state: "hidden", timeout: 10000 }).catch(() => {});
    await page.waitForTimeout(2000);

    // Step 1: 새로고침 (Ctrl+Shift+R)
    console.log("Step 1: 새로고침 (Ctrl+Shift+R)...");
    await page.keyboard.press("Control+Shift+r");
    await page.waitForLoadState("load");
    console.log("Step 2: 3초 대기...");
    await page.waitForTimeout(3000);
    await page.getByText("로딩중", { exact: false }).waitFor({ state: "hidden", timeout: 8000 }).catch(() => {});

    // Step 3: 첫 스크린샷
    await page.screenshot({ path: path.join(SCREENSHOT_DIR, "verify-08.png"), fullPage: true });
    console.log("verify-08.png 저장");

    // Step 4: JavaScript로 width 확인 (순수 함수로 작성)
    const dims = await page.evaluate(() => {
      const screenRuntime = document.querySelector("[data-screen-runtime]");
      const table = document.querySelector("table");
      const tableContainer = table?.closest("[style*='overflow'], [class*='overflow']");
      const overflowHiddenDiv = table?.closest("[style*='overflow-hidden'], [class*='overflow-hidden']");

      const tableAncestors: Array<{ level: number; tag: string; class: string; offsetWidth: number; scrollWidth: number; clientWidth: number; overflowX: string }> = [];
      let p = table?.parentElement;
      let idx = 0;
      while (p && idx < 6) {
        const s = window.getComputedStyle(p);
        tableAncestors.push({
          level: idx,
          tag: p.tagName,
          class: (p.className && typeof p.className === "string" ? p.className : "").slice(0, 60),
          offsetWidth: p.offsetWidth,
          scrollWidth: p.scrollWidth,
          clientWidth: p.clientWidth,
          overflowX: s.overflowX,
        });
        p = p.parentElement;
        idx++;
      }

      return {
        screenRuntime: screenRuntime
          ? { offsetWidth: (screenRuntime as HTMLElement).offsetWidth, scrollWidth: (screenRuntime as HTMLElement).scrollWidth, clientWidth: (screenRuntime as HTMLElement).clientWidth }
          : null,
        table: table
          ? { offsetWidth: (table as HTMLElement).offsetWidth, scrollWidth: (table as HTMLElement).scrollWidth, clientWidth: (table as HTMLElement).clientWidth }
          : null,
        tableContainer: tableContainer
          ? { offsetWidth: (tableContainer as HTMLElement).offsetWidth, scrollWidth: (tableContainer as HTMLElement).scrollWidth, clientWidth: (tableContainer as HTMLElement).clientWidth }
          : null,
        overflowHiddenDiv: overflowHiddenDiv
          ? { offsetWidth: (overflowHiddenDiv as HTMLElement).offsetWidth, scrollWidth: (overflowHiddenDiv as HTMLElement).scrollWidth, clientWidth: (overflowHiddenDiv as HTMLElement).clientWidth }
          : null,
        tableAncestors,
        viewport: { innerWidth: window.innerWidth },
      };
    });

    console.log("\n=== JavaScript 실행 결과 ===");
    console.log("data-screen-runtime div:");
    if (dims.screenRuntime) {
      console.log("  offsetWidth:", dims.screenRuntime.offsetWidth);
      console.log("  scrollWidth:", dims.screenRuntime.scrollWidth);
      console.log("  clientWidth:", dims.screenRuntime.clientWidth);
    } else {
      console.log("  (없음)");
    }
    console.log("\n테이블:");
    if (dims.table) {
      console.log("  offsetWidth:", dims.table.offsetWidth);
      console.log("  scrollWidth:", dims.table.scrollWidth);
    }
    console.log("\n테이블 컨테이너 (overflow):");
    if (dims.tableContainer) {
      console.log("  offsetWidth:", dims.tableContainer.offsetWidth);
      console.log("  scrollWidth:", dims.tableContainer.scrollWidth);
      console.log("  clientWidth:", dims.tableContainer.clientWidth);
    }
    console.log("\noverflow-hidden div:");
    if (dims.overflowHiddenDiv) {
      console.log("  offsetWidth:", dims.overflowHiddenDiv.offsetWidth);
      console.log("  scrollWidth:", dims.overflowHiddenDiv.scrollWidth);
    } else {
      console.log("  (없음)");
    }
    console.log("\n테이블 조상 div들 (width):");
    dims.tableAncestors?.forEach((a) => {
      console.log(`  L${a.level} ${a.tag} overflow=${a.overflowX} offsetW=${a.offsetWidth} scrollW=${a.scrollWidth} clientW=${a.clientWidth}`);
    });

    // Step 5: 가로 스크롤 가능 여부
    const canScroll = dims.table && dims.tableContainer && dims.table.scrollWidth > dims.tableContainer.clientWidth;
    console.log("\n가로 스크롤 가능:", canScroll, "(테이블 scrollWidth > 컨테이너 clientWidth)");

    // Step 6: 최종 스크린샷
    await page.screenshot({ path: path.join(SCREENSHOT_DIR, "verify-09.png"), fullPage: true });
    console.log("\nverify-09.png 저장");

    fs.writeFileSync(
      path.join(SCREENSHOT_DIR, "verify-refresh2-result.json"),
      JSON.stringify({ ...dims, canScroll }, null, 2)
    );
  } catch (error: any) {
    console.error("오류:", error.message);
    await page.screenshot({ path: path.join(SCREENSHOT_DIR, "verify-99-error.png"), fullPage: true }).catch(() => {});
  } finally {
    await browser.close();
  }
}

main();
