<script setup>
import { reactive, ref } from 'vue';
const props = defineProps({
  editor: {
    type: Object,
    required: true,
  }
});
const editor = reactive(props.editor);

const setLink = () => {
  const previousUrl = editor?.getAttributes('link').href
  const url = window.prompt('Enter the URL', previousUrl)
  
  if (url === null) {
    return
  }

  if (url === '') {
    editor.chain().focus().extendMarkRange('link').unsetLink().run()
    return
  }

  editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run()
}

const removeLink = () => {
  editor.chain().focus().extendMarkRange('link').unsetLink().run()
}

const addImage = () => {
  const url = window.prompt('Enter image URL')
  if (url) {
    editor
      .chain()
      .focus()
      .setImage({ src: url })
      .run()
  }
}
</script>

<template>
<!-- Media Tab -->
<div class="flex items-center space-x-1 flex-wrap text-sm text-gray-800">
  <button 
    @click="setLink" 
    class="px-2 py-0.5 rounded-lg hover:bg-gray-200 bg-gray-300 my-0.5"
    :class="{ 'bg-gray-400': editor.isActive('link') }"
    title="Add Link"
  >
    Link
  </button>

  <button 
    @click="addImage" 
    class="px-2 py-0.5 rounded-lg hover:bg-gray-200 bg-gray-300 my-0.5"
    title="Add Image from URL"
  >
    image via url
  </button>

  <label class="px-2 py-0.5 rounded-lg hover:bg-gray-200 bg-gray-300 my-0.5 cursor-pointer" title="Upload Image">
    charger une image
    <input 
      type="file" 
      @change="uploadImage" 
      accept="image/*" 
      class="hidden"
    />
  </label>
</div>
</template>