import { browser, expect } from '@wdio/globals';
// Phase A — Navigation: Terminal tabs + command palette + project focus + NEW tests.
// Shares a single Tauri app session with other phase-a-* spec files.

describe('Scenario 4 — Terminal Tab Management (data-testid)', () => {
  before(async () => {
    // Ensure Model tab active (terminal section only visible in Model tab)
    await browser.execute(() => {
      const tabs = document.querySelectorAll('[data-testid="project-tabs"] .ptab');
      if (tabs[0]) (tabs[0] as HTMLElement).click(); // Model is first tab
    });
    await browser.pause(300);
    // Expand terminal section if collapsed
    const isExpanded = await browser.execute(() =>
      document.querySelector('[data-testid="terminal-tabs"]') !== null
    );
    if (!isExpanded) {
      await browser.execute(() => {
        const toggle = document.querySelector('[data-testid="terminal-toggle"]');
        if (toggle) (toggle as HTMLElement).click();
      });
      await browser.waitUntil(
        async () => browser.execute(() =>
          document.querySelector('[data-testid="terminal-tabs"]') !== null
        ) as Promise<boolean>,
        { timeout: 5000, timeoutMsg: 'Terminal tabs did not appear after expanding' },
      );
    }
  });

  it('should display terminal tabs container', async () => {
    const exists = await browser.execute(() =>
      document.querySelector('[data-testid="terminal-tabs"]') !== null
    );
    expect(exists).toBe(true);
  });

  it('should add a shell tab via data-testid button', async () => {
    await browser.execute(() => {
      const btn = document.querySelector('[data-testid="tab-add"]');
      if (btn) (btn as HTMLElement).click();
    });
    await browser.pause(500);
    const tabTitle = await browser.execute(() => {
      const el = document.querySelector('.tab-bar .tab-title');
      return el?.textContent ?? '';
    });
    expect(tabTitle.toLowerCase()).toContain('shell');
  });

  it('should show active tab styling after adding tab', async () => {
    // Ensure at least one tab exists (may need to add one)
    const tabCount = await browser.execute(() =>
      document.querySelectorAll('[data-testid="terminal-tabs"] .tab-bar .tab').length
    );
    if (tabCount === 0) {
      await browser.execute(() => {
        const btn = document.querySelector('[data-testid="tab-add"]') ?? document.querySelector('.add-first');
        if (btn) (btn as HTMLElement).click();
      });
      await browser.pause(500);
    }
    const hasActive = await browser.execute(() =>
      document.querySelector('[data-testid="terminal-tabs"] .tab.active') !== null
    );
    expect(hasActive).toBe(true);
  });

  it('should close tab and show empty state', async () => {
    await browser.execute(() => {
      document.querySelectorAll('[data-testid="terminal-tabs"] .tab-close').forEach(btn => (btn as HTMLElement).click());
    });
    await browser.pause(500);
    const hasEmpty = await browser.execute(() =>
      document.querySelector('[data-testid="terminal-tabs"] .add-first') !== null
        || document.querySelector('[data-testid="terminal-tabs"] .empty-terminals') !== null
    );
    expect(hasEmpty).toBe(true);
  });

  it('should show terminal toggle chevron', async () => {
    const has = await browser.execute(() => {
      const toggle = document.querySelector('[data-testid="terminal-toggle"]');
      return toggle?.querySelector('.toggle-chevron') !== null;
    });
    expect(has).toBe(true);
  });

  it('should show agent preview button (eye icon) if agent session active', async () => {
    // Preview button presence depends on active agent session — may not be present
    const hasPreviewBtn = await browser.execute(() => {
      const tabs = document.querySelector('[data-testid="terminal-tabs"]');
      return tabs?.querySelector('.tab-add.tab-agent-preview') !== null;
    });
    if (hasPreviewBtn) {
      const withinTabs = await browser.execute(() => {
        const tabs = document.querySelector('[data-testid="terminal-tabs"]');
        return tabs?.querySelector('.tab-add.tab-agent-preview') !== null;
      });
      expect(withinTabs).toBe(true);
    }
  });

  it('should maintain terminal state across project tab switches', async () => {
    // Add a shell tab
    await browser.execute(() => {
      const btn = document.querySelector('[data-testid="tab-add"]');
      if (btn) (btn as HTMLElement).click();
    });
    await browser.pause(500);
    const countBefore = await browser.execute(() =>
      document.querySelectorAll('.tab-bar .tab').length,
    );
    // Switch to Files tab and back
    await browser.execute(() => {
      const tabs = document.querySelectorAll('[data-testid="project-tabs"] .ptab');
      if (tabs.length >= 2) (tabs[1] as HTMLElement).click();
    });
    await browser.pause(300);
    await browser.execute(() => {
      const tab = document.querySelector('[data-testid="project-tabs"] .ptab');
      if (tab) (tab as HTMLElement).click();
    });
    await browser.pause(300);
    const countAfter = await browser.execute(() =>
      document.querySelectorAll('.tab-bar .tab').length,
    );
    expect(countAfter).toBe(countBefore);
    // Clean up
    await browser.execute(() => {
      document.querySelectorAll('.tab-close').forEach(btn => (btn as HTMLElement).click());
    });
    await browser.pause(300);
  });

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

describe('Scenario 5 — Command Palette (data-testid)', () => {
  before(async () => {
    await browser.execute(() => {
      const p = document.querySelector('[data-testid="command-palette"]');
      if (p && (p as HTMLElement).offsetParent !== null)
        document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
    });
    await browser.pause(200);
  });

  it('should open palette and show data-testid input', async () => {
    await browser.execute(() => document.body.focus());
    await browser.pause(200);
    await browser.keys(['Control', 'k']);
    const palette = await browser.$('[data-testid="command-palette"]');
    await palette.waitForDisplayed({ timeout: 3000 });
    const input = await browser.$('[data-testid="palette-input"]');
    await expect(input).toBeDisplayed();
  });

  it('should have focused input', async () => {
    const isFocused = await browser.execute(() => {
      const el = document.querySelector('[data-testid="palette-input"]') as HTMLInputElement | null;
      if (!el) return false;
      el.focus();
      return el === document.activeElement;
    });
    expect(isFocused).toBe(true);
  });

  it('should show at least one group item', async () => {
    const items = await browser.$$('.palette-item');
    expect(items.length).toBeGreaterThanOrEqual(1);
  });

  it('should filter and show no-results for nonsense query', async () => {
    const input = await browser.$('[data-testid="palette-input"]');
    await input.setValue('zzz_no_match_xyz');
    await browser.pause(300);
    const noResults = await browser.$('.no-results');
    await expect(noResults).toBeDisplayed();
  });

  it('should show command categories in palette', async () => {
    // Re-open palette if closed by previous test
    const isOpen = await browser.execute(() =>
      document.querySelector('[data-testid="command-palette"]') !== null
    );
    if (!isOpen) {
      await browser.keys(['Control', 'k']);
      await browser.pause(500);
    }
    const catCount = await browser.execute(() =>
      document.querySelectorAll('.palette-category').length,
    );
    expect(catCount).toBeGreaterThanOrEqual(1);
  });

  it('should execute palette command (e.g., toggle settings)', async () => {
    const input = await browser.$('[data-testid="palette-input"]');
    await input.clearValue();
    await input.setValue('settings');
    await browser.pause(300);
    const executed = await browser.execute(() => {
      const item = document.querySelector('.palette-item');
      if (item) { (item as HTMLElement).click(); return true; }
      return false;
    });
    expect(executed).toBe(true);
    await browser.pause(500);
    const paletteGone = await browser.execute(() => {
      const p = document.querySelector('[data-testid="command-palette"]');
      return p === null || (p as HTMLElement).offsetParent === null;
    });
    expect(paletteGone).toBe(true);
    // Clean up
    await browser.keys('Escape');
    await browser.pause(300);
  });

  it('should show keyboard shortcut hints in palette items', async () => {
    await browser.execute(() => document.body.focus());
    await browser.pause(200);
    await browser.keys(['Control', 'k']);
    await browser.pause(300);
    const has = await browser.execute(() =>
      document.querySelectorAll('.palette-item .cmd-shortcut').length > 0,
    );
    expect(has).toBe(true);
  });

  it('should close on Escape', async () => {
    await browser.keys('Escape');
    const palette = await browser.$('[data-testid="command-palette"]');
    await browser.waitUntil(async () => !(await palette.isDisplayed()), { timeout: 3000 });
  });
});

describe('Scenario 6 — Project Focus & Tab Switching', () => {
  before(async () => {
    await browser.execute(() => {
      const tab = document.querySelector('[data-testid="project-tabs"] .ptab');
      if (tab) (tab as HTMLElement).click();
    });
    await browser.pause(300);
  });

  it('should focus project on header click', async () => {
    await browser.execute(() => {
      const header = document.querySelector('.project-header');
      if (header) (header as HTMLElement).click();
    });
    await browser.pause(300);
    const activeBox = await browser.$('.project-box.active');
    await expect(activeBox).toBeDisplayed();
  });

  it('should switch to Files tab and back without losing agent session', async () => {
    expect(await browser.execute(() =>
      document.querySelector('[data-testid="agent-session"]') !== null,
    )).toBe(true);
    await browser.execute(() => {
      const tabs = document.querySelectorAll('[data-testid="project-tabs"] .ptab');
      if (tabs.length >= 2) (tabs[1] as HTMLElement).click();
    });
    await browser.pause(500);
    expect(await browser.execute(() =>
      document.querySelector('[data-testid="agent-session"]') !== null,
    )).toBe(true);
    await browser.execute(() => {
      const tab = document.querySelector('[data-testid="project-tabs"] .ptab');
      if (tab) (tab as HTMLElement).click();
    });
    await browser.pause(300);
    const session = await browser.$('[data-testid="agent-session"]');
    await expect(session).toBeDisplayed();
  });

  it('should preserve agent status across tab switches', async () => {
    const statusBefore = await browser.execute(() =>
      document.querySelector('[data-testid="agent-pane"]')?.getAttribute('data-agent-status') ?? 'unknown',
    );
    await browser.execute(() => {
      const tabs = document.querySelectorAll('[data-testid="project-tabs"] .ptab');
      if (tabs.length >= 3) (tabs[2] as HTMLElement).click();
    });
    await browser.pause(300);
    await browser.execute(() => {
      const tab = document.querySelector('[data-testid="project-tabs"] .ptab');
      if (tab) (tab as HTMLElement).click();
    });
    await browser.pause(300);
    const statusAfter = await browser.execute(() =>
      document.querySelector('[data-testid="agent-pane"]')?.getAttribute('data-agent-status') ?? 'unknown',
    );
    expect(statusAfter).toBe(statusBefore);
  });

  it('should show tab count badge in terminal toggle', async () => {
    await browser.execute(() => {
      const toggle = document.querySelector('[data-testid="terminal-toggle"]');
      if (toggle) (toggle as HTMLElement).click();
    });
    await browser.pause(300);
    await browser.execute(() => {
      const btn = document.querySelector('[data-testid="tab-add"]');
      if (btn) (btn as HTMLElement).click();
    });
    await browser.pause(500);
    const text = await browser.execute(() =>
      document.querySelector('[data-testid="terminal-toggle"]')?.textContent?.trim() ?? '',
    );
    expect(text.length).toBeGreaterThan(0);
    // Clean up
    await browser.execute(() => {
      document.querySelectorAll('.tab-close').forEach(btn => (btn as HTMLElement).click());
    });
    await browser.pause(300);
    await browser.execute(() => {
      const toggle = document.querySelector('[data-testid="terminal-toggle"]');
      if (toggle?.querySelector('.toggle-chevron.expanded')) (toggle as HTMLElement).click();
    });
    await browser.pause(300);
  });
});
