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

const screenshotsDir = path.join(__dirname, 'test-screenshots-correct');
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('ERROR - 로그인 진행 중: ' + e.message + '\n');
    }
    
    await takeScreenshot(page, 'step2-after-login');
    
    logResult('STEP 3: 좌측 메뉴 구조 분석');
    
    // 첫 번째 메뉴 항목 찾기 (기준정보)
    const firstMenuItems = await page.locator('nav button').all();
    logResult('- 발견된 최상위 메뉴 항목:');
    
    for (let i = 0; i < Math.min(10, firstMenuItems.length); i++) {
      const text = await firstMenuItems[i].textContent();
      if (text && text.trim().length > 0) {
        logResult('  ' + (i + 1) + '. ' + text.trim());
      }
    }
    logResult('');
    
    logResult('STEP 4: 기준정보 메뉴 클릭 및 서브메뉴 펼치기');
    
    try {
      // 기준정보 메뉴 찾기 - 정확한 선택자 사용
      const standardInfoBtn = await page.locator('nav').first().locator('button').first();
      const standardInfoText = await standardInfoBtn.textContent();
      
      logResult('- 클릭할 메뉴: ' + standardInfoText.trim());
      await standardInfoBtn.click();
      await page.waitForTimeout(1500);
      logResult('OK - 메뉴 클릭 완료\n');
    } catch (e) {
      logResult('ERROR - 메뉴 클릭 오류: ' + e.message + '\n');
    }
    
    await takeScreenshot(page, 'step3-menu-expanded');
    
    logResult('STEP 5: 서브메뉴 확인');
    
    // 펼쳐진 메뉴 구조 분석
    const subMenuStructure = await page.evaluate(() => {
      const nav = document.querySelector('nav');
      if (!nav) return [];
      
      const items = [];
      const buttons = nav.querySelectorAll('button');
      
      buttons.forEach(btn => {
        const text = btn.textContent?.trim() || '';
        if (text && text.length > 0) {
          // 아이콘 확인
          const hasIcon = btn.querySelector('svg') ? true : false;
          // 배치 확인
          const rect = btn.getBoundingClientRect();
          const style = window.getComputedStyle(btn);
          
          items.push({
            text: text,
            hasIcon: hasIcon,
            isVisible: style.display !== 'none' && rect.height > 0,
            indentLevel: btn.parentElement?.className.includes('pl-') ? 'sub' : 'main'
          });
        }
      });
      
      return items;
    });
    
    logResult('- 메뉴 항목 목록:');
    const expectedSubmenus = [
      '품목기준관리',
      '공정기준관리',
      '검사기준관리',
      '거래처기준관리',
      '현장기준관리'
    ];
    
    let foundCount = 0;
    subMenuStructure.forEach((item, idx) => {
      const isExpected = expectedSubmenus.some(sub => item.text.includes(sub) || sub.includes(item.text.substring(0, 3)));
      const marker = isExpected ? '[EXPECTED]' : '         ';
      logResult('  ' + marker + ' ' + item.text);
      
      if (isExpected) foundCount++;
    });
    
    logResult('\n발견된 예상 메뉴: ' + foundCount + '/' + expectedSubmenus.length);
    logResult('\n예상 메뉴 상세 확인:');
    
    expectedSubmenus.forEach(submenu => {
      const found = subMenuStructure.some(item => item.text === submenu);
      logResult('  ' + (found ? 'OK' : 'NOT FOUND') + ' - ' + submenu);
    });
    logResult('');
    
    // 각 메뉴 클릭 테스트
    logResult('STEP 6-10: 각 서브메뉴 클릭 및 페이지 로드 확인');
    
    for (let i = 0; i < expectedSubmenus.length; i++) {
      const submenu = expectedSubmenus[i];
      logResult('\nSub-Step ' + (i + 1) + ': ' + submenu + ' 테스트');
      
      try {
        // 정확한 메뉴 찾기
        const submenuBtn = await page.locator('nav').first().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 tabs = await page.locator('[role="tab"], .tab, [class*="tab"], button[class*="tab"]').allTextContents();
          const expectedTabs = ['계층구조', '섹션', '항목', '속성', '분류', '템플릿 관리'];
          
          const foundTabs = expectedTabs.filter(tab => tabs.some(t => t.includes(tab)));
          
          logResult('- 탭 발견: ' + foundTabs.length + '/' + expectedTabs.length);
          foundTabs.forEach(tab => {
            logResult('  ✓ ' + tab);
          });
          
          expectedTabs.filter(tab => !foundTabs.includes(tab)).forEach(tab => {
            logResult('  ✗ ' + tab);
          });
          
        } else {
          logResult('WARNING - 메뉴를 찾을 수 없음');
        }
      } catch (e) {
        logResult('ERROR - ' + e.message);
      }
      
      const safeMenuName = submenu.replace(/\s+/g, '_');
      await takeScreenshot(page, 'step' + (6 + i) + '-' + safeMenuName);
    }
    
    logResult('\n========== 테스트 완료 ==========');
    logResult('스크린샷 저장: ' + screenshotsDir);
    logResult('총 스크린샷: ' + screenshotCount);
    
    const reportPath = path.join(__dirname, 'TEST_MENU_FINAL_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();
