import { ref, type Ref } from 'vue'
import DOMPurify from 'dompurify'

export function useEditable(elementRef: Ref<HTMLElement | null>) {

  const isEditing = ref(false)

  const enableEdit = () => {
    if (!elementRef.value) return

    isEditing.value = true

    Array.from(elementRef.value.children).forEach(item => {
      item.setAttribute('contenteditable', 'true')
    })
  }

  const disableEdit = () => {
    if (!elementRef.value) return

    isEditing.value = false

    Array.from(elementRef.value.children).forEach(item => {
      item.setAttribute('contenteditable', 'false')
    })
  }

  const getCleanHtml = () => {
    if (!elementRef.value) return ''

    const html = elementRef.value.innerHTML
    return DOMPurify.sanitize(html)
  }

  return {
    isEditing,
    enableEdit,
    disableEdit,
    getCleanHtml
  }
}