import { menuStore } from '../src/components/menu/MenuStore'
import type { IntentMenuSpec } from '../src/components/menu/intents'

const makeSpec = (title: string): IntentMenuSpec => ({ title, intents: [] })

describe('menuStore', () => {
  afterEach(() => {
    // Drain the stack between tests so leftover entries don't leak.
    let active = menuStore.active()
    while (active) {
      // @ts-expect-error — id is internal but needed for cleanup
      menuStore.unregister(active.id)
      active = menuStore.active()
    }
  })

  it('replaces the active entry by reference on update so subscribers see a new snapshot', () => {
    const id = menuStore.register({
      spec: makeSpec('A'),
      searchActive: false,
      toggleSearch: () => {},
    })
    const before = menuStore.active()
    menuStore.update(id, {
      spec: makeSpec('B'),
      searchActive: true,
      toggleSearch: () => {},
    })
    const after = menuStore.active()
    expect(after).not.toBe(before)
    expect(after?.spec.title).toBe('B')
    expect(after?.searchActive).toBe(true)
  })

  it('notifies only when the topmost entry is updated', () => {
    const calls: number[] = []
    const unsub = menuStore.subscribe(() => calls.push(1))
    const idA = menuStore.register({
      spec: makeSpec('A'),
      searchActive: false,
      toggleSearch: () => {},
    })
    const idB = menuStore.register({
      spec: makeSpec('B'),
      searchActive: false,
      toggleSearch: () => {},
    })
    const baseline = calls.length
    menuStore.update(idA, {
      spec: makeSpec('A2'),
      searchActive: false,
      toggleSearch: () => {},
    })
    expect(calls.length).toBe(baseline)
    menuStore.update(idB, {
      spec: makeSpec('B2'),
      searchActive: false,
      toggleSearch: () => {},
    })
    expect(calls.length).toBeGreaterThan(baseline)
    unsub()
  })
})
