import { ref } from 'vue'
import { api } from '@/api'
import {
  DEFAULT_SCRIPT_COMPLETE_SOUND,
  normalizeScriptCompleteSound,
  playScriptCompleteSoundById,
  type ScriptCompleteSoundId,
} from '@/utils/scriptCompleteSound'

const LS_KEY = 'nexus_push_complete_sound'
const soundMode = ref<ScriptCompleteSoundId>(readCached())

function readCached(): ScriptCompleteSoundId {
  try {
    const raw = localStorage.getItem(LS_KEY)
    if (raw) return normalizeScriptCompleteSound(raw)
  } catch {
    /* ignore */
  }
  return DEFAULT_SCRIPT_COMPLETE_SOUND
}

function persistCache(mode: ScriptCompleteSoundId) {
  try {
    localStorage.setItem(LS_KEY, mode)
  } catch {
    /* ignore */
  }
}

export function usePushCompleteSound() {
  async function syncFromServer() {
    try {
      const data = await api<{ value: string }>('/settings/push_complete_sound')
      const mode = normalizeScriptCompleteSound(data.value)
      soundMode.value = mode
      persistCache(mode)
    } catch {
      soundMode.value = readCached()
    }
  }

  async function saveToServer(mode: ScriptCompleteSoundId) {
    const normalized = normalizeScriptCompleteSound(mode)
    await api('/settings/push_complete_sound', {
      method: 'PUT',
      body: JSON.stringify({ value: normalized }),
    })
    soundMode.value = normalized
    persistCache(normalized)
  }

  function playPushCompleteSound() {
    playScriptCompleteSoundById(soundMode.value)
  }

  function previewSound(mode?: ScriptCompleteSoundId) {
    playScriptCompleteSoundById(mode ?? soundMode.value)
  }

  return {
    soundMode,
    syncFromServer,
    saveToServer,
    playPushCompleteSound,
    previewSound,
  }
}
