const { chromium } = require('playwright');
const path = require('path');

const BASE = 'https://el3ab-player.caprover.al-arcade.com';
const DIR = __dirname;

(async () => {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({
    viewport: { width: 1440, height: 900 },
    locale: 'ar',
  });
  const page = await context.newPage();

  // Navigate first so fetch works
  await page.goto(BASE + '/login', { waitUntil: 'networkidle', timeout: 15000 });

  // Login
  await page.evaluate(async () => {
    const res = await fetch('https://safe-supabase-kong.caprover.al-arcade.com/auth/v1/token?grant_type=password', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlzcyI6InN1cGFiYXNlIiwiaWF0IjoxNzM1Njg5NjAwLCJleHAiOjE4OTM0NTYwMDB9.31PF6PvP-pSrvRuQwLFptQoejR0W1A7o53lZhEbnz84'
      },
      body: JSON.stringify({ email: 'uitest@el3ab.com', password: 'UiTest2026!' })
    });
    const data = await res.json();
    if (data.access_token) {
      localStorage.setItem('el3ab_token', data.access_token);
      localStorage.setItem('el3ab_user', JSON.stringify(data.user));
    }
  });

  // 1. Save a test theme override (change ludo-p1 to purple)
  console.log('1. Saving test theme override (ludo-p1 = #9C27B0)...');
  const saveRes = await page.evaluate(async () => {
    const res = await fetch('/api/theme', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        admin_user: 'admin',
        admin_pass: 'Alarcade123#',
        action: 'save',
        settings: [{ key: 'ludo-p1', value: '#9C27B0', category: 'ludo', label: 'ludo-p1' }]
      })
    });
    return await res.json();
  });
  console.log('   Save result:', JSON.stringify(saveRes));

  // Delete theme cache so override takes effect immediately
  // The server caches for 60s but we need to reload anyway
  await page.waitForTimeout(1000);

  // 2. Load ludo page and check if the override is applied
  console.log('2. Loading ludo game page to check override...');
  await page.goto(BASE + '/ludo-game?mode=bot&bots=1&difficulty=easy', { waitUntil: 'networkidle', timeout: 15000 });
  await page.waitForTimeout(2000);

  const themeCheck = await page.evaluate(() => {
    const style = document.getElementById('theme-overrides');
    const hasOverride = style ? style.textContent.includes('ludo-p1') : false;
    const computedColor = getComputedStyle(document.documentElement).getPropertyValue('--ludo-p1').trim();
    return {
      hasStyleTag: !!style,
      hasOverride: hasOverride,
      computedColor: computedColor,
      styleContent: style ? style.textContent : 'NO STYLE TAG'
    };
  });

  console.log('   Theme <style> tag exists:', themeCheck.hasStyleTag);
  console.log('   Contains ludo-p1 override:', themeCheck.hasOverride);
  console.log('   Computed --ludo-p1 value:', themeCheck.computedColor);
  console.log('   Full style content:', themeCheck.styleContent);

  await page.screenshot({ path: path.join(DIR, 'theme-test-purple-p1.png'), fullPage: true });

  // 3. Remove the test override
  console.log('\n3. Removing test override...');
  const delRes = await page.evaluate(async () => {
    const res = await fetch('/api/theme', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        admin_user: 'admin',
        admin_pass: 'Alarcade123#',
        action: 'delete',
        key: 'ludo-p1'
      })
    });
    return await res.json();
  });
  console.log('   Delete result:', JSON.stringify(delRes));

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