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: true });
  console.log(`  [Screenshot saved: ${name}.png]`);
  return path;
}

console.log('\n=== Step 1: Navigate to /fertilizer/new ===');
await page.goto('http://localhost:3000/fertilizer/new');
await page.waitForLoadState('networkidle');
console.log('URL:', page.url());

if (page.url().includes('/login')) {
  console.log('\n=== Step 2: Login ===');
  // Use the id-based selectors since name attribute is null
  await page.fill('#username', 'akira');
  await page.fill('input[type="password"]', 'keina2025');
  await screenshot('login_filled');
  await page.click('button[type="submit"]');
  await page.waitForNavigation({ timeout: 10000 }).catch(() => console.log('No navigation event'));
  await page.waitForLoadState('networkidle');
  console.log('After login URL:', page.url());
  
  // Navigate to fertilizer/new
  await page.goto('http://localhost:3000/fertilizer/new');
  await page.waitForLoadState('networkidle');
  console.log('After redirect URL:', page.url());
}

await screenshot('step3_fertilizer_new');
console.log('\n=== Step 3: Page content ===');
const h1Text = await page.locator('h1, h2').first().textContent().catch(() => 'not found');
console.log('Heading:', h1Text);

// List all select elements
const selects = await page.locator('select').all();
console.log('Select elements:', selects.length);
for (const sel of selects) {
  const label = await sel.getAttribute('aria-label') || await sel.getAttribute('id') || 'no label';
  const options = await sel.locator('option').allTextContents();
  console.log(`  Select [${label}]: options = ${options.slice(0, 10).join(', ')}`);
}

// List all visible text to understand the page
const allText = await page.locator('body').textContent();
console.log('Page text (first 1000 chars):', allText?.substring(0, 1000));

await browser.close();
