import { create } from 'zustand'

interface State {
  open: boolean
  videoKey: string | null
  title: string
  /** Optional caption shown under the title (e.g. "Trailer · Official"). */
  subtitle?: string
  onClose?: (() => void) | null
  show: (args: { videoKey: string; title: string; subtitle?: string; onClose?: () => void }) => void
  close: () => void
}

/**
 * Tiny global store for the in-app YouTube viewer modal. Any component
 * (VideosSection, the hero Trailer button, etc.) can call `show({...})`
 * to open the player without dragging the user out to youtube.com.
 */
export const useYoutubeViewer = create<State>(set => ({
  open: false,
  videoKey: null,
  title: '',
  subtitle: undefined,
  onClose: null,
  show: ({ videoKey, title, subtitle, onClose }) =>
    set({ open: true, videoKey, title, subtitle, onClose: onClose || null }),
  close: () =>
    set(s => {
      const cb = s.onClose
      setTimeout(() => cb?.(), 0)
      return { open: false, onClose: null }
    }),
}))
