/**
 * Reusable test actions — common UI operations used across spec files.
 *
 * All actions use exec() (cross-protocol safe wrapper) for DOM queries with
 * fallback selectors to support both Tauri and Electrobun UIs.
 */

import { browser } from '@wdio/globals';
import { exec } from './execute.ts';
import * as S from './selectors.ts';

/**
 * Wait for a TCP port to accept connections. Used by CDP-based E2E configs
 * to wait for the debugging port before connecting WebDriverIO.
 *
 * Polls `http://localhost:{port}/json` (CDP discovery endpoint) every 500ms.
 */
export async function waitForPort(port: number, timeout: number): Promise<void> {
  const start = Date.now();
  while (Date.now() - start < timeout) {
    try {
      const res = await fetch(`http://localhost:${port}/json`);
      if (res.ok) return;
    } catch {
      // Port not ready yet — retry
    }
    await new Promise(r => setTimeout(r, 500));
  }
  throw new Error(`CDP port ${port} not ready after ${timeout}ms`);
}

/** Open settings panel via gear icon click */
export async function openSettings(): Promise<void> {
  // Strategy 1: keyboard shortcut (most reliable across both stacks)
  await browser.keys(['Control', ',']);
  await browser.pause(500);

  // Strategy 2: if keyboard didn't work, try clicking
  let opened = await exec(() => {
    const el = document.querySelector('.sidebar-panel, .settings-drawer, .settings-panel');
    return el ? getComputedStyle(el).display !== 'none' : false;
  });
  if (!opened) {
    const settingsBtn = await browser.$('[data-testid="settings-btn"]');
    if (await settingsBtn.isExisting()) await settingsBtn.click();
    else await exec(() => {
      const btn = document.querySelector('.sidebar-icon[title*="Settings"]')
        ?? document.querySelector('.sidebar-icon')
        ?? document.querySelector('.rail-btn');
      if (btn) (btn as HTMLElement).click();
    });
    await browser.pause(500);
  }

  // Wait for either settings panel class
  await browser.waitUntil(
    async () =>
      exec(() =>
        document.querySelector('.sidebar-panel, .settings-drawer, .settings-panel') !== null,
      ),
    { timeout: 8_000 },
  ).catch(() => {
    // Settings panel failed to open — may be in degraded RPC mode
    console.warn('[actions] Settings panel did not open (degraded mode?)');
  });
}

/** Close settings panel */
export async function closeSettings(): Promise<void> {
  await exec(() => {
    const btn = document.querySelector('.settings-close')
      ?? document.querySelector('.panel-close');
    if (btn) (btn as HTMLElement).click();
  });
  await browser.pause(400);
}

/** Switch to a settings category by index (0-based) */
export async function switchSettingsCategory(index: number): Promise<void> {
  await exec((idx: number) => {
    const tabs = document.querySelectorAll('.settings-sidebar .sidebar-item, .settings-tab, .cat-btn');
    if (tabs[idx]) (tabs[idx] as HTMLElement).click();
  }, index);
  await browser.pause(300);
}

/** Switch active group by clicking the nth group button (0-based) */
export async function switchGroup(index: number): Promise<void> {
  await exec((idx: number) => {
    const groups = document.querySelectorAll('.group-btn:not(.add-group-btn)');
    if (groups[idx]) (groups[idx] as HTMLElement).click();
  }, index);
  await browser.pause(300);
}

/** Type text into the agent prompt input */
export async function sendPrompt(text: string): Promise<void> {
  const textarea = await browser.$(S.CHAT_INPUT_TEXTAREA);
  if (await textarea.isExisting()) {
    await textarea.setValue(text);
    return;
  }
  const input = await browser.$(S.CHAT_INPUT_ALT);
  if (await input.isExisting()) {
    await input.setValue(text);
  }
}

/** Open command palette via Ctrl+K */
export async function openCommandPalette(): Promise<void> {
  await browser.keys(['Control', 'k']);
  await browser.pause(400);
}

/** Close command palette via Escape */
export async function closeCommandPalette(): Promise<void> {
  await browser.keys('Escape');
  await browser.pause(300);
}

/** Open search overlay via Ctrl+Shift+F */
export async function openSearch(): Promise<void> {
  await browser.keys(['Control', 'Shift', 'f']);
  await browser.pause(400);
}

/** Close search overlay via Escape */
export async function closeSearch(): Promise<void> {
  await browser.keys('Escape');
  await browser.pause(300);
}

/** Add a new terminal tab by clicking the add button */
export async function addTerminalTab(): Promise<void> {
  await exec(() => {
    const btn = document.querySelector('.tab-add-btn');
    if (btn) (btn as HTMLElement).click();
  });
  await browser.pause(500);
}

/** Click a project-level tab (model, docs, files, etc.) */
export async function clickProjectTab(tabName: string): Promise<void> {
  await exec((name: string) => {
    const tabs = document.querySelectorAll('.ptab, .project-tab, .tab-btn');
    for (const tab of tabs) {
      if ((tab as HTMLElement).textContent?.toLowerCase().includes(name.toLowerCase())) {
        (tab as HTMLElement).click();
        return;
      }
    }
  }, tabName);
  await browser.pause(300);
}

/** Wait until an element with given selector is displayed */
export async function waitForElement(selector: string, timeout = 5_000): Promise<void> {
  const el = await browser.$(selector);
  await el.waitForDisplayed({ timeout });
}

/** Check if an element exists and is displayed (safe for optional elements) */
export async function isVisible(selector: string): Promise<boolean> {
  return exec((sel: string) => {
    const el = document.querySelector(sel);
    if (!el) return false;
    const style = getComputedStyle(el);
    return style.display !== 'none' && style.visibility !== 'hidden';
  }, selector);
}

/** Get the display CSS value for an element (for display-toggle awareness) */
export async function getDisplay(selector: string): Promise<string> {
  return exec((sel: string) => {
    const el = document.querySelector(sel);
    if (!el) return 'not-found';
    return getComputedStyle(el).display;
  }, selector);
}

/** Open notification drawer by clicking bell */
export async function openNotifications(): Promise<void> {
  // Try native click first
  const bell = await browser.$('.notif-btn');
  if (await bell.isExisting()) {
    await bell.click();
  } else {
    const bell2 = await browser.$('.bell-btn');
    if (await bell2.isExisting()) await bell2.click();
    else await exec(() => {
      const btn = document.querySelector('[data-testid="notification-bell"]');
      if (btn) (btn as HTMLElement).click();
    });
  }
  await browser.pause(400);
}

/** Close notification drawer */
export async function closeNotifications(): Promise<void> {
  await exec(() => {
    const backdrop = document.querySelector('.notif-backdrop')
      ?? document.querySelector('.notification-center .backdrop');
    if (backdrop) (backdrop as HTMLElement).click();
  });
  await browser.pause(300);
}
