<script setup>
import { computed, ref } from "vue";
import GoogleIcon from "@Shared/GoogleIcon.vue";

const props = defineProps({
  editor: { type: Object, default: null },
  selectedElement: { type: Object, default: null },
  isTableEditing: { type: Boolean, default: false },
});
const emit = defineEmits(["table-action"]);

const colorGrid = ref(null);

// CORRECCIÓN: Usar props.editor directamente para mantener la reactividad.
const isTextSelected = computed(
  () => props.selectedElement?.type === "text" && props.editor
);
const isTableSelected = computed(
  () => props.selectedElement?.type === "table" && props.isTableEditing
);

const FONT_SIZES = ["12", "14", "16", "20", "24", "30"];
const PRIMARY_COLORS = [
  "#000000",
  "#FF0000",
  "#00FF00",
  "#0000FF",
  "#FFFF00",
  "#FF00FF",
  "#00FFFF",
  "#FFFFFF",
  "#800000",
  "#008000",
  "#000080",
  "#808000",
  "#800080",
  "#008080",
  "#C0C0C0",
  "#808080",
];

const currentFontSize = computed({
  get() {
    if (!props.editor) return "16";
    const sz = props.editor.getAttributes("textStyle").fontSize;
    return sz ? sz.replace("px", "") : "16";
  },
  set(value) {
    if (props.editor) {
      props.editor.chain().focus().setFontSize(`${value}px`).run();
    }
  },
});

const setColor = (color) => {
  if (props.editor) {
    props.editor.chain().focus().setColor(color).run();
    if (colorGrid.value) {
      colorGrid.value.classList.add("hidden");
    }
  }
};

const toggleColorGrid = () => {
  if (colorGrid.value) {
    colorGrid.value.classList.toggle("hidden");
  }
};

const currentColour = computed(() => {
  if (!props.editor) return "#000000";
  return props.editor.getAttributes("textStyle").color || "#000000";
});

const textActions = [
  {
    action: () => {
      if (props.editor) props.editor.chain().focus().toggleBold().run();
    },
    icon: "format_bold",
    isActive: "bold",
  },
  {
    action: () => {
      if (props.editor) props.editor.chain().focus().toggleItalic().run();
    },
    icon: "format_italic",
    isActive: "italic",
  },
  {
    action: () => {
      if (props.editor) props.editor.chain().focus().toggleUnderline().run();
    },
    icon: "format_underlined",
    isActive: "underline",
  },
  { type: "divider" },
  {
    action: () => {
      if (props.editor) props.editor.chain().focus().setTextAlign("left").run();
    },
    icon: "format_align_left",
    isActive: { textAlign: "left" },
  },
  {
    action: () => {
      if (props.editor)
        props.editor.chain().focus().setTextAlign("center").run();
    },
    icon: "format_align_center",
    isActive: { textAlign: "center" },
  },
  {
    action: () => {
      if (props.editor)
        props.editor.chain().focus().setTextAlign("right").run();
    },
    icon: "format_align_right",
    isActive: { textAlign: "right" },
  },
];
</script>

<template>
  <div
    class="w-full bg-white border-b px-4 py-2 shadow-sm h-14 flex items-center gap-2"
  >
    <template v-if="isTextSelected || isTableSelected">
      <!-- Botones de formato de texto (disponibles para texto y tabla) -->
      <template v-if="editor">
        <button
          v-for="item in textActions.filter((i) => !i.type)"
          :key="item.icon"
          @click="item.action"
          @mousedown.prevent
          :class="{ 'bg-gray-200': editor.isActive(item.isActive) }"
          class="p-2 rounded hover:bg-gray-100"
        >
          <GoogleIcon :name="item.icon" />
        </button>

        <div class="w-px h-6 bg-gray-200 mx-1"></div>

        <!-- Controles de tamaño y color para texto -->
        <div class="flex items-center gap-2" @mousedown.stop>
          <select
            v-model="currentFontSize"
            class="px-2 py-1 text-sm border border-gray-300 rounded"
          >
            <option v-for="size in FONT_SIZES" :key="size" :value="size">
              {{ size }}px
            </option>
          </select>
          
          <!-- Selector de colores -->
          <div class="relative">
            <button
              type="button"
              @click="toggleColorGrid"
              class="w-8 h-6 border border-gray-300 rounded flex items-center justify-center"
              :style="{ backgroundColor: currentColour }"
            >
              <GoogleIcon name="palette" class="text-xs text-white mix-blend-difference" />
            </button>
            <div
              ref="colorGrid"
              class="absolute top-full left-0 mt-1 p-2 bg-white border rounded shadow-lg z-50 hidden"
            >
              <div class="grid grid-cols-4 gap-1">
                <button
                  v-for="color in PRIMARY_COLORS"
                  :key="color"
                  type="button"
                  @click="setColor(color)"
                  class="w-6 h-6 border rounded cursor-pointer hover:scale-110"
                  :style="{ backgroundColor: color }"
                />
              </div>
            </div>
          </div>
        </div>
      </template>

      <!-- Controles específicos de tabla -->
      <div v-if="isTableSelected" class="flex items-center gap-2 ml-auto" @mousedown.stop>
        <button
          type="button"
          @click="emit('table-action', 'addRow')"
          class="px-2 py-1 text-xs bg-green-500 text-white rounded hover:bg-green-600"
        >
          + Fila
        </button>
        <button
          type="button"
          @click="emit('table-action', 'delRow')"
          class="px-2 py-1 text-xs bg-red-500 text-white rounded hover:bg-red-600"
        >
          - Fila
        </button>
        <button
          type="button"
          @click="emit('table-action', 'addCol')"
          class="px-2 py-1 text-xs bg-blue-500 text-white rounded hover:bg-blue-600"
        >
          + Col
        </button>
        <button
          type="button"
          @click="emit('table-action', 'delCol')"
          class="px-2 py-1 text-xs bg-red-600 text-white rounded hover:bg-red-700"
        >
          - Col
        </button>
      </div>
    </template>

    <div v-else class="text-sm text-gray-400">
      Selecciona un elemento para ver sus opciones
    </div>
  </div>
</template>
