<template>
  <div>
    <canvas
      ref="canvas"
      class="sig-canvas"
      @pointerdown="start"
      @pointermove="draw"
      @pointerup="end"
      @pointerleave="end"
    />
    <div class="d-flex align-center mt-1">
      <span class="quiet text-caption">Sign in the box above</span>
      <v-spacer />
      <v-btn size="x-small" variant="text" @click="clear">Clear</v-btn>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    modelValue: { type: String, default: '' }
  },
  emits: ['update:modelValue'],
  data() {
    return { drawing: false, ctx: null, hasInk: false };
  },
  mounted() {
    const canvas = this.$refs.canvas;
    canvas.width = canvas.offsetWidth || 460;
    canvas.height = 150;
    this.ctx = canvas.getContext('2d');
    this.ctx.lineWidth = 2;
    this.ctx.lineCap = 'round';
    this.ctx.strokeStyle = '#111';
  },
  methods: {
    pos(event) {
      const rect = this.$refs.canvas.getBoundingClientRect();
      return { x: event.clientX - rect.left, y: event.clientY - rect.top };
    },
    start(event) {
      this.drawing = true;
      const point = this.pos(event);
      this.ctx.beginPath();
      this.ctx.moveTo(point.x, point.y);
      try { this.$refs.canvas.setPointerCapture(event.pointerId); } catch { /* not supported */ }
    },
    draw(event) {
      if (!this.drawing) return;
      const point = this.pos(event);
      this.ctx.lineTo(point.x, point.y);
      this.ctx.stroke();
      this.hasInk = true;
    },
    end() {
      if (!this.drawing) return;
      this.drawing = false;
      if (this.hasInk) this.$emit('update:modelValue', this.$refs.canvas.toDataURL('image/png'));
    },
    clear() {
      this.ctx.clearRect(0, 0, this.$refs.canvas.width, this.$refs.canvas.height);
      this.hasInk = false;
      this.$emit('update:modelValue', '');
    }
  }
};
</script>

<style scoped>
.sig-canvas {
  width: 100%;
  height: 150px;
  border: 1px solid rgba(var(--v-theme-on-surface), 0.3);
  border-radius: 8px;
  background: #fff;
  touch-action: none;
  cursor: crosshair;
}
</style>
