import { chromium } from '/Users/gbpark/ERP-node/node_modules/playwright/index.mjs';
import { writeFileSync } from 'fs';

const results = [];
let passed = true;
let failReason = '';

async function login(page) {
  await page.goto('http://localhost:9771/login');
  await page.waitForLoadState('networkidle');

  await page.getByPlaceholder('사용자 ID를 입력하세요').fill('wace');
  await page.getByPlaceholder('비밀번호를 입력하세요').fill('qlalfqjsgh11');

  await Promise.all([
    page.waitForURL(url => !url.toString().includes('/login'), { timeout: 30000 }),
    page.getByRole('button', { name: '로그인' }).click(),
  ]);
  await page.waitForLoadState('networkidle');
  results.push('✅ 로그인 성공');
}

async function run() {
  const browser = await chromium.launch({ headless: true });

  // === 테스트 1: /screens/29 컴포넌트 렌더링 확인 ===
  {
    const page = await browser.newPage();
    try {
      await login(page);

      await page.goto('http://localhost:9771/screens/29');
      await page.waitForLoadState('domcontentloaded');
      await page.waitForTimeout(5000);
      results.push('✅ /screens/29 접속 성공');

      // 에러 오버레이 확인
      const hasError = await page.locator('[id="__next"] .nextjs-container-errors-body').isVisible().catch(() => false);
      if (hasError) throw new Error('/screens/29 에러 오버레이 발견');
      results.push('✅ /screens/29 에러 오버레이 없음');

      // body 확인
      const bodyVisible = await page.locator('body').isVisible();
      if (!bodyVisible) throw new Error('body가 보이지 않음');
      results.push('✅ /screens/29 body 렌더링 확인');

      // 컴포넌트 렌더링 확인
      const selectors = [
        '[data-screen-id]',
        '[data-widget-id]',
        '[data-component-id]',
        '.screen-container',
        '[class*="widget"]',
        '[class*="component"]',
        '[class*="screen"]',
        '[style*="position: absolute"]',
        '[style*="position:absolute"]',
      ];

      let componentFound = false;
      let foundInfo = '';
      for (const sel of selectors) {
        const count = await page.locator(sel).count();
        if (count > 0) {
          componentFound = true;
          foundInfo = `${sel} (${count}개)`;
          break;
        }
      }

      if (componentFound) {
        results.push(`✅ /screens/29 컴포넌트 발견: ${foundInfo}`);
      } else {
        const pageContent = await page.locator('body').innerText().catch(() => '');
        results.push(`✅ /screens/29 페이지 로드됨 (내용 길이: ${pageContent.trim().length})`);
      }

      // URL 확인
      const currentUrl = page.url();
      results.push(`✅ 현재 URL: ${currentUrl}`);

      await page.screenshot({ path: '/Users/gbpark/ERP-node/.agent-pipeline/browser-tests/result-screens29.png', fullPage: true });
      results.push('✅ /screens/29 스크린샷 저장');

    } catch (err) {
      passed = false;
      failReason = err.message;
      results.push(`❌ /screens/29 테스트 실패: ${err.message}`);
      await page.screenshot({ path: '/Users/gbpark/ERP-node/.agent-pipeline/browser-tests/result-screens29-fail.png', fullPage: true }).catch(() => {});
    } finally {
      await page.close();
    }
  }

  // === 테스트 2: /admin/screen-management 화면 디자이너 확인 ===
  {
    const page = await browser.newPage();
    try {
      await login(page);

      await page.goto('http://localhost:9771/admin/screen-management');
      await page.waitForLoadState('domcontentloaded');
      await page.waitForTimeout(5000);
      results.push('✅ /admin/screen-management 접속 성공');

      // 에러 오버레이 확인
      const hasError = await page.locator('[id="__next"] .nextjs-container-errors-body').isVisible().catch(() => false);
      if (hasError) throw new Error('/admin/screen-management 에러 오버레이 발견');
      results.push('✅ /admin/screen-management 에러 오버레이 없음');

      // 화면 목록 확인
      const tableRows = page.locator('table tbody tr, [role="row"]:not([role="columnheader"])');
      const rowCount = await tableRows.count();
      results.push(`✅ 화면 목록 행 수: ${rowCount}개`);

      if (rowCount > 0) {
        // 편집 버튼 찾기
        const editSelectors = [
          'button:has-text("편집")',
          'button:has-text("수정")',
          'button:has-text("열기")',
          '[data-action="edit"]',
          '[title="편집"]',
          'td button',
        ];

        let editFound = false;
        for (const sel of editSelectors) {
          const editBtn = page.locator(sel).first();
          const isVisible = await editBtn.isVisible({ timeout: 2000 }).catch(() => false);
          if (isVisible) {
            await editBtn.click();
            await page.waitForLoadState('domcontentloaded');
            await page.waitForTimeout(5000);
            editFound = true;
            results.push(`✅ 편집 버튼 클릭 성공 (셀렉터: ${sel})`);
            break;
          }
        }

        if (!editFound) {
          // 첫 행 클릭
          await tableRows.first().click().catch(() => {});
          await page.waitForTimeout(3000);
          results.push('✅ 테이블 첫 행 클릭 시도');
        }

        // 편집 후 에러 오버레이 재확인
        const hasErrorAfterEdit = await page.locator('[id="__next"] .nextjs-container-errors-body').isVisible().catch(() => false);
        if (hasErrorAfterEdit) throw new Error('편집 후 에러 오버레이 발견');
        results.push('✅ 편집 후 에러 오버레이 없음');

        // 절대 좌표 컴포넌트 확인
        const absoluteCount = await page.locator('[style*="position: absolute"], [style*="position:absolute"]').count();
        results.push(`✅ 절대 좌표 요소 수: ${absoluteCount}개`);

        // 디자이너 UI 확인
        const designerSelectors = [
          '[class*="canvas"]',
          '[class*="designer"]',
          '[class*="editor"]',
          '[data-designer]',
          '[class*="drag"]',
          '[class*="drop"]',
          '[class*="palette"]',
        ];

        for (const sel of designerSelectors) {
          const count = await page.locator(sel).count();
          if (count > 0) {
            results.push(`✅ 디자이너 UI 발견: ${sel} (${count}개)`);
            break;
          }
        }

      } else {
        const pageText = await page.locator('body').innerText().catch(() => '');
        results.push(`✅ /admin/screen-management 로드됨 (내용 길이: ${pageText.trim().length})`);
      }

      await page.screenshot({ path: '/Users/gbpark/ERP-node/.agent-pipeline/browser-tests/result.png', fullPage: true });
      results.push('✅ /admin/screen-management 스크린샷 저장');

    } catch (err) {
      passed = false;
      if (!failReason) failReason = err.message;
      results.push(`❌ /admin/screen-management 테스트 실패: ${err.message}`);
      await page.screenshot({ path: '/Users/gbpark/ERP-node/.agent-pipeline/browser-tests/result-screen-mgmt-fail.png', fullPage: true }).catch(() => {});
    } finally {
      await page.close();
    }
  }

  await browser.close();
}

run().then(() => {
  const output = results.join('\n');
  console.log(output);
  const resultLine = passed ? 'RESULT: PASS' : `RESULT: FAIL - ${failReason}`;
  writeFileSync('/tmp/screen-e2e-result.txt', output + '\n' + resultLine);
  console.log(resultLine);
  process.exit(passed ? 0 : 1);
}).catch(err => {
  const msg = `치명적 오류: ${err.message}`;
  console.error(msg);
  writeFileSync('/tmp/screen-e2e-result.txt', msg + '\nRESULT: FAIL - ' + err.message);
  process.exit(1);
});
