import { useSyncExternalStore } from 'react'
import type { IntentMenuSpec } from './intents'

// Single store replacing the prior iosAccessoryStore + androidToolbarStore
// split. Last-focused tab/screen wins. The globally-mounted MenuBarToolbar
// reads `active()` via useSyncExternalStore. Consumers describe intents (v3);
// legacy slot-based specs are translated at the consumer edge.

export interface MenuEntry {
  spec: IntentMenuSpec
  searchActive: boolean
  toggleSearch: () => void
}

interface InternalEntry extends MenuEntry {
  id: number
}

let nextEntryId = 1
const stack: InternalEntry[] = []
const listeners = new Set<() => void>()

function notify() {
  for (const l of listeners) l()
}

export const menuStore = {
  register(entry: MenuEntry): number {
    const id = nextEntryId++
    stack.push({ id, ...entry })
    notify()
    return id
  },
  update(id: number, entry: MenuEntry): void {
    const i = stack.findIndex((x) => x.id === id)
    if (i < 0) return
    // Replace by reference so useSyncExternalStore sees a new snapshot — in-place
    // mutation bailed `Object.is` and prevented every toolbar re-render.
    stack[i] = { id, ...entry }
    if (stack[stack.length - 1].id === id) notify()
  },
  unregister(id: number): void {
    const i = stack.findIndex((x) => x.id === id)
    if (i < 0) return
    stack.splice(i, 1)
    notify()
  },
  active(): MenuEntry | null {
    return stack.length > 0 ? stack[stack.length - 1] : null
  },
  subscribe(l: () => void): () => void {
    listeners.add(l)
    return () => {
      listeners.delete(l)
    }
  },
}

export function useActiveMenuEntry(): MenuEntry | null {
  return useSyncExternalStore(menuStore.subscribe, menuStore.active, menuStore.active)
}
