/**
 * Diagnostics settings tab tests — connection status, fleet info, refresh.
 *
 * Diagnostics tab is Electrobun-specific. Tests gracefully skip on Tauri
 * where this tab does not exist.
 */

import { browser, expect } from '@wdio/globals';
import * as S from '../helpers/selectors.ts';
import { openSettings, closeSettings, switchSettingsCategory } from '../helpers/actions.ts';
import { exec } from '../helpers/execute.ts';

/** Navigate to the last settings tab (expected to be Diagnostics on Electrobun) */
async function navigateToLastTab(): Promise<number> {
  const tabCount = await exec(() => {
    return (document.querySelectorAll('.settings-sidebar .sidebar-item').length
      || document.querySelectorAll('.settings-tab').length
      || document.querySelectorAll('.cat-btn').length);
  });
  if (tabCount > 0) {
    await switchSettingsCategory(tabCount - 1);
  }
  return tabCount;
}

describe('Diagnostics tab', function () {
  before(async function () {
    await openSettings();
    const isOpen = await exec(() => {
      const el = document.querySelector('.sidebar-panel, .settings-drawer, .settings-panel');
      return el ? getComputedStyle(el).display !== 'none' : false;
    });
    if (!isOpen) { this.skip(); return; }
    await navigateToLastTab();
  });

  after(async () => {
    await browser.keys('Escape');
    await browser.pause(300);
  });

  it('should render the diagnostics container', async function () {
    const exists = await exec((sel: string) => {
      return document.querySelector(sel) !== null;
    }, S.DIAGNOSTICS);
    if (!exists) {
      // Diagnostics tab is Electrobun-only — skip on Tauri
      this.skip();
      return;
    }
    const el = await browser.$(S.DIAGNOSTICS);
    await expect(el).toBeDisplayed();
  });

  it('should show Transport Diagnostics heading', async function () {
    const exists = await exec(() => {
      return document.querySelector('.diagnostics') !== null;
    });
    if (!exists) { this.skip(); return; }

    const text = await exec((sel: string) => {
      const el = document.querySelector(sel);
      return el?.textContent ?? '';
    }, S.DIAG_HEADING);
    if (text) {
      expect(text).toContain('Transport Diagnostics');
    }
  });

  it('should show PTY daemon connection status', async function () {
    const exists = await exec(() => {
      return document.querySelector('.diagnostics') !== null;
    });
    if (!exists) { this.skip(); return; }

    const texts = await exec((sel: string) => {
      const keys = document.querySelectorAll(sel);
      return Array.from(keys).map(k => k.textContent ?? '');
    }, S.DIAG_KEY);
    if (texts.length > 0) {
      expect(texts.some((t: string) => t.includes('PTY'))).toBe(true);
    }
  });

  it('should show agent fleet section', async function () {
    const exists = await exec(() => {
      return document.querySelector('.diagnostics') !== null;
    });
    if (!exists) { this.skip(); return; }

    const texts = await exec((sel: string) => {
      const labels = document.querySelectorAll(sel);
      return Array.from(labels).map(l => l.textContent?.toLowerCase() ?? '');
    }, S.DIAG_LABEL);
    if (texts.length > 0) {
      expect(texts.some((t: string) => t.includes('agent fleet'))).toBe(true);
    }
  });

  it('should show last refresh timestamp', async function () {
    const exists = await exec(() => {
      return document.querySelector('.diagnostics') !== null;
    });
    if (!exists) { this.skip(); return; }

    const footerExists = await exec((sel: string) => {
      return document.querySelector(sel) !== null;
    }, S.DIAG_FOOTER);
    if (footerExists) {
      const el = await browser.$(S.DIAG_FOOTER);
      await expect(el).toBeDisplayed();
    }
  });

  it('should have a refresh button', async function () {
    const exists = await exec(() => {
      return document.querySelector('.diagnostics') !== null;
    });
    if (!exists) { this.skip(); return; }

    const refreshBtn = await browser.$(S.REFRESH_BTN);
    if (await refreshBtn.isExisting()) {
      expect(await refreshBtn.isClickable()).toBe(true);
    }
  });

  it('should show connection indicator with color', async function () {
    const exists = await exec(() => {
      return document.querySelector('.diagnostics') !== null;
    });
    if (!exists) { this.skip(); return; }

    const hasIndicator = await exec(() => {
      return (document.querySelector('.diag-status')
        ?? document.querySelector('.status-dot')
        ?? document.querySelector('.connection-status')) !== null;
    });
    expect(typeof hasIndicator).toBe('boolean');
  });

  it('should show session count', async function () {
    const exists = await exec(() => {
      return document.querySelector('.diagnostics') !== null;
    });
    if (!exists) { this.skip(); return; }

    const hasCount = await exec(() => {
      return (document.querySelector('.session-count')
        ?? document.querySelector('.diag-value')) !== null;
    });
    expect(typeof hasCount).toBe('boolean');
  });
});
