Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

76.2 KB
Raw Blame
import { Point } from '../types/editor';

export type QuickShapeKind =
  | 'line'
  | 'arc'
  | 'circle'
  | 'ellipse'
  | 'triangle'
  | 'rectangle';

export interface Vec2 {
  x: number;
  y: number;
}

export interface QuickShapeLine {
  kind: 'line';
  start: Vec2;
  end: Vec2;
}

export interface QuickShapeArc {
  kind: 'arc';
  start: Vec2;
  mid: Vec2;
  end: Vec2;
}

export interface QuickShapeCircle {
  kind: 'circle';
  center: Vec2;
  radius: number;
  handleAngle: number;
}

export interface QuickShapeEllipse {
  kind: 'ellipse';
  center: Vec2;
  rx: number;
  ry: number;
  rotation: number;
  handleAngle: number;
}

export interface QuickShapeTriangle {
  kind: 'triangle';
  vertices: [Vec2, Vec2, Vec2];
}

export interface QuickShapeRectangle {
  kind: 'rectangle';
  center: Vec2;
  width: number;
  height: number;
  rotation: number;
}

export type QuickShapeGeometry =
  | QuickShapeLine
  | QuickShapeArc
  | QuickShapeCircle
  | QuickShapeEllipse
  | QuickShapeTriangle
  | QuickShapeRectangle;

export interface QuickShapeHandle {
  id: string;
  x: number;
  y: number;
  kind: 'corner' | 'endpoint' | 'mid' | 'rim' | 'axis' | 'center';
  active?: boolean;
}

export interface QuickShapeStrokeStyle {
  pressure: number;
  width: number;
  tiltX: number;
  tiltY: number;
  twist: number;
}

export interface QuickShapeRecognitionResult {
  shape: QuickShapeGeometry;
  confidence: number;
  rmsNorm: number;
}

export interface QuickShapePreviewState {
  shape: QuickShapeGeometry;
  label: string;
  readout: string;
  hint: string;
  svgPath: string;
  guideLine?: { x1: number; y1: number; x2: number; y2: number };
  centerMarker?: Vec2;
  handles: QuickShapeHandle[];
  anchorPos: Vec2;
  activeHandleId: string;
  snappedAtMs: number;
}

export interface QuickShapeSession {
  initialShape: QuickShapeGeometry;
  currentShape: QuickShapeGeometry;
  snapPenPos: Vec2;
  activeHandleId: string;
  activeCornerIndex: number;
  initialArcBulgeRatio: number;
  hasExitedDeadzone: boolean;
  style: QuickShapeStrokeStyle;
  snappedAtMs: number;
}

export const QUICK_SHAPE_HOLD_MS = 350;
export const QUICK_SHAPE_HOLD_TOLERANCE_SCREEN_PX = 6;
export const QUICK_SHAPE_DRAG_DEADZONE_SCREEN_PX = 4;
export const QUICK_SHAPE_MIN_STROKE_LENGTH_DOC = 24;

const TWO_PI = Math.PI * 2;

function clamp(v: number, min: number, max: number): number {
  return v < min ? min : v > max ? max : v;
}

function mod2Pi(a: number): number {
  const m = a % TWO_PI;
  return m < 0 ? m + TWO_PI : m;
}

function normalizeHalfPiAngle(a: number): number {
  let r = a % Math.PI;
  if (r > Math.PI * 0.5) r -= Math.PI;
  if (r <= -Math.PI * 0.5) r += Math.PI;
  return r;
}

function snapAngleRad(rad: number, stepDeg: number): number {
  const step = (stepDeg * Math.PI) / 180;
  return Math.round(rad / step) * step;
}

function distSq(a: Vec2, b: Vec2): number {
  const dx = a.x - b.x;
  const dy = a.y - b.y;
  return dx * dx + dy * dy;
}

function dist(a: Vec2, b: Vec2): number {
  return Math.hypot(a.x - b.x, a.y - b.y);
}

function pointToSegmentDistSq(p: Vec2, a: Vec2, b: Vec2): number {
  const dx = b.x - a.x;
  const dy = b.y - a.y;
  const lenSq = dx * dx + dy * dy;
  if (lenSq < 1e-9) return distSq(p, a);
  const t = clamp(((p.x - a.x) * dx + (p.y - a.y) * dy) / lenSq, 0, 1);
  const projX = a.x + t * dx;
  const projY = a.y + t * dy;
  const ex = p.x - projX;
  const ey = p.y - projY;
  return ex * ex + ey * ey;
}

function pointToSegmentDist(p: Vec2, a: Vec2, b: Vec2): number {
  return Math.sqrt(pointToSegmentDistSq(p, a, b));
}

function polylineLength(pts: ReadonlyArray<Vec2>): number {
  let len = 0;
  for (let i = 1; i < pts.length; i++) {
    len += dist(pts[i - 1], pts[i]);
  }
  return len;
}

function computeBounds(pts: ReadonlyArray<Vec2>): {
  minX: number;
  minY: number;
  maxX: number;
  maxY: number;
  width: number;
  height: number;
  diag: number;
} {
  let minX = Infinity;
  let minY = Infinity;
  let maxX = -Infinity;
  let maxY = -Infinity;
  for (let i = 0; i < pts.length; i++) {
    const p = pts[i];
    if (p.x < minX) minX = p.x;
    if (p.y < minY) minY = p.y;
    if (p.x > maxX) maxX = p.x;
    if (p.y > maxY) maxY = p.y;
  }
  const width = Math.max(0, maxX - minX);
  const height = Math.max(0, maxY - minY);
  return { minX, minY, maxX, maxY, width, height, diag: Math.hypot(width, height) };
}

function resamplePolyline(pts: ReadonlyArray<Vec2>, targetCount: number): Vec2[] {
  if (pts.length === 0) return [];
  if (pts.length === 1 || targetCount <= 1) return [{ x: pts[0].x, y: pts[0].y }];

  const cumLen = new Float64Array(pts.length);
  for (let i = 1; i < pts.length; i++) {
    cumLen[i] = cumLen[i - 1] + dist(pts[i - 1], pts[i]);
  }
  const totalLen = cumLen[pts.length - 1];
  if (totalLen < 1e-6) {
    return Array.from({ length: targetCount }, () => ({ x: pts[0].x, y: pts[0].y }));
  }

  const out: Vec2[] = new Array(targetCount);
  out[0] = { x: pts[0].x, y: pts[0].y };
  let segIdx = 0;
  for (let k = 1; k < targetCount - 1; k++) {
    const targetDist = (totalLen * k) / (targetCount - 1);
    while (segIdx < pts.length - 2 && cumLen[segIdx + 1] < targetDist) {
      segIdx++;
    }
    const segStart = cumLen[segIdx];
    const segEnd = cumLen[segIdx + 1];
    const span = segEnd - segStart;
    const t = span > 1e-9 ? (targetDist - segStart) / span : 0;
    const a = pts[segIdx];
    const b = pts[segIdx + 1];
    out[k] = {
      x: a.x + (b.x - a.x) * t,
      y: a.y + (b.y - a.y) * t,
    };
  }
  out[targetCount - 1] = { x: pts[pts.length - 1].x, y: pts[pts.length - 1].y };
  return out;
}

/**
 * Trims trailing micro-jitter points accumulated while the artist holds the stylus still.
 */
function trimTrailingHoldJitter(pts: ReadonlyArray<Vec2>, toleranceDoc: number): Vec2[] {
  if (pts.length <= 4) return pts.map((p) => ({ x: p.x, y: p.y }));
  const endPt = pts[pts.length - 1];
  const tolSq = toleranceDoc * toleranceDoc;
  let lastOutside = pts.length - 1;
  while (lastOutside > 2 && distSq(pts[lastOutside - 1], endPt) <= tolSq) {
    lastOutside--;
  }
  const trimmed = pts.slice(0, lastOutside + 1).map((p) => ({ x: p.x, y: p.y }));
  if (lastOutside < pts.length - 1) {
    // Anchor final point at the actual resting stylus coordinate
    trimmed[trimmed.length - 1] = { x: endPt.x, y: endPt.y };
  }
  return trimmed;
}

function shoelaceArea(pts: ReadonlyArray<Vec2>): number {
  let sum = 0;
  const n = pts.length;
  for (let i = 0; i < n; i++) {
    const a = pts[i];
    const b = pts[(i + 1) % n];
    sum += a.x * b.y - b.x * a.y;
  }
  return Math.abs(sum) * 0.5;
}

function computeCentroidWindingAngle(pts: ReadonlyArray<Vec2>): number {
  const n = pts.length;
  if (n < 3) return 0;
  let cx = 0;
  let cy = 0;
  for (let i = 0; i < n; i++) {
    cx += pts[i].x;
    cy += pts[i].y;
  }
  cx /= n;
  cy /= n;
  let total = 0;
  let prevA = Math.atan2(pts[0].y - cy, pts[0].x - cx);
  for (let i = 1; i <= n; i++) {
    const p = pts[i % n];
    const dx = p.x - cx;
    const dy = p.y - cy;
    if (dx * dx + dy * dy < 1e-4) continue;
    const a = Math.atan2(dy, dx);
    let da = a - prevA;
    while (da > Math.PI) da -= TWO_PI;
    while (da < -Math.PI) da += TWO_PI;
    total += da;
    prevA = a;
  }
  return total;
}

/**
 * Algebraic Kasa circle fit + Gauss-Newton geometric refinement.
 */
function fitCircleLeastSquares(
  pts: ReadonlyArray<Vec2>
): { cx: number; cy: number; radius: number } | null {
  const n = pts.length;
  if (n < 3) return null;

  let meanX = 0;
  let meanY = 0;
  for (let i = 0; i < n; i++) {
    meanX += pts[i].x;
    meanY += pts[i].y;
  }
  meanX /= n;
  meanY /= n;

  let suu = 0;
  let suv = 0;
  let svv = 0;
  let suuu = 0;
  let svvv = 0;
  let suvv = 0;
  let svuu = 0;

  for (let i = 0; i < n; i++) {
    const u = pts[i].x - meanX;
    const v = pts[i].y - meanY;
    const u2 = u * u;
    const v2 = v * v;
    suu += u2;
    suv += u * v;
    svv += v2;
    suuu += u2 * u;
    svvv += v2 * v;
    suvv += u * v2;
    svuu += v * u2;
  }

  const det = suu * svv - suv * suv;
  if (Math.abs(det) < 1e-6) return null;

  const rhs1 = 0.5 * (suuu + suvv);
  const rhs2 = 0.5 * (svvv + svuu);
  const uc = (rhs1 * svv - rhs2 * suv) / det;
  const vc = (suu * rhs2 - suv * rhs1) / det;

  let cx = meanX + uc;
  let cy = meanY + vc;
  let rSum = 0;
  for (let i = 0; i < n; i++) {
    rSum += Math.hypot(pts[i].x - cx, pts[i].y - cy);
  }
  let radius = rSum / n;
  if (!Number.isFinite(cx) || !Number.isFinite(cy) || !Number.isFinite(radius) || radius < 2) {
    return null;
  }

  // 4 iterations of geometric Gauss-Newton refinement
  for (let iter = 0; iter < 4; iter++) {
    let j00 = 0;
    let j01 = 0;
    let j02 = 0;
    let j11 = 0;
    let j12 = 0;
    const j22 = n;
    let b0 = 0;
    let b1 = 0;
    let b2 = 0;

    for (let i = 0; i < n; i++) {
      const dx = cx - pts[i].x;
      const dy = cy - pts[i].y;
      const d = Math.hypot(dx, dy);
      if (d < 1e-6) continue;
      const gx = dx / d;
      const gy = dy / d;
      const err = d - radius;
      j00 += gx * gx;
      j01 += gx * gy;
      j02 -= gx;
      j11 += gy * gy;
      j12 -= gy;
      b0 -= gx * err;
      b1 -= gy * err;
      b2 += err;
    }

    // Solve 3x3 symmetric system (with light Tikhonov damping)
    const a00 = j00 + 1e-4;
    const a01 = j01;
    const a02 = j02;
    const a11 = j11 + 1e-4;
    const a12 = j12;
    const a22 = j22 + 1e-4;

    const d3 =
      a00 * (a11 * a22 - a12 * a12) -
      a01 * (a01 * a22 - a12 * a02) +
      a02 * (a01 * a12 - a11 * a02);
    if (Math.abs(d3) < 1e-9) break;

    const dcx =
      (b0 * (a11 * a22 - a12 * a12) -
        a01 * (b1 * a22 - a12 * b2) +
        a02 * (b1 * a12 - a11 * b2)) /
      d3;
    const dcy =
      (a00 * (b1 * a22 - a12 * b2) -
        b0 * (a01 * a22 - a12 * a02) +
        a02 * (a01 * b2 - b1 * a02)) /
      d3;
    const dr =
      (a00 * (a11 * b2 - b1 * a12) -
        a01 * (a01 * b2 - b1 * a02) +
        b0 * (a01 * a12 - a11 * a02)) /
      d3;

    if (!Number.isFinite(dcx) || !Number.isFinite(dcy) || !Number.isFinite(dr)) break;
    if (Math.hypot(dcx, dcy) > radius * 0.5) break;
    cx += dcx;
    cy += dcy;
    radius = Math.max(2, radius + dr);
    if (Math.hypot(dcx, dcy) + Math.abs(dr) < 1e-3) break;
  }

  return { cx, cy, radius };
}

/**
 * Computes exact-ish closest distance from a point to an ellipse centered at origin with semi-axes (rx, ry).
 */
function pointToAlignedEllipseDist(lx: number, ly: number, rx: number, ry: number): number {
  const safeRx = Math.max(1e-3, rx);
  const safeRy = Math.max(1e-3, ry);
  let t = Math.atan2(ly / safeRy, lx / safeRx);
  // 2 Newton steps to minimize f(t) = 0.5 * ((rx cos t - lx)^2 + (ry sin t - ly)^2)
  for (let k = 0; k < 2; k++) {
    const ct = Math.cos(t);
    const st = Math.sin(t);
    const ex = safeRx * ct - lx;
    const ey = safeRy * st - ly;
    const d1 = -safeRx * st * ex + safeRy * ct * ey;
    const d2 =
      -safeRx * ct * ex +
      safeRx * safeRx * st * st -
      safeRy * st * ey +
      safeRy * safeRy * ct * ct;
    if (d2 > 1e-6) {
      t -= clamp(d1 / d2, -0.5, 0.5);
    }
  }
  const px = safeRx * Math.cos(t);
  const py = safeRy * Math.sin(t);
  return Math.hypot(lx - px, ly - py);
}

function evaluateEllipseError(
  pts: ReadonlyArray<Vec2>,
  cx: number,
  cy: number,
  rx: number,
  ry: number,
  rot: number
): { rms: number; max: number } {
  const cos = Math.cos(-rot);
  const sin = Math.sin(-rot);
  let sumSq = 0;
  let maxD = 0;
  for (let i = 0; i < pts.length; i++) {
    const dx = pts[i].x - cx;
    const dy = pts[i].y - cy;
    const lx = dx * cos - dy * sin;
    const ly = dx * sin + dy * cos;
    const d = pointToAlignedEllipseDist(lx, ly, rx, ry);
    sumSq += d * d;
    if (d > maxD) maxD = d;
  }
  return { rms: Math.sqrt(sumSq / Math.max(1, pts.length)), max: maxD };
}

function fitEllipseGeometric(
  pts: ReadonlyArray<Vec2>
): { cx: number; cy: number; rx: number; ry: number; rotation: number; rms: number; max: number } | null {
  const n = pts.length;
  if (n < 6) return null;

  let cx = 0;
  let cy = 0;
  for (let i = 0; i < n; i++) {
    cx += pts[i].x;
    cy += pts[i].y;
  }
  cx /= n;
  cy /= n;

  // PCA for initial orientation
  let sxx = 0;
  let sxy = 0;
  let syy = 0;
  for (let i = 0; i < n; i++) {
    const dx = pts[i].x - cx;
    const dy = pts[i].y - cy;
    sxx += dx * dx;
    sxy += dx * dy;
    syy += dy * dy;
  }
  let rot = 0.5 * Math.atan2(2 * sxy, sxx - syy);

  // Project onto PCA frame to estimate center & semi-axes
  const cos0 = Math.cos(-rot);
  const sin0 = Math.sin(-rot);
  let minU = Infinity;
  let maxU = -Infinity;
  let minV = Infinity;
  let maxV = -Infinity;
  for (let i = 0; i < n; i++) {
    const dx = pts[i].x - cx;
    const dy = pts[i].y - cy;
    const u = dx * cos0 - dy * sin0;
    const v = dx * sin0 + dy * cos0;
    if (u < minU) minU = u;
    if (u > maxU) maxU = u;
    if (v < minV) minV = v;
    if (v > maxV) maxV = v;
  }

  const du = (minU + maxU) * 0.5;
  const dv = (minV + maxV) * 0.5;
  const cRot = Math.cos(rot);
  const sRot = Math.sin(rot);
  cx += du * cRot - dv * sRot;
  cy += du * sRot + dv * cRot;
  let rx = Math.max(3, (maxU - minU) * 0.5);
  let ry = Math.max(3, (maxV - minV) * 0.5);

  let bestErr = evaluateEllipseError(pts, cx, cy, rx, ry, rot);
  const scaleRef = Math.max(rx, ry);

  // Coordinate-search refinement (deterministic, fast, handles partial gaps & hand wobble)
  let stepPos = scaleRef * 0.08;
  let stepRad = scaleRef * 0.08;
  let stepAng = 0.14;

  for (let round = 0; round < 6; round++) {
    // Refine rotation
    for (const dir of [-1, 1]) {
      const cand = rot + dir * stepAng;
      const err = evaluateEllipseError(pts, cx, cy, rx, ry, cand);
      if (err.rms < bestErr.rms) {
        rot = cand;
        bestErr = err;
      }
    }
    // Refine center X / Y
    for (const dir of [-1, 1]) {
      const cand = cx + dir * stepPos;
      const err = evaluateEllipseError(pts, cand, cy, rx, ry, rot);
      if (err.rms < bestErr.rms) {
        cx = cand;
        bestErr = err;
      }
    }
    for (const dir of [-1, 1]) {
      const cand = cy + dir * stepPos;
      const err = evaluateEllipseError(pts, cx, cand, rx, ry, rot);
      if (err.rms < bestErr.rms) {
        cy = cand;
        bestErr = err;
      }
    }
    // Refine rx / ry
    for (const dir of [-1, 1]) {
      const cand = Math.max(3, rx + dir * stepRad);
      const err = evaluateEllipseError(pts, cx, cy, cand, ry, rot);
      if (err.rms < bestErr.rms) {
        rx = cand;
        bestErr = err;
      }
    }
    for (const dir of [-1, 1]) {
      const cand = Math.max(3, ry + dir * stepRad);
      const err = evaluateEllipseError(pts, cx, cy, rx, cand, rot);
      if (err.rms < bestErr.rms) {
        ry = cand;
        bestErr = err;
      }
    }
    stepPos *= 0.5;
    stepRad *= 0.5;
    stepAng *= 0.5;
  }

  // Canonicalize rx >= ry
  if (ry > rx) {
    const tmp = rx;
    rx = ry;
    ry = tmp;
    rot += Math.PI * 0.5;
  }
  rot = normalizeHalfPiAngle(rot);

  // Gentle axis-alignment snap within 3.5 deg for nearly horizontal/vertical ellipses
  const snapDist = Math.abs(rot - snapAngleRad(rot, 90));
  if (snapDist < (3.5 * Math.PI) / 180) {
    const snappedRot = normalizeHalfPiAngle(snapAngleRad(rot, 90));
    const snappedErr = evaluateEllipseError(pts, cx, cy, rx, ry, snappedRot);
    if (snappedErr.rms <= bestErr.rms * 1.06 + 0.5) {
      rot = snappedRot;
      bestErr = snappedErr;
    }
  }

  return { cx, cy, rx, ry, rotation: rot, rms: bestErr.rms, max: bestErr.max };
}

function computeConvexHull(pts: ReadonlyArray<Vec2>): Vec2[] {
  if (pts.length <= 3) return pts.map((p) => ({ x: p.x, y: p.y }));
  const sorted = pts
    .map((p) => ({ x: p.x, y: p.y }))
    .sort((a, b) => (a.x !== b.x ? a.x - b.x : a.y - b.y));
  const cross = (o: Vec2, a: Vec2, b: Vec2) =>
    (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);

  const lower: Vec2[] = [];
  for (let i = 0; i < sorted.length; i++) {
    const p = sorted[i];
    while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) {
      lower.pop();
    }
    lower.push(p);
  }
  const upper: Vec2[] = [];
  for (let i = sorted.length - 1; i >= 0; i--) {
    const p = sorted[i];
    while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) {
      upper.pop();
    }
    upper.push(p);
  }
  lower.pop();
  upper.pop();
  return lower.concat(upper);
}

/**
 * Fits an infinite line (normal nx, ny and offset c: nx*x + ny*y = c) via orthogonal regression.
 */
function fitLineTLS(pts: ReadonlyArray<Vec2>): { nx: number; ny: number; c: number } | null {
  const n = pts.length;
  if (n < 2) return null;
  let mx = 0;
  let my = 0;
  for (let i = 0; i < n; i++) {
    mx += pts[i].x;
    my += pts[i].y;
  }
  mx /= n;
  my /= n;

  let sxx = 0;
  let sxy = 0;
  let syy = 0;
  for (let i = 0; i < n; i++) {
    const dx = pts[i].x - mx;
    const dy = pts[i].y - my;
    sxx += dx * dx;
    sxy += dx * dy;
    syy += dy * dy;
  }
  // Direction of largest variance is theta; normal is theta + pi/2
  const theta = 0.5 * Math.atan2(2 * sxy, sxx - syy);
  const nx = -Math.sin(theta);
  const ny = Math.cos(theta);
  const c = nx * mx + ny * my;
  return { nx, ny, c };
}

function intersectLines(
  l1: { nx: number; ny: number; c: number },
  l2: { nx: number; ny: number; c: number }
): Vec2 | null {
  const det = l1.nx * l2.ny - l1.ny * l2.nx;
  if (Math.abs(det) < 0.08) return null; // nearly parallel
  return {
    x: (l1.c * l2.ny - l1.ny * l2.c) / det,
    y: (l1.nx * l2.c - l1.c * l2.nx) / det,
  };
}

function evaluateTriangleFit(
  pts: ReadonlyArray<Vec2>,
  verts: [Vec2, Vec2, Vec2]
): { rms: number; max: number; edgeCounts: [number, number, number] } {
  let sumSq = 0;
  let maxD = 0;
  const edgeCounts: [number, number, number] = [0, 0, 0];
  for (let i = 0; i < pts.length; i++) {
    const p = pts[i];
    const d0 = pointToSegmentDistSq(p, verts[0], verts[1]);
    const d1 = pointToSegmentDistSq(p, verts[1], verts[2]);
    const d2 = pointToSegmentDistSq(p, verts[2], verts[0]);
    let best = d0;
    let bestIdx: 0 | 1 | 2 = 0;
    if (d1 < best) {
      best = d1;
      bestIdx = 1;
    }
    if (d2 < best) {
      best = d2;
      bestIdx = 2;
    }
    edgeCounts[bestIdx]++;
    sumSq += best;
    const d = Math.sqrt(best);
    if (d > maxD) maxD = d;
  }
  return {
    rms: Math.sqrt(sumSq / Math.max(1, pts.length)),
    max: maxD,
    edgeCounts,
  };
}

function fitTriangleClosed(
  pts: ReadonlyArray<Vec2>,
  diag: number
): { vertices: [Vec2, Vec2, Vec2]; rms: number; max: number; perimeter: number } | null {
  const n = pts.length;
  if (n < 9) return null;

  const triArea2 = (a: Vec2, b: Vec2, c: Vec2) =>
    Math.abs((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x));

  // Find maximum-area inscribed triangle over the closed loop (O(N^2) with advancing third pointer)
  let bestI = 0;
  let bestJ = Math.floor(n / 3);
  let bestK = Math.floor((2 * n) / 3);
  let maxArea2 = -1;

  for (let i = 0; i < n; i++) {
    let k = (i + 2) % n;
    for (let stepJ = 1; stepJ < n - 1; stepJ++) {
      const j = (i + stepJ) % n;
      if (k === j) k = (j + 1) % n;
      let curArea = triArea2(pts[i], pts[j], pts[k]);
      while (true) {
        const nextK = (k + 1) % n;
        if (nextK === i) break;
        const nextArea = triArea2(pts[i], pts[j], pts[nextK]);
        if (nextArea > curArea) {
          k = nextK;
          curArea = nextArea;
        } else {
          break;
        }
      }
      if (curArea > maxArea2) {
        maxArea2 = curArea;
        bestI = i;
        bestJ = j;
        bestK = k;
      }
    }
  }

  if (maxArea2 < 0.04 * diag * diag) return null;

  const indices = [bestI, bestJ, bestK].sort((a, b) => a - b);
  let vertices: [Vec2, Vec2, Vec2] = [
    { x: pts[indices[0]].x, y: pts[indices[0]].y },
    { x: pts[indices[1]].x, y: pts[indices[1]].y },
    { x: pts[indices[2]].x, y: pts[indices[2]].y },
  ];
  let bestEval = evaluateTriangleFit(pts, vertices);

  // Refine corners by fitting orthogonal lines to the middle 65% of each of the 3 edge chains
  const chains: Vec2[][] = [[], [], []];
  for (let edge = 0; edge < 3; edge++) {
    const startIdx = indices[edge];
    const endIdx = indices[(edge + 1) % 3];
    const span = (endIdx - startIdx + n) % n;
    const trim = Math.max(1, Math.floor(span * 0.18));
    for (let s = trim; s <= span - trim; s++) {
      chains[edge].push(pts[(startIdx + s) % n]);
    }
  }

  const l0 = fitLineTLS(chains[0]);
  const l1 = fitLineTLS(chains[1]);
  const l2 = fitLineTLS(chains[2]);
  if (l0 && l1 && l2) {
    const r0 = intersectLines(l2, l0);
    const r1 = intersectLines(l0, l1);
    const r2 = intersectLines(l1, l2);
    if (
      r0 &&
      r1 &&
      r2 &&
      dist(r0, vertices[0]) <= 0.22 * diag &&
      dist(r1, vertices[1]) <= 0.22 * diag &&
      dist(r2, vertices[2]) <= 0.22 * diag
    ) {
      const refined: [Vec2, Vec2, Vec2] = [r0, r1, r2];
      const refinedEval = evaluateTriangleFit(pts, refined);
      if (refinedEval.rms <= bestEval.rms * 1.02) {
        vertices = refined;
        bestEval = refinedEval;
      }
    }
  }

  const e0 = dist(vertices[0], vertices[1]);
  const e1 = dist(vertices[1], vertices[2]);
  const e2 = dist(vertices[2], vertices[0]);
  const minEdge = Math.min(e0, e1, e2);
  const minCount = Math.min(bestEval.edgeCounts[0], bestEval.edgeCounts[1], bestEval.edgeCounts[2]);
  if (minEdge < 0.15 * diag || minCount < Math.max(3, Math.floor(n * 0.08))) {
    return null;
  }

  return {
    vertices,
    rms: bestEval.rms,
    max: bestEval.max,
    perimeter: e0 + e1 + e2,
  };
}

export function getRectangleCorners(rect: QuickShapeRectangle): [Vec2, Vec2, Vec2, Vec2] {
  const cos = Math.cos(rect.rotation);
  const sin = Math.sin(rect.rotation);
  const hw = rect.width * 0.5;
  const hh = rect.height * 0.5;
  const ux = cos * hw;
  const uy = sin * hw;
  const vx = -sin * hh;
  const vy = cos * hh;
  return [
    { x: rect.center.x - ux - vx, y: rect.center.y - uy - vy },
    { x: rect.center.x + ux - vx, y: rect.center.y + uy - vy },
    { x: rect.center.x + ux + vx, y: rect.center.y + uy + vy },
    { x: rect.center.x - ux + vx, y: rect.center.y - uy + vy },
  ];
}

function evaluateRectAtAngle(
  pts: ReadonlyArray<Vec2>,
  angle: number,
  refineEdges: boolean
): {
  rect: QuickShapeRectangle;
  rms: number;
  max: number;
  sideCounts: [number, number, number, number];
  meanNormCornerDist: number;
} {
  const cos = Math.cos(-angle);
  const sin = Math.sin(-angle);
  const n = pts.length;
  const us = new Float64Array(n);
  const vs = new Float64Array(n);
  let minU = Infinity;
  let maxU = -Infinity;
  let minV = Infinity;
  let maxV = -Infinity;

  for (let i = 0; i < n; i++) {
    const u = pts[i].x * cos - pts[i].y * sin;
    const v = pts[i].x * sin + pts[i].y * cos;
    us[i] = u;
    vs[i] = v;
    if (u < minU) minU = u;
    if (u > maxU) maxU = u;
    if (v < minV) minV = v;
    if (v > maxV) maxV = v;
  }

  if (refineEdges && maxU - minU > 4 && maxV - minV > 4) {
    // Refine each of the 4 sides to the mean coordinate of points clearly belonging to that side
    let sumLeft = 0;
    let cntLeft = 0;
    let sumRight = 0;
    let cntRight = 0;
    let sumTop = 0;
    let cntTop = 0;
    let sumBot = 0;
    let cntBot = 0;
    const spanU = maxU - minU;
    const spanV = maxV - minV;

    for (let i = 0; i < n; i++) {
      const u = us[i];
      const v = vs[i];
      const dL = Math.abs(u - minU);
      const dR = Math.abs(maxU - u);
      const dT = Math.abs(v - minV);
      const dB = Math.abs(maxV - v);
      const m = Math.min(dL, dR, dT, dB);
      if (m === dL && v > minV + spanV * 0.1 && v < maxV - spanV * 0.1) {
        sumLeft += u;
        cntLeft++;
      } else if (m === dR && v > minV + spanV * 0.1 && v < maxV - spanV * 0.1) {
        sumRight += u;
        cntRight++;
      } else if (m === dT && u > minU + spanU * 0.1 && u < maxU - spanU * 0.1) {
        sumTop += v;
        cntTop++;
      } else if (m === dB && u > minU + spanU * 0.1 && u < maxU - spanU * 0.1) {
        sumBot += v;
        cntBot++;
      }
    }
    if (cntLeft >= 3) minU = sumLeft / cntLeft;
    if (cntRight >= 3) maxU = sumRight / cntRight;
    if (cntTop >= 3) minV = sumTop / cntTop;
    if (cntBot >= 3) maxV = sumBot / cntBot;
  }

  const width = Math.max(2, maxU - minU);
  const height = Math.max(2, maxV - minV);
  const cu = (minU + maxU) * 0.5;
  const cv = (minV + maxV) * 0.5;
  const hw = width * 0.5;
  const hh = height * 0.5;

  let sumSq = 0;
  let maxD = 0;
  const sideCounts: [number, number, number, number] = [0, 0, 0, 0];
  const minCornerNorm = [Infinity, Infinity, Infinity, Infinity];

  for (let i = 0; i < n; i++) {
    const du = us[i] - cu;
    const dv = vs[i] - cv;

    // Distance to rectangle boundary in local frame
    const dxOut = Math.abs(du) - hw;
    const dyOut = Math.abs(dv) - hh;
    let d: number;
    if (dxOut > 0 && dyOut > 0) {
      d = Math.hypot(dxOut, dyOut);
    } else if (dxOut > 0) {
      d = dxOut;
    } else if (dyOut > 0) {
      d = dyOut;
    } else {
      d = Math.min(-dxOut, -dyOut);
    }
    sumSq += d * d;
    if (d > maxD) maxD = d;

    // Side assignment
    const dL = Math.abs(us[i] - minU);
    const dR = Math.abs(maxU - us[i]);
    const dT = Math.abs(vs[i] - minV);
    const dB = Math.abs(maxV - vs[i]);
    const m = Math.min(dL, dR, dT, dB);
    if (m === dL) sideCounts[0]++;
    else if (m === dR) sideCounts[1]++;
    else if (m === dT) sideCounts[2]++;
    else sideCounts[3]++;

    // Normalized corner proximity in [-1, 1]^2 unit box coordinates
    const nu = du / Math.max(1e-3, hw);
    const nv = dv / Math.max(1e-3, hh);
    const c0 = Math.hypot(nu + 1, nv + 1);
    const c1 = Math.hypot(nu - 1, nv + 1);
    const c2 = Math.hypot(nu - 1, nv - 1);
    const c3 = Math.hypot(nu + 1, nv - 1);
    if (c0 < minCornerNorm[0]) minCornerNorm[0] = c0;
    if (c1 < minCornerNorm[1]) minCornerNorm[1] = c1;
    if (c2 < minCornerNorm[2]) minCornerNorm[2] = c2;
    if (c3 < minCornerNorm[3]) minCornerNorm[3] = c3;
  }

  const cRot = Math.cos(angle);
  const sRot = Math.sin(angle);
  const cx = cu * cRot - cv * sRot;
  const cy = cu * sRot + cv * cRot;

  return {
    rect: {
      kind: 'rectangle',
      center: { x: cx, y: cy },
      width,
      height,
      rotation: normalizeHalfPiAngle(angle),
    },
    rms: Math.sqrt(sumSq / Math.max(1, n)),
    max: maxD,
    sideCounts,
    meanNormCornerDist:
      (minCornerNorm[0] + minCornerNorm[1] + minCornerNorm[2] + minCornerNorm[3]) * 0.25,
  };
}

function fitRectangleClosed(
  pts: ReadonlyArray<Vec2>,
  diag: number
): {
  rect: QuickShapeRectangle;
  rms: number;
  max: number;
  perimeter: number;
  meanNormCornerDist: number;
} | null {
  const hull = computeConvexHull(pts);
  if (hull.length < 3) return null;

  const candidateAngles: number[] = [0];
  for (let i = 0; i < hull.length; i++) {
    const a = hull[i];
    const b = hull[(i + 1) % hull.length];
    if (distSq(a, b) > 1) {
      candidateAngles.push(normalizeHalfPiAngle(Math.atan2(b.y - a.y, b.x - a.x)));
    }
  }

  let best = evaluateRectAtAngle(pts, 0, false);
  for (let i = 1; i < candidateAngles.length; i++) {
    const res = evaluateRectAtAngle(pts, candidateAngles[i], false);
    if (res.rms < best.rms) {
      best = res;
    }
  }

  // Fine local angle search around best orientation (+/- 4 deg in 0.5 deg steps)
  const baseAngle = best.rect.rotation;
  best = evaluateRectAtAngle(pts, baseAngle, true);
  for (let deg = -4; deg <= 4; deg += 0.5) {
    if (deg === 0) continue;
    const cand = baseAngle + (deg * Math.PI) / 180;
    const res = evaluateRectAtAngle(pts, cand, true);
    if (res.rms < best.rms) {
      best = res;
    }
  }

  // Gentle auto-alignment within 4 deg to horizontal/vertical axes
  const snappedAxis = normalizeHalfPiAngle(snapAngleRad(best.rect.rotation, 90));
  if (Math.abs(best.rect.rotation - snappedAxis) < (4 * Math.PI) / 180) {
    const axisRes = evaluateRectAtAngle(pts, snappedAxis, true);
    if (axisRes.rms <= best.rms * 1.08 + 0.75) {
      best = axisRes;
    }
  }

  // Canonicalize rotation into (-pi/4, pi/4] so width is always the more-horizontal side
  let rect = best.rect;
  if (rect.rotation > Math.PI * 0.25) {
    rect = {
      kind: 'rectangle',
      center: rect.center,
      width: rect.height,
      height: rect.width,
      rotation: rect.rotation - Math.PI * 0.5,
    };
  } else if (rect.rotation <= -Math.PI * 0.25) {
    rect = {
      kind: 'rectangle',
      center: rect.center,
      width: rect.height,
      height: rect.width,
      rotation: rect.rotation + Math.PI * 0.5,
    };
  }

  const minSide = Math.min(rect.width, rect.height);
  const minCount = Math.min(
    best.sideCounts[0],
    best.sideCounts[1],
    best.sideCounts[2],
    best.sideCounts[3]
  );
  if (minSide < 0.1 * diag || minCount < Math.max(2, Math.floor(pts.length * 0.05))) {
    return null;
  }

  // Gentle square snap when sides are already within 8% of each other
  const ratio = minSide / Math.max(rect.width, rect.height);
  if (ratio >= 0.92) {
    const avgSide = (rect.width + rect.height) * 0.5;
    rect = { ...rect, width: avgSide, height: avgSide };
  }

  return {
    rect,
    rms: best.rms,
    max: best.max,
    perimeter: 2 * (rect.width + rect.height),
    meanNormCornerDist: best.meanNormCornerDist,
  };
}

/**
 * Computes the circumcircle and signed sweep of an arc passing from start -> mid -> end.
 */
export function computeArcCircle(
  start: Vec2,
  mid: Vec2,
  end: Vec2
): { cx: number; cy: number; radius: number; startAngle: number; sweep: number } | null {
  const ax = start.x;
  const ay = start.y;
  const bx = mid.x;
  const by = mid.y;
  const cx = end.x;
  const cy = end.y;

  const chordLen = Math.hypot(cx - ax, cy - ay);
  const d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by));
  if (Math.abs(d) < Math.max(1e-3, 1e-4 * chordLen * chordLen)) {
    return null;
  }

  const a2 = ax * ax + ay * ay;
  const b2 = bx * bx + by * by;
  const c2 = cx * cx + cy * cy;
  const ux = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / d;
  const uy = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / d;
  const radius = Math.hypot(ax - ux, ay - uy);

  if (!Number.isFinite(radius) || radius < 1 || radius > Math.max(20000, chordLen * 35)) {
    return null;
  }

  const startAngle = Math.atan2(ay - uy, ax - ux);
  const midAngle = Math.atan2(by - uy, bx - ux);
  const endAngle = Math.atan2(cy - uy, cx - ux);

  const ccwMid = mod2Pi(midAngle - startAngle);
  const ccwEnd = mod2Pi(endAngle - startAngle);

  const sweep = ccwMid < ccwEnd ? ccwEnd : ccwEnd - TWO_PI;
  return { cx: ux, cy: uy, radius, startAngle, sweep };
}

/**
 * Recognizes a freehand stroke as one of:
 * line, arc, circle, ellipse, triangle, or rectangle.
 * Returns null if the stroke is too short or does not cleanly match any of the 6 shapes.
 */
export function recognizeQuickShape(
  rawPoints: ReadonlyArray<Point>,
  holdToleranceDoc: number = 4
): QuickShapeRecognitionResult | null {
  if (!rawPoints || rawPoints.length < 2) return null;

  const trimmed = trimTrailingHoldJitter(rawPoints, Math.max(0.5, holdToleranceDoc));
  const totalLen = polylineLength(trimmed);
  if (totalLen < QUICK_SHAPE_MIN_STROKE_LENGTH_DOC) return null;

  const bounds = computeBounds(trimmed);
  if (bounds.diag < 18) return null;

  const resampled = resamplePolyline(trimmed, 64);
  const first = resampled[0];
  const last = resampled[resampled.length - 1];
  const endDist = dist(first, last);

  // Check for closure (direct or slight overshoot past start)
  let closedTrimStart = 0;
  let closedTrimEnd = resampled.length - 1;
  let minClosureDist = endDist;
  const n = resampled.length;
  const tailRange = Math.floor(n * 0.22);
  for (let i = 0; i <= tailRange; i++) {
    for (let j = n - 1 - tailRange; j < n; j++) {
      if (j - i < Math.floor(n * 0.65)) continue;
      const d = dist(resampled[i], resampled[j]);
      if (d < minClosureDist) {
        minClosureDist = d;
        closedTrimStart = i;
        closedTrimEnd = j;
      }
    }
  }

  const isClosed =
    (endDist <= Math.max(22, 0.34 * bounds.diag) && endDist <= 0.24 * totalLen) ||
    (minClosureDist <= Math.max(18, 0.22 * bounds.diag) &&
      minClosureDist <= 0.18 * totalLen &&
      Math.abs(computeCentroidWindingAngle(resampled.slice(closedTrimStart, closedTrimEnd + 1))) >=
        1.55 * Math.PI);

  // 1. Evaluate Line candidate (open stroke)
  let lineCandidate: { shape: QuickShapeLine; rmsNorm: number; maxNorm: number } | null = null;
  if (!isClosed && endDist >= 16) {
    const straightRatio = endDist / Math.max(1e-6, totalLen);
    if (straightRatio >= 0.88) {
      const dx = last.x - first.x;
      const dy = last.y - first.y;
      const lenSq = dx * dx + dy * dy;
      let sumSq = 0;
      let maxD = 0;
      let outOfRange = false;
      for (let i = 0; i < resampled.length; i++) {
        const p = resampled[i];
        const t = ((p.x - first.x) * dx + (p.y - first.y) * dy) / lenSq;
        if (t < -0.1 || t > 1.1) {
          outOfRange = true;
          break;
        }
        const d = pointToSegmentDist(p, first, last);
        sumSq += d * d;
        if (d > maxD) maxD = d;
      }
      if (!outOfRange) {
        const rmsNorm = Math.sqrt(sumSq / resampled.length) / endDist;
        const maxNorm = maxD / endDist;
        if (rmsNorm <= 0.055 && maxNorm <= 0.13) {
          let endPt = { x: last.x, y: last.y };
          // Subtle snap within 2 deg to pure horizontal/vertical for clean lines
          const angle = Math.atan2(dy, dx);
          const snappedAxis = snapAngleRad(angle, 90);
          if (Math.abs(angle - snappedAxis) < (2.0 * Math.PI) / 180) {
            endPt = {
              x: first.x + Math.cos(snappedAxis) * endDist,
              y: first.y + Math.sin(snappedAxis) * endDist,
            };
          }
          lineCandidate = {
            shape: { kind: 'line', start: { x: first.x, y: first.y }, end: endPt },
            rmsNorm,
            maxNorm,
          };
        }
      }
    }
  }

  // 2. Evaluate Arc candidate (open curved stroke)
  let arcCandidate: {
    shape: QuickShapeArc;
    rmsNorm: number;
    maxNorm: number;
    sagittaRatio: number;
  } | null = null;
  if (!isClosed) {
    const circ = fitCircleLeastSquares(resampled);
    if (circ && circ.radius <= totalLen * 12) {
      // Unwrap angles from start to end to check monotonicity (rejects S-curves)
      let netSweep = 0;
      let absSweep = 0;
      let prevA = Math.atan2(resampled[0].y - circ.cy, resampled[0].x - circ.cx);
      for (let i = 1; i < resampled.length; i++) {
        const a = Math.atan2(resampled[i].y - circ.cy, resampled[i].x - circ.cx);
        let da = a - prevA;
        while (da > Math.PI) da -= TWO_PI;
        while (da < -Math.PI) da += TWO_PI;
        netSweep += da;
        absSweep += Math.abs(da);
        prevA = a;
      }

      const absNetSweep = Math.abs(netSweep);
      const monotonicity = absSweep > 1e-4 ? absNetSweep / absSweep : 0;
      const startAngle = Math.atan2(first.y - circ.cy, first.x - circ.cx);
      const midAngle = startAngle + netSweep * 0.5;
      const arcStart: Vec2 = {
        x: circ.cx + Math.cos(startAngle) * circ.radius,
        y: circ.cy + Math.sin(startAngle) * circ.radius,
      };
      const arcMid: Vec2 = {
        x: circ.cx + Math.cos(midAngle) * circ.radius,
        y: circ.cy + Math.sin(midAngle) * circ.radius,
      };
      const arcEndAngle = startAngle + netSweep;
      const arcEnd: Vec2 = {
        x: circ.cx + Math.cos(arcEndAngle) * circ.radius,
        y: circ.cy + Math.sin(arcEndAngle) * circ.radius,
      };

      const chordLen = Math.max(1, dist(arcStart, arcEnd));
      const sagitta = pointToSegmentDist(arcMid, arcStart, arcEnd);
      const sagittaRatio = sagitta / chordLen;

      if (
        monotonicity >= 0.8 &&
        absNetSweep >= 0.32 &&
        absNetSweep <= 5.65 &&
        sagittaRatio >= 0.065
      ) {
        let sumSq = 0;
        let maxD = 0;
        for (let i = 0; i < resampled.length; i++) {
          const d = Math.abs(Math.hypot(resampled[i].x - circ.cx, resampled[i].y - circ.cy) - circ.radius);
          sumSq += d * d;
          if (d > maxD) maxD = d;
        }
        const rmsNorm = Math.sqrt(sumSq / resampled.length) / bounds.diag;
        const maxNorm = maxD / bounds.diag;
        const expectedArcLen = circ.radius * absNetSweep;
        const lenRatio = totalLen / Math.max(1, expectedArcLen);

        if (rmsNorm <= 0.085 && maxNorm <= 0.2 && lenRatio >= 0.78 && lenRatio <= 1.28) {
          arcCandidate = {
            shape: { kind: 'arc', start: arcStart, mid: arcMid, end: arcEnd },
            rmsNorm,
            maxNorm,
            sagittaRatio,
          };
        }
      }
    }
  }

  if (!isClosed) {
    if (lineCandidate && (!arcCandidate || arcCandidate.sagittaRatio < 0.085)) {
      return {
        shape: lineCandidate.shape,
        confidence: clamp(1 - lineCandidate.rmsNorm * 8, 0.2, 1),
        rmsNorm: lineCandidate.rmsNorm,
      };
    }
    if (arcCandidate) {
      return {
        shape: arcCandidate.shape,
        confidence: clamp(1 - arcCandidate.rmsNorm * 8, 0.2, 1),
        rmsNorm: arcCandidate.rmsNorm,
      };
    }
    if (lineCandidate) {
      return {
        shape: lineCandidate.shape,
        confidence: clamp(1 - lineCandidate.rmsNorm * 8, 0.2, 1),
        rmsNorm: lineCandidate.rmsNorm,
      };
    }
    return null;
  }

  // 3. Closed Shapes: Circle, Ellipse, Triangle, Rectangle
  const loopSource =
    closedTrimEnd - closedTrimStart >= Math.floor(n * 0.65)
      ? resampled.slice(closedTrimStart, closedTrimEnd + 1)
      : resampled;
  const loopPts = resamplePolyline(loopSource, 64);
  const loopBounds = computeBounds(loopPts);
  const loopDiag = Math.max(1, loopBounds.diag);
  const loopLen = polylineLength(loopPts) + dist(loopPts[0], loopPts[loopPts.length - 1]);
  const enclosedArea = shoelaceArea(loopPts);

  // Reject folded back-and-forth lines and figure-8 self-crossing scribbles
  const totalTurn = Math.abs(computeCentroidWindingAngle(loopPts));
  if (totalTurn < 1.3 * Math.PI || enclosedArea < 0.035 * loopDiag * loopDiag) {
    return null;
  }

  // Candidate A: Circle
  let circleCand: {
    shape: QuickShapeCircle;
    rmsNorm: number;
    maxNorm: number;
    score: number;
  } | null = null;
  const circleFit = fitCircleLeastSquares(loopPts);
  if (circleFit) {
    // Verify angular coverage across 12 bins
    const bins = new Uint8Array(12);
    let sumSq = 0;
    let maxD = 0;
    for (let i = 0; i < loopPts.length; i++) {
      const dx = loopPts[i].x - circleFit.cx;
      const dy = loopPts[i].y - circleFit.cy;
      const d = Math.abs(Math.hypot(dx, dy) - circleFit.radius);
      sumSq += d * d;
      if (d > maxD) maxD = d;
      const bin = Math.floor((mod2Pi(Math.atan2(dy, dx)) / TWO_PI) * 12) % 12;
      bins[bin] = 1;
    }
    let filledBins = 0;
    for (let b = 0; b < 12; b++) filledBins += bins[b];
    const rmsNorm = Math.sqrt(sumSq / loopPts.length) / loopDiag;
    const maxNorm = maxD / loopDiag;
    const perimRatio = loopLen / Math.max(1, TWO_PI * circleFit.radius);

    if (filledBins >= 10 && rmsNorm <= 0.095 && maxNorm <= 0.23 && perimRatio >= 0.78 && perimRatio <= 1.32) {
      const handleAngle = Math.atan2(last.y - circleFit.cy, last.x - circleFit.cx);
      circleCand = {
        shape: {
          kind: 'circle',
          center: { x: circleFit.cx, y: circleFit.cy },
          radius: circleFit.radius,
          handleAngle,
        },
        rmsNorm,
        maxNorm,
        score: rmsNorm * 0.72 + maxNorm * 0.28,
      };
    }
  }

  // Candidate B: Ellipse
  let ellipseCand: {
    shape: QuickShapeEllipse;
    rmsNorm: number;
    maxNorm: number;
    score: number;
    aspect: number;
  } | null = null;
  const ellFit = fitEllipseGeometric(loopPts);
  if (ellFit && ellFit.ry >= 4 && ellFit.rx >= 6) {
    const rmsNorm = ellFit.rms / loopDiag;
    const maxNorm = ellFit.max / loopDiag;
    // Ramanujan perimeter approximation
    const h = Math.pow(ellFit.rx - ellFit.ry, 2) / Math.pow(ellFit.rx + ellFit.ry, 2);
    const ellPerim = Math.PI * (ellFit.rx + ellFit.ry) * (1 + (3 * h) / (10 + Math.sqrt(4 - 3 * h)));
    const perimRatio = loopLen / Math.max(1, ellPerim);
    const aspect = ellFit.ry / ellFit.rx;

    if (rmsNorm <= 0.095 && maxNorm <= 0.23 && perimRatio >= 0.78 && perimRatio <= 1.34) {
      const cosR = Math.cos(-ellFit.rotation);
      const sinR = Math.sin(-ellFit.rotation);
      const ldx = (last.x - ellFit.cx) * cosR - (last.y - ellFit.cy) * sinR;
      const ldy = (last.x - ellFit.cx) * sinR + (last.y - ellFit.cy) * cosR;
      const handleAngle = Math.atan2(ldy / ellFit.ry, ldx / ellFit.rx);
      ellipseCand = {
        shape: {
          kind: 'ellipse',
          center: { x: ellFit.cx, y: ellFit.cy },
          rx: ellFit.rx,
          ry: ellFit.ry,
          rotation: ellFit.rotation,
          handleAngle,
        },
        rmsNorm,
        maxNorm,
        score: rmsNorm * 0.72 + maxNorm * 0.28,
        aspect,
      };
    }
  }

  // Candidate C: Triangle
  let triCand: {
    shape: QuickShapeTriangle;
    rmsNorm: number;
    maxNorm: number;
    score: number;
  } | null = null;
  const triFit = fitTriangleClosed(loopPts, loopDiag);
  if (triFit) {
    const rmsNorm = triFit.rms / loopDiag;
    const maxNorm = triFit.max / loopDiag;
    const perimRatio = loopLen / Math.max(1, triFit.perimeter);
    if (rmsNorm <= 0.095 && maxNorm <= 0.24 && perimRatio >= 0.78 && perimRatio <= 1.34) {
      triCand = {
        shape: {
          kind: 'triangle',
          vertices: triFit.vertices,
        },
        rmsNorm,
        maxNorm,
        score: rmsNorm * 0.72 + maxNorm * 0.28,
      };
    }
  }

  // Candidate D: Rectangle
  let rectCand: {
    shape: QuickShapeRectangle;
    rmsNorm: number;
    maxNorm: number;
    score: number;
    meanNormCornerDist: number;
  } | null = null;
  const rectFit = fitRectangleClosed(loopPts, loopDiag);
  if (rectFit) {
    const rmsNorm = rectFit.rms / loopDiag;
    const maxNorm = rectFit.max / loopDiag;
    const perimRatio = loopLen / Math.max(1, rectFit.perimeter);
    if (rmsNorm <= 0.095 && maxNorm <= 0.24 && perimRatio >= 0.78 && perimRatio <= 1.34) {
      // Corner-proximity invariant cleanly separates rectangles (meanNormCornerDist ~0.0-0.20)
      // from ellipses/circles (meanNormCornerDist ~0.414 in unit-square space)
      let cornerAdj = 0;
      if (rectFit.meanNormCornerDist > 0.28) {
        cornerAdj += (rectFit.meanNormCornerDist - 0.28) * 0.22;
      } else if (rectFit.meanNormCornerDist < 0.19) {
        cornerAdj -= (0.19 - rectFit.meanNormCornerDist) * 0.08;
      }
      rectCand = {
        shape: rectFit.rect,
        rmsNorm,
        maxNorm,
        score: Math.max(0, rmsNorm * 0.72 + maxNorm * 0.28 + cornerAdj),
        meanNormCornerDist: rectFit.meanNormCornerDist,
      };
    }
  }

  // Pick best curved candidate (prefer Circle over Ellipse when nearly circular)
  let bestCurved: {
    shape: QuickShapeCircle | QuickShapeEllipse;
    rmsNorm: number;
    score: number;
  } | null = null;
  if (circleCand && ellipseCand) {
    if (ellipseCand.aspect >= 0.85 && circleCand.rmsNorm <= ellipseCand.rmsNorm + 0.025) {
      bestCurved = circleCand;
    } else {
      bestCurved = ellipseCand;
    }
  } else if (circleCand) {
    bestCurved = circleCand;
  } else if (ellipseCand) {
    bestCurved = ellipseCand;
  }

  // Pick overall best closed shape
  const candidates: Array<{ shape: QuickShapeGeometry; rmsNorm: number; score: number }> = [];
  if (bestCurved) candidates.push(bestCurved);
  if (triCand) candidates.push(triCand);
  if (rectCand) candidates.push(rectCand);

  if (candidates.length === 0) return null;

  candidates.sort((a, b) => a.score - b.score);
  const winner = candidates[0];

  return {
    shape: winner.shape,
    confidence: clamp(1 - winner.rmsNorm * 7.5, 0.2, 1),
    rmsNorm: winner.rmsNorm,
  };
}

/**
 * Extracts a clean median-trimmed brush style profile from the original freehand stroke
 * so the snapped geometric shape preserves the artist's actual pressure & width feel.
 */
export function extractQuickShapeStrokeStyle(
  points: ReadonlyArray<Point>,
  fallbackSize: number
): QuickShapeStrokeStyle {
  if (!points || points.length === 0) {
    return { pressure: 0.5, width: Math.max(1, fallbackSize), tiltX: 0, tiltY: 0, twist: 0 };
  }

  // Use middle 70% of points to avoid soft pen-down/pen-up taper outliers
  const n = points.length;
  const start = n >= 6 ? Math.floor(n * 0.15) : 0;
  const end = n >= 6 ? Math.max(start + 1, Math.ceil(n * 0.85)) : n;
  const slice = points.slice(start, end);

  const widths = slice.map((p) => p.width).sort((a, b) => a - b);
  const pressures = slice.map((p) => p.pressure).sort((a, b) => a - b);
  const midIdx = Math.floor(widths.length * 0.55);

  let tiltX = 0;
  let tiltY = 0;
  let twist = 0;
  for (let i = 0; i < slice.length; i++) {
    tiltX += slice[i].tiltX ?? 0;
    tiltY += slice[i].tiltY ?? 0;
    twist += slice[i].twist ?? 0;
  }
  const inv = 1 / Math.max(1, slice.length);

  return {
    pressure: clamp(pressures[midIdx] ?? 0.5, 0.05, 1.0),
    width: Math.max(0.5, widths[midIdx] ?? fallbackSize),
    tiltX: tiltX * inv,
    tiltY: tiltY * inv,
    twist: twist * inv,
  };
}

function makeStrokePoint(
  x: number,
  y: number,
  style: QuickShapeStrokeStyle,
  timestamp: number,
  isCorner: boolean = false
): Point {
  return {
    x,
    y,
    pressure: style.pressure,
    width: style.width,
    tiltX: style.tiltX,
    tiltY: style.tiltY,
    twist: style.twist,
    timestamp,
    isCorner,
  };
}

/**
 * Samples a straight segment with tight corner brackets so centripetal Catmull-Rom splines
 * stay razor-sharp at polygon corners with zero loop overshoot.
 */
function appendStraightSegment(
  out: Point[],
  a: Vec2,
  b: Vec2,
  style: QuickShapeStrokeStyle,
  stepPx: number,
  includeStart: boolean
): void {
  const segLen = dist(a, b);
  const baseTs = out.length * 4;
  if (includeStart) {
    out.push(makeStrokePoint(a.x, a.y, style, baseTs, true));
  }
  if (segLen < 1e-4) return;

  const ux = (b.x - a.x) / segLen;
  const uy = (b.y - a.y) / segLen;

  // Tight bracket just after start corner
  if (segLen > 2.5) {
    out.push(makeStrokePoint(a.x + ux * 0.6, a.y + uy * 0.6, style, out.length * 4, false));
  }

  const steps = Math.max(2, Math.ceil(segLen / Math.max(2, stepPx)));
  for (let i = 1; i < steps; i++) {
    const t = i / steps;
    const d = t * segLen;
    if (d <= 0.8 || d >= segLen - 0.8) continue;
    out.push(makeStrokePoint(a.x + ux * d, a.y + uy * d, style, out.length * 4, false));
  }

  // Tight bracket just before end corner
  if (segLen > 2.5) {
    out.push(makeStrokePoint(b.x - ux * 0.6, b.y - uy * 0.6, style, out.length * 4, false));
  }
  out.push(makeStrokePoint(b.x, b.y, style, out.length * 4, true));
}

/**
 * Generates dense, perfectly smooth brush `Point[]` along any QuickShape geometry
 * ready for `renderCompleteStroke` (raster, natural paint, ribbon, dual brush, vector, mask).
 */
export function sampleQuickShapePoints(
  shape: QuickShapeGeometry,
  style: QuickShapeStrokeStyle
): Point[] {
  const stepPx = clamp(style.width * 0.45, 2.5, 8);
  const out: Point[] = [];

  switch (shape.kind) {
    case 'line': {
      appendStraightSegment(out, shape.start, shape.end, style, stepPx, true);
      return out;
    }

    case 'arc': {
      const circle = computeArcCircle(shape.start, shape.mid, shape.end);
      if (!circle) {
        appendStraightSegment(out, shape.start, shape.end, style, stepPx, true);
        return out;
      }
      const arcLen = Math.abs(circle.sweep) * circle.radius;
      const steps = clamp(Math.ceil(arcLen / stepPx), 16, 360);
      for (let i = 0; i <= steps; i++) {
        const t = i / steps;
        const a = circle.startAngle + circle.sweep * t;
        out.push(
          makeStrokePoint(
            circle.cx + Math.cos(a) * circle.radius,
            circle.cy + Math.sin(a) * circle.radius,
            style,
            i * 4,
            i === 0 || i === steps
          )
        );
      }
      return out;
    }

    case 'circle': {
      const r = Math.max(1, shape.radius);
      const circum = TWO_PI * r;
      const steps = clamp(Math.ceil(circum / stepPx), 36, 480);
      const startA = shape.handleAngle;
      for (let i = 0; i <= steps; i++) {
        const a = startA + (TWO_PI * i) / steps;
        out.push(
          makeStrokePoint(
            shape.center.x + Math.cos(a) * r,
            shape.center.y + Math.sin(a) * r,
            style,
            i * 4,
            false
          )
        );
      }
      return out;
    }

    case 'ellipse': {
      const rx = Math.max(1, shape.rx);
      const ry = Math.max(1, shape.ry);
      const h = Math.pow(rx - ry, 2) / Math.pow(rx + ry, 2);
      const perim = Math.PI * (rx + ry) * (1 + (3 * h) / (10 + Math.sqrt(4 - 3 * h)));
      const steps = clamp(Math.ceil(perim / stepPx), 40, 520);
      const cosR = Math.cos(shape.rotation);
      const sinR = Math.sin(shape.rotation);
      const startA = shape.handleAngle;
      for (let i = 0; i <= steps; i++) {
        const a = startA + (TWO_PI * i) / steps;
        const lx = Math.cos(a) * rx;
        const ly = Math.sin(a) * ry;
        out.push(
          makeStrokePoint(
            shape.center.x + lx * cosR - ly * sinR,
            shape.center.y + lx * sinR + ly * cosR,
            style,
            i * 4,
            false
          )
        );
      }
      return out;
    }

    case 'triangle': {
      const [v0, v1, v2] = shape.vertices;
      appendStraightSegment(out, v0, v1, style, stepPx, true);
      appendStraightSegment(out, v1, v2, style, stepPx, false);
      appendStraightSegment(out, v2, v0, style, stepPx, false);
      return out;
    }

    case 'rectangle': {
      const [c0, c1, c2, c3] = getRectangleCorners(shape);
      appendStraightSegment(out, c0, c1, style, stepPx, true);
      appendStraightSegment(out, c1, c2, style, stepPx, false);
      appendStraightSegment(out, c2, c3, style, stepPx, false);
      appendStraightSegment(out, c3, c0, style, stepPx, false);
      return out;
    }
  }
}

export function computeQuickShapeBounds(shape: QuickShapeGeometry): {
  minX: number;
  minY: number;
  maxX: number;
  maxY: number;
} {
  switch (shape.kind) {
    case 'line':
      return {
        minX: Math.min(shape.start.x, shape.end.x),
        minY: Math.min(shape.start.y, shape.end.y),
        maxX: Math.max(shape.start.x, shape.end.x),
        maxY: Math.max(shape.start.y, shape.end.y),
      };
    case 'arc': {
      const circle = computeArcCircle(shape.start, shape.mid, shape.end);
      if (!circle) {
        return {
          minX: Math.min(shape.start.x, shape.mid.x, shape.end.x),
          minY: Math.min(shape.start.y, shape.mid.y, shape.end.y),
          maxX: Math.max(shape.start.x, shape.mid.x, shape.end.x),
          maxY: Math.max(shape.start.y, shape.mid.y, shape.end.y),
        };
      }
      let minX = Math.min(shape.start.x, shape.mid.x, shape.end.x);
      let minY = Math.min(shape.start.y, shape.mid.y, shape.end.y);
      let maxX = Math.max(shape.start.x, shape.mid.x, shape.end.x);
      let maxY = Math.max(shape.start.y, shape.mid.y, shape.end.y);
      const samples = 24;
      for (let i = 1; i < samples; i++) {
        const a = circle.startAngle + (circle.sweep * i) / samples;
        const x = circle.cx + Math.cos(a) * circle.radius;
        const y = circle.cy + Math.sin(a) * circle.radius;
        if (x < minX) minX = x;
        if (y < minY) minY = y;
        if (x > maxX) maxX = x;
        if (y > maxY) maxY = y;
      }
      return { minX, minY, maxX, maxY };
    }
    case 'circle':
      return {
        minX: shape.center.x - shape.radius,
        minY: shape.center.y - shape.radius,
        maxX: shape.center.x + shape.radius,
        maxY: shape.center.y + shape.radius,
      };
    case 'ellipse': {
      const cos = Math.cos(shape.rotation);
      const sin = Math.sin(shape.rotation);
      const ex = Math.hypot(shape.rx * cos, shape.ry * sin);
      const ey = Math.hypot(shape.rx * sin, shape.ry * cos);
      return {
        minX: shape.center.x - ex,
        minY: shape.center.y - ey,
        maxX: shape.center.x + ex,
        maxY: shape.center.y + ey,
      };
    }
    case 'triangle': {
      const [v0, v1, v2] = shape.vertices;
      return {
        minX: Math.min(v0.x, v1.x, v2.x),
        minY: Math.min(v0.y, v1.y, v2.y),
        maxX: Math.max(v0.x, v1.x, v2.x),
        maxY: Math.max(v0.y, v1.y, v2.y),
      };
    }
    case 'rectangle': {
      const [c0, c1, c2, c3] = getRectangleCorners(shape);
      return {
        minX: Math.min(c0.x, c1.x, c2.x, c3.x),
        minY: Math.min(c0.y, c1.y, c2.y, c3.y),
        maxX: Math.max(c0.x, c1.x, c2.x, c3.x),
        maxY: Math.max(c0.y, c1.y, c2.y, c3.y),
      };
    }
  }
}

export function getQuickShapeLabel(kind: QuickShapeKind): string {
  switch (kind) {
    case 'line':
      return 'Line';
    case 'arc':
      return 'Arc';
    case 'circle':
      return 'Circle';
    case 'ellipse':
      return 'Ellipse';
    case 'triangle':
      return 'Triangle';
    case 'rectangle':
      return 'Rectangle';
  }
}

export function getQuickShapeHandles(
  shape: QuickShapeGeometry,
  activeHandleId: string
): QuickShapeHandle[] {
  switch (shape.kind) {
    case 'line':
      return [
        { id: 'start', x: shape.start.x, y: shape.start.y, kind: 'endpoint', active: activeHandleId === 'start' },
        { id: 'end', x: shape.end.x, y: shape.end.y, kind: 'endpoint', active: activeHandleId === 'end' },
      ];
    case 'arc':
      return [
        { id: 'start', x: shape.start.x, y: shape.start.y, kind: 'endpoint', active: activeHandleId === 'start' },
        { id: 'mid', x: shape.mid.x, y: shape.mid.y, kind: 'mid', active: activeHandleId === 'mid' },
        { id: 'end', x: shape.end.x, y: shape.end.y, kind: 'endpoint', active: activeHandleId === 'end' },
      ];
    case 'circle': {
      const rx = shape.center.x + Math.cos(shape.handleAngle) * shape.radius;
      const ry = shape.center.y + Math.sin(shape.handleAngle) * shape.radius;
      return [
        { id: 'center', x: shape.center.x, y: shape.center.y, kind: 'center', active: activeHandleId === 'center' },
        { id: 'rim', x: rx, y: ry, kind: 'rim', active: activeHandleId === 'rim' },
      ];
    }
    case 'ellipse': {
      const cos = Math.cos(shape.rotation);
      const sin = Math.sin(shape.rotation);
      const ux = cos * shape.rx;
      const uy = sin * shape.rx;
      const vx = -sin * shape.ry;
      const vy = cos * shape.ry;
      const lx = Math.cos(shape.handleAngle) * shape.rx;
      const ly = Math.sin(shape.handleAngle) * shape.ry;
      const px = shape.center.x + lx * cos - ly * sin;
      const py = shape.center.y + lx * sin + ly * cos;
      return [
        { id: 'axis-pos-x', x: shape.center.x + ux, y: shape.center.y + uy, kind: 'axis', active: false },
        { id: 'axis-neg-x', x: shape.center.x - ux, y: shape.center.y - uy, kind: 'axis', active: false },
        { id: 'axis-pos-y', x: shape.center.x + vx, y: shape.center.y + vy, kind: 'axis', active: false },
        { id: 'axis-neg-y', x: shape.center.x - vx, y: shape.center.y - vy, kind: 'axis', active: false },
        { id: 'rim', x: px, y: py, kind: 'rim', active: activeHandleId === 'rim' },
      ];
    }
    case 'triangle':
      return shape.vertices.map((v, i) => ({
        id: `corner-${i}`,
        x: v.x,
        y: v.y,
        kind: 'corner' as const,
        active: activeHandleId === `corner-${i}`,
      }));
    case 'rectangle':
      return getRectangleCorners(shape).map((c, i) => ({
        id: `corner-${i}`,
        x: c.x,
        y: c.y,
        kind: 'corner' as const,
        active: activeHandleId === `corner-${i}`,
      }));
  }
}

export function buildQuickShapePreview(session: QuickShapeSession): QuickShapePreviewState {
  const shape = session.currentShape;
  const handles = getQuickShapeHandles(shape, session.activeHandleId);
  const activeHandle = handles.find((h) => h.active) ?? handles[handles.length - 1];

  let svgPath = '';
  let readout = '';
  let hint = '';
  let guideLine: { x1: number; y1: number; x2: number; y2: number } | undefined;
  let centerMarker: Vec2 | undefined;

  switch (shape.kind) {
    case 'line': {
      svgPath = `M ${shape.start.x} ${shape.start.y} L ${shape.end.x} ${shape.end.y}`;
      const len = Math.round(dist(shape.start, shape.end));
      const deg = Math.round((Math.atan2(shape.end.y - shape.start.y, shape.end.x - shape.start.x) * 180) / Math.PI);
      readout = `${len}px · ${deg}°`;
      hint = 'Shift: 15° · Alt: Move';
      break;
    }
    case 'arc': {
      const circle = computeArcCircle(shape.start, shape.mid, shape.end);
      if (circle) {
        const largeArc = Math.abs(circle.sweep) > Math.PI ? 1 : 0;
        const sweepFlag = circle.sweep >= 0 ? 1 : 0;
        svgPath = `M ${shape.start.x} ${shape.start.y} A ${circle.radius} ${circle.radius} 0 ${largeArc} ${sweepFlag} ${shape.end.x} ${shape.end.y}`;
        readout = `${Math.round((Math.abs(circle.sweep) * 180) / Math.PI)}° · R ${Math.round(circle.radius)}px`;
        centerMarker = { x: circle.cx, y: circle.cy };
      } else {
        svgPath = `M ${shape.start.x} ${shape.start.y} L ${shape.end.x} ${shape.end.y}`;
        readout = `${Math.round(dist(shape.start, shape.end))}px`;
      }
      guideLine = { x1: shape.start.x, y1: shape.start.y, x2: shape.end.x, y2: shape.end.y };
      hint = 'Alt: Bend · Shift: 15°';
      break;
    }
    case 'circle': {
      const r = Math.max(1, shape.radius);
      const { x: cx, y: cy } = shape.center;
      svgPath = `M ${cx - r} ${cy} A ${r} ${r} 0 1 0 ${cx + r} ${cy} A ${r} ${r} 0 1 0 ${cx - r} ${cy} Z`;
      const rim = handles.find((h) => h.id === 'rim');
      if (rim) {
        guideLine = { x1: cx, y1: cy, x2: rim.x, y2: rim.y };
      }
      centerMarker = shape.center;
      readout = `Ø ${Math.round(r * 2)}px`;
      hint = 'Alt: Move';
      break;
    }
    case 'ellipse': {
      const rx = Math.max(1, shape.rx);
      const ry = Math.max(1, shape.ry);
      const cos = Math.cos(shape.rotation);
      const sin = Math.sin(shape.rotation);
      const deg = (shape.rotation * 180) / Math.PI;
      const p1x = shape.center.x - rx * cos;
      const p1y = shape.center.y - rx * sin;
      const p2x = shape.center.x + rx * cos;
      const p2y = shape.center.y + rx * sin;
      svgPath = `M ${p1x} ${p1y} A ${rx} ${ry} ${deg} 1 0 ${p2x} ${p2y} A ${rx} ${ry} ${deg} 1 0 ${p1x} ${p1y} Z`;
      centerMarker = shape.center;
      readout = `${Math.round(rx * 2)} × ${Math.round(ry * 2)}px`;
      hint = 'Shift: Circle · Alt: Stretch';
      break;
    }
    case 'triangle': {
      const [v0, v1, v2] = shape.vertices;
      svgPath = `M ${v0.x} ${v0.y} L ${v1.x} ${v1.y} L ${v2.x} ${v2.y} Z`;
      const perim = Math.round(dist(v0, v1) + dist(v1, v2) + dist(v2, v0));
      readout = `P ${perim}px`;
      hint = 'Shift: Snap · Alt: Scale/Rotate';
      break;
    }
    case 'rectangle': {
      const [c0, c1, c2, c3] = getRectangleCorners(shape);
      svgPath = `M ${c0.x} ${c0.y} L ${c1.x} ${c1.y} L ${c2.x} ${c2.y} L ${c3.x} ${c3.y} Z`;
      centerMarker = shape.center;
      readout = `${Math.round(shape.width)} × ${Math.round(shape.height)}px`;
      hint = 'Shift: Square · Alt: Rotate';
      break;
    }
  }

  return {
    shape,
    label: getQuickShapeLabel(shape.kind),
    readout,
    hint,
    svgPath,
    guideLine,
    centerMarker,
    handles,
    anchorPos: activeHandle ? { x: activeHandle.x, y: activeHandle.y } : session.snapPenPos,
    activeHandleId: session.activeHandleId,
    snappedAtMs: session.snappedAtMs,
  };
}

/**
 * Creates a live interactive QuickShape session immediately upon hold-snap.
 */
export function createQuickShapeSession(
  shape: QuickShapeGeometry,
  snapPenPos: Vec2,
  style: QuickShapeStrokeStyle,
  nowMs: number = performance.now()
): QuickShapeSession {
  let activeHandleId = 'end';
  let activeCornerIndex = 0;
  let initialArcBulgeRatio = 0;

  switch (shape.kind) {
    case 'line':
      activeHandleId = 'end';
      break;
    case 'arc': {
      activeHandleId = 'end';
      const dx = shape.end.x - shape.start.x;
      const dy = shape.end.y - shape.start.y;
      const chordLen = Math.max(1e-4, Math.hypot(dx, dy));
      const nx = -dy / chordLen;
      const ny = dx / chordLen;
      const mx = shape.mid.x - (shape.start.x + shape.end.x) * 0.5;
      const my = shape.mid.y - (shape.start.y + shape.end.y) * 0.5;
      initialArcBulgeRatio = (mx * nx + my * ny) / chordLen;
      break;
    }
    case 'circle':
    case 'ellipse':
      activeHandleId = 'rim';
      break;
    case 'triangle': {
      let bestDist = Infinity;
      for (let i = 0; i < 3; i++) {
        const d = distSq(shape.vertices[i], snapPenPos);
        if (d < bestDist) {
          bestDist = d;
          activeCornerIndex = i;
        }
      }
      activeHandleId = `corner-${activeCornerIndex}`;
      break;
    }
    case 'rectangle': {
      const corners = getRectangleCorners(shape);
      let bestDist = Infinity;
      for (let i = 0; i < 4; i++) {
        const d = distSq(corners[i], snapPenPos);
        if (d < bestDist) {
          bestDist = d;
          activeCornerIndex = i;
        }
      }
      activeHandleId = `corner-${activeCornerIndex}`;
      break;
    }
  }

  return {
    initialShape: shape,
    currentShape: shape,
    snapPenPos: { x: snapPenPos.x, y: snapPenPos.y },
    activeHandleId,
    activeCornerIndex,
    initialArcBulgeRatio,
    hasExitedDeadzone: false,
    style,
    snappedAtMs: nowMs,
  };
}

/**
 * Updates the active QuickShape geometry while the artist drags the pen before releasing it.
 * Uses a tiny screen-space deadzone to prevent unintentional jumps on lift/jitter,
 * and supports direct handle/corner dragging + Shift/Alt modifiers.
 */
export function updateQuickShapeFromDrag(
  session: QuickShapeSession,
  penDocPos: Vec2,
  modifiers: { shiftKey: boolean; altKey: boolean },
  zoom: number = 1.0
): QuickShapeGeometry {
  const dx = penDocPos.x - session.snapPenPos.x;
  const dy = penDocPos.y - session.snapPenPos.y;
  const deadzoneDoc = QUICK_SHAPE_DRAG_DEADZONE_SCREEN_PX / Math.max(0.1, zoom);

  if (!session.hasExitedDeadzone) {
    if (Math.hypot(dx, dy) < deadzoneDoc && !modifiers.shiftKey) {
      session.currentShape = session.initialShape;
      return session.currentShape;
    }
    if (Math.hypot(dx, dy) >= deadzoneDoc) {
      session.hasExitedDeadzone = true;
    }
  }

  const init = session.initialShape;

  switch (init.kind) {
    case 'line': {
      if (modifiers.altKey) {
        session.activeHandleId = 'end';
        session.currentShape = {
          kind: 'line',
          start: { x: init.start.x + dx, y: init.start.y + dy },
          end: { x: init.end.x + dx, y: init.end.y + dy },
        };
      } else {
        session.activeHandleId = 'end';
        let endX = init.end.x + dx;
        let endY = init.end.y + dy;
        if (modifiers.shiftKey) {
          const vx = endX - init.start.x;
          const vy = endY - init.start.y;
          const len = Math.hypot(vx, vy);
          if (len > 1) {
            const ang = snapAngleRad(Math.atan2(vy, vx), 15);
            endX = init.start.x + Math.cos(ang) * len;
            endY = init.start.y + Math.sin(ang) * len;
          }
        }
        session.currentShape = {
          kind: 'line',
          start: init.start,
          end: { x: endX, y: endY },
        };
      }
      return session.currentShape;
    }

    case 'arc': {
      if (modifiers.altKey) {
        // Alt bends the arc by dragging the curvature midpoint handle directly
        session.activeHandleId = 'mid';
        const curMidX = init.mid.x + dx;
        const curMidY = init.mid.y + dy;
        let mid: Vec2 = { x: curMidX, y: curMidY };
        if (modifiers.shiftKey) {
          // Snap to clean semicircle on the side the user dragged toward
          const cdx = init.end.x - init.start.x;
          const cdy = init.end.y - init.start.y;
          const cLen = Math.max(1, Math.hypot(cdx, cdy));
          const nx = -cdy / cLen;
          const ny = cdx / cLen;
          const side =
            (curMidX - (init.start.x + init.end.x) * 0.5) * nx +
              (curMidY - (init.start.y + init.end.y) * 0.5) * ny >=
            0
              ? 1
              : -1;
          mid = {
            x: (init.start.x + init.end.x) * 0.5 + nx * (cLen * 0.5 * side),
            y: (init.start.y + init.end.y) * 0.5 + ny * (cLen * 0.5 * side),
          };
        }
        session.currentShape = {
          kind: 'arc',
          start: init.start,
          mid,
          end: init.end,
        };
      } else {
        // Default: drag endpoint while preserving relative arc curvature bulge
        session.activeHandleId = 'end';
        let endX = init.end.x + dx;
        let endY = init.end.y + dy;
        if (modifiers.shiftKey) {
          const vx = endX - init.start.x;
          const vy = endY - init.start.y;
          const len = Math.hypot(vx, vy);
          if (len > 1) {
            const ang = snapAngleRad(Math.atan2(vy, vx), 15);
            endX = init.start.x + Math.cos(ang) * len;
            endY = init.start.y + Math.sin(ang) * len;
          }
        }
        const cdx = endX - init.start.x;
        const cdy = endY - init.start.y;
        const cLen = Math.max(1e-4, Math.hypot(cdx, cdy));
        const nx = -cdy / cLen;
        const ny = cdx / cLen;
        const mid: Vec2 = {
          x: (init.start.x + endX) * 0.5 + nx * (cLen * session.initialArcBulgeRatio),
          y: (init.start.y + endY) * 0.5 + ny * (cLen * session.initialArcBulgeRatio),
        };
        session.currentShape = {
          kind: 'arc',
          start: init.start,
          mid,
          end: { x: endX, y: endY },
        };
      }
      return session.currentShape;
    }

    case 'circle': {
      if (modifiers.altKey) {
        session.activeHandleId = 'center';
        session.currentShape = {
          kind: 'circle',
          center: { x: init.center.x + dx, y: init.center.y + dy },
          radius: init.radius,
          handleAngle: init.handleAngle,
        };
      } else {
        session.activeHandleId = 'rim';
        const initRimX = init.center.x + Math.cos(init.handleAngle) * init.radius;
        const initRimY = init.center.y + Math.sin(init.handleAngle) * init.radius;
        const targetX = initRimX + dx;
        const targetY = initRimY + dy;
        let radius = Math.max(4, Math.hypot(targetX - init.center.x, targetY - init.center.y));
        if (modifiers.shiftKey) {
          radius = Math.max(5, Math.round(radius / 5) * 5);
        }
        const handleAngle = Math.atan2(targetY - init.center.y, targetX - init.center.x);
        session.currentShape = {
          kind: 'circle',
          center: init.center,
          radius,
          handleAngle,
        };
      }
      return session.currentShape;
    }

    case 'ellipse': {
      session.activeHandleId = 'rim';
      const cosR = Math.cos(init.rotation);
      const sinR = Math.sin(init.rotation);
      const initLx = Math.cos(init.handleAngle) * init.rx;
      const initLy = Math.sin(init.handleAngle) * init.ry;
      const initRimX = init.center.x + initLx * cosR - initLy * sinR;
      const initRimY = init.center.y + initLx * sinR + initLy * cosR;
      const targetX = initRimX + dx;
      const targetY = initRimY + dy;

      if (modifiers.altKey) {
        // Alt stretches rx / ry independently in the ellipse's local frame
        const relX = targetX - init.center.x;
        const relY = targetY - init.center.y;
        const locX = relX * cosR + relY * sinR;
        const locY = -relX * sinR + relY * cosR;
        const initCosH = Math.abs(Math.cos(init.handleAngle));
        const initSinH = Math.abs(Math.sin(init.handleAngle));
        const newRx =
          initCosH > 0.25 ? Math.max(4, Math.abs(locX) / initCosH) : Math.max(4, init.rx + Math.abs(locX) - Math.abs(initLx));
        const newRy =
          initSinH > 0.25 ? Math.max(4, Math.abs(locY) / initSinH) : Math.max(4, init.ry + Math.abs(locY) - Math.abs(initLy));
        session.currentShape = {
          kind: 'ellipse',
          center: init.center,
          rx: newRx,
          ry: newRy,
          rotation: init.rotation,
          handleAngle: Math.atan2(locY / newRy, locX / newRx),
        };
      } else {
        const initVecR = Math.max(4, Math.hypot(initRimX - init.center.x, initRimY - init.center.y));
        const curVecR = Math.max(4, Math.hypot(targetX - init.center.x, targetY - init.center.y));
        const scale = curVecR / initVecR;
        const initAng = Math.atan2(initRimY - init.center.y, initRimX - init.center.x);
        const curAng = Math.atan2(targetY - init.center.y, targetX - init.center.x);
        let rotDelta = curAng - initAng;
        while (rotDelta > Math.PI) rotDelta -= TWO_PI;
        while (rotDelta < -Math.PI) rotDelta += TWO_PI;

        let rx = Math.max(4, init.rx * scale);
        let ry = Math.max(4, init.ry * scale);
        let rotation = normalizeHalfPiAngle(init.rotation + rotDelta);

        if (modifiers.shiftKey) {
          // Shift snaps ellipse to a perfect circle + 15 deg rotation
          const avgR = (rx + ry) * 0.5;
          rx = avgR;
          ry = avgR;
          rotation = normalizeHalfPiAngle(snapAngleRad(rotation, 15));
        }

        session.currentShape = {
          kind: 'ellipse',
          center: init.center,
          rx,
          ry,
          rotation,
          handleAngle: init.handleAngle,
        };
      }
      return session.currentShape;
    }

    case 'triangle': {
      const k = session.activeCornerIndex;
      session.activeHandleId = `corner-${k}`;
      if (modifiers.altKey) {
        // Alt uniformly scales & rotates the entire triangle around its centroid
        const cx = (init.vertices[0].x + init.vertices[1].x + init.vertices[2].x) / 3;
        const cy = (init.vertices[0].y + init.vertices[1].y + init.vertices[2].y) / 3;
        const initCorner = init.vertices[k];
        const targetX = initCorner.x + dx;
        const targetY = initCorner.y + dy;
        const r0 = Math.max(4, Math.hypot(initCorner.x - cx, initCorner.y - cy));
        const r1 = Math.max(4, Math.hypot(targetX - cx, targetY - cy));
        const scale = r1 / r0;
        let rotDelta = Math.atan2(targetY - cy, targetX - cx) - Math.atan2(initCorner.y - cy, initCorner.x - cx);
        if (modifiers.shiftKey) {
          rotDelta = snapAngleRad(rotDelta, 15);
        }
        const cos = Math.cos(rotDelta);
        const sin = Math.sin(rotDelta);
        const nextVerts = init.vertices.map((v) => {
          const rx = (v.x - cx) * scale;
          const ry = (v.y - cy) * scale;
          return { x: cx + rx * cos - ry * sin, y: cy + rx * sin + ry * cos };
        }) as [Vec2, Vec2, Vec2];
        session.currentShape = { kind: 'triangle', vertices: nextVerts };
      } else {
        // Default: drag the active corner handle directly!
        const nextVerts: [Vec2, Vec2, Vec2] = [
          { ...init.vertices[0] },
          { ...init.vertices[1] },
          { ...init.vertices[2] },
        ];
        const targetX = init.vertices[k].x + dx;
        const targetY = init.vertices[k].y + dy;

        if (modifiers.shiftKey) {
          // Shift snaps active corner to form a clean symmetric isosceles / equilateral apex over the opposite base
          const a = init.vertices[(k + 1) % 3];
          const b = init.vertices[(k + 2) % 3];
          const midX = (a.x + b.x) * 0.5;
          const midY = (a.y + b.y) * 0.5;
          const bdx = b.x - a.x;
          const bdy = b.y - a.y;
          const baseLen = Math.max(1, Math.hypot(bdx, bdy));
          const nx = -bdy / baseLen;
          const ny = bdx / baseLen;
          const proj = (targetX - midX) * nx + (targetY - midY) * ny;
          const sign = proj >= 0 ? 1 : -1;
          const eqHeight = baseLen * (Math.sqrt(3) * 0.5);
          const height =
            Math.abs(Math.abs(proj) - eqHeight) < baseLen * 0.25 ? eqHeight : Math.max(4, Math.abs(proj));
          nextVerts[k] = {
            x: midX + nx * height * sign,
            y: midY + ny * height * sign,
          };
        } else {
          nextVerts[k] = { x: targetX, y: targetY };
        }
        session.currentShape = { kind: 'triangle', vertices: nextVerts };
      }
      return session.currentShape;
    }

    case 'rectangle': {
      const k = session.activeCornerIndex;
      session.activeHandleId = `corner-${k}`;
      const initCorners = getRectangleCorners(init);
      const initCorner = initCorners[k];
      const oppCorner = initCorners[(k + 2) % 4];
      const targetX = initCorner.x + dx;
      const targetY = initCorner.y + dy;

      if (modifiers.altKey) {
        // Alt rotates & uniformly scales the rectangle around its center
        const cx = init.center.x;
        const cy = init.center.y;
        const r0 = Math.max(4, Math.hypot(initCorner.x - cx, initCorner.y - cy));
        const r1 = Math.max(4, Math.hypot(targetX - cx, targetY - cy));
        const scale = r1 / r0;
        let rotDelta = Math.atan2(targetY - cy, targetX - cx) - Math.atan2(initCorner.y - cy, initCorner.x - cx);
        let nextRot = normalizeHalfPiAngle(init.rotation + rotDelta);
        if (modifiers.shiftKey) {
          nextRot = normalizeHalfPiAngle(snapAngleRad(nextRot, 15));
        }
        let nextW = Math.max(4, init.width * scale);
        let nextH = Math.max(4, init.height * scale);
        if (modifiers.shiftKey) {
          const s = (nextW + nextH) * 0.5;
          nextW = s;
          nextH = s;
        }
        session.currentShape = {
          kind: 'rectangle',
          center: init.center,
          width: nextW,
          height: nextH,
          rotation: nextRot,
        };
      } else {
        // Default: drag corner handle k with opposite corner anchored (preserves crisp 90 deg angles)
        const cos = Math.cos(init.rotation);
        const sin = Math.sin(init.rotation);
        const vx = targetX - oppCorner.x;
        const vy = targetY - oppCorner.y;
        let projU = vx * cos + vy * sin;
        let projV = -vx * sin + vy * cos;

        if (modifiers.shiftKey) {
          const side = Math.max(4, Math.max(Math.abs(projU), Math.abs(projV)));
          projU = (projU >= 0 ? 1 : -1) * side;
          projV = (projV >= 0 ? 1 : -1) * side;
        }

        const nextW = Math.max(4, Math.abs(projU));
        const nextH = Math.max(4, Math.abs(projV));
        const signedU = (projU >= 0 ? 1 : -1) * nextW;
        const signedV = (projV >= 0 ? 1 : -1) * nextH;

        const nextCenter: Vec2 = {
          x: oppCorner.x + (cos * signedU - sin * signedV) * 0.5,
          y: oppCorner.y + (sin * signedU + cos * signedV) * 0.5,
        };

        session.currentShape = {
          kind: 'rectangle',
          center: nextCenter,
          width: nextW,
          height: nextH,
          rotation: init.rotation,
        };
      }
      return session.currentShape;
    }
  }
}

// ============================================================================
// Subtle Soft-Click Synthesized Tactile Audio Feedback
// ============================================================================

let sharedAudioCtx: AudioContext | null = null;

/**
 * Plays a gentle, refined tactile "soft click" (~20ms damped acoustic transient)
 * using Web Audio API when QuickShape snaps a freehand stroke into a smooth shape.
 * Fails silently in headless/test environments or if audio autoplay is restricted.
 */
export function playQuickShapeSnapClick(): void {
  try {
    if (typeof navigator !== 'undefined' && typeof navigator.vibrate === 'function') {
      navigator.vibrate(8);
    }
  } catch {
    // Ignore vibration errors on unsupported platforms
  }

  try {
    if (typeof window === 'undefined') return;
    const AudioCtxCtor =
      window.AudioContext ||
      (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
    if (!AudioCtxCtor) return;

    if (!sharedAudioCtx || sharedAudioCtx.state === 'closed') {
      sharedAudioCtx = new AudioCtxCtor();
    }
    const ctx = sharedAudioCtx;
    if (ctx.state === 'suspended') {
      void ctx.resume().catch(() => {});
    }

    const now = ctx.currentTime;

    // Soft resonant wood/ceramic-like click: brief pitched sine transient + gentle lowpass
    const osc = ctx.createOscillator();
    const filter = ctx.createBiquadFilter();
    const gain = ctx.createGain();

    osc.type = 'triangle';
    osc.frequency.setValueAtTime(1150, now);
    osc.frequency.exponentialRampToValueAtTime(380, now + 0.018);

    filter.type = 'lowpass';
    filter.frequency.setValueAtTime(2200, now);
    filter.Q.setValueAtTime(1.2, now);

    gain.gain.setValueAtTime(0.0001, now);
    gain.gain.linearRampToValueAtTime(0.075, now + 0.002);
    gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.024);

    osc.connect(filter);
    filter.connect(gain);
    gain.connect(ctx.destination);

    osc.start(now);
    osc.stop(now + 0.028);
  } catch {
    // Silently ignore if Web Audio is unavailable or blocked
  }
}