<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-2 flex-wrap">
  <button 
    @click="setLink" 
    class="p-1 rounded hover:bg-gray-100 flex items-center"
    :class="{ 'bg-gray-200': editor.isActive('link') }"
    title="Add Link"
  >
    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
      <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path>
      <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path>
    </svg>
    <span class="ml-1 text-sm">Link</span>
  </button>

  <button 
    @click="addImage" 
    class="p-1 rounded hover:bg-gray-100 flex items-center"
    title="Add Image from URL"
  >
    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
      <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
      <circle cx="8.5" cy="8.5" r="1.5"></circle>
      <polyline points="21 15 16 10 5 21"></polyline>
    </svg>
    <span class="ml-1 text-sm">URL Image</span>
  </button>

  <label class="p-1 rounded hover:bg-gray-100 flex items-center cursor-pointer" title="Upload Image">
    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
      <path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7"></path>
      <line x1="16" y1="5" x2="22" y2="5"></line>
      <line x1="19" y1="2" x2="19" y2="8"></line>
      <rect x="3" y="10" width="18" height="12" rx="2"></rect>
      <circle cx="8.5" cy="15.5" r="1.5"></circle>
      <polyline points="21 18 16 13 8 21"></polyline>
    </svg>
    <span class="ml-1 text-sm">Upload</span>
    <input 
      type="file" 
      @change="uploadImage" 
      accept="image/*" 
      class="hidden"
    />
  </label>
</div>
</template>