// localStorage scoping: selectedEncounter + scrollY keyed per campaign.
// Two tabs on different campaigns don't fight over selection/scroll.

import React from 'react';
import { screen, fireEvent, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';
import { setupReady, addMonsterViaUI } from './testHelpers';

describe('localStorage campaign scoping', () => {
  test('selectedEncounter key is scoped (not bare)', async () => {
    await setupReady('ScopeCamp1', 'ScopeEnc1');
    // bare key should not exist
    expect(localStorage.getItem('ttrpg.selectedEncounter')).toBeNull();
    // scoped key with suffix should exist
    const scoped = Object.keys(localStorage).find(
      k => k.startsWith('ttrpg.selectedEncounter.') && k !== 'ttrpg.selectedEncounter'
    );
    expect(scoped).toBeTruthy();
    expect(localStorage.getItem(scoped)).toBeTruthy();
  });

  test('scrollY key is scoped (not bare)', async () => {
    await setupReady('ScopeCamp2', 'ScopeEnc2');
    await addMonsterViaUI('Goblin', 10, 5);
    expect(localStorage.getItem('ttrpg.scrollY')).toBeNull();
    const scoped = Object.keys(localStorage).find(
      k => k.startsWith('ttrpg.scrollY.') && k !== 'ttrpg.scrollY'
    );
    // key may not exist until save fires — trigger by checking bare is null
    // and at least scoped format is used if any scrollY key present
    const scrollKeys = Object.keys(localStorage).filter(k => k.startsWith('ttrpg.scrollY'));
    scrollKeys.forEach(k => expect(k).not.toBe('ttrpg.scrollY'));
  });

  test('global keys still exist (campaign selection, wake lock)', async () => {
    await setupReady('ScopeCamp3', 'ScopeEnc3');
    expect(localStorage.getItem('ttrpg.selectedCampaign')).toBeTruthy();
  });
});
