import { browser, expect } from '@wdio/globals';
import { exec } from '../helpers/execute.ts';

/** Reset UI to home state (close any open panels/overlays). */
async function resetToHomeState(): Promise<void> {
  const panel = await browser.$('.sidebar-panel');
  if (await panel.isDisplayed().catch(() => false)) {
    await exec(() => {
      const btn = document.querySelector('.panel-close');
      if (btn) (btn as HTMLElement).click();
    });
    await browser.pause(500);
  }
  const overlay = await browser.$('.search-overlay');
  if (await overlay.isExisting()) await browser.keys('Escape');
}

/** Open the settings panel, waiting for content to render. */
async function openSettings(): Promise<void> {
  const panel = await browser.$('.sidebar-panel');
  const isOpen = await panel.isDisplayed().catch(() => false);
  if (!isOpen) {
    await exec(() => {
      const btn = document.querySelector('[data-testid="settings-btn"]');
      if (btn) (btn as HTMLElement).click();
    });
    await panel.waitForDisplayed({ timeout: 5000 });
  }
  await browser.waitUntil(
    async () => {
      const has = await exec(() =>
        document.querySelector('.settings-panel .settings-content') !== null,
      );
      return has as boolean;
    },
    { timeout: 5000, timeoutMsg: 'Settings content did not render within 5s' },
  );
  await browser.pause(200);
}

/** Close the settings panel if open. */
async function closeSettings(): Promise<void> {
  const panel = await browser.$('.sidebar-panel');
  if (await panel.isDisplayed().catch(() => false)) {
    await exec(() => {
      const btn = document.querySelector('.panel-close');
      if (btn) (btn as HTMLElement).click();
    });
    await browser.pause(500);
  }
}

describe('Agent Orchestrator — Terminal Tabs', () => {
  before(async () => {
    await resetToHomeState();
    // Ensure Model tab is active so terminal section is visible
    await exec(() => {
      const tab = document.querySelector('.project-box .ptab');
      if (tab) (tab as HTMLElement).click();
    });
    await browser.pause(300);
  });

  it('should show terminal toggle on Model tab', async () => {
    const toggle = await browser.$('[data-testid="terminal-toggle"]');
    await expect(toggle).toBeDisplayed();

    const label = await browser.$('.toggle-label');
    const text = await label.getText();
    expect(text.toLowerCase()).toContain('terminal');
  });

  it('should expand terminal area on toggle click', async () => {
    // Click terminal toggle via JS
    await exec(() => {
      const toggle = document.querySelector('[data-testid="terminal-toggle"]');
      if (toggle) (toggle as HTMLElement).click();
    });
    await browser.pause(500);

    const termTabs = await browser.$('[data-testid="terminal-tabs"]');
    await expect(termTabs).toBeDisplayed();

    // Chevron should have expanded class
    const chevron = await browser.$('.toggle-chevron.expanded');
    await expect(chevron).toBeExisting();
  });

  it('should show add tab button when terminal expanded', async () => {
    const addBtn = await browser.$('[data-testid="tab-add"]');
    await expect(addBtn).toBeDisplayed();
  });

  it('should add a shell tab', async () => {
    // Click add tab button via JS
    await exec(() => {
      const btn = document.querySelector('[data-testid="tab-add"]');
      if (btn) (btn as HTMLElement).click();
    });
    await browser.pause(500);

    // Verify tab title via JS to avoid stale element issues
    const title = await exec(() => {
      const el = document.querySelector('.tab-bar .tab-title');
      return el ? el.textContent : '';
    });
    expect((title as string).toLowerCase()).toContain('shell');
  });

  it('should show active tab styling', async () => {
    const activeTab = await browser.$('.tab.active');
    await expect(activeTab).toBeExisting();
  });

  it('should add a second shell tab and switch between them', async () => {
    // Add second tab via JS
    await exec(() => {
      const btn = document.querySelector('[data-testid="tab-add"]');
      if (btn) (btn as HTMLElement).click();
    });
    await browser.pause(500);

    const tabCount = await exec(() => {
      return document.querySelectorAll('.tab-bar .tab').length;
    });
    expect(tabCount as number).toBeGreaterThanOrEqual(2);

    // Click first tab and verify it becomes active with Shell title
    await exec(() => {
      const tabs = document.querySelectorAll('.tab-bar .tab');
      if (tabs[0]) (tabs[0] as HTMLElement).click();
    });
    await browser.pause(300);

    const activeTitle = await exec(() => {
      const active = document.querySelector('.tab-bar .tab.active .tab-title');
      return active ? active.textContent : '';
    });
    expect(activeTitle as string).toContain('Shell');
  });

  it('should close a tab', async () => {
    const tabsBefore = await browser.$$('.tab');
    const countBefore = tabsBefore.length;

    // Close the last tab
    await exec(() => {
      const closeBtns = document.querySelectorAll('.tab-close');
      if (closeBtns.length > 0) {
        (closeBtns[closeBtns.length - 1] as HTMLElement).click();
      }
    });
    await browser.pause(500);

    const tabsAfter = await browser.$$('.tab');
    expect(tabsAfter.length).toBe(Number(countBefore) - 1);
  });

  after(async () => {
    // Clean up: close remaining tabs and collapse terminal
    await exec(() => {
      const closeBtns = document.querySelectorAll('.tab-close');
      closeBtns.forEach(btn => (btn as HTMLElement).click());
    });
    await browser.pause(300);

    // Collapse terminal
    await exec(() => {
      const toggle = document.querySelector('[data-testid="terminal-toggle"]');
      if (toggle) {
        const chevron = toggle.querySelector('.toggle-chevron.expanded');
        if (chevron) (toggle as HTMLElement).click();
      }
    });
    await browser.pause(300);
  });
});

describe('Agent Orchestrator — Theme Switching', () => {
  before(async () => {
    await resetToHomeState();
    await openSettings();
  });

  after(async () => {
    await closeSettings();
  });

  it('should show theme dropdown with group labels', async () => {
    // Close any open dropdowns first
    await exec(() => {
      const openMenu = document.querySelector('.dropdown-menu');
      if (openMenu) {
        const trigger = openMenu.closest('.custom-dropdown')?.querySelector('.dropdown-btn');
        if (trigger) (trigger as HTMLElement).click();
      }
    });
    await browser.pause(200);

    // Click the theme dropdown button (first dropdown in appearance)
    await exec(() => {
      const trigger = document.querySelector('.appearance .custom-dropdown .dropdown-btn');
      if (trigger) (trigger as HTMLElement).click();
    });
    await browser.pause(500);

    const menu = await browser.$('.dropdown-menu');
    await menu.waitForExist({ timeout: 5000 });

    // Should have group labels (Catppuccin, Editor, Deep Dark)
    const groupLabels = await browser.$$('.group-label');
    expect(groupLabels.length).toBeGreaterThanOrEqual(2);

    // Close dropdown
    await exec(() => {
      const trigger = document.querySelector('.appearance .custom-dropdown .dropdown-btn');
      if (trigger) (trigger as HTMLElement).click();
    });
    await browser.pause(300);
  });

  it('should switch theme and update CSS variables', async () => {
    // Get current base color
    const baseBefore = await exec(() => {
      return getComputedStyle(document.documentElement).getPropertyValue('--ctp-base').trim();
    });

    // Open theme dropdown
    await exec(() => {
      const trigger = document.querySelector('.appearance .custom-dropdown .dropdown-btn');
      if (trigger) (trigger as HTMLElement).click();
    });
    await browser.pause(500);

    const menu = await browser.$('.dropdown-menu');
    await menu.waitForExist({ timeout: 5000 });

    // Click the first non-active theme option
    const changed = await exec(() => {
      const options = document.querySelectorAll('.dropdown-menu .dropdown-item:not(.active)');
      if (options.length > 0) {
        (options[0] as HTMLElement).click();
        return true;
      }
      return false;
    });
    expect(changed).toBe(true);
    await browser.pause(500);

    // Verify CSS variable changed
    const baseAfter = await exec(() => {
      return getComputedStyle(document.documentElement).getPropertyValue('--ctp-base').trim();
    });
    expect(baseAfter).not.toBe(baseBefore);

    // Switch back to Catppuccin Mocha (first option) to restore state
    await exec(() => {
      const trigger = document.querySelector('.appearance .custom-dropdown .dropdown-btn');
      if (trigger) (trigger as HTMLElement).click();
    });
    await browser.pause(500);
    await exec(() => {
      const options = document.querySelectorAll('.dropdown-menu .dropdown-item');
      if (options.length > 0) (options[0] as HTMLElement).click();
    });
    await browser.pause(300);
  });

  it('should show active theme option', async () => {
    await exec(() => {
      const trigger = document.querySelector('.appearance .custom-dropdown .dropdown-btn');
      if (trigger) (trigger as HTMLElement).click();
    });
    await browser.pause(500);

    const menu = await browser.$('.dropdown-menu');
    await menu.waitForExist({ timeout: 5000 });

    const activeOption = await browser.$('.dropdown-item.active');
    await expect(activeOption).toBeExisting();

    await exec(() => {
      const trigger = document.querySelector('.appearance .custom-dropdown .dropdown-btn');
      if (trigger) (trigger as HTMLElement).click();
    });
    await browser.pause(300);
  });
});
