/**
 * Journey: UnifiedCard CTA routing — view_draft + topic_gap
 *
 * Verifies the two CTA-routing fixes shipped in UnifiedCard.tsx:
 *
 *   1. A recommendation row that already has an AI draft surfaces a
 *      "View draft" primary CTA (not "Generate draft") and its href targets
 *      the existing draft — /sites/<id>/ai-drafts/<draft_id>.
 *
 *   2. A topic_gap row routes to `topic-clusters.show` via `topic_cluster_id`
 *      (not the gap-suggestion id). — skipped when no topic-gap row is seeded;
 *      see finding note in artifact.
 *
 * Both scenarios require the opportunity map to aggregate the seeded records
 * via OpportunityFetcher + ActionQueueContractEnricher, so they exercise the
 * full Laravel → React rendering pipeline rather than just the component unit.
 *
 * Scope source: SUCCESS_CRITERIA_ca340290-fefc-4ce8-adb9-a3a0b257162a.md
 * human_success_check: clicking action on a row with an existing draft takes
 * the user straight to that draft, not "Generate draft".
 */

import { expect, test } from '../fixtures/auth';

test.describe('UnifiedCard CTA routing: view_draft', () => {
  test('renders "View draft" CTA (not "Generate draft") for a row that already has a draft', async ({
    page,
    seedData,
  }) => {
    // Capture console errors / failed requests for the console-clean assertion.
    const consoleErrors: string[] = [];
    const failedRequests: string[] = [];
    page.on('pageerror', (err) => consoleErrors.push(err.message));
    page.on('console', (msg) => {
      if (msg.type() === 'error') consoleErrors.push(msg.text());
    });
    page.on('requestfailed', (req) => failedRequests.push(`${req.method()} ${req.url()}`));
    page.on('response', (res) => {
      if (res.status() >= 400 && res.url().includes(String(seedData.siteId))) {
        failedRequests.push(`${res.status()} ${res.url()}`);
      }
    });

    await page.goto(`/sites/${seedData.siteId}/opportunity-map`, {
      waitUntil: 'domcontentloaded',
    });

    // The seeded recommendation has an AI draft — ActionQueueContractEnricher
    // must produce primary_cta='view_draft' for it.
    const viewDraftLink = page.getByRole('link', { name: /view draft/i }).first();
    await expect(viewDraftLink).toBeVisible({ timeout: 10_000 });

    // SC-1: label is "View draft", not "Generate draft"
    await expect(viewDraftLink).not.toHaveText(/generate draft/i);

    // SC-2: href contains the seeded aiDraftId
    const href = await viewDraftLink.getAttribute('href');
    expect(href).toContain(`/ai-drafts/${seedData.aiDraftId}`);

    // No uncaught JavaScript errors (filter browser-native resource errors and extensions).
    // 401/419 on background polling/CSRF endpoints are pre-existing infra noise, not
    // UnifiedCard regressions — they're excluded with the "Failed to load resource" filter.
    const appErrors = consoleErrors.filter(
      (e) =>
        !e.includes('extension') &&
        !e.includes('chrome-extension') &&
        !e.includes('Failed to load resource'),
    );
    expect(appErrors, `Console errors: ${appErrors.join(', ')}`).toHaveLength(0);
  });

  test('clicking "View draft" navigates to the correct AI draft page', async ({
    page,
    seedData,
  }) => {
    await page.goto(`/sites/${seedData.siteId}/opportunity-map`, {
      waitUntil: 'domcontentloaded',
    });

    const viewDraftLink = page.getByRole('link', { name: /view draft/i }).first();
    await expect(viewDraftLink).toBeVisible({ timeout: 10_000 });

    // human_success_check: clicking the CTA lands on the draft page (not a 404 or error).
    await viewDraftLink.click();
    await page.waitForURL((url) => url.pathname.includes(`/ai-drafts/${seedData.aiDraftId}`), {
      timeout: 10_000,
    });

    // The URL must contain the draft id — proving the link used latest_draft_id, not
    // the opportunity_id (which would be a different number).
    expect(page.url()).toContain(`/ai-drafts/${seedData.aiDraftId}`);

    // The page should not be a 404 or error page.
    const bodyText = await page.innerText('body');
    expect(bodyText).not.toMatch(/404|not found|page not found/i);
  });

  test.skip('topic_gap CTA routes via topic_cluster_id (requires seeded topic_gap row)', async () => {
    // SC-4 / SC-5: The E2E seed (E2ESeedCommand) does not currently seed a
    // TopicGapSuggestion / TopicCluster record. Without a topic_gap row in the
    // opportunity map there is nothing browser-observable to assert. The
    // unit-level test coverage in UnifiedCard.test.tsx covers this path
    // (verify_by: test).
    //
    // To add browser coverage: extend E2ESeedCommand to create a TopicCluster
    // and a TopicGapSuggestion, expose `topicClusterId` in the seed JSON, then
    // replace this skip with an assertion that the rendered link contains that id.
  });
});
