import { chromium } from 'playwright';

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

const screenshotDir = 'C:/tmp/playwright_screenshots';
// Create directory via node
import { mkdirSync } from 'fs';
mkdirSync(screenshotDir, { recursive: true });

function screenshot(name) {
  return page.screenshot({ path: `${screenshotDir}/${name}.png`, fullPage: true });
}

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

// Check if redirected to login
if (page.url().includes('/login')) {
  console.log('\n=== Step 2: Redirected to login, logging in... ===');
  
  // Find and fill login form
  await page.waitForSelector('input', { timeout: 5000 });
  const inputs = await page.locator('input').all();
  console.log('Found inputs:', inputs.length);
  
  // Try different selectors for username/password
  try {
    await page.fill('input[name="username"]', 'akira');
  } catch {
    await page.fill('input[type="text"]:first-of-type', 'akira');
  }
  
  try {
    await page.fill('input[name="password"]', 'keina2025');
  } catch {
    await page.fill('input[type="password"]', 'keina2025');
  }
  
  await screenshot('step2_login_form');
  await page.click('button[type="submit"]');
  await page.waitForLoadState('networkidle');
  console.log('After login URL:', page.url());
  
  // Navigate to fertilizer/new after login
  await page.goto('http://localhost:3000/fertilizer/new');
  await page.waitForLoadState('networkidle');
  console.log('After navigate URL:', page.url());
}

await screenshot('step3_fertilizer_new');
console.log('\n=== Step 3: On fertilizer/new page ===');
console.log('URL:', page.url());

// Check page content
const pageTitle = await page.title();
console.log('Page title:', pageTitle);
const bodyText = await page.locator('body').textContent();
console.log('Body preview:', bodyText?.substring(0, 500));

await browser.close();
console.log('\nDone!');
