#!/usr/bin/env node

/**
 * Test script to inspect owner page structure
 */

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

const REONOMY_EMAIL = 'henry@realestateenhanced.com';
const REONOMY_PASSWORD = '9082166532';
const OWNER_URL = 'https://app.reonomy.com/#!/person/7785933b-5fa2-5be5-8a52-502b328a95ce';

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

async function testOwnerPage() {
  console.log('🚀 Starting owner page inspection...');

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

    // Visit owner page
    console.log(`\n📍 Visiting owner page: ${OWNER_URL}`);
    await page.goto(OWNER_URL, {
      waitUntil: 'networkidle2',
      timeout: 60000
    });

    await sleep(3000);

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

    // Save HTML
    const html = await page.content();
    fs.writeFileSync('/tmp/owner-page-test.html', html);
    console.log('📄 HTML saved: /tmp/owner-page-test.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}`);
      });
    }

    // Also check for specific known IDs
    console.log('\n🔍 Checking for known IDs...');
    const knownIds = await page.evaluate(() => {
      const ids = [
        'people-contact-email-id',
        'people-contact-phone-1',
        'people-contact-phone-2',
        'people-contact-phone-3'
      ];

      const results = {};
      ids.forEach(id => {
        const el = document.getElementById(id);
        results[id] = {
          exists: !!el,
          text: el ? (el.innerText || el.textContent || '').trim() : 'N/A'
        };
      });

      return results;
    });

    console.log('Known ID results:');
    Object.entries(knownIds).forEach(([id, info]) => {
      console.log(`  ${id}: ${info.exists ? '✓' : '✗'} (${info.text})`);
    });

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

testOwnerPage().catch(console.error);
