import { describe, test, expect } from 'vitest';
import React from 'react';
import { createRoot, Root } from 'react-dom/client';
import { act } from 'react-dom/test-utils';
import { LayerFocusProvider, useLayerFocus } from './LayerFocusContext';

let container: HTMLDivElement;
let root: Root;

const Probe: React.FC = () => {
  const { focus, requestFocus } = useLayerFocus();
  return (
    <div>
      <button onClick={() => requestFocus('n1', 'features', 2)}>request</button>
      <span data-testid="state">{focus ? `${focus.nodeId}:${focus.prop}:${focus.index}:${focus.nonce}` : 'none'}</span>
    </div>
  );
};

function render() {
  container = document.createElement('div');
  document.body.appendChild(container);
  act(() => {
    root = createRoot(container);
    root.render(<LayerFocusProvider><Probe /></LayerFocusProvider>);
  });
}

describe('LayerFocusContext', () => {
  test('starts with no focus request', () => {
    render();
    expect(container.querySelector('[data-testid="state"]')!.textContent).toBe('none');
  });

  test('requestFocus publishes the target', () => {
    render();
    act(() => { (container.querySelector('button') as HTMLButtonElement).click(); });
    expect(container.querySelector('[data-testid="state"]')!.textContent).toBe('n1:features:2:1');
  });

  test('repeating the same request bumps the nonce so consumers re-fire', () => {
    render();
    const btn = container.querySelector('button') as HTMLButtonElement;
    act(() => { btn.click(); });
    act(() => { btn.click(); });
    expect(container.querySelector('[data-testid="state"]')!.textContent).toBe('n1:features:2:2');
  });

  test('useLayerFocus outside a provider is inert rather than a crash', () => {
    container = document.createElement('div');
    document.body.appendChild(container);
    expect(() => {
      act(() => {
        root = createRoot(container);
        root.render(<Probe />);
      });
    }).not.toThrow();
  });
});
