<template>
  <div
    class="z-[1] select-none touch-none"
    :class="selected ? 'outline outline-2 outline-accent outline-offset-2' : ''"
    :style="computedStyle"
    @mousedown.stop="$emit('drag-start', { id: widget.id, event: $event })"
    @touchstart.stop="$emit('drag-start', { id: widget.id, event: $event })"
    @click.stop="$emit('select')"
  >
    <div class="flex w-full h-full overflow-hidden" :style="tabViewStyle">
      <div class="flex overflow-hidden bg-black/20" :style="tabBtnsStyle">
        <div
          v-for="(child, idx) in children"
          :key="child.id"
          :class="tabBtnClass(activePageId === child.id)"
          @click.stop="activeTabIndex = idx; store.selectedWidgetId = child.id"
        >
          {{ child.text }}
        </div>
      </div>
      <div class="flex-1 relative overflow-hidden">
        <TabPageElement
          v-for="child in children"
          :key="child.id"
          :widget="child"
          :scale="scale"
          :selected="store.selectedWidgetId === child.id"
          :style="{ display: activePageId === child.id ? 'block' : 'none' }"
          @select="store.selectedWidgetId = child.id"
          @drag-start="$emit('drag-start', $event)"
          @resize-start="$emit('resize-start', $event)"
        />
      </div>
    </div>

    <!-- Resize Handle -->
    <div
      v-if="selected"
      class="absolute -right-1.5 -bottom-1.5 w-3.5 h-3.5 rounded-[4px] bg-accent border-[2px] border-[#1b1308] shadow-[0_4px_12px_rgba(0,0,0,0.35)] cursor-se-resize z-10"
      data-resize-handle
      @mousedown.stop="$emit('resize-start', { id: widget.id, event: $event })"
      @touchstart.stop="$emit('resize-start', { id: widget.id, event: $event })"
    >
      <span class="absolute right-[2px] bottom-[2px] w-[6px] h-[6px] border-r-2 border-b-2 border-[#1b1308a6] rounded-[2px]"></span>
    </div>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue';
import { useEditorStore } from '../../../stores/editor';
import { getBaseStyle, getBorderStyle, clamp, hexToRgba } from '../shared/utils';
import TabPageElement from './TabPageElement.vue';

const props = defineProps({
  widget: { type: Object, required: true },
  scale: { type: Number, default: 1 },
  selected: { type: Boolean, default: false }
});

defineEmits(['select', 'drag-start', 'resize-start']);

const store = useEditorStore();
const activeTabIndex = ref(0);

const children = computed(() => {
  if (!store.activeScreen) return [];
  return store.activeScreen.widgets.filter(w => w.parentId === props.widget.id);
});

const tabPosition = computed(() => props.widget.iconPosition || 0);
const tabHeight = computed(() => (props.widget.iconSize || 5) * 10);

const activePageId = computed(() => {
  const selectedChild = children.value.find(c => store.selectedWidgetId === c.id);
  if (selectedChild) return selectedChild.id;

  if (store.selectedWidget && store.selectedWidget.parentId !== -1) {
    let curr = store.selectedWidget;
    while (curr && curr.parentId !== -1 && curr.parentId !== props.widget.id) {
      curr = store.activeScreen.widgets.find(w => w.id === curr.parentId);
    }
    if (curr && curr.parentId === props.widget.id) return curr.id;
  }

  if (children.value.length > 0) return children.value[activeTabIndex.value]?.id;
  return -1;
});

const computedStyle = computed(() => {
  const w = props.widget;
  const s = props.scale;

  const style = getBaseStyle(w, s);
  style.background = hexToRgba(w.bgColor, clamp((w.bgOpacity ?? 255) / 255, 0, 1));
  style.borderRadius = `${w.radius * s}px`;
  Object.assign(style, getBorderStyle(w, s));

  return style;
});

const tabViewStyle = computed(() => ({
  flexDirection: tabPosition.value === 0 || tabPosition.value === 1 ? 'column' : 'row'
}));

const tabBtnsStyle = computed(() => {
  const s = props.scale;
  const h = tabHeight.value * s;
  const isVert = tabPosition.value === 0 || tabPosition.value === 1;

  return {
    [isVert ? 'height' : 'width']: `${h}px`,
    order: tabPosition.value === 1 || tabPosition.value === 3 ? 2 : 0,
    flexDirection: isVert ? 'row' : 'column'
  };
});

const tabBtnClass = (isActive) => {
  const isVerticalTabs = tabPosition.value === 2 || tabPosition.value === 3;
  const base = 'flex-1 flex items-center justify-center px-1 py-1 text-[12px] cursor-pointer select-none';
  const border = isVerticalTabs ? 'border-b border-white/10' : 'border-b border-r border-white/10';
  const active = isVerticalTabs
    ? 'bg-white/10 font-bold border-b-0 border-r-2 border-accent'
    : 'bg-white/10 font-bold border-b-2 border-accent';
  return `${base} ${border}${isActive ? ` ${active}` : ''}`;
};
</script>
