const { chromium } = require('/Users/jakeshore/ClawdBot/node_modules/playwright');

(async () => {
  const browser = await chromium.launch({ headless: false });
  const context = await browser.newContext();
  const page = await context.newPage();

  console.log('Navigating to Reonomy...');
  await page.goto('https://app.reonomy.com');

  // Wait for login form
  await page.waitForSelector('input[placeholder="yours@example.com"]', { timeout: 10000 });

  console.log('Filling in credentials...');
  await page.fill('input[placeholder="yours@example.com"]', 'henry@realestateenhanced.com');
  await page.fill('input[placeholder="your password"]', '9082166532');

  console.log('Clicking login...');
  await page.click('button:has-text("Log In")');

  // Wait for navigation
  await page.waitForLoadState('networkidle', { timeout: 15000 });

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

  // Take screenshot
  await page.screenshot({ path: '/Users/jakeshore/.clawdbot/workspace/reonomy-after-login.png', fullPage: true });
  console.log('Screenshot saved');

  // Look for property links or recently viewed
  console.log('Looking for property links...');
  const propertyLinks = await page.$$eval('a[href*="/property/"]', links =>
    links.map(link => ({
      text: link.textContent.trim(),
      href: link.href
    }))
  );

  if (propertyLinks.length > 0) {
    console.log('Found', propertyLinks.length, 'property links');
    console.log('First few links:', propertyLinks.slice(0, 3));

    // Navigate to first property
    console.log('Navigating to first property...');
    await page.goto(propertyLinks[0].href);
    await page.waitForLoadState('networkidle', { timeout: 15000 });

    console.log('Property page URL:', page.url());

    // Take screenshot of property page
    await page.screenshot({ path: '/Users/jakeshore/.clawdbot/workspace/reonomy-property-page.png', fullPage: true });
    console.log('Property page screenshot saved');

    // Extract HTML structure for contact info
    console.log('Analyzing contact info structure...');
    const contactInfo = await page.evaluate(() => {
      // Look for email patterns
      const emailRegex = /[\w.-]+@[\w.-]+\.\w+/;
      const phoneRegex = /\(\d{3}\)\s*\d{3}-\d{4}|\d{3}[-.]?\d{3}[-.]?\d{4}/;

      // Get all elements that might contain email/phone
      const allElements = document.querySelectorAll('*');
      const candidates = [];

      allElements.forEach(el => {
        const text = el.textContent?.trim() || '';
        if (emailRegex.test(text) || phoneRegex.test(text)) {
          candidates.push({
            tag: el.tagName,
            class: el.className,
            id: el.id,
            text: text.substring(0, 100),
            html: el.outerHTML.substring(0, 200),
            parent: el.parentElement?.tagName + '.' + el.parentElement?.className
          });
        }
      });

      return candidates.slice(0, 20); // Return first 20 matches
    });

    console.log('\n=== CONTACT INFO CANDIDATES ===');
    contactInfo.forEach((item, i) => {
      console.log(`\n${i + 1}. Tag: ${item.tag}`);
      console.log(`   Class: ${item.class}`);
      console.log(`   ID: ${item.id}`);
      console.log(`   Text: ${item.text}`);
      console.log(`   Parent: ${item.parent}`);
    });

    // Save detailed info to file
    const fs = require('fs');
    fs.writeFileSync('/Users/jakeshore/.clawdbot/workspace/reonomy-contact-info.json', JSON.stringify(contactInfo, null, 2));

    console.log('\n=== SEARCHING FOR SPECIFIC SELECTORS ===');
    // Try specific selector patterns
    const selectorPatterns = [
      '[class*="email"]',
      '[class*="phone"]',
      '[class*="contact"]',
      '[data-testid*="email"]',
      '[data-testid*="phone"]',
      '[aria-label*="email"]',
      '[aria-label*="phone"]',
      'a[href^="mailto:"]',
      'a[href^="tel:"]'
    ];

    for (const pattern of selectorPatterns) {
      try {
        const elements = await page.$$(pattern);
        if (elements.length > 0) {
          console.log(`\nFound ${elements.length} elements matching: ${pattern}`);
          for (const el of elements.slice(0, 3)) {
            const text = await el.textContent();
            console.log(`  - ${text?.trim().substring(0, 50)}`);
          }
        }
      } catch (e) {
        // Ignore selector errors
      }
    }

  } else {
    console.log('No property links found. Looking for search functionality...');
    // Try to search for a property
    const searchInput = await page.$('input[placeholder*="search"], input[placeholder*="Search"], input[placeholder*="address"], input[placeholder*="Address"]');
    if (searchInput) {
      console.log('Found search input, trying to search...');
      await searchInput.fill('123 Main St');
      await page.keyboard.press('Enter');
      await page.waitForTimeout(3000);

      // Check for results
      const propertyLinks = await page.$$eval('a[href*="/property/"]', links =>
        links.map(link => ({
          text: link.textContent.trim(),
          href: link.href
        }))
      );

      if (propertyLinks.length > 0) {
        console.log('Found', propertyLinks.length, 'property links after search');
        await page.goto(propertyLinks[0].href);
        await page.waitForLoadState('networkidle', { timeout: 15000 });
        await page.screenshot({ path: '/Users/jakeshore/.clawdbot/workspace/reonomy-property-page.png', fullPage: true });
        console.log('Property page screenshot saved');
      }
    }
  }

  console.log('\nKeeping browser open for 30 seconds for inspection...');
  await page.waitForTimeout(30000);

  await browser.close();
  console.log('Done!');
})();
