const puppeteer = require('puppeteer');
const fs = require('fs');

const sleep = ms => new Promise(r => setTimeout(r, ms));

(async () => {
  const browser = await puppeteer.launch({
    headless: false,
    args: ['--no-sandbox', '--disable-setuid-sandbox']
  });
  const page = await browser.newPage();

  console.log('🚀 Navigating to Reonomy...');
  await page.goto('https://app.reonomy.com/#!/account', { waitUntil: 'networkidle2' });

  // Fill credentials
  console.log('📝 Filling credentials...');
  await page.type('input[type="email"]', 'henry@realestateenhanced.com', { delay: 100 });
  await page.type('input[type="password"]', '9082166532', { delay: 100 });

  // Click login
  console.log('🔐 Clicking login...');
  await Promise.race([
    page.click('button[type="submit"]'),
    sleep(2000)
  ]);

  // Wait for redirect
  console.log('⏳ Waiting for redirect...');
  await sleep(10000);

  const currentUrl = page.url();
  console.log('Current URL:', currentUrl);

  // If still on login page, something went wrong
  if (currentUrl.includes('login')) {
    console.log('❌ Still on login page. Checking for errors...');
    const pageContent = await page.content();
    fs.writeFileSync('/tmp/reonomy-login-error.html', pageContent);
    console.log('📄 Saved login page HTML to /tmp/reonomy-login-error.html');
    await page.screenshot({ path: '/tmp/reonomy-login-error.png' });
    await browser.close();
    process.exit(1);
  }

  // Navigate to search page
  console.log('🔍 Navigating to search...');
  await page.goto('https://app.reonomy.com/#!/search', { waitUntil: 'networkidle2' });
  await sleep(5000);

  console.log('📸 Taking screenshot of search results...');
  await page.screenshot({ path: '/tmp/reonomy-search-results.png', fullPage: true });
  console.log('💾 Saved to /tmp/reonomy-search-results.png');

  // Find a property or owner link
  console.log('🔎 Looking for property/owner links...');

  const links = await page.evaluate(() => {
    const results = [];
    const propertyLinks = document.querySelectorAll('a[href*="/property/"]');
    const ownerLinks = document.querySelectorAll('a[href*="/person/"]');

    propertyLinks.forEach((link, i) => {
      if (i < 3) {
        results.push({
          type: 'property',
          url: link.href,
          text: link.textContent.trim().substring(0, 50)
        });
      }
    });

    ownerLinks.forEach((link, i) => {
      if (i < 3) {
        results.push({
          type: 'owner',
          url: link.href,
          text: link.textContent.trim().substring(0, 50)
        });
      }
    });

    return results;
  });

  console.log('Found links:', JSON.stringify(links, null, 2));

  // Navigate to first owner page to inspect contact info
  const firstOwner = links.find(l => l.type === 'owner');
  if (firstOwner) {
    console.log(`\n👤 Navigating to owner page: ${firstOwner.url}`);
    await page.goto(firstOwner.url, { waitUntil: 'networkidle2' });
    await sleep(5000);

    console.log('📸 Taking screenshot of owner page...');
    await page.screenshot({ path: '/tmp/reonomy-owner-page.png', fullPage: true });
    console.log('💾 Saved to /tmp/reonomy-owner-page.png');

    // Save HTML for inspection
    const html = await page.content();
    fs.writeFileSync('/tmp/reonomy-owner-page.html', html);
    console.log('📄 Saved HTML to /tmp/reonomy-owner-page.html');

    // Look for email/phone patterns in the page
    console.log('\n🔍 Looking for email/phone patterns...');

    const contactInfo = await page.evaluate(() => {
      const results = {
        emailElements: [],
        phoneElements: [],
        allContactSelectors: []
      };

      // Check various selectors
      const selectors = [
        'a[href^="mailto:"]',
        'a[href^="tel:"]',
        '[class*="email"]',
        '[class*="phone"]',
        '[class*="contact"]',
        '[data-testid*="email"]',
        '[data-testid*="phone"]',
        '[data-test*="email"]',
        '[data-test*="phone"]',
        '.email-address',
        '.phone-number',
        '.contact-info'
      ];

      selectors.forEach(sel => {
        const elements = document.querySelectorAll(sel);
        if (elements.length > 0) {
          results.allContactSelectors.push({
            selector: sel,
            count: elements.length
          });

          Array.from(elements).forEach((el, i) => {
            if (i < 3) {
              results.allContactSelectors.push({
                selector: sel,
                text: el.textContent.trim().substring(0, 100),
                html: el.outerHTML.substring(0, 200)
              });
            }
          });
        }
      });

      // Specific: email links
      document.querySelectorAll('a[href^="mailto:"]').forEach((el, i) => {
        if (i < 5) {
          results.emailElements.push({
            href: el.href,
            text: el.textContent.trim()
          });
        }
      });

      // Specific: phone links
      document.querySelectorAll('a[href^="tel:"]').forEach((el, i) => {
        if (i < 5) {
          results.phoneElements.push({
            href: el.href,
            text: el.textContent.trim()
          });
        }
      });

      return results;
    });

    console.log('\n📊 Contact Info Analysis:');
    console.log('Email elements:', JSON.stringify(contactInfo.emailElements, null, 2));
    console.log('\nPhone elements:', JSON.stringify(contactInfo.phoneElements, null, 2));
    console.log('\nAll matching selectors:', JSON.stringify(contactInfo.allContactSelectors.slice(0, 20), null, 2));

    fs.writeFileSync('/tmp/reonomy-contact-analysis.json', JSON.stringify(contactInfo, null, 2));
    console.log('\n💾 Full analysis saved to /tmp/reonomy-contact-analysis.json');
  } else {
    console.log('⚠️  No owner links found on search page');
  }

  console.log('\n✅ Inspection complete!');
  console.log('   Files saved:');
  console.log('   - /tmp/reonomy-search-results.png');
  console.log('   - /tmp/reonomy-owner-page.png');
  console.log('   - /tmp/reonomy-owner-page.html');
  console.log('   - /tmp/reonomy-contact-analysis.json');

  console.log('\n🔍 Browser is open for manual inspection.');
  console.log('   Press Ctrl+C in terminal to close it.');

  // Keep browser open
  await new Promise(() => {});

  await browser.close();
})();
