/**
 * E2E coverage for the `autoStartFocusOnPlay` opt-in.
 *
 * Behavior under test: when the user enables this setting and starts
 * tracking a task, a focus session must spawn automatically *without*
 * opening the focus-mode overlay — the header focus-button countdown is
 * the only surface.
 *
 * If this regresses, the headline feature of the rework is broken with
 * no other automated test catching it.
 */

import { test, expect } from '../../fixtures/test.fixture';
import { Page } from '@playwright/test';
import { ensureSettingState } from '../../utils/config-helpers';

const enableAutoStartOnPlay = async (page: Page): Promise<void> => {
  await page.goto('/#/config');
  await page.locator('.page-settings').waitFor({ state: 'visible', timeout: 10000 });

  // The setting lives in the Productivity → Focus Mode section.
  await page.getByRole('tab', { name: /Productivity/i }).click();

  const focusModeSection = page
    .locator('config-section')
    .filter({
      has: page.locator('.collapsible-title', { hasText: /^Focus Mode$/ }),
    })
    .first();
  await focusModeSection.scrollIntoViewIfNeeded();

  const collapsible = focusModeSection.locator('collapsible');
  const isExpanded = await collapsible
    .evaluate((el) => el.classList.contains('isExpanded'))
    .catch(() => false);

  if (!isExpanded) {
    const header = collapsible.locator('.collapsible-header');
    await header.click();
    await page.waitForTimeout(500);
  }

  // Use shared helper that handles both mat-slide-toggle and mat-checkbox
  await ensureSettingState(
    page,
    'Start a focus session when I start tracking a task',
    true,
  );
};

test.describe('autoStartFocusOnPlay', () => {
  test('pressing play with the opt-in on starts a focus session indicator-only (no overlay)', async ({
    page,
    workViewPage,
  }) => {
    const focusOverlay = page.locator('focus-mode-overlay');
    const focusRunningLabel = page.locator('focus-button .focus-running-label');

    // Step 1: enable the new setting via Settings UI.
    await enableAutoStartOnPlay(page);

    // Step 2: navigate back to the work view and add a task.
    // Use a same-document hash navigation rather than `page.goto('/')`. A hard
    // reload re-bootstraps the app and re-reads the config from IndexedDB,
    // which races the debounced persistence of the toggle we just flipped: if
    // the write hasn't flushed yet, the reloaded app boots with
    // autoStartFocusOnPlay=false and the session never spawns — a flake no
    // timeout can fix. Hash nav keeps the in-memory NgRx config that the toggle
    // already updated synchronously, so we test the auto-start behavior without
    // depending on persistence timing.
    await page.goto('/#/tag/TODAY/tasks');
    await page.waitForURL(/tag\/TODAY/);
    await workViewPage.waitForTaskList();
    await workViewPage.addTask('AutoStartTask');

    const firstTask = page.locator('task').first();
    await expect(firstTask).toBeVisible();

    // Sanity: overlay must not be open before we press play.
    await expect(focusOverlay).not.toBeVisible();

    // Step 3: start tracking via the task's play button.
    await firstTask.hover();
    const trackingPlayBtn = firstTask.locator('.start-task-btn').first();
    await trackingPlayBtn.waitFor({ state: 'visible' });
    await trackingPlayBtn.click();
    await expect(firstTask).toHaveClass(/isCurrent/, { timeout: 5000 });

    // Expected: focus session spawns and the header countdown becomes the
    // surface (per the rework, the overlay must NOT auto-open here).
    // The indicator appears only after an async effect chain
    // (syncTrackingStartToSession$ → startFocusSession → reducer → selector →
    // OnPush render), so use the suite's default expect timeout (20s, set for
    // slow rendering) rather than a tight 5s that flakes under CI parallel load.
    await expect(focusRunningLabel).toBeVisible();
    await expect(focusOverlay).not.toBeVisible();
  });

  test('with the opt-in OFF (default), pressing play does not spawn a focus session', async ({
    page,
    workViewPage,
  }) => {
    const focusOverlay = page.locator('focus-mode-overlay');
    const focusRunningLabel = page.locator('focus-button .focus-running-label');

    await workViewPage.waitForTaskList();
    await workViewPage.addTask('NoAutoStartTask');

    const firstTask = page.locator('task').first();
    await expect(firstTask).toBeVisible();

    await firstTask.hover();
    const trackingPlayBtn = firstTask.locator('.start-task-btn').first();
    await trackingPlayBtn.waitFor({ state: 'visible' });
    await trackingPlayBtn.click();
    await expect(firstTask).toHaveClass(/isCurrent/, { timeout: 5000 });

    // Tracking is on, but no focus session — countdown badge stays hidden,
    // overlay stays closed.
    await expect(focusOverlay).not.toBeVisible();
    // Wait a beat in case the spawn is async; assert it never appears.
    await page.waitForTimeout(1000);
    await expect(focusRunningLabel).not.toBeVisible();
  });
});
