export function useGuidedMode() {
  const route = useRoute()
  const store = usePlayerStore()
  const bookData = useBookData()
  const { loadAndPlay } = useAudioPlayer()

  async function activateGuidedMode(chapterSlug: string) {
    await bookData.init()

    if (!store.isGuidedMode) return

    const primarySong = bookData.getPrimarySong(chapterSlug)
    if (primarySong && primarySong.id !== store.currentSong?.id) {
      // Set the chapter's songs as the playlist
      const chapterSongs = bookData.getChapterSongs(chapterSlug)
      if (chapterSongs.length > 0) {
        store.setPlaylist(chapterSongs)
      }
      loadAndPlay(primarySong)
    }
  }

  // Watch route changes for guided mode
  watch(
    () => route.params.slug,
    async (slug) => {
      if (slug && typeof slug === 'string' && store.isGuidedMode) {
        await activateGuidedMode(slug)
      }
    },
  )

  return {
    activateGuidedMode,
  }
}
