import { chromium } from 'playwright';
import { mkdirSync } from 'fs';

const screenshotDir = 'C:/tmp/playwright_screenshots';
mkdirSync(screenshotDir, { recursive: true });

const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({ viewport: { width: 1400, height: 900 } });
const page = await context.newPage();

async function screenshot(name) {
  const path = `${screenshotDir}/${name}.png`;
  await page.screenshot({ path, fullPage: false });
  console.log(`  [Screenshot: ${name}.png]`);
}

async function screenshotFull(name) {
  const path = `${screenshotDir}/${name}.png`;
  await page.screenshot({ path, fullPage: true });
  console.log(`  [Screenshot (full): ${name}.png]`);
}

// Login flow
console.log('\n=== Login ===');
await page.goto('http://localhost:3000/fertilizer/new');
await page.waitForLoadState('networkidle');
if (page.url().includes('/login')) {
  await page.fill('#username', 'akira');
  await page.fill('input[type="password"]', 'keina2025');
  await page.click('button[type="submit"]');
  await page.waitForNavigation({ timeout: 10000 }).catch(() => {});
  await page.waitForLoadState('networkidle');
  await page.goto('http://localhost:3000/fertilizer/new');
  await page.waitForLoadState('networkidle');
}
console.log('On page:', page.url());

// Step 3: Select variety "にこまる"
console.log('\n=== Step 3: Select 品種 "にこまる" ===');
// Find the 品種 select (second select - first is year)
const selects = await page.locator('select').all();
console.log('Number of select elements:', selects.length);
// The variety select should contain "にこまる"
for (let i = 0; i < selects.length; i++) {
  const options = await selects[i].locator('option').allTextContents();
  console.log(`Select[${i}] options:`, options.join(', '));
}

// Select にこまる
await selects[1].selectOption({ label: 'にこまる' });
await page.waitForTimeout(2000); // Wait for any async updates
await screenshotFull('step3_variety_selected');
console.log('Selected にこまる');

// Check if any fields were auto-added
const allText = await page.locator('body').textContent();
const relevantText = allText?.replace(/\s+/g, ' ').substring(0, 500);
console.log('Page text after variety select:', relevantText);

// Step 4: Add fertilizer by clicking "+ 肥料を追加"
console.log('\n=== Step 4: Click "+ 肥料を追加" ===');
// Find the button
const addBtn = page.locator('button').filter({ hasText: '肥料を追加' }).first();
const addBtnVisible = await addBtn.isVisible();
console.log('Add fertilizer button visible:', addBtnVisible);

if (addBtnVisible) {
  await addBtn.click();
  await page.waitForTimeout(1000);
  await screenshotFull('step4_after_add_click');
  
  // Now we need to select "グアノ" from the new fertilizer row
  const allText2 = await page.locator('body').textContent();
  console.log('Page text after click:', allText2?.replace(/\s+/g, ' ').substring(0, 300));
  
  // Check for any new select/dropdown that appeared
  const newSelects = await page.locator('select').all();
  console.log('Selects after click:', newSelects.length);
  
  for (let i = 0; i < newSelects.length; i++) {
    const options = await newSelects[i].locator('option').allTextContents();
    if (options.some(o => o.includes('グアノ'))) {
      console.log(`Found グアノ in select[${i}], selecting...`);
      await newSelects[i].selectOption({ label: 'グアノ' });
      break;
    }
  }
}

await page.waitForTimeout(2000);
await screenshotFull('step4_guano_selected');

// Check page state
const pageBody = await page.locator('body').textContent();
console.log('After グアノ selection:', pageBody?.replace(/\s+/g, ' ').substring(0, 500));

await browser.close();
