#!/usr/bin/env bun
/**
 * ZOOM FUNCTIONALITY TEST
 * ========================
 * Tests zoom control visibility, interaction, and real-time updates
 */

import { chromium } from 'playwright';

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

async function testZoom() {
  console.log('🔍 ZOOM FUNCTIONALITY TEST\n');
  console.log('='.repeat(70));

  const browser = await chromium.launch({
    headless: false,
    args: ['--disable-http-cache', '--disable-cache']
  });

  const context = await browser.newContext({
    ignoreHTTPSErrors: true,
    bypassCSP: true
  });

  const page = await context.newPage();

  // Track errors
  const errors = [];
  page.on('console', msg => {
    if (msg.type() === 'error') {
      errors.push(msg.text());
      console.log('  ❌ ERROR:', msg.text());
    }
  });

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

  console.log(`\n1️⃣  Loading: ${URL}\n`);
  await page.goto(URL, { waitUntil: 'networkidle' });
  await page.waitForTimeout(2000);

  // TEST 1: Check zoom-control exists
  console.log('2️⃣  ZOOM CONTROL ELEMENTS:');
  const elements = await page.evaluate(() => {
    return {
      zoomControl: !!document.querySelector('#zoom-control'),
      zoomSlider: !!document.querySelector('#zoom-slider'),
      zoomWrapper: !!document.querySelector('#zoom-wrapper'),
      zoomToggleButton: !!document.querySelector('#zoom-toggle-button')
    };
  });

  const allExist = Object.values(elements).every(v => v);

  console.log(`   - Zoom control: ${elements.zoomControl ? '✅' : '❌'}`);
  console.log(`   - Zoom slider: ${elements.zoomSlider ? '✅' : '❌'}`);
  console.log(`   - Zoom wrapper: ${elements.zoomWrapper ? '✅' : '❌'}`);
  console.log(`   - Zoom toggle button: ${elements.zoomToggleButton ? '✅' : '❌'}`);
  console.log(`   ${allExist ? '✅ All elements present' : '❌ Some elements missing'}\n`);

  // TEST 2: Check if zoom control is visible
  console.log('3️⃣  ZOOM CONTROL VISIBILITY:');
  const visibility = await page.evaluate(() => {
    const ctrl = document.querySelector('#zoom-control');
    return {
      hasHiddenClass: ctrl?.classList.contains('zoom-hidden'),
      displayStyle: ctrl ? window.getComputedStyle(ctrl).display : 'N/A',
      visibilityStyle: ctrl ? window.getComputedStyle(ctrl).visibility : 'N/A'
    };
  });

  const isVisible = !visibility.hasHiddenClass && visibility.displayStyle !== 'none';
  console.log(`   - Has .zoom-hidden class: ${visibility.hasHiddenClass ? 'YES' : 'NO'}`);
  console.log(`   - Display: ${visibility.displayStyle}`);
  console.log(`   - Visibility: ${visibility.visibilityStyle}`);
  console.log(`   ${isVisible ? '✅ Visible' : '⚠️  Hidden (expected on load)'}\n`);

  // TEST 3: Show zoom control (click toggle button)
  console.log('4️⃣  SHOWING ZOOM CONTROL:');
  await page.click('#zoom-toggle-button');
  await page.waitForTimeout(500);

  const afterShow = await page.evaluate(() => {
    const ctrl = document.querySelector('#zoom-control');
    return {
      hasHiddenClass: ctrl?.classList.contains('zoom-hidden'),
      displayStyle: ctrl ? window.getComputedStyle(ctrl).display : 'N/A'
    };
  });

  const isVisibleAfter = !afterShow.hasHiddenClass && afterShow.displayStyle !== 'none';
  console.log(`   - After clicking toggle:`);
  console.log(`   - Has .zoom-hidden class: ${afterShow.hasHiddenClass ? 'YES' : 'NO'}`);
  console.log(`   - Display: ${afterShow.displayStyle}`);
  console.log(`   ${isVisibleAfter ? '✅ Now visible' : '❌ Still hidden - BUG!'}\n`);

  // TEST 4: Test zoom functionality
  console.log('5️⃣  ZOOM FUNCTIONALITY TEST:');

  const zoomTest = await page.evaluate(() => {
    const slider = document.querySelector('#zoom-slider');
    const wrapper = document.querySelector('#zoom-wrapper');

    if (!slider || !wrapper) {
      return { error: 'Zoom elements not found' };
    }

    // Get initial state
    const initialZoom = wrapper.style.zoom || window.getComputedStyle(wrapper).zoom || '1';

    // Set zoom to 150%
    slider.value = '150';
    slider.dispatchEvent(new Event('input', { bubbles: true }));

    // Wait for event to process
    const newZoom = wrapper.style.zoom || window.getComputedStyle(wrapper).zoom || '1';

    // Reset to 100%
    slider.value = '100';
    slider.dispatchEvent(new Event('input', { bubbles: true }));

    const resetZoom = wrapper.style.zoom || window.getComputedStyle(wrapper).zoom || '1';

    return {
      initialZoom,
      zoomAt150: newZoom,
      zoomAfterReset: resetZoom,
      sliderValue: slider.value
    };
  });

  console.log(`   - Initial zoom: ${zoomTest.initialZoom}`);
  console.log(`   - Zoom after setting to 150%: ${zoomTest.zoomAt150}`);
  console.log(`   - Zoom after reset to 100%: ${zoomTest.zoomAfterReset}`);
  console.log(`   - Slider value: ${zoomTest.sliderValue}`);

  const zoomWorks = zoomTest.zoomAt150 !== '1' && zoomTest.zoomAt150 !== zoomTest.initialZoom;
  console.log(`   ${zoomWorks ? '✅ Zoom changes value (WORKING)' : '❌ Zoom does not change (BROKEN)'}\n`);

  // SUMMARY
  console.log('='.repeat(70));
  console.log('📊 TEST SUMMARY\n');

  const allTestsPassed = allExist && isVisibleAfter && zoomWorks;

  console.log(`   ${allExist ? '✅' : '❌'} All zoom elements present`);
  console.log(`   ${isVisibleAfter ? '✅' : '❌'} Zoom control shows on toggle`);
  console.log(`   ${zoomWorks ? '✅' : '❌'} Zoom functionality works`);
  console.log(`   ${errors.length === 0 ? '✅' : '❌'} No console errors`);

  if (errors.length > 0) {
    console.log(`\n   Errors found: ${errors.length}`);
    errors.forEach((err, i) => console.log(`   ${i + 1}. ${err}`));
  }

  console.log('\n' + '='.repeat(70));

  if (allTestsPassed && errors.length === 0) {
    console.log('\n✅ ALL ZOOM TESTS PASSED!');
  } else {
    console.log('\n❌ SOME ZOOM TESTS FAILED - See details above');
  }

  console.log('\n💡 Browser window left open for manual testing');
  console.log('   Try moving the slider manually to verify');
  console.log('\nPress Ctrl+C to exit\n');

  await new Promise(() => {});
}

await testZoom();
