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

const screenshotsDir = path.join(__dirname, 'test-screenshots-menu-detailed');
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);
    
    logResult('Step 2: 로그인');
    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');
        
        const loginBtn = await page.locator('button').first();
        await loginBtn.click();
        await page.waitForNavigation({ timeout: 10000 }).catch(() => null);
        await page.waitForTimeout(2000);
        logResult('로그인 완료');
      }
    } catch (e) {
      logResult('로그인 오류: ' + e.message);
    }
    
    logResult('\nStep 3: 좌측 메뉴 전체 구조 분석');
    
    // 모든 메뉴 요소 추출
    const menuStructure = await page.evaluate(() => {
      const result = [];
      
      // 사이드바의 모든 li 요소
      const sidebarItems = document.querySelectorAll('aside li, nav li, [class*="sidebar"] li, [class*="menu"] li');
      
      sidebarItems.forEach((item, idx) => {
        const text = item.textContent?.trim() || '';
        const hasArrow = item.querySelector('svg') ? 'has-icon' : 'no-icon';
        const level = item.parentElement?.tagName === 'UL' ? 'sub' : 'main';
        
        if (text && text.length > 0 && text.length < 100) {
          result.push({
            index: idx,
            text: text,
            hasIcon: hasArrow,
            level: level,
            classes: item.className
          });
        }
      });
      
      // 버튼 형식의 메뉴
      const buttons = document.querySelectorAll('button');
      buttons.forEach((btn, idx) => {
        const text = btn.textContent?.trim() || '';
        if (text && text.includes('관리') && text.length < 50) {
          result.push({
            type: 'button',
            index: idx,
            text: text,
            classes: btn.className
          });
        }
      });
      
      return result;
    });
    
    logResult('\n발견된 메뉴 구조:');
    menuStructure.forEach((item, idx) => {
      const prefix = item.level === 'sub' ? '  └─' : '►';
      logResult(prefix + ' ' + item.text);
    });
    
    logResult('\nStep 4: 기준정보 메뉴 클릭 및 상태 확인');
    
    const basicInfoElement = await page.locator('text="기준정보"').first();
    if (await basicInfoElement.count() > 0) {
      logResult('기준정보 메뉴 발견');
      
      // 현재 상태 확인
      const isExpanded = await basicInfoElement.evaluate((el) => {
        return el.parentElement?.getAttribute('class')?.includes('expanded') ||
               el.parentElement?.getAttribute('aria-expanded') === 'true' ||
               el.nextElementSibling?.style.display !== 'none';
      });
      
      logResult('현재 확장 상태: ' + (isExpanded ? '펼쳐짐' : '접혀있음'));
      
      // 클릭
      await basicInfoElement.click();
      await page.waitForTimeout(1000);
      
      logResult('메뉴 클릭 완료');
    }
    
    await takeScreenshot(page, '01-after-click-standard-info');
    
    logResult('\nStep 5: 클릭 후 메뉴 구조 재분석');
    
    const afterClickStructure = await page.evaluate(() => {
      const result = [];
      const sidebarItems = document.querySelectorAll('aside li, nav li, [class*="sidebar"] li, [class*="menu"] li');
      
      sidebarItems.forEach((item) => {
        const text = item.textContent?.trim() || '';
        if (text && text.length > 0 && text.length < 100) {
          result.push(text);
        }
      });
      
      return result;
    });
    
    logResult('\n클릭 후 메뉴 항목:');
    afterClickStructure.forEach((text) => {
      logResult('  - ' + text);
    });
    
    logResult('\nStep 6: 예상 서브메뉴 검색');
    
    const expectedSubmenus = [
      '품목기준관리',
      '공정기준관리',
      '검사기준관리',
      '거래처기준관리',
      '현장기준관리'
    ];
    
    const pageContent = await page.content();
    
    logResult('예상 메뉴들의 존재 여부:');
    expectedSubmenus.forEach(submenu => {
      const found = pageContent.includes(submenu);
      logResult('  ' + (found ? 'FOUND' : 'NOT FOUND') + ' - ' + submenu);
    });
    
    logResult('\nStep 7: 기준정보 메뉴 구조 상세 분석');
    
    const basicInfoDetails = await page.evaluate(() => {
      const basicInfoBtn = Array.from(document.querySelectorAll('button, a, li, div')).find(el => 
        el.textContent?.trim() === '기준정보'
      );
      
      if (!basicInfoBtn) return null;
      
      const parent = basicInfoBtn.parentElement;
      const siblings = parent?.parentElement?.querySelectorAll('li, div[class*="submenu"]');
      
      const result = {
        menuFound: true,
        parent: parent?.tagName,
        parentClass: parent?.className,
        siblingCount: siblings?.length || 0,
        siblingTexts: []
      };
      
      if (siblings) {
        Array.from(siblings).forEach(sib => {
          const text = sib.textContent?.trim() || '';
          if (text && text.length < 100) {
            result.siblingTexts.push(text);
          }
        });
      }
      
      return result;
    });
    
    if (basicInfoDetails) {
      logResult('기준정보 메뉴 상세 정보:');
      logResult('  부모 요소: ' + basicInfoDetails.parent);
      logResult('  부모 클래스: ' + basicInfoDetails.parentClass);
      logResult('  형제 요소 수: ' + basicInfoDetails.siblingCount);
      logResult('  형제 요소 텍스트들:');
      basicInfoDetails.siblingTexts.forEach(text => {
        logResult('    - ' + text);
      });
    }
    
    logResult('\n========== 상세 분석 완료 ==========\n');
    
    const reportPath = path.join(__dirname, 'TEST_MENU_DETAILED_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();
