import { chromium } from 'playwright';
import { config } from 'dotenv';
import path from 'path';
config({ path: path.resolve(process.cwd(), '.env.local') });

(async () => {
  const savedState = await import('node:fs/promises').then(fs =>
    fs.readFile(path.resolve(process.cwd(), 'scripts/.ure-session.json'), 'utf8').then(JSON.parse).catch(() => null)
  );
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ storageState: savedState ?? undefined });
  const page = await browser.newPage();
  await page.goto('https://www.utahrealestate.com/sso/connect/client/skyslope', { waitUntil: 'domcontentloaded' });
  const [newPage] = await Promise.all([
    context.waitForEvent('page', { timeout: 10_000 }).catch(() => null),
    Promise.resolve(),
  ]);
  const activePage = newPage ?? page;
  await activePage.waitForLoadState('domcontentloaded');
  await activePage.waitForTimeout(3000);

  // Navigate to browse-libraries
  await activePage.goto('https://forms.skyslope.com/browse-libraries', { waitUntil: 'domcontentloaded' });
  await activePage.waitForTimeout(4000);

  // Inspect the first Add button's ancestors
  const result = await activePage.evaluate(() => {
    const addBtns = Array.from(document.querySelectorAll('button')).filter(b => b.textContent?.trim() === 'Add');
    if (addBtns.length === 0) return 'No Add buttons found';
    const btn = addBtns[0];
    // Walk up the tree and print each ancestor's tag, class, and text
    const info: string[] = [];
    let el: Element | null = btn;
    for (let i = 0; i < 6; i++) {
      if (!el) break;
      info.push(`[${i}] <${el.tagName.toLowerCase()} class="${el.className}"> text="${el.textContent?.replace(/\s+/g,' ').trim().slice(0,80)}"`);
      el = el.parentElement;
    }
    return info.join('\n');
  });
  console.log('Add button ancestry:\n', result);
  await browser.close();
})();
