// Touch Therapies CMS — admin behaviours (rich text editor + image uploads).

// Rich text: sync contenteditable into its hidden textarea on submit.
document.querySelectorAll('.rte').forEach((rte) => {
  const textarea = document.getElementById(rte.id.replace('rte-', 'f-'))
  rte.closest('form')?.addEventListener('submit', () => {
    textarea.value = rte.innerHTML
  })
})

document.querySelectorAll('.rte-toolbar button').forEach((btn) => {
  btn.addEventListener('click', () => {
    const cmd = btn.dataset.cmd
    if (cmd === 'createLink') {
      const url = prompt('Link URL:')
      if (url) document.execCommand(cmd, false, url)
    } else {
      document.execCommand(cmd, false, btn.dataset.arg || undefined)
    }
  })
})

// Image upload widgets: POST to /admin/media/upload, drop the URL in the input.
document.querySelectorAll('.upload-btn input[type=file]').forEach((input) => {
  input.addEventListener('change', async () => {
    const file = input.files?.[0]
    if (!file) return
    const target = document.getElementById(input.dataset.target)
    const label = input.closest('.upload-btn')
    label.style.opacity = '0.5'

    const body = new FormData()
    body.append('file', file)
    body.append('_csrf', window.__CSRF || '')

    try {
      const res = await fetch((window.__BASE || '') + '/admin/media/upload', { method: 'POST', body })
      const json = await res.json()
      if (json.data?.url) {
        target.value = json.data.url
        let preview = target.closest('.field').querySelector('.preview')
        if (!preview) {
          preview = document.createElement('img')
          preview.className = 'preview'
          target.closest('.field').appendChild(preview)
        }
        preview.src = json.data.url
      } else {
        alert(json.error || 'Upload failed')
      }
    } catch {
      alert('Upload failed')
    } finally {
      label.style.opacity = ''
      input.value = ''
    }
  })
})
