#!/usr/bin/env bun
/**
 * PDF DOWNLOAD DEBUG TEST
 * =======================
 * Debug why the download button isn't working
 */

import { chromium } from 'playwright';

const URL = "http://localhost:1999";

async function debugPDFDownload() {
  console.log('🐛 PDF DOWNLOAD DEBUG TEST\n');
  console.log('='.repeat(70));

  const browser = await chromium.launch({ headless: false });
  const page = await browser.newPage({ viewport: { width: 1920, height: 1080 } });

  // Capture console messages
  page.on('console', msg => {
    console.log(`[BROWSER ${msg.type()}]:`, msg.text());
  });

  // Capture errors
  page.on('pageerror', error => {
    console.log('❌ PAGE ERROR:', error.message);
  });

  console.log("\n1️⃣  Loading page...");
  await page.goto(URL);
  await page.waitForTimeout(2000);

  console.log("\n2️⃣  Opening PDF modal...");
  await page.click('.pdf-btn');
  await page.waitForTimeout(1000);

  console.log("\n3️⃣  Checking button state...");
  const buttonState = await page.evaluate(() => {
    const btn = document.querySelector('.pdf-download-btn');
    return {
      exists: !!btn,
      disabled: btn?.disabled,
      hasClickHandler: btn?.getAttribute('_')?.includes('on click')
    };
  });
  console.log('   Button exists:', buttonState.exists);
  console.log('   Button disabled:', buttonState.disabled);
  console.log('   Has click handler:', buttonState.hasClickHandler);

  console.log("\n4️⃣  Selecting Short CV...");
  await page.click('[data-cv-format="short"]');
  await page.waitForTimeout(500);

  const afterSelection = await page.evaluate(() => {
    const btn = document.querySelector('.pdf-download-btn');
    return {
      disabled: btn?.disabled,
      selectedFormat: window._hyperscript?.runtime?.getLocalGlobal?.(':selectedFormat')
    };
  });
  console.log('   Button disabled after selection:', afterSelection.disabled);
  console.log('   Selected format:', afterSelection.selectedFormat);

  console.log("\n5️⃣  Clicking download button...");

  // Listen for navigation
  let navigationURL = null;
  page.on('framenavigated', (frame) => {
    if (frame === page.mainFrame()) {
      navigationURL = frame.url();
      console.log('   📍 Navigation to:', navigationURL);
    }
  });

  // Check what happens when we click
  const clickResult = await page.evaluate(() => {
    const btn = document.querySelector('.pdf-download-btn');
    console.log('About to click button');
    btn.click();
    return 'Clicked';
  });

  console.log('   Click result:', clickResult);

  // Wait to see if navigation happens
  await page.waitForTimeout(3000);

  if (navigationURL) {
    console.log('   ✅ Navigation occurred to:', navigationURL);
  } else {
    console.log('   ❌ No navigation occurred');

    // Check for hyperscript errors
    const hyperscriptErrors = await page.evaluate(() => {
      return window._hyperscript?.internals?.errors || [];
    });

    if (hyperscriptErrors.length > 0) {
      console.log('   Hyperscript errors:', hyperscriptErrors);
    }
  }

  console.log("\n6️⃣  Checking localStorage...");
  const localStorage = await page.evaluate(() => {
    return {
      length: localStorage.getItem('cv-length'),
      icons: localStorage.getItem('cv-icons'),
      theme: localStorage.getItem('cv-theme')
    };
  });
  console.log('   localStorage:', localStorage);

  console.log('\n' + '='.repeat(70));
  console.log('🔍 DEBUG COMPLETE');
  console.log('\nBrowser will stay open for manual inspection.');
  console.log('Press Ctrl+C when done.');

  // Keep browser open
  await new Promise(() => {});
}

debugPDFDownload().catch(err => {
  console.error('❌ Test failed:', err);
  process.exit(1);
});
