#!/usr/bin/env node
/**
 * Test: Mobile Colored Buttons - Colors at 50% transparency, full on hover
 *
 * Verifies that on mobile view (max-width: 900px):
 * - Buttons show their colors (not gray) at 50% transparency
 * - On hover, colors become fully opaque (100%)
 * - Colors match the "at-bottom" or hover states from desktop
 */

import { chromium } from 'playwright';

const TEST_URL = 'http://localhost:1999';
const VIEWPORT_WIDTH = 375; // Mobile width
const VIEWPORT_HEIGHT = 812; // iPhone X height

// Helper to extract RGB values from background color
function parseRGB(colorString) {
  const match = colorString.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
  if (!match) return null;
  return {
    r: parseInt(match[1]),
    g: parseInt(match[2]),
    b: parseInt(match[3]),
    a: match[4] ? parseFloat(match[4]) : 1
  };
}

async function testMobileColoredButtons() {
  console.log('🧪 Testing Mobile Colored Buttons (50% transparent → 100% on hover)');
  console.log('='.repeat(70));

  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({
    viewport: { width: VIEWPORT_WIDTH, height: VIEWPORT_HEIGHT },
    deviceScaleFactor: 2,
  });
  const page = await context.newPage();

  // Disable cache
  await page.route('**/*', (route) => {
    route.continue({
      headers: {
        ...route.request().headers(),
        'Cache-Control': 'no-cache, no-store, must-revalidate',
      },
    });
  });

  try {
    await page.goto(TEST_URL, { waitUntil: 'networkidle' });
    console.log(`✅ Navigated to ${TEST_URL}`);
    await page.waitForTimeout(1000);

    const buttons = [
      { selector: '.download-btn', name: 'Download', expectedColor: { r: 205, g: 96, b: 96 } }, // Red
      { selector: '.print-friendly-btn', name: 'Print', expectedColor: { r: 255, g: 255, b: 255 } }, // White
      { selector: '.shortcuts-btn', name: 'Shortcuts', expectedColor: { r: 243, g: 156, b: 18 } }, // Orange
      { selector: '.info-button', name: 'Info', expectedColor: { r: 39, g: 174, b: 96 } }, // Green
      { selector: '.back-to-top', name: 'Back to Top', expectedColor: { r: 39, g: 174, b: 96 } }, // Green
    ];

    console.log('\n🎨 Testing Mobile Button Colors:');
    console.log('-'.repeat(70));

    let allTestsPassed = true;

    for (const button of buttons) {
      try {
        const buttonElement = await page.$(button.selector);
        if (!buttonElement) {
          console.log(`❌ ${button.name}: Button not found`);
          allTestsPassed = false;
          continue;
        }

        // Get default background color
        const defaultBg = await page.evaluate((sel) => {
          const btn = document.querySelector(sel);
          return btn ? window.getComputedStyle(btn).backgroundColor : null;
        }, button.selector);

        const defaultColor = parseRGB(defaultBg);

        // Check if color matches expected (RGB should match, alpha should be ~0.5)
        if (defaultColor) {
          const colorMatches =
            Math.abs(defaultColor.r - button.expectedColor.r) <= 5 &&
            Math.abs(defaultColor.g - button.expectedColor.g) <= 5 &&
            Math.abs(defaultColor.b - button.expectedColor.b) <= 5;

          const alphaCorrect = Math.abs(defaultColor.a - 0.5) < 0.1;

          if (colorMatches && alphaCorrect) {
            console.log(`✅ ${button.name}: Color rgba(${defaultColor.r}, ${defaultColor.g}, ${defaultColor.b}, ${defaultColor.a.toFixed(2)}) ✓`);
          } else {
            console.log(`❌ ${button.name}: Color rgba(${defaultColor.r}, ${defaultColor.g}, ${defaultColor.b}, ${defaultColor.a.toFixed(2)})`);
            console.log(`   Expected: rgba(${button.expectedColor.r}, ${button.expectedColor.g}, ${button.expectedColor.b}, ~0.5)`);
            allTestsPassed = false;
          }
        } else {
          console.log(`❌ ${button.name}: Could not parse background color`);
          allTestsPassed = false;
          continue;
        }

        // Hover and check color becomes fully opaque
        await buttonElement.hover();
        await page.waitForTimeout(500);

        const hoverBg = await page.evaluate((sel) => {
          const btn = document.querySelector(sel);
          return btn ? window.getComputedStyle(btn).backgroundColor : null;
        }, button.selector);

        const hoverColor = parseRGB(hoverBg);

        if (hoverColor) {
          const hoverAlphaCorrect = Math.abs(hoverColor.a - 1.0) < 0.1;

          if (hoverAlphaCorrect) {
            console.log(`   ✅ Hover: rgba(${hoverColor.r}, ${hoverColor.g}, ${hoverColor.b}, ${hoverColor.a.toFixed(2)}) ✓`);
          } else {
            console.log(`   ❌ Hover: rgba(${hoverColor.r}, ${hoverColor.g}, ${hoverColor.b}, ${hoverColor.a.toFixed(2)})`);
            console.log(`      Expected alpha: ~1.0`);
            allTestsPassed = false;
          }
        }

        // Move mouse away
        await page.mouse.move(0, 0);
        await page.waitForTimeout(500);

      } catch (error) {
        console.log(`❌ ${button.name}: Error - ${error.message}`);
        allTestsPassed = false;
      }
    }

    console.log('-'.repeat(70));

    if (allTestsPassed) {
      console.log('\n✅ ALL TESTS PASSED - Mobile colored buttons working correctly!');
      console.log('   • Buttons show colors at 50% transparency');
      console.log('   • Colors become fully opaque (100%) on hover');
    } else {
      console.log('\n❌ SOME TESTS FAILED - Check output above');
    }

    await browser.close();
    process.exit(allTestsPassed ? 0 : 1);

  } catch (error) {
    console.error('\n❌ Test error:', error);
    await browser.close();
    process.exit(1);
  }
}

testMobileColoredButtons();
