/**
 * Interactive States Tests
 *
 * Tests for active/expanded UI states where CSS often breaks:
 * - Research page advanced options expanded
 * - Settings search filtering
 * - Mobile "More" menu navigation
 * - Benchmark form sections
 * - Help panel expanded states
 *
 * These tests verify that interactive elements don't cause overflow,
 * z-index issues, or layout breakage when activated.
 *
 * Note: Authentication is handled by auth.setup.js via storageState
 */

import { test, expect } from '@playwright/test';
const {
  MOBILE_NAV_SELECTOR,
  waitForPageLoad,
} = require('./helpers/mobile-utils');

// ============================================
// RESEARCH PAGE - ADVANCED OPTIONS EXPANDED
// ============================================

test.describe('Research - Advanced Options Expanded', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/');
    await waitForPageLoad(page, { path: '/' });
  });

  test('advanced options expand without overflow', async ({ page }) => {
    const toggleBtn = page.locator('.ldr-advanced-options-toggle');

    if (await toggleBtn.count() > 0 && await toggleBtn.isVisible()) {
      // Ensure panel is expanded (may already be open by default)
      const panel = page.locator('.ldr-advanced-options-panel, #advanced-options-panel');
      const isAlreadyVisible = await panel.first().isVisible().catch(() => false);
      if (!isAlreadyVisible) {
        await toggleBtn.click();
        await panel.first().waitFor({ state: 'visible' });
      }
      if (await panel.count() > 0) {
        await expect(panel.first()).toBeVisible();
      }

      // Check no horizontal overflow
      const hasOverflow = await page.evaluate(() =>
        document.documentElement.scrollWidth > window.innerWidth
      );

      if (hasOverflow) {
        const overflowInfo = await page.evaluate(() => {
          const elements = [];
          document.querySelectorAll('.ldr-advanced-options-panel *, #advanced-options-panel *').forEach((el) => {
            const rect = el.getBoundingClientRect();
            if (rect.right > window.innerWidth) {
              elements.push({
                tag: el.tagName.toLowerCase(),
                class: el.className?.toString().slice(0, 60),
                overflow: Math.round(rect.right - window.innerWidth),
              });
            }
          });
          return elements.slice(0, 5);
        });
        console.log('Advanced options overflow:', JSON.stringify(overflowInfo, null, 2));
      }

      expect(hasOverflow, 'Advanced options should not cause horizontal overflow').toBe(false);
    }
  });

  test('advanced options panel fits viewport on mobile', async ({ page, isMobile }, testInfo) => {
    if (!isMobile) {
      test.skip();
      return;
    }

    const isTablet = testInfo.project.name.includes('iPad');
    if (isTablet) {
      test.skip();
      return;
    }

    const toggleBtn = page.locator('.ldr-advanced-options-toggle');

    if (await toggleBtn.count() > 0 && await toggleBtn.isVisible()) {
      // Ensure panel is expanded (may already be open by default)
      const panel = page.locator('.ldr-advanced-options-panel, #advanced-options-panel');
      const isAlreadyVisible = await panel.first().isVisible().catch(() => false);
      if (!isAlreadyVisible) {
        await toggleBtn.click();
        await panel.first().waitFor({ state: 'visible' });
      }

      if (await panel.count() > 0 && await panel.first().isVisible()) {
        const box = await panel.first().boundingBox();
        const viewportWidth = await page.evaluate(() => window.innerWidth);

        if (box) {
          expect(
            box.x + box.width,
            'Advanced options panel should fit viewport width'
          ).toBeLessThanOrEqual(viewportWidth + 5);
        }
      }
    }
  });
});

// ============================================
// SETTINGS SEARCH FILTERING
// ============================================

test.describe('Settings - Search Filtering', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/settings/');
    await waitForPageLoad(page, { path: '/settings/' });
    await page.waitForSelector('.ldr-loading-spinner', { state: 'hidden', timeout: 10000 }).catch(() => {});
  });

  test('search filter shows results for "model"', async ({ page }) => {
    const searchInput = page.locator('#settings-search, .ldr-search-input');

    if (await searchInput.count() > 0 && await searchInput.isVisible()) {
      await searchInput.fill('model');
      await page.locator('.ldr-settings-group, .ldr-setting-item, [class*="setting"]').first().waitFor({ state: 'visible' });

      // Some settings should be visible (matching "model")
      const visibleSettings = await page.evaluate(() => {
        const items = document.querySelectorAll(
          '.ldr-settings-group, .ldr-setting-item, [class*="setting"]'
        );
        let visibleCount = 0;
        items.forEach(el => {
          const style = window.getComputedStyle(el);
          if (style.display !== 'none' && style.visibility !== 'hidden') {
            visibleCount++;
          }
        });
        return visibleCount;
      });

      expect(visibleSettings, 'Should show some settings matching "model"').toBeGreaterThan(0);
    }
  });

  test('search filter empty state for non-matching query', async ({ page }) => {
    const searchInput = page.locator('#settings-search, .ldr-search-input');

    if (await searchInput.count() > 0 && await searchInput.isVisible()) {
      await searchInput.fill('zzz_nonexistent_setting_xyz');
      await page.waitForLoadState('domcontentloaded');
      await page.waitForFunction(() => {
        const items = document.querySelectorAll('.settings-item');
        let visibleCount = 0;
        items.forEach(el => {
          const style = window.getComputedStyle(el);
          if (style.display !== 'none' && style.visibility !== 'hidden' && el.getBoundingClientRect().height > 0) {
            visibleCount++;
          }
        });
        return visibleCount === 0;
      }, { timeout: 10000 });

      // Check that no setting items are visible
      const visibleSettings = await page.evaluate(() => {
        const items = document.querySelectorAll('.settings-item');
        let visibleCount = 0;
        items.forEach(el => {
          const style = window.getComputedStyle(el);
          if (style.display !== 'none' && style.visibility !== 'hidden' && el.getBoundingClientRect().height > 0) {
            visibleCount++;
          }
        });
        return visibleCount;
      });

      // With a nonsense query, no setting items should match
      expect(visibleSettings, 'Non-matching query should show no setting items').toBe(0);
    }
  });

});

// ============================================
// MOBILE "MORE" MENU NAVIGATION
// ============================================

test.describe('Mobile More Menu - Navigation', () => {
  test('navigate to Metrics via More menu', async ({ page, isMobile }, testInfo) => {
    if (!isMobile) {
      test.skip();
      return;
    }

    const isTablet = testInfo.project.name.includes('iPad');
    if (isTablet) {
      test.skip();
      return;
    }

    await page.goto('/');
    await waitForPageLoad(page, { path: '/' });

    // Look for the "More" button in mobile nav
    const moreBtn = page.locator('.ldr-mobile-bottom-nav button:has-text("More"), .ldr-mobile-bottom-nav [aria-label="More"]');

    if (await moreBtn.count() > 0) {
      await moreBtn.click();

      // Look for Metrics item in the opened sheet menu (rendered as button, not <a>)
      const metricsItem = page.locator('.ldr-mobile-sheet-item[data-item-id="metrics"]');
      await metricsItem.first().waitFor({ state: 'visible' });

      if (await metricsItem.count() > 0 && await metricsItem.first().isVisible()) {
        await metricsItem.first().click();
        await page.waitForLoadState('domcontentloaded');

        // Should now be on the metrics page
        expect(page.url()).toContain('/metrics');
      }
    }
  });

  test('navigate to Library via bottom nav', async ({ page, isMobile }, testInfo) => {
    if (!isMobile) {
      test.skip();
      return;
    }

    const isTablet = testInfo.project.name.includes('iPad');
    if (isTablet) {
      test.skip();
      return;
    }

    await page.goto('/');
    await waitForPageLoad(page, { path: '/' });

    // Wait for mobile navigation JS to finish initializing
    await page.waitForFunction(() => window.mobileNav && window.mobileNav.initialized, { timeout: 10000 }).catch(() => {});

    const libraryTab = page.locator('.ldr-mobile-nav-tab[data-tab-id="library"]');

    if (await libraryTab.count() > 0) {
      await libraryTab.first().click();
      await page.waitForURL('**/library**', { timeout: 15000 });

      expect(page.url()).toContain('/library');
    }
  });

});

// ============================================
// BENCHMARK FORM SECTIONS
// ============================================

test.describe('Benchmark Form - Layout', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/benchmark/');
    await page.waitForLoadState('domcontentloaded');
    // Wait for benchmark form to load
    await page.waitForSelector('#benchmark-form, form, .ldr-card', { timeout: 10000 }).catch(() => {});
  });

  test('benchmark form has no horizontal overflow', async ({ page }) => {
    const hasOverflow = await page.evaluate(() =>
      document.documentElement.scrollWidth > window.innerWidth
    );

    expect(hasOverflow, 'Benchmark form should have no horizontal overflow').toBe(false);
  });
});

// ============================================
// HELP PANEL EXPANDED STATE
// ============================================

test.describe('Help Panel - Expanded State', () => {
  test('help panel expands without overflow on Research page', async ({ page }) => {
    await page.goto('/');
    await waitForPageLoad(page, { path: '/' });

    // Look for help panel toggle
    const helpToggle = page.locator('.ldr-help-panel-toggle, [class*="help-toggle"], button:has-text("Help")');

    if (await helpToggle.count() > 0 && await helpToggle.first().isVisible()) {
      await helpToggle.first().click();
      await page.locator('.ldr-help-panel, [class*="help-panel"]').first().waitFor({ state: 'visible' });

      // Check for overflow
      const hasOverflow = await page.evaluate(() =>
        document.documentElement.scrollWidth > window.innerWidth
      );

      expect(hasOverflow, 'Help panel should not cause overflow').toBe(false);
    }
  });

});
