import { test, expect } from '@playwright/test';
import { setupApiMocks, login, navigateTo, MOCK_PLUGINS } from './helpers';

test.describe('Plugin Toggle E2E', () => {
  test.beforeEach(async ({ page }) => {
    await setupApiMocks(page);
    await login(page);
  });

  test('settings plugins page renders with plugin list', async ({ page }) => {
    await navigateTo(page, '/settings/plugins');

    await expect(page.locator('[data-testid="settings-plugins-page"]')).toBeVisible({ timeout: 10_000 });
  });

  test('activate an inactive plugin', async ({ page }) => {
    await navigateTo(page, '/settings/plugins');

    await expect(page.locator('[data-testid="settings-plugins-page"]')).toBeVisible({ timeout: 10_000 });

    // Find the inactive plugin (entity_links) and click activate
    const activateBtn = page.locator('[data-testid="activate-plugin-entity_links"]');
    if (await activateBtn.isVisible({ timeout: 10_000 })) {
      await activateBtn.click();

      // Button should change (deactivate should appear)
      await expect(page.locator('[data-testid="deactivate-plugin-entity_links"]')).toBeVisible({ timeout: 10_000 });
    }
  });

  test('deactivate an active plugin', async ({ page }) => {
    await navigateTo(page, '/settings/plugins');

    await expect(page.locator('[data-testid="settings-plugins-page"]')).toBeVisible({ timeout: 10_000 });

    // Find the active plugin (tags) and click deactivate
    const deactivateBtn = page.locator('[data-testid="deactivate-plugin-tags"]');
    if (await deactivateBtn.isVisible({ timeout: 10_000 })) {
      await deactivateBtn.click();

      // Button should change (activate should appear)
      await expect(page.locator('[data-testid="activate-plugin-tags"]')).toBeVisible({ timeout: 10_000 });
    }
  });

  test('refresh plugins button works', async ({ page }) => {
    await navigateTo(page, '/settings/plugins');

    await expect(page.locator('[data-testid="settings-plugins-page"]')).toBeVisible({ timeout: 10_000 });

    const refreshBtn = page.locator('[data-testid="refresh-plugins-btn"]');
    await expect(refreshBtn).toBeVisible();
    await refreshBtn.click();

    // Page should still be visible
    await expect(page.locator('[data-testid="settings-plugins-page"]')).toBeVisible();
  });

  test('plugin install section is visible', async ({ page }) => {
    await navigateTo(page, '/settings/plugins');

    await expect(page.locator('[data-testid="settings-plugins-page"]')).toBeVisible({ timeout: 10_000 });

    // Upload and URL install options should be present
    await expect(page.locator('[data-testid="plugin-zip-upload-input"], [data-testid="plugin-upload-btn"], [data-testid="plugin-url-input"], [data-testid="plugin-install-url-btn"]')).toBeVisible({ timeout: 10_000 });
  });
});
