#!/usr/bin/env node

/**
 * Test script to extract contact info by clicking interactive elements
 */

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

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

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function testContactExtraction() {
  console.log('🚀 Starting contact extraction test...');

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

  const page = await browser.newPage();
  await page.setViewport({ width: 1920, height: 1080 });

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

    await sleep(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 sleep(10000);

    const url = page.url();
    if (url.includes('login') || url.includes('auth')) {
      throw new Error('Login failed');
    }

    console.log('✅ Logged in!');

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

    await sleep(3000);

    // Look for owner links and click one
    console.log('\n🔍 Looking for owner links...');

    const ownerLinks = await page.evaluate(() => {
      const links = [];
      const anchors = Array.from(document.querySelectorAll('a'));

      anchors.forEach(anchor => {
        const href = anchor.href || '';
        const text = (anchor.innerText || anchor.textContent || '').trim();

        if (href.includes('/person/') || href.includes('/owner/')) {
          links.push({
            href: href,
            text: text
          });
        }
      });

      return links;
    });

    if (ownerLinks.length > 0) {
      console.log(`\n📍 Clicking on first owner: ${ownerLinks[0].text}`);

      // Click the first owner link
      await page.evaluate((href) => {
        const anchors = Array.from(document.querySelectorAll('a'));
        for (const anchor of anchors) {
          if (anchor.href === href) {
            anchor.click();
            break;
          }
        }
      }, ownerLinks[0].href);

      console.log('⏳ Waiting for owner page to load...');
      await sleep(5000);

      // Try clicking on the "Contact" button
      console.log('\n🔍 Looking for Contact button...');

      const contactButtonFound = await page.evaluate(() => {
        // Look for buttons with text "Contact"
        const buttons = Array.from(document.querySelectorAll('button'));
        for (const button of buttons) {
          const text = (button.innerText || button.textContent || '').trim();
          if (text.toLowerCase().includes('contact')) {
            button.click();
            return true;
          }
        }
        return false;
      });

      if (contactButtonFound) {
        console.log('✅ Clicked Contact button');
        await sleep(3000);

        // Extract content after clicking
        console.log('\n🔍 Extracting contact info...');

        const contactInfo = await page.evaluate(() => {
          const info = {
            email: '',
            phone: '',
            allText: document.body.innerText.substring(0, 2000)
          };

          // Look for email in the entire page
          const emailPattern = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
          const emailMatches = document.body.innerText.match(emailPattern);
          if (emailMatches) {
            info.email = emailMatches[0];
          }

          // Look for phone in the entire page
          const phonePatterns = [
            /\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}/g,
            /\d{3}[-.\s]?\d{3}[-.\s]?\d{4}/g
          ];

          for (const pattern of phonePatterns) {
            const phoneMatches = document.body.innerText.match(pattern);
            if (phoneMatches && phoneMatches.length > 0) {
              // Filter out common non-phone numbers
              for (const phone of phoneMatches) {
                if (!phone.startsWith('214748') && !phone.startsWith('266666')) {
                  info.phone = phone;
                  break;
                }
              }
              if (info.phone) break;
            }
          }

          return info;
        });

        console.log('\n📊 Contact Info Found:');
        console.log(`   Email: ${contactInfo.email || 'Not found'}`);
        console.log(`   Phone: ${contactInfo.phone || 'Not found'}`);
        console.log(`   Page preview: ${contactInfo.allText.substring(0, 500)}...`);

        // Save screenshot
        await page.screenshot({ path: '/tmp/contact-after-click.png', fullPage: true });
        console.log('\n📸 Screenshot saved: /tmp/contact-after-click.png');
      } else {
        console.log('⚠️  Contact button not found');
      }
    }

    console.log('\n✅ Test complete!');
    await sleep(5000);

  } catch (error) {
    console.error(`\n❌ Error: ${error.message}`);
    console.error(error.stack);
  } finally {
    await browser.close();
  }
}

testContactExtraction().catch(console.error);
