/**
 * 화면 1244 새로고침 후 상세 검증
 * - data-screen-runtime, 테이블, body의 scrollWidth/clientWidth 확인
 */

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();

  const results: Record<string, number | string | null> = {};

  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 - hard refresh)
    console.log("Step 1: 새로고침 (Ctrl+Shift+R)...");
    await page.keyboard.press("Control+Shift+r");
    await page.waitForLoadState("load");
    await page.waitForTimeout(3000);
    await page.getByText("로딩중", { exact: false }).waitFor({ state: "hidden", timeout: 10000 }).catch(() => {});

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

    // Step 3: JavaScript로 dimension 확인
    const dims = await page.evaluate(() => {
      const screenRuntime = document.querySelector("[data-screen-runtime]");
      const table = document.querySelector("table");
      const body = document.body;
      const html = document.documentElement;

      const tableContainer = table?.closest("[style*='overflow'], [class*='overflow']") || table?.parentElement;

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

    results.screenRuntime_offsetWidth = dims.screenRuntime?.offsetWidth ?? null;
    results.screenRuntime_scrollWidth = dims.screenRuntime?.scrollWidth ?? null;
    results.screenRuntime_clientWidth = dims.screenRuntime?.clientWidth ?? null;
    results.table_offsetWidth = dims.table?.offsetWidth ?? null;
    results.table_scrollWidth = dims.table?.scrollWidth ?? null;
    results.table_clientWidth = dims.table?.clientWidth ?? null;
    results.tableContainer_clientWidth = dims.tableContainer?.clientWidth ?? null;
    results.tableContainer_scrollWidth = dims.tableContainer?.scrollWidth ?? null;
    results.body_scrollWidth = dims.body.scrollWidth;
    results.body_clientWidth = dims.body.clientWidth;
    results.viewport_innerWidth = dims.viewport.innerWidth;

    // Step 4: 가로 overflow 확인
    const hasOverflow = dims.body.scrollWidth > dims.viewport.innerWidth;
    results.bodyOverflowX = hasOverflow;

    // Step 5: 두 번째 스크린샷
    await page.screenshot({ path: path.join(SCREENSHOT_DIR, "verify-07.png"), fullPage: true });
    console.log("verify-07.png 저장");

    console.log("\n=== 검증 결과 ===");
    console.log("data-screen-runtime div:");
    console.log("  offsetWidth:", results.screenRuntime_offsetWidth);
    console.log("  scrollWidth:", results.screenRuntime_scrollWidth);
    console.log("  clientWidth:", results.screenRuntime_clientWidth);
    console.log("테이블:");
    console.log("  offsetWidth:", results.table_offsetWidth);
    console.log("  scrollWidth:", results.table_scrollWidth);
    console.log("  clientWidth:", results.table_clientWidth);
    console.log("테이블 컨테이너:");
    console.log("  clientWidth:", results.tableContainer_clientWidth);
    console.log("  scrollWidth:", results.tableContainer_scrollWidth);
    console.log("body:");
    console.log("  scrollWidth:", results.body_scrollWidth);
    console.log("  clientWidth:", results.body_clientWidth);
    console.log("뷰포트 innerWidth:", results.viewport_innerWidth);
    console.log("가로 overflow:", results.bodyOverflowX);

    fs.writeFileSync(
      path.join(SCREENSHOT_DIR, "verify-refresh-result.json"),
      JSON.stringify({ ...results, rawDims: dims }, 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();
