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

// Phase A — Structure: App structural integrity + settings panel + NEW structural tests.
// Shares a single Tauri app session with other phase-a-* spec files.

// --- Scenario 1: App renders with project grid and data-testid anchors ---

describe('Scenario 1 — App Structural Integrity', () => {
  it('should render the status bar with data-testid', async () => {
    const bar = await browser.$('[data-testid="status-bar"]');
    await expect(bar).toBeDisplayed();
  });

  it('should render the sidebar rail with data-testid', async () => {
    const rail = await browser.$('[data-testid="sidebar-rail"]');
    await expect(rail).toBeDisplayed();
  });

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

  it('should have data-project-id on project boxes', async () => {
    const projectId = await exec(() => {
      const box = document.querySelector('[data-testid="project-box"]');
      return box?.getAttribute('data-project-id') ?? null;
    });
    expect(projectId).not.toBeNull();
    expect((projectId as string).length).toBeGreaterThan(0);
  });

  it('should render project tabs with data-testid', async () => {
    const tabs = await browser.$('[data-testid="project-tabs"]');
    await expect(tabs).toBeDisplayed();
  });

  it('should render agent session component', async () => {
    const session = await browser.$('[data-testid="agent-session"]');
    await expect(session).toBeDisplayed();
  });

  // --- NEW structural tests ---

  it('should render sidebar gear icon for settings', async () => {
    const btn = await browser.$('[data-testid="settings-btn"]');
    await expect(btn).toBeExisting();
    await expect(btn).toBeDisplayed();
  });

  it('should have data-testid on status bar sections (agent-counts, cost, attention)', async () => {
    // Status bar left section contains agent state items and attention
    const leftItems = await exec(() => {
      const bar = document.querySelector('[data-testid="status-bar"]');
      if (!bar) return { left: false, right: false };
      const left = bar.querySelector('.left');
      const right = bar.querySelector('.right');
      return { left: left !== null, right: right !== null };
    });
    expect(leftItems.left).toBe(true);
    expect(leftItems.right).toBe(true);
  });

  it('should render project accent colors (different per slot)', async () => {
    const accents = await exec(() => {
      const boxes = document.querySelectorAll('[data-testid="project-box"]');
      const styles: string[] = [];
      boxes.forEach(box => {
        const style = (box as HTMLElement).getAttribute('style') ?? '';
        styles.push(style);
      });
      return styles;
    });
    // Each project box should have a --accent CSS variable
    for (const style of accents) {
      expect(style).toContain('--accent');
    }
    // If multiple boxes exist, accents should differ (cyclic assignment)
    if (accents.length >= 2) {
      // At least the first two should have different accent values
      expect(accents[0]).not.toBe(accents[1]);
    }
  });

  it('should show project name in header', async () => {
    const name = await exec(() => {
      const el = document.querySelector('.project-header .project-name');
      return el?.textContent?.trim() ?? '';
    });
    expect(name.length).toBeGreaterThan(0);
  });

  it('should show project icon in header', async () => {
    const icon = await exec(() => {
      const el = document.querySelector('.project-header .project-icon');
      return el?.textContent?.trim() ?? '';
    });
    // Icon should be a non-empty string (emoji or fallback folder icon)
    expect(icon.length).toBeGreaterThan(0);
  });

  it('should have correct grid layout (project boxes fill available space)', async () => {
    const layout = await exec(() => {
      const box = document.querySelector('[data-testid="project-box"]') as HTMLElement | null;
      if (!box) return { width: 0, height: 0 };
      const rect = box.getBoundingClientRect();
      return { width: rect.width, height: rect.height };
    });
    // Project box should have non-trivial dimensions (fills grid slot)
    expect(layout.width).toBeGreaterThan(100);
    expect(layout.height).toBeGreaterThan(100);
  });
});

// --- Scenario 2: Settings panel via data-testid ---

describe('Scenario 2 — Settings Panel (data-testid)', () => {
  before(async () => {
    // Ensure settings panel is closed before starting
    await exec(() => {
      const panel = document.querySelector('.sidebar-panel');
      if (panel && (panel as HTMLElement).offsetParent !== null) {
        const btn = document.querySelector('.panel-close');
        if (btn) (btn as HTMLElement).click();
      }
    });
    await browser.pause(300);
  });

  it('should open settings via data-testid button', async () => {
    // Use JS click for reliability with WebKit2GTK/tauri-driver
    await exec(() => {
      const btn = document.querySelector('[data-testid="settings-btn"]');
      if (btn) (btn as HTMLElement).click();
    });

    const panel = await browser.$('.sidebar-panel');
    await panel.waitForDisplayed({ timeout: 5000 });
    // Wait for settings panel content to mount
    await browser.waitUntil(
      async () => {
        const has = await exec(() =>
          document.querySelector('.settings-panel .settings-content') !== null,
        );
        return has as boolean;
      },
      { timeout: 5000 },
    );
    await expect(panel).toBeDisplayed();
  });

  it('should close settings with Escape', async () => {
    await browser.keys('Escape');
    const panel = await browser.$('.sidebar-panel');
    await panel.waitForDisplayed({ timeout: 3000, reverse: true });
  });
});
