/**
 * 화면 1053 검증 - admin/1234 로그인
 */

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 report: Record<string, any> = {};

  try {
    await page.goto(`${BASE_URL}/login`, { waitUntil: "domcontentloaded", timeout: 60000 });
    await page.waitForTimeout(2000);

    await page.fill("#userId", "admin");
    await page.fill("#password", "1234");
    await page.locator('button[type="submit"]').first().click();
    await page.waitForURL((u: URL) => !u.includes("/login"), { timeout: 20000 }).catch(() => {});
    await page.waitForTimeout(3000);

    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: 20000 }).catch(() => {});
      await page.waitForTimeout(3000);
    }

    await page.goto(`${BASE_URL}/screens/1053`, { waitUntil: "domcontentloaded", timeout: 60000 });
    await page.waitForTimeout(3000);
    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: 20000 }).catch(() => {});
      await page.waitForTimeout(3000);
      await page.goto(`${BASE_URL}/screens/1053`, { waitUntil: "domcontentloaded", timeout: 60000 });
      await page.waitForTimeout(3000);
    }

    await page.getByText("화면을 불러오는 중", { exact: false }).waitFor({ state: "hidden", timeout: 35000 }).catch(() => {});
    await page.waitForTimeout(30000);

    const table = page.locator("table tbody tr").first();
    await table.waitFor({ state: "visible", timeout: 20000 }).catch(() => {});
    await page.waitForTimeout(3000);

    const info = await page.evaluate(() => {
      const buttons = Array.from(document.querySelectorAll("button")).filter((b) => {
        const t = (b as HTMLElement).innerText?.trim() || "";
        const r = (b as HTMLElement).getBoundingClientRect();
        return t.length > 1 && r.x > 250;
      });
      const leftPanel = document.querySelector("[class*='border-r']");
      const tables = document.querySelectorAll("table");
      const bodyText = document.body.innerText;

      return {
        buttonCount: buttons.length,
        buttonDetails: buttons.slice(0, 15).map((b) => {
          const r = (b as HTMLElement).getBoundingClientRect();
          return {
            text: (b as HTMLElement).innerText?.trim().substring(0, 30),
            x: Math.round(r.x),
            y: Math.round(r.y),
            width: Math.round(r.width),
            height: Math.round(r.height),
          };
        }),
        splitPanelVisible: !!leftPanel || bodyText.includes("공급처") || bodyText.includes("좌측에서"),
        tableCount: tables.length,
        hasExcelDownload: bodyText.includes("엑셀") || bodyText.includes("다운로드") || bodyText.includes("업로드"),
      };
    });

    report.screen1053 = info;
    await page.screenshot({ path: path.join(SCREENSHOT_DIR, "screen-1053-admin.png"), fullPage: true });
    console.log("screen-1053-admin.png saved");

    fs.writeFileSync(
      path.join(SCREENSHOT_DIR, "screen-1053-admin-report.json"),
      JSON.stringify(report, null, 2)
    );
    console.log("\n=== Report ===");
    console.log(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, "screen-1053-admin-error.png"), fullPage: true }).catch(() => {});
  } finally {
    await browser.close();
  }
}

main();
