#!/usr/bin/env node

/**
 * Test script to navigate to owner page via clicking
 */

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 testOwnerClick() {
  console.log('🚀 Starting owner page click 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);

    console.log('✅ On dashboard');

    // 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;
    });

    console.log(`👤 Found ${ownerLinks.length} owner links`);
    ownerLinks.forEach((link, i) => {
      console.log(`  ${i + 1}. ${link.text} - ${link.href}`);
    });

    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);

      const currentUrl = page.url();
      console.log(`📍 Current URL: ${currentUrl}`);

      // Save screenshot
      await page.screenshot({ path: '/tmp/owner-page-click.png', fullPage: true });
      console.log('📸 Screenshot saved: /tmp/owner-page-click.png');

      // Save HTML
      const html = await page.content();
      fs.writeFileSync('/tmp/owner-page-click.html', html);
      console.log('📄 HTML saved: /tmp/owner-page-click.html');

      // Extract all elements that might contain email or phone
      console.log('\n🔍 Searching for email and phone elements...');

      const elements = await page.evaluate(() => {
        const results = [];

        // Search for elements with common patterns
        const allElements = document.querySelectorAll('*');

        allElements.forEach(el => {
          const text = (el.innerText || el.textContent || '').trim();
          const id = el.id || '';
          const className = el.className || '';
          const dataAttrs = Array.from(el.attributes)
            .filter(attr => attr.name.startsWith('data-'))
            .map(attr => `${attr.name}="${attr.value}"`)
            .join(' ');

          // Check for email patterns
          if (text.match(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/)) {
            const emailMatch = text.match(/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/);
            if (emailMatch) {
              results.push({
                type: 'email',
                value: emailMatch[1],
                tag: el.tagName,
                id: id,
                class: className,
                data: dataAttrs,
                text: text.substring(0, 100)
              });
            }
          }

          // Check for phone patterns
          if (text.match(/\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}/)) {
            const phoneMatch = text.match(/\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}/);
            if (phoneMatch) {
              results.push({
                type: 'phone',
                value: phoneMatch[0],
                tag: el.tagName,
                id: id,
                class: className,
                data: dataAttrs,
                text: text.substring(0, 100)
              });
            }
          }
        });

        return results;
      });

      console.log('\n📊 Found elements:');
      if (elements.length === 0) {
        console.log('   ⚠️  No email or phone elements found!');
      } else {
        elements.forEach(el => {
          console.log(`\n   ${el.type.toUpperCase()}: ${el.value}`);
          console.log(`     Tag: ${el.tag}`);
          if (el.id) console.log(`     ID: ${el.id}`);
          if (el.class) console.log(`     Class: ${el.class}`);
          if (el.data) console.log(`     Data: ${el.data}`);
          console.log(`     Text: ${el.text}`);
        });
      }
    } else {
      console.log('\n⚠️  No owner links found on the page');
    }

    console.log('\n✅ Test complete!');
    console.log('📸 Check the screenshot and HTML for visual inspection');

    await sleep(5000);

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

testOwnerClick().catch(console.error);
