import { ref } from 'vue'

const pendingSave = ref(null)

function splitFilename(filename) {
  const idx = filename.lastIndexOf('.')
  if (idx <= 0) return { stem: filename, extension: '' }
  return { stem: filename.slice(0, idx), extension: filename.slice(idx) }
}

/**
 * Singleton prompt service backing the global <SaveFileDialog>.
 * promptFilename() resolves to the chosen filename, or null if cancelled.
 */
export function useSaveFilePrompt() {
  function promptFilename(defaultFilename) {
    return new Promise((resolve) => {
      const { stem, extension } = splitFilename(defaultFilename)
      pendingSave.value = { defaultStem: stem, extension, resolve }
    })
  }

  function confirmFilename(stem) {
    const { defaultStem, extension, resolve } = pendingSave.value
    const finalStem = stem.trim() || defaultStem
    pendingSave.value = null
    resolve(`${finalStem}${extension}`)
  }

  function cancelFilename() {
    const { resolve } = pendingSave.value
    pendingSave.value = null
    resolve(null)
  }

  return { pendingSave, promptFilename, confirmFilename, cancelFilename }
}
