<script setup lang="ts">
/**
 * Selection outline + resize handles for the active element, drawn in the
 * Stage's mm viewBox. Presentational only: it emits `handledown(name, event)`
 * on pointerdown and the Stage performs the geometry math against the shared
 * design model. Handles are kept a constant on-screen size via `pxPerMm`.
 */
import type { LdElement } from '~/composables/useLabelDesign'

const props = defineProps<{ el: LdElement; pxPerMm: number }>()
const emit = defineEmits<{ (e: 'handledown', name: string, ev: PointerEvent): void }>()

const HANDLE_PX = 9
const hs = computed(() => HANDLE_PX / Math.max(0.0001, props.pxPerMm)) // handle side, mm
const strokeMm = computed(() => 1 / Math.max(0.0001, props.pxPerMm))

const isLine = computed(() => props.el.type === 'line')

const boxHandles = computed(() => {
  const { x, y, w, h } = props.el
  return [
    { name: 'nw', cx: x, cy: y, cursor: 'nwse-resize' },
    { name: 'n', cx: x + w / 2, cy: y, cursor: 'ns-resize' },
    { name: 'ne', cx: x + w, cy: y, cursor: 'nesw-resize' },
    { name: 'e', cx: x + w, cy: y + h / 2, cursor: 'ew-resize' },
    { name: 'se', cx: x + w, cy: y + h, cursor: 'nwse-resize' },
    { name: 's', cx: x + w / 2, cy: y + h, cursor: 'ns-resize' },
    { name: 'sw', cx: x, cy: y + h, cursor: 'nesw-resize' },
    { name: 'w', cx: x, cy: y + h / 2, cursor: 'ew-resize' }
  ]
})

const lineHandles = computed(() => {
  const { x, y, w, h } = props.el
  return [
    { name: 'p1', cx: x, cy: y },
    { name: 'p2', cx: x + w, cy: y + h }
  ]
})

const down = (name: string, ev: PointerEvent) => emit('handledown', name, ev)
</script>

<template>
  <g class="ldHandles" style="pointer-events: all">
    <template v-if="isLine">
      <line
        :x1="el.x" :y1="el.y" :x2="el.x + el.w" :y2="el.y + el.h"
        stroke="#3b82f6" :stroke-width="strokeMm" :stroke-dasharray="`${strokeMm * 3} ${strokeMm * 3}`"
        pointer-events="none"
      />
      <circle
        v-for="h in lineHandles" :key="h.name"
        :cx="h.cx" :cy="h.cy" :r="hs * 0.6"
        fill="#ffffff" stroke="#3b82f6" :stroke-width="strokeMm"
        style="cursor: crosshair"
        @pointerdown.stop.prevent="down(h.name, $event)"
      />
    </template>

    <template v-else>
      <rect
        :x="el.x" :y="el.y" :width="el.w" :height="el.h"
        fill="none" stroke="#3b82f6" :stroke-width="strokeMm"
        :stroke-dasharray="`${strokeMm * 3} ${strokeMm * 3}`"
        pointer-events="none"
      />
      <rect
        v-for="h in boxHandles" :key="h.name"
        :x="h.cx - hs / 2" :y="h.cy - hs / 2" :width="hs" :height="hs"
        fill="#ffffff" stroke="#3b82f6" :stroke-width="strokeMm"
        :style="{ cursor: h.cursor }"
        @pointerdown.stop.prevent="down(h.name, $event)"
      />
    </template>
  </g>
</template>
