<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')"
  >
    <span class="material-symbols-outlined flex items-center justify-center" :style="iconOnlyStyle">
      {{ iconChar }}
    </span>

    <!-- 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 } from 'vue';
import { fontSizes } from '../../../constants';
import { getBaseStyle, clamp, hexToRgba, getBorderStyle } 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 iconChar = computed(() => {
  const cp = props.widget.iconCodepoint || 0xe88a;
  return String.fromCodePoint(cp);
});

const iconOnlyStyle = computed(() => {
  const s = props.scale;
  const sizeIdx = props.widget.iconSize ?? 3;
  const size = fontSizes[sizeIdx] || 28;
  return {
    fontSize: `${size * s}px`,
    color: props.widget.textColor
  };
});

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

  const style = getBaseStyle(w, s);
  style.display = 'flex';
  style.alignItems = 'center';
  style.justifyContent = 'center';

  if (w.bgOpacity > 0) {
    const alpha = clamp(w.bgOpacity / 255, 0, 1).toFixed(2);
    style.background = hexToRgba(w.bgColor, alpha);
  }

  if (w.radius > 0) {
    style.borderRadius = `${w.radius * s}px`;
  }

  Object.assign(style, getBorderStyle(w, s));

  return style;
});
</script>
