/**
 * Alpine.js component for the 4-figure body diagram.
 * Multi-mark: each click adds a numbered gold dot.
 * Uses a <canvas> overlay drawn via Alpine watchers — avoids x-for inside SVG.
 */
function bodyDiagram(initial) {
  return {
    figures: ['male_front', 'male_back', 'female_front', 'female_back'],
    labels: {
      male_front:   'Male · Front',
      male_back:    'Male · Back',
      female_front: 'Female · Front',
      female_back:  'Female · Back',
    },
    marks: Array.isArray(initial) ? initial : [],
    imgBase: (typeof BODY_IMG_BASE !== 'undefined') ? BODY_IMG_BASE : '/assets/img/body/',
    _canvases: {}, // fig -> canvas element

    init() {
      // Watch marks and redraw all canvases whenever marks change
      this.$watch('marks', () => this._redrawAll());
    },

    imgUrl(fig) { return this.imgBase + fig + '.png'; },

    // Called by x-init on each canvas element
    registerCanvas(fig, canvas) {
      this._canvases[fig] = canvas;
      // Set initial size after layout (offsetWidth may be 0 before paint)
      requestAnimationFrame(() => this._redraw(fig));
    },

    _redrawAll() {
      for (const fig of this.figures) {
        if (this._canvases[fig]) this._redraw(fig);
      }
    },

    _redraw(fig) {
      const canvas = this._canvases[fig];
      if (!canvas) return;
      // Sync canvas buffer size to its CSS display size (fixes blurry dots on resize)
      const dpr = window.devicePixelRatio || 1;
      const cssW = canvas.offsetWidth || canvas.width;
      const cssH = canvas.offsetHeight || canvas.height;
      if (canvas.width !== Math.round(cssW * dpr) || canvas.height !== Math.round(cssH * dpr)) {
        canvas.width  = Math.round(cssW * dpr);
        canvas.height = Math.round(cssH * dpr);
      }
      const W = canvas.width, H = canvas.height;
      const ctx = canvas.getContext('2d');
      ctx.clearRect(0, 0, W, H);
      ctx.save();
      ctx.scale(dpr, dpr);

      const figMarks = this.marks.filter(m => m.figure === fig);
      figMarks.forEach((m) => {
        const globalIdx = this.marks.indexOf(m);
        // Scale from diagram coords (200x500) to CSS pixels
        const cx = (m.x / 200) * cssW;
        const cy = (m.y / 500) * cssH;
        const r = Math.max(6, cssW * 0.04); // small pin dot

        // Subtle shadow/glow
        ctx.shadowColor = 'rgba(212,175,55,0.6)';
        ctx.shadowBlur = 4;

        // Solid gold dot
        ctx.beginPath();
        ctx.arc(cx, cy, r, 0, Math.PI * 2);
        ctx.fillStyle = '#d4af37';
        ctx.fill();

        ctx.shadowBlur = 0;

        // Number label (white, small)
        const fontSize = Math.max(8, Math.round(r * 1.1));
        ctx.fillStyle = '#0a0a0a';
        ctx.font = `bold ${fontSize}px Inter,Arial,sans-serif`;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(String(globalIdx + 1), cx, cy);
      });
      ctx.restore();
    },

    addMark(fig, event) {
      const canvas = this._canvases[fig];
      if (!canvas) return;
      const rect = canvas.getBoundingClientRect();
      // Convert click position to diagram coordinate space (200x500)
      const px = ((event.clientX - rect.left) / rect.width)  * 200;
      const py = ((event.clientY - rect.top)  / rect.height) * 500;
      this.marks = [...this.marks, { figure: fig, x: Math.round(px), y: Math.round(py) }];
    },

    removeMark(index) {
      this.marks = this.marks.filter((_, i) => i !== index);
    },

    clear() { this.marks = []; },
  };
}
window.bodyDiagram = bodyDiagram;
