/**
 * 화면 1244 검증: 테이블, 가로 스크롤, 페이지네이션 확인
 */

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, boolean | string> = {};

  try {
    // Step 1: 로그인 먼저 (Playwright는 새 브라우저)
    console.log("Step 1: 로그인...");
    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);

    // Step 2: /screens/1244 접속
    console.log("Step 2: /screens/1244 접속...");
    await page.goto(`${BASE_URL}/screens/1244`, { waitUntil: "load", timeout: 45000 });
    await page.waitForTimeout(2000);

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

    // Step 2: 화면 로드 스크린샷
    await page.screenshot({ path: path.join(SCREENSHOT_DIR, "verify-01-initial.png"), fullPage: true });
    console.log("verify-01-initial.png 저장");

    // Step 3: 테이블 확인
    const table = page.locator("table").first();
    const tableCount = await table.count();
    results.tableVisible = tableCount > 0;
    console.log("테이블 보임:", results.tableVisible);

    // Step 4: 가로 스크롤바 확인
    const scrollContainer = page.locator("[class*='overflow'], .overflow-x-auto, [style*='overflow']").first();
    const hasScrollContainer = (await scrollContainer.count()) > 0;
    let scrollWidth = 0;
    let clientWidth = 0;
    if (results.tableVisible) {
      scrollWidth = await table.evaluate((el) => el.scrollWidth);
      clientWidth = await table.evaluate((el) => el.clientWidth);
      results.tableScrollWidth = String(scrollWidth);
      results.tableClientWidth = String(clientWidth);
      results.horizontalScrollNeeded = scrollWidth > clientWidth;
    }
    console.log("테이블 scrollWidth:", scrollWidth, "clientWidth:", clientWidth);

    // Step 5: 테이블 영역 오른쪽 스크롤 시도 (overflow-auto인 조상 요소 찾기)
    if (results.tableVisible) {
      try {
        const scrollableAncestor = await table.evaluateHandle((el) => {
          let parent: HTMLElement | null = el.parentElement;
          while (parent) {
            const style = getComputedStyle(parent);
            if (style.overflowX === "auto" || style.overflowX === "scroll" || style.overflow === "auto") {
              return parent;
            }
            parent = parent.parentElement;
          }
          return el.parentElement;
        });
        const scrollEl = scrollableAncestor.asElement();
        if (scrollEl) {
          await scrollEl.evaluate((el) => (el.scrollLeft = 300));
          await page.waitForTimeout(500);
        }
      } catch (_) {}
    }
    await page.screenshot({ path: path.join(SCREENSHOT_DIR, "verify-02-after-scroll.png"), fullPage: true });
    console.log("verify-02-after-scroll.png 저장");

    // Step 6: 페이지네이션 확인
    const paginationText = page.getByText("표시", { exact: false }).or(page.getByText("1/1", { exact: false }));
    results.paginationVisible = (await paginationText.count()) > 0;
    console.log("페이지네이션 보임:", results.paginationVisible);

    // Step 7: 테이블이 뷰포트에 맞는지 (overflow 확인)
    const bodyOverflow = await page.evaluate(() => {
      const main = document.querySelector("main") || document.body;
      return window.getComputedStyle(main).overflowX;
    });
    results.bodyOverflowX = bodyOverflow;

    // Step 8: 중간 스크린샷 (테이블 + 페이지네이션 영역)
    await page.screenshot({ path: path.join(SCREENSHOT_DIR, "verify-03-mid.png"), fullPage: true });
    console.log("verify-03-mid.png 저장");

    // Step 9: 페이지 하단으로 스크롤 (페이지네이션 바 확인)
    await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
    await page.waitForTimeout(500);
    await page.screenshot({ path: path.join(SCREENSHOT_DIR, "verify-04-pagination-area.png"), fullPage: true });
    console.log("verify-04-pagination-area.png 저장");

    // Step 10: 최종 스크린샷
    await page.evaluate(() => window.scrollTo(0, 0));
    await page.waitForTimeout(300);
    await page.screenshot({ path: path.join(SCREENSHOT_DIR, "verify-05-final.png"), fullPage: true });
    console.log("verify-05-final.png 저장");

    fs.writeFileSync(
      path.join(SCREENSHOT_DIR, "verify-result.json"),
      JSON.stringify(results, null, 2)
    );
    console.log("\n검증 결과:", results);
  } 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();
