import { browser, expect } from '@wdio/globals';

describe('BTerminal — Workspace & Projects', () => {
  it('should display the project grid', async () => {
    const grid = await browser.$('.project-grid');
    await expect(grid).toBeDisplayed();
  });

  it('should render at least one project box', async () => {
    const boxes = await browser.$$('.project-box');
    expect(boxes.length).toBeGreaterThanOrEqual(1);
  });

  it('should show project header with name', async () => {
    const header = await browser.$('.project-header');
    await expect(header).toBeDisplayed();

    const name = await browser.$('.project-name');
    const text = await name.getText();
    expect(text.length).toBeGreaterThan(0);
  });

  it('should show project-level tabs (Model, Docs, Context, Files, SSH, Memory, ...)', async () => {
    const box = await browser.$('.project-box');
    const tabs = await box.$$('.ptab');
    // v3 has 6+ tabs: Model, Docs, Context, Files, SSH, Memory (+ role-specific)
    expect(tabs.length).toBeGreaterThanOrEqual(6);
  });

  it('should highlight active project on click', async () => {
    const header = await browser.$('.project-header');
    await header.click();

    const activeBox = await browser.$('.project-box.active');
    await expect(activeBox).toBeDisplayed();
  });

  it('should switch project tabs', async () => {
    // Use JS click — WebDriver clicks don't always trigger Svelte onclick
    // on buttons inside complex components via WebKit2GTK/tauri-driver
    const switched = await browser.execute(() => {
      const box = document.querySelector('.project-box');
      if (!box) return false;
      const tabs = box.querySelectorAll('.ptab');
      if (tabs.length < 2) return false;
      (tabs[1] as HTMLElement).click();
      return true;
    });
    expect(switched).toBe(true);
    await browser.pause(500);

    const box = await browser.$('.project-box');
    const activeTab = await box.$('.ptab.active');
    const text = await activeTab.getText();
    // Tab[1] is "Docs" in v3 tab bar (Model, Docs, Context, Files, ...)
    expect(text.toLowerCase()).toContain('docs');

    // Switch back to Model tab
    await browser.execute(() => {
      const tab = document.querySelector('.project-box .ptab');
      if (tab) (tab as HTMLElement).click();
    });
    await browser.pause(300);
  });

  it('should display the status bar with project count', async () => {
    const statusBar = await browser.$('.status-bar .left');
    const text = await statusBar.getText();
    expect(text).toContain('projects');
  });

  it('should display project and agent info in status bar', async () => {
    const statusBar = await browser.$('.status-bar .left');
    const text = await statusBar.getText();
    // Status bar always shows project count; agent counts only when > 0
    // (shows "X running", "X idle", "X stalled" — not the word "agents")
    expect(text).toContain('projects');
  });
});
