/* global React, ANNOTATIONS */
/* HudChromeLayer — renders the draggable selection chrome (EDIT mode) and
   the numbered annotation callouts (ANNOTATE mode) on top of the active overlay.
   Drag state is applied as a transform: translate(dx, dy) on the actual overlay
   element so the design is what gets moved — not a proxy. */

function HudChromeLayer({ archetype, mode, positions, setPosition, scale, focused, setFocused }) {
  const items = ANNOTATIONS[archetype] || [];

  // Apply position transforms to the actual overlay elements.
  // Runs whenever positions or archetype change.
  React.useLayoutEffect(() => {
    for (const item of items) {
      const el = document.querySelector(item.selector);
      if (!el) continue;
      const pos = positions[`${archetype}.${item.id}`] || { dx: 0, dy: 0 };
      if (pos.dx === 0 && pos.dy === 0) {
        el.style.transform = '';
      } else {
        el.style.transform = `translate(${pos.dx}px, ${pos.dy}px)`;
      }
    }
    // cleanup on archetype change — clear styles
    return () => {
      for (const item of items) {
        const el = document.querySelector(item.selector);
        if (el) el.style.transform = '';
      }
    };
  }, [items, positions, archetype]);

  if (mode === 'live') return null;

  return (
    <div className={`hud-chrome mode-${mode}`}>
      {items.map((item, i) => {
        const pos = positions[`${archetype}.${item.id}`] || { dx: 0, dy: 0 };
        const x = item.x + pos.dx;
        const y = item.y + pos.dy;

        return mode === 'edit' ? (
          <EditChrome
            key={item.id}
            item={item}
            x={x} y={y}
            scale={scale}
            focused={focused === item.id}
            onFocus={() => setFocused(item.id)}
            onDrag={(ddx, ddy) => {
              setPosition(`${archetype}.${item.id}`, { dx: pos.dx + ddx, dy: pos.dy + ddy });
            }}
            onReset={() => setPosition(`${archetype}.${item.id}`, { dx: 0, dy: 0 })}
          />
        ) : (
          <AnnotateChrome
            key={item.id}
            item={item}
            num={i + 1}
            x={x} y={y}
            focused={focused === item.id}
            onFocus={() => setFocused(item.id)}
          />
        );
      })}
    </div>
  );
}

/* ============================================================
   EDIT mode — dashed outline + drag handle
   ============================================================ */
function EditChrome({ item, x, y, scale, focused, onFocus, onDrag, onReset }) {
  const [dragging, setDragging] = React.useState(false);
  const startRef = React.useRef(null);

  const onMouseDown = (e) => {
    e.preventDefault();
    e.stopPropagation();
    onFocus();
    setDragging(true);
    startRef.current = { x: e.clientX, y: e.clientY };
    const onMove = (ev) => {
      const dx = (ev.clientX - startRef.current.x) / scale;
      const dy = (ev.clientY - startRef.current.y) / scale;
      startRef.current = { x: ev.clientX, y: ev.clientY };
      onDrag(dx, dy);
    };
    const onUp = () => {
      setDragging(false);
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
    };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
  };

  return (
    <div
      className={`edit-chrome ${focused ? 'is-focused' : ''} ${dragging ? 'is-dragging' : ''}`}
      style={{
        left: x + 'px', top: y + 'px',
        width: item.w + 'px', height: item.h + 'px',
      }}
      onMouseDown={onMouseDown}
    >
      <span className="edit-corner tl"></span>
      <span className="edit-corner tr"></span>
      <span className="edit-corner bl"></span>
      <span className="edit-corner br"></span>
      <div className="edit-label">
        <span className="lab">{item.label}</span>
        <button type="button" className="edit-reset" onClick={(e) => { e.stopPropagation(); onReset(); }}>RESET</button>
      </div>
    </div>
  );
}

/* ============================================================
   ANNOTATE mode — numbered badge + callout balloon + pointer line
   ============================================================ */
function AnnotateChrome({ item, num, x, y, focused, onFocus }) {
  // Where the callout balloon goes
  const side = item.side || 'right';
  const CALLOUT_W = 320;
  const GAP = 56;

  // Anchor point on the box (closest to callout)
  let ax, ay, bx, by, balloonX, balloonY;
  if (side === 'right') {
    ax = x + item.w; ay = y + item.h / 2;
    balloonX = ax + GAP; balloonY = ay - 40;
    bx = balloonX; by = ay;
  } else if (side === 'left') {
    ax = x; ay = y + item.h / 2;
    balloonX = ax - GAP - CALLOUT_W; balloonY = ay - 40;
    bx = balloonX + CALLOUT_W; by = ay;
  } else if (side === 'top') {
    ax = x + item.w / 2; ay = y;
    balloonX = ax - CALLOUT_W / 2; balloonY = ay - GAP - 100;
    bx = ax; by = balloonY + 100;
  } else { // bottom
    ax = x + item.w / 2; ay = y + item.h;
    balloonX = ax - CALLOUT_W / 2; balloonY = ay + GAP;
    bx = ax; by = balloonY;
  }

  // Clamp to canvas
  balloonX = Math.max(12, Math.min(1920 - CALLOUT_W - 12, balloonX));
  balloonY = Math.max(60, Math.min(1080 - 140, balloonY));

  return (
    <>
      {/* Outline ring */}
      <div
        className={`annot-ring ${focused ? 'is-focused' : ''}`}
        style={{
          left: x + 'px', top: y + 'px',
          width: item.w + 'px', height: item.h + 'px',
        }}
        onMouseEnter={onFocus}
      >
        <span className="annot-corner tl"></span>
        <span className="annot-corner tr"></span>
        <span className="annot-corner bl"></span>
        <span className="annot-corner br"></span>
        <span className="annot-badge">{String(num).padStart(2, '0')}</span>
      </div>

      {/* Pointer line — SVG, drawn in canvas coords */}
      <svg className="annot-line" viewBox="0 0 1920 1080" preserveAspectRatio="none">
        <line
          x1={ax} y1={ay} x2={bx} y2={by}
          stroke="var(--annot-line, #fff)" strokeWidth="1.5"
          strokeDasharray="6 4"
        />
        <circle cx={ax} cy={ay} r="4" fill="var(--annot-line, #fff)" />
      </svg>

      {/* Balloon */}
      <div
        className={`annot-balloon ${focused ? 'is-focused' : ''}`}
        style={{ left: balloonX + 'px', top: balloonY + 'px', width: CALLOUT_W + 'px' }}
        onMouseEnter={onFocus}
      >
        <div className="annot-balloon-head">
          <span className="annot-num">{String(num).padStart(2, '0')}</span>
          <span className="annot-lab">{item.label}</span>
        </div>
        <div className="annot-balloon-body">{item.description}</div>
      </div>
    </>
  );
}

Object.assign(window, { HudChromeLayer });
