// @vitest-environment happy-dom
//
// Settings are persisted as one JSON blob under a single localStorage key,
// merged over DEFAULT_SETTINGS on load — so an absent field must fall back to
// its default rather than to undefined. listChangesHint drives the
// Repository header's "List Changes" shimmer and defaults ON.
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { SettingsProvider, useSettings } from './SettingsContext';

let container;
let api;

function Probe() {
  api = useSettings();
  return null;
}

beforeEach(() => {
  localStorage.clear();
  container = document.createElement('div');
  document.body.appendChild(container);
});

afterEach(() => {
  document.body.removeChild(container);
  container = null;
  api = null;
  localStorage.clear();
});

function render() {
  const root = createRoot(container);
  act(() =>
    root.render(
      <SettingsProvider>
        <Probe />
      </SettingsProvider>
    )
  );
  return root;
}

describe('listChangesHint', () => {
  it('defaults on', () => {
    render();
    expect(api.listChangesHint).toBe(true);
  });

  it('persists through the cbm- settings key', () => {
    render();
    act(() => api.setListChangesHint(false));
    expect(api.listChangesHint).toBe(false);
    expect(JSON.parse(localStorage.getItem('cbm-settings-v1')).listChangesHint).toBe(false);
  });

  it('falls back to the default when the stored blob predates it', () => {
    localStorage.setItem('cbm-settings-v1', JSON.stringify({ showServerNames: false }));
    render();
    expect(api.showServerNames).toBe(false);
    expect(api.listChangesHint).toBe(true);
  });
});
