#!/usr/bin/env node

/**
 * Simple Test - Just login and check page
 */

const puppeteer = require('puppeteer');

const REONOMY_EMAIL = process.env.REONOMY_EMAIL || 'henry@realestateenhanced.com';
const REONOMY_PASSWORD = process.env.REONOMY_PASSWORD || '9082166532';

(async () => {
  console.log('🚀 Starting simple login test...\n');

  const browser = await puppeteer.launch({
    headless: false,
    args: ['--no-sandbox', '--disable-setuid-sandbox', '--window-size=1920,1080']
  });

  const page = await browser.newPage();

  try {
    // Login
    console.log('📍 Logging into Reonomy...');
    await page.goto('https://app.reonomy.com/#!/account', {
      waitUntil: 'domcontentloaded',
      timeout: 60000
    });

    await new Promise(resolve => setTimeout(resolve, 2000));

    await page.type('input[type="email"]', REONOMY_EMAIL, { delay: 100 });
    await page.type('input[type="password"]', REONOMY_PASSWORD, { delay: 100 });
    await page.click('button[type="submit"]');

    console.log('⏳ Waiting for login...');
    await new Promise(resolve => setTimeout(resolve, 10000));

    // Check if logged in
    const url = page.url();
    console.log('Current URL:', url);

    if (url.includes('login') || url.includes('auth')) {
      console.log('❌ Login failed');
      process.exit(1);
    }

    console.log('✅ Successfully logged in!');

    // Navigate to search
    console.log('\n📍 Navigating to search...');
    await page.goto('https://app.reonomy.com/#!/search', {
      waitUntil: 'networkidle2',
      timeout: 60000
    });

    await new Promise(resolve => setTimeout(resolve, 5000));

    // Take screenshot
    console.log('📸 Taking screenshot...');
    await page.screenshot({ path: '/tmp/reonomy-test-login.png', fullPage: false });
    console.log('💾 Saved to: /tmp/reonomy-test-login.png');

    // Get page title
    const title = await page.title();
    console.log('Page title:', title);

    // Check for property links
    const links = await page.evaluate(() => {
      const aTags = Array.from(document.querySelectorAll('a[href*="/property/"]'));
      return {
        count: aTags.length,
        sample: aTags.slice(0, 3).map(a => ({ href: a.href, text: a.textContent.trim().substring(0, 50) }))
      };
    });

    console.log(`\nFound ${links.count} property links`);
    links.sample.forEach(link => {
      console.log(`  - ${link.href}`);
      if (link.text) {
        console.log(`    "${link.text}"`);
      }
    });

    console.log('\n✅ Test complete! Keeping browser open for inspection...');
    console.log('Press Ctrl+C to close.');

    await new Promise(() => {});

  } catch (error) {
    console.error('❌ Error:', error.message);
    console.error(error.stack);
    await page.screenshot({ path: '/tmp/reonomy-test-error.png', fullPage: true });
    process.exit(1);
  } finally {
    await browser.close();
    console.log('🔚 Browser closed');
  }
})();
