<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
      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 } from 'vue';
import { getBaseStyle, getShadowStyle, clamp, hexToRgba } from '../shared/utils';

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 computedStyle = computed(() => {
  const w = props.widget;
  const s = props.scale;
  const style = getBaseStyle(w, s);

  const bgAlpha = clamp((w.bgOpacity ?? 255) / 255, 0, 1);
  style.background = hexToRgba(w.bgColor || '#000000', bgAlpha);
  style.borderRadius = `${(w.radius || 0) * s}px`;

  const borderWidth = Math.max(0, (w.borderWidth || 0) * s);
  const borderAlpha = clamp((w.borderOpacity ?? 0) / 255, 0, 1);
  if (borderWidth > 0 && borderAlpha > 0) {
    style.border = `${borderWidth}px solid ${hexToRgba(w.borderColor || '#ffffff', borderAlpha)}`;
  } else {
    style.border = 'none';
  }

  Object.assign(style, getShadowStyle(w, s));
  return style;
});
</script>
