// RED test: campaign selection must follow activeDisplay.activeCampaignId changes.
// Bug: once selected, new activeDisplay writes ignored (guard `!selectedCampaignId`).
// Scenario: replay tool writes activeDisplay to new campaign -> UI must switch.
import React from 'react';
import { screen, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';
import { MOCK_DB } from '../__mocks__/firebase/_mock-db';
import { renderApp, createCampaignViaUI, selectCampaignByName } from './testHelpers';

const PUBLIC_DATA = 'artifacts/ttrpg-initiative-tracker-default/public/data';

describe('Selection follows activeDisplay (BUG-12)', () => {
  test('new activeCampaignId switches selection', async () => {
    await renderApp();
    const idA = await createCampaignViaUI('Campaign A');
    const idB = await createCampaignViaUI('Campaign B');

    // seed activeDisplay so useFirestoreDocument has a value to emit
    const activePath = Object.keys(MOCK_DB._state.docs).find(p => p.includes('/activeDisplay/status'))
      || `${PUBLIC_DATA}/activeDisplay/status`;
    MOCK_DB.set(activePath, { activeCampaignId: null, activeEncounterId: null });

    // manually select A first
    await selectCampaignByName('Campaign A');
    expect(screen.getByText(/Managing:/i).textContent).toMatch(/Campaign A/);

    // simulate replay/another-DM setting activeDisplay to B
    MOCK_DB.merge(activePath, { activeCampaignId: idB });

    // selection should now follow -> Managing: Campaign B
    await waitFor(() => {
      expect(screen.getByText(/Managing:/i).textContent).toMatch(/Campaign B/);
    });
  });

  test('activeDisplay cleared (null) does not force-select', async () => {
    await renderApp();
    const idA = await createCampaignViaUI('Persist A');
    const activePath = Object.keys(MOCK_DB._state.docs).find(p => p.includes('/activeDisplay/status'))
      || `${PUBLIC_DATA}/activeDisplay/status`;
    MOCK_DB.set(activePath, { activeCampaignId: null, activeEncounterId: null });
    await selectCampaignByName('Persist A');

    MOCK_DB.merge(activePath, { activeCampaignId: null });

    // should stay on A (manual selection persists)
    expect(screen.getByText(/Managing:/i).textContent).toMatch(/Persist A/);
  });
});
