import { create } from 'zustand'
import type { TabValue } from '../components/Sidebar'

/**
 * The active screen, owned in a store so any component can navigate without
 * threading an `onTabChange` prop through the tree. It also carries a one-shot
 * URL handoff: the Downloads bar detects a channel/playlist link (which belongs
 * in the Library, not the one-off queue) and hands it here; the Library consumes
 * it once to pre-fill its add field (UX3).
 */
interface NavState {
  tab: TabValue
  setTab: (tab: TabValue) => void
  /** A channel/playlist URL handed from the Downloads bar to the Library. */
  pendingLibraryUrl: string | null
  /** Switch to the Library tab and stage `url` for its add field. */
  openLibraryWith: (url: string) => void
  /** Read and clear the staged Library URL (returns null if none is pending). */
  consumeLibraryUrl: () => string | null
  /**
   * The DownloadBar registers a focuser for its URL field here (L118), so App can
   * ask for focus (on launch / "New download") without reaching into the DOM by a
   * hardcoded element id. The DownloadBar owns *how* it focuses (its own ref);
   * callers just call `focusUrlField()`.
   */
  urlFocuser: (() => void) | null
  registerUrlFocuser: (fn: (() => void) | null) => void
  focusUrlField: () => void
}

export const useNav = create<NavState>((set, get) => ({
  tab: 'downloads',
  setTab: (tab) => set({ tab }),
  pendingLibraryUrl: null,
  openLibraryWith: (url) => set({ tab: 'library', pendingLibraryUrl: url }),
  consumeLibraryUrl: () => {
    const url = get().pendingLibraryUrl
    if (url !== null) set({ pendingLibraryUrl: null })
    return url
  },
  urlFocuser: null,
  registerUrlFocuser: (fn) => set({ urlFocuser: fn }),
  focusUrlField: () => get().urlFocuser?.()
}))
