const { chromium } = require('playwright');
const path = require('path');
const fs = require('fs');

const screenshotsDir = path.join(__dirname, 'test-screenshots-menu');
if (!fs.existsSync(screenshotsDir)) {
  fs.mkdirSync(screenshotsDir, { recursive: true });
}

let screenshotCount = 0;
const results = [];

async function takeScreenshot(page, name) {
  screenshotCount++;
  const num = screenshotCount.toString().padStart(2, '0');
  const filename = num + '-' + name + '.png';
  const filepath = path.join(screenshotsDir, filename);
  await page.screenshot({ path: filepath, fullPage: true });
  const msg = 'Screenshot: ' + filename;
  console.log(msg);
  results.push(msg);
  return filepath;
}

function logResult(msg) {
  console.log(msg);
  results.push(msg);
}

async function runTest() {
  let browser;
  try {
    logResult('\n========== 기준정보 메뉴 테스트 시작 ==========\n');
    
    browser = await chromium.launch({ headless: false });
    const context = await browser.newContext();
    const page = await context.newPage();
    
    logResult('STEP 1: 페이지 로드 및 로그인 화면 확인');
    await page.goto('http://localhost:3000', { waitUntil: 'networkidle', timeout: 30000 });
    await page.waitForTimeout(2000);
    await takeScreenshot(page, 'step1-login-page');
    logResult('OK - 페이지 로드 완료\n');
    
    logResult('STEP 2: 관리자 계정으로 로그인 (admin/admin123)');
    
    try {
      const userInput = await page.locator('input[type="text"]').first();
      const passInput = await page.locator('input[type="password"]').first();
      
      if (await userInput.count() > 0 && await passInput.count() > 0) {
        await userInput.fill('admin');
        await passInput.fill('admin123');
        logResult('- 로그인 정보 입력 완료');
        
        const loginBtn = await page.locator('button').first();
        await loginBtn.click();
        await page.waitForNavigation({ timeout: 10000 }).catch(() => null);
        await page.waitForTimeout(2000);
        logResult('OK - 로그인 완료\n');
      }
    } catch (e) {
      logResult('WARNING - 로그인 진행 중: ' + e.message + '\n');
    }
    
    await takeScreenshot(page, 'step2-after-login');
    
    logResult('STEP 3: 좌측 메뉴 구조 확인');
    const menuElements = await page.locator('button, a, [role="menuitem"], [class*="menu"]').allTextContents();
    logResult('- 발견된 메뉴 항목들:');
    let menuCount = 0;
    for (let i = 0; i < Math.min(30, menuElements.length); i++) {
      const item = menuElements[i];
      if (item && item.trim().length > 0 && item.length < 50) {
        logResult('  ' + (i + 1) + '. ' + item.trim());
        menuCount++;
      }
    }
    logResult('');
    
    logResult('STEP 4: 기준정보 메뉴 찾기 및 클릭');
    try {
      const basicInfoBtn = await page.locator('text="기준정보"').first();
      if (await basicInfoBtn.count() > 0) {
        logResult('OK - 기준정보 메뉴 발견');
        await basicInfoBtn.click();
        await page.waitForTimeout(1500);
        logResult('OK - 기준정보 메뉴 클릭 완료\n');
      } else {
        logResult('WARNING - 기준정보 메뉴를 찾을 수 없음\n');
      }
    } catch (e) {
      logResult('ERROR - 기준정보 클릭 중 오류: ' + e.message + '\n');
    }
    
    await takeScreenshot(page, 'step3-menu-expanded');
    
    logResult('STEP 5: 서브메뉴 확인');
    const expectedSubmenus = [
      '품목기준관리',
      '공정기준관리',
      '검사기준관리',
      '거래처기준관리',
      '현장기준관리'
    ];
    
    const allPageText = await page.textContent('body');
    logResult('- 서브메뉴 확인 결과:');
    let foundCount = 0;
    for (let i = 0; i < expectedSubmenus.length; i++) {
      const submenu = expectedSubmenus[i];
      const found = allPageText.includes(submenu);
      if (found) foundCount++;
      logResult('  ' + (found ? 'OK' : 'NOT FOUND') + ' - ' + submenu);
    }
    logResult('발견률: ' + foundCount + '/' + expectedSubmenus.length + '\n');
    
    for (let i = 0; i < expectedSubmenus.length; i++) {
      const submenu = expectedSubmenus[i];
      logResult('STEP ' + (6 + i) + ': ' + submenu + ' 테스트');
      
      try {
        const submenuBtn = await page.locator('text="' + submenu + '"').first();
        if (await submenuBtn.count() > 0) {
          logResult('- 메뉴 발견');
          await submenuBtn.click();
          await page.waitForNavigation({ timeout: 5000 }).catch(() => null);
          await page.waitForTimeout(1500);
          logResult('OK - 페이지 로드 완료');
          
          const tabElements = await page.locator('[role="tab"], .tab, [class*="tab"]').allTextContents();
          const expectedTabs = ['계층구조', '섹션', '항목', '속성', '분류', '템플릿 관리'];
          
          logResult('- 탭 확인:');
          let tabCount = 0;
          for (let j = 0; j < expectedTabs.length; j++) {
            const tab = expectedTabs[j];
            const hasTab = tabElements.some(t => t && t.includes(tab));
            if (hasTab) {
              logResult('    OK - ' + tab);
              tabCount++;
            } else {
              logResult('    NOT FOUND - ' + tab);
            }
          }
          logResult('발견된 탭: ' + tabCount + '/' + expectedTabs.length + '\n');
        } else {
          logResult('WARNING - 메뉴를 찾을 수 없음\n');
        }
      } catch (e) {
        logResult('ERROR - ' + e.message + '\n');
      }
      
      const safeMenuName = submenu.replace(/\s+/g, '_');
      await takeScreenshot(page, 'step' + (6 + i) + '-' + safeMenuName);
    }
    
    logResult('========== 테스트 완료 ==========');
    logResult('스크린샷 저장 위치: ' + screenshotsDir);
    logResult('총 스크린샷: ' + screenshotCount);
    
    const reportPath = path.join(__dirname, 'TEST_MENU_RESULT.txt');
    fs.writeFileSync(reportPath, results.join('\n'));
    logResult('상세 리포트: ' + reportPath);
    
    await context.close();
    await browser.close();
    
  } catch (error) {
    logResult('\nERROR: ' + error.message);
    logResult(error.stack);
    if (browser) await browser.close();
    process.exit(1);
  }
}

runTest();
