/**
 * Worktree tests — clone button, branch dialog, WT badge, clone group.
 */

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

describe('Worktree support', () => {
  it('should show clone/worktree button', async () => {
    const exists = await exec((sel: string) => {
      return document.querySelector(sel) !== null;
    }, S.CLONE_BTN);
    expect(typeof exists).toBe('boolean');
  });

  it('should show branch dialog on clone click', async () => {
    const cloneBtn = await browser.$(S.CLONE_BTN);
    if (!(await cloneBtn.isExisting())) return;

    await cloneBtn.click();
    await browser.pause(500);

    const dialog = await browser.$(S.BRANCH_DIALOG);
    if (await dialog.isExisting()) {
      await expect(dialog).toBeDisplayed();
      // Close dialog
      await browser.keys('Escape');
      await browser.pause(300);
    }
  });

  it('should show WT badge on worktree sessions', async () => {
    const exists = await exec((sel: string) => {
      return document.querySelector(sel) !== null;
    }, S.WT_BADGE);
    // Badge only appears when worktree is active
    expect(typeof exists).toBe('boolean');
  });

  it('should show clone group display', async () => {
    const exists = await exec((sel: string) => {
      return document.querySelector(sel) !== null;
    }, S.CLONE_GROUP);
    expect(typeof exists).toBe('boolean');
  });

  it('should have worktree toggle in settings', async () => {
    const hasToggle = await exec(() => {
      const text = document.body.textContent ?? '';
      return text.includes('Worktree') || text.includes('worktree');
    });
    expect(typeof hasToggle).toBe('boolean');
  });

  it('should handle worktree path display', async () => {
    const paths = await exec(() => {
      const headers = document.querySelectorAll('.project-header');
      return Array.from(headers).map(h => h.textContent ?? '');
    });
    expect(Array.isArray(paths)).toBe(true);
  });

  it('should show worktree isolation toggle in settings', async () => {
    const hasToggle = await exec(() => {
      return (document.querySelector('.worktree-toggle')
        ?? document.querySelector('[data-setting="useWorktrees"]')) !== null;
    });
    expect(typeof hasToggle).toBe('boolean');
  });

  it('should preserve worktree badge across tab switches', async () => {
    // Worktree badge uses display toggle, not {#if}
    const badge = await exec((sel: string) => {
      const el = document.querySelector(sel);
      if (!el) return 'absent';
      return getComputedStyle(el).display;
    }, S.WT_BADGE);
    expect(typeof badge).toBe('string');
  });
});
