// HowTo — animated stick-figure form demos + cues per exercise
// Stick figure built from line segments; animation = interpolating joint angles
// Each animation has 2 keyframes (top/bottom) and we lerp between them on a 1.4s loop.

const STICK = {
  // Each pose: head[cx,cy,r], spine[x1,y1,x2,y2], shoulders[x,y], hips[x,y],
  // arms: [shoulder, elbow, hand] both sides, legs: [hip, knee, foot]
  // Coordinate system: 200×280 viewBox, ground at y=260
  poses: {
    // SQUAT
    squat_top: {
      head: [100, 60, 12], hips: [100, 150],
      shoulderL: [88, 82], shoulderR: [112, 82],
      elbowL: [78, 105], elbowR: [122, 105],
      handL: [70, 130], handR: [130, 130],
      kneeL: [88, 200], kneeR: [112, 200],
      footL: [82, 258], footR: [118, 258],
      barbell: { x1: 60, y1: 78, x2: 140, y2: 78, plates: true }
    },
    squat_bot: {
      head: [100, 90, 12], hips: [100, 165],
      shoulderL: [88, 110], shoulderR: [112, 110],
      elbowL: [76, 130], elbowR: [124, 130],
      handL: [68, 150], handR: [132, 150],
      kneeL: [76, 200], kneeR: [124, 200],
      footL: [76, 258], footR: [124, 258],
      barbell: { x1: 60, y1: 106, x2: 140, y2: 106, plates: true }
    },
    // DEADLIFT
    dl_top: {
      head: [100, 50, 12], hips: [100, 140],
      shoulderL: [90, 72], shoulderR: [110, 72],
      elbowL: [86, 110], elbowR: [114, 110],
      handL: [82, 150], handR: [118, 150],
      kneeL: [88, 200], kneeR: [112, 200],
      footL: [82, 258], footR: [118, 258],
      barbell: { x1: 60, y1: 150, x2: 140, y2: 150, plates: true }
    },
    dl_bot: {
      head: [120, 90, 12], hips: [110, 150],
      shoulderL: [105, 105], shoulderR: [115, 100],
      elbowL: [98, 175], elbowR: [108, 175],
      handL: [92, 220], handR: [108, 220],
      kneeL: [88, 215], kneeR: [112, 215],
      footL: [82, 258], footR: [118, 258],
      barbell: { x1: 50, y1: 230, x2: 140, y2: 230, plates: true }
    },
    // BENCH (lying horizontal, head left, body right)
    // TOP = arms locked out (bar high above chest = small y on screen since arm goes UP from shoulder)
    // Actually: lying on back with body horizontal, "up" from chest = upward on screen = smaller y
    bench_top: {
      head: [40, 170, 12], hips: [120, 175],
      shoulderL: [60, 170], shoulderR: [60, 170],
      elbowL: [60, 140], elbowR: [60, 140],
      handL: [60, 110], handR: [60, 110],
      kneeL: [150, 175], kneeR: [150, 175],
      footL: [180, 230], footR: [180, 230],
      barbell: { x1: 30, y1: 110, x2: 90, y2: 110, plates: true },
      bench: true
    },
    bench_bot: {
      head: [40, 170, 12], hips: [120, 175],
      shoulderL: [60, 170], shoulderR: [60, 170],
      elbowL: [80, 155], elbowR: [80, 155],
      handL: [60, 165], handR: [60, 165],
      kneeL: [150, 175], kneeR: [150, 175],
      footL: [180, 230], footR: [180, 230],
      barbell: { x1: 30, y1: 165, x2: 90, y2: 165, plates: true },
      bench: true
    },
    // OHP
    ohp_top: {
      head: [100, 50, 12], hips: [100, 145],
      shoulderL: [88, 75], shoulderR: [112, 75],
      elbowL: [80, 50], elbowR: [120, 50],
      handL: [80, 22], handR: [120, 22],
      kneeL: [92, 200], kneeR: [108, 200],
      footL: [88, 258], footR: [112, 258],
      barbell: { x1: 60, y1: 22, x2: 140, y2: 22, plates: true }
    },
    ohp_bot: {
      head: [100, 50, 12], hips: [100, 145],
      shoulderL: [88, 75], shoulderR: [112, 75],
      elbowL: [78, 100], elbowR: [122, 100],
      handL: [82, 70], handR: [118, 70],
      kneeL: [92, 200], kneeR: [108, 200],
      footL: [88, 258], footR: [112, 258],
      barbell: { x1: 60, y1: 70, x2: 140, y2: 70, plates: true }
    },
    // ROW (bent over) — "down" = arms extended hanging, "up" = bar pulled to chest
    row_down: {
      head: [70, 90, 12], hips: [120, 130],
      shoulderL: [85, 110], shoulderR: [95, 105],
      elbowL: [90, 145], elbowR: [100, 140],
      handL: [95, 180], handR: [105, 175],
      kneeL: [128, 200], kneeR: [142, 200],
      footL: [128, 258], footR: [142, 258],
      barbell: { x1: 55, y1: 180, x2: 145, y2: 180, plates: true }
    },
    row_up: {
      head: [70, 90, 12], hips: [120, 130],
      shoulderL: [85, 110], shoulderR: [95, 105],
      elbowL: [70, 130], elbowR: [80, 125],
      handL: [95, 130], handR: [105, 125],
      kneeL: [128, 200], kneeR: [142, 200],
      footL: [128, 258], footR: [142, 258],
      barbell: { x1: 55, y1: 130, x2: 145, y2: 130, plates: true }
    },
    // CURL
    curl_down: {
      head: [100, 50, 12], hips: [100, 145],
      shoulderL: [88, 75], shoulderR: [112, 75],
      elbowL: [86, 130], elbowR: [114, 130],
      handL: [86, 175], handR: [114, 175],
      kneeL: [92, 200], kneeR: [108, 200],
      footL: [88, 258], footR: [112, 258],
      barbell: { x1: 56, y1: 175, x2: 144, y2: 175, plates: true }
    },
    curl_up: {
      head: [100, 50, 12], hips: [100, 145],
      shoulderL: [88, 75], shoulderR: [112, 75],
      elbowL: [86, 130], elbowR: [114, 130],
      handL: [94, 88], handR: [106, 88],
      kneeL: [92, 200], kneeR: [108, 200],
      footL: [88, 258], footR: [112, 258],
      barbell: { x1: 60, y1: 88, x2: 140, y2: 88, plates: true }
    },
    // PULL-UP
    pullup_down: {
      head: [100, 70, 12], hips: [100, 165],
      shoulderL: [88, 92], shoulderR: [112, 92],
      elbowL: [82, 60], elbowR: [118, 60],
      handL: [82, 22], handR: [118, 22],
      kneeL: [92, 220], kneeR: [108, 220],
      footL: [88, 258], footR: [112, 258],
      bar: { x1: 50, y1: 22, x2: 150, y2: 22 }
    },
    pullup_up: {
      head: [100, 35, 12], hips: [100, 130],
      shoulderL: [88, 56], shoulderR: [112, 56],
      elbowL: [82, 38], elbowR: [118, 38],
      handL: [82, 22], handR: [118, 22],
      kneeL: [92, 200], kneeR: [108, 200],
      footL: [88, 250], footR: [112, 250],
      bar: { x1: 50, y1: 22, x2: 150, y2: 22 }
    },
    // DIP
    dip_top: {
      head: [100, 60, 12], hips: [100, 145],
      shoulderL: [88, 82], shoulderR: [112, 82],
      elbowL: [70, 100], elbowR: [130, 100],
      handL: [60, 130], handR: [140, 130],
      kneeL: [92, 200], kneeR: [108, 200],
      footL: [88, 250], footR: [112, 250],
      bar: { x1: 50, y1: 130, x2: 150, y2: 130, dual: true }
    },
    dip_bot: {
      head: [100, 100, 12], hips: [100, 175],
      shoulderL: [88, 122], shoulderR: [112, 122],
      elbowL: [60, 130], elbowR: [140, 130],
      handL: [60, 130], handR: [140, 130],
      kneeL: [92, 220], kneeR: [108, 220],
      footL: [88, 256], footR: [112, 256],
      bar: { x1: 50, y1: 130, x2: 150, y2: 130, dual: true }
    },
    // PUSH-UP (lying horizontally)
    pushup_top: {
      head: [40, 130, 12], hips: [120, 145],
      shoulderL: [55, 135], shoulderR: [55, 135],
      elbowL: [55, 165], elbowR: [55, 165],
      handL: [55, 195], handR: [55, 195],
      kneeL: [170, 145], kneeR: [170, 145],
      footL: [200, 145], footR: [200, 145]
    },
    pushup_bot: {
      head: [40, 175, 12], hips: [120, 185],
      shoulderL: [55, 180], shoulderR: [55, 180],
      elbowL: [40, 195], elbowR: [40, 195],
      handL: [55, 195], handR: [55, 195],
      kneeL: [170, 185], kneeR: [170, 185],
      footL: [200, 185], footR: [200, 185]
    },
    // LEG RAISE (hanging)
    legraise_down: {
      head: [100, 50, 12], hips: [100, 165],
      shoulderL: [88, 72], shoulderR: [112, 72],
      elbowL: [82, 45], elbowR: [118, 45],
      handL: [82, 22], handR: [118, 22],
      kneeL: [92, 220], kneeR: [108, 220],
      footL: [88, 258], footR: [112, 258],
      bar: { x1: 50, y1: 22, x2: 150, y2: 22 }
    },
    legraise_up: {
      head: [100, 50, 12], hips: [100, 165],
      shoulderL: [88, 72], shoulderR: [112, 72],
      elbowL: [82, 45], elbowR: [118, 45],
      handL: [82, 22], handR: [118, 22],
      kneeL: [120, 130], kneeR: [80, 130],
      footL: [150, 110], footR: [50, 110],
      bar: { x1: 50, y1: 22, x2: 150, y2: 22 }
    },
    // LATERAL RAISE — arms out to sides (T-shape)
    lateral_down: {
      head: [100, 50, 12], hips: [100, 145],
      shoulderL: [88, 75], shoulderR: [112, 75],
      elbowL: [76, 105], elbowR: [124, 105],
      handL: [70, 135], handR: [130, 135],
      kneeL: [92, 200], kneeR: [108, 200],
      footL: [88, 258], footR: [112, 258]
    },
    lateral_up: {
      head: [100, 50, 12], hips: [100, 145],
      shoulderL: [88, 75], shoulderR: [112, 75],
      elbowL: [55, 75], elbowR: [145, 75],
      handL: [25, 70], handR: [175, 70],
      kneeL: [92, 200], kneeR: [108, 200],
      footL: [88, 258], footR: [112, 258]
    },
    // REAR FLY — bent over, arms out to sides
    rearfly_down: {
      head: [80, 100, 12], hips: [120, 130],
      shoulderL: [92, 118], shoulderR: [108, 118],
      elbowL: [95, 145], elbowR: [105, 145],
      handL: [98, 175], handR: [102, 175],
      kneeL: [128, 200], kneeR: [142, 200],
      footL: [128, 258], footR: [142, 258]
    },
    rearfly_up: {
      head: [80, 100, 12], hips: [120, 130],
      shoulderL: [92, 118], shoulderR: [108, 118],
      elbowL: [60, 105], elbowR: [140, 105],
      handL: [35, 100], handR: [165, 100],
      kneeL: [128, 200], kneeR: [142, 200],
      footL: [128, 258], footR: [142, 258]
    },
    // RDL — stops at mid-shin, NOT floor
    rdl_top: {
      head: [100, 50, 12], hips: [100, 140],
      shoulderL: [90, 72], shoulderR: [110, 72],
      elbowL: [86, 110], elbowR: [114, 110],
      handL: [82, 150], handR: [118, 150],
      kneeL: [88, 200], kneeR: [112, 200],
      footL: [82, 258], footR: [118, 258],
      barbell: { x1: 60, y1: 150, x2: 140, y2: 150, plates: true }
    },
    rdl_bot: {
      head: [115, 100, 12], hips: [105, 145],
      shoulderL: [100, 115], shoulderR: [110, 110],
      elbowL: [98, 155], elbowR: [108, 150],
      handL: [96, 195], handR: [108, 190],
      kneeL: [88, 205], kneeR: [112, 205],
      footL: [82, 258], footR: [118, 258],
      barbell: { x1: 50, y1: 195, x2: 140, y2: 195, plates: true }
    },
    // HIP THRUST — sitting back on bench, hips up/down
    hipthrust_down: {
      head: [40, 130, 12], hips: [110, 200],
      shoulderL: [55, 140], shoulderR: [55, 140],
      elbowL: [70, 155], elbowR: [70, 155],
      handL: [85, 165], handR: [85, 165],
      kneeL: [150, 195], kneeR: [150, 195],
      footL: [180, 258], footR: [180, 258],
      barbell: { x1: 75, y1: 200, x2: 155, y2: 200, plates: true },
      bench: true
    },
    hipthrust_up: {
      head: [40, 135, 12], hips: [115, 145],
      shoulderL: [55, 140], shoulderR: [55, 140],
      elbowL: [70, 145], elbowR: [70, 145],
      handL: [85, 145], handR: [85, 145],
      kneeL: [150, 145], kneeR: [150, 145],
      footL: [180, 258], footR: [180, 258],
      barbell: { x1: 75, y1: 140, x2: 155, y2: 140, plates: true },
      bench: true
    },
    // GOBLET SQUAT — hold weight at chest
    goblet_top: {
      head: [100, 60, 12], hips: [100, 150],
      shoulderL: [88, 82], shoulderR: [112, 82],
      elbowL: [85, 110], elbowR: [115, 110],
      handL: [95, 105], handR: [105, 105],
      kneeL: [88, 200], kneeR: [112, 200],
      footL: [82, 258], footR: [118, 258],
      dumbbell: { cx: 100, cy: 100 }
    },
    goblet_bot: {
      head: [100, 90, 12], hips: [100, 165],
      shoulderL: [88, 110], shoulderR: [112, 110],
      elbowL: [85, 138], elbowR: [115, 138],
      handL: [95, 135], handR: [105, 135],
      kneeL: [76, 200], kneeR: [124, 200],
      footL: [76, 258], footR: [124, 258],
      dumbbell: { cx: 100, cy: 130 }
    },
    // PLANK — hold position
    plank_pose: {
      head: [40, 145, 11], hips: [120, 155],
      shoulderL: [55, 150], shoulderR: [55, 150],
      elbowL: [55, 175], elbowR: [55, 175],
      handL: [70, 195], handR: [70, 195],
      kneeL: [170, 175], kneeR: [170, 175],
      footL: [200, 195], footR: [200, 195]
    },
    // GLUTE BRIDGE — like hip thrust, no bench
    bridge_down: {
      head: [40, 200, 11], hips: [110, 215],
      shoulderL: [55, 210], shoulderR: [55, 210],
      elbowL: [55, 235], elbowR: [55, 235],
      handL: [55, 255], handR: [55, 255],
      kneeL: [150, 215], kneeR: [150, 215],
      footL: [180, 258], footR: [180, 258]
    },
    bridge_up: {
      head: [40, 205, 11], hips: [115, 165],
      shoulderL: [55, 210], shoulderR: [55, 210],
      elbowL: [55, 235], elbowR: [55, 235],
      handL: [55, 255], handR: [55, 255],
      kneeL: [150, 165], kneeR: [150, 165],
      footL: [180, 258], footR: [180, 258]
    },
    // SHRUG — shoulders go up
    shrug_down: {
      head: [100, 50, 12], hips: [100, 145],
      shoulderL: [88, 80], shoulderR: [112, 80],
      elbowL: [82, 130], elbowR: [118, 130],
      handL: [78, 180], handR: [122, 180],
      kneeL: [92, 200], kneeR: [108, 200],
      footL: [88, 258], footR: [112, 258],
      dumbbell: { cx: 78, cy: 185 },
      dumbbell2: { cx: 122, cy: 185 }
    },
    shrug_up: {
      head: [100, 50, 12], hips: [100, 145],
      shoulderL: [88, 65], shoulderR: [112, 65],
      elbowL: [82, 115], elbowR: [118, 115],
      handL: [78, 165], handR: [122, 165],
      kneeL: [92, 200], kneeR: [108, 200],
      footL: [88, 258], footR: [112, 258],
      dumbbell: { cx: 78, cy: 170 },
      dumbbell2: { cx: 122, cy: 170 }
    },
    // CALF RAISE — heels up/down
    calf_down: {
      head: [100, 50, 12], hips: [100, 145],
      shoulderL: [88, 75], shoulderR: [112, 75],
      elbowL: [78, 130], elbowR: [122, 130],
      handL: [70, 165], handR: [130, 165],
      kneeL: [92, 200], kneeR: [108, 200],
      footL: [88, 258], footR: [112, 258]
    },
    calf_up: {
      head: [100, 35, 12], hips: [100, 130],
      shoulderL: [88, 60], shoulderR: [112, 60],
      elbowL: [78, 115], elbowR: [122, 115],
      handL: [70, 150], handR: [130, 150],
      kneeL: [92, 185], kneeR: [108, 185],
      footL: [88, 248], footR: [112, 248]
    },
    // SIT-UP — lying, curl up
    situp_down: {
      head: [40, 175, 12], hips: [120, 200],
      shoulderL: [60, 185], shoulderR: [60, 185],
      elbowL: [50, 200], elbowR: [50, 200],
      handL: [45, 215], handR: [45, 215],
      kneeL: [150, 175], kneeR: [150, 175],
      footL: [170, 230], footR: [170, 230]
    },
    situp_up: {
      head: [110, 130, 12], hips: [120, 200],
      shoulderL: [115, 155], shoulderR: [115, 155],
      elbowL: [120, 175], elbowR: [120, 175],
      handL: [130, 165], handR: [130, 165],
      kneeL: [150, 175], kneeR: [150, 175],
      footL: [170, 230], footR: [170, 230]
    },
    // RUSSIAN TWIST — seated, rotate side to side
    russian_left: {
      head: [85, 110, 12], hips: [110, 200],
      shoulderL: [95, 130], shoulderR: [105, 135],
      elbowL: [80, 155], elbowR: [90, 160],
      handL: [70, 175], handR: [78, 180],
      kneeL: [145, 180], kneeR: [155, 185],
      footL: [175, 220], footR: [185, 225]
    },
    russian_right: {
      head: [115, 110, 12], hips: [110, 200],
      shoulderL: [105, 130], shoulderR: [115, 135],
      elbowL: [120, 155], elbowR: [130, 160],
      handL: [130, 175], handR: [142, 180],
      kneeL: [145, 180], kneeR: [155, 185],
      footL: [175, 220], footR: [185, 225]
    },
    // SUPERMAN — face down, arms+legs lift
    superman_down: {
      head: [40, 195, 11], hips: [120, 200],
      shoulderL: [55, 198], shoulderR: [55, 198],
      elbowL: [35, 198], elbowR: [35, 198],
      handL: [15, 198], handR: [15, 198],
      kneeL: [170, 200], kneeR: [170, 200],
      footL: [195, 200], footR: [195, 200]
    },
    superman_up: {
      head: [40, 175, 11], hips: [120, 195],
      shoulderL: [55, 180], shoulderR: [55, 180],
      elbowL: [35, 170], elbowR: [35, 170],
      handL: [15, 160], handR: [15, 160],
      kneeL: [170, 195], kneeR: [170, 195],
      footL: [195, 175], footR: [195, 175]
    },
    // L-SIT — hold position, legs out parallel
    lsit_pose: {
      head: [100, 80, 12], hips: [100, 175],
      shoulderL: [88, 100], shoulderR: [112, 100],
      elbowL: [82, 130], elbowR: [118, 130],
      handL: [82, 165], handR: [118, 165],
      kneeL: [150, 175], kneeR: [150, 175],
      footL: [200, 175], footR: [200, 175]
    },
    // SKULLCRUSHER — lying, hinge at elbow only
    skull_top: {
      head: [40, 170, 12], hips: [120, 175],
      shoulderL: [60, 170], shoulderR: [60, 170],
      elbowL: [60, 140], elbowR: [60, 140],
      handL: [60, 110], handR: [60, 110],
      kneeL: [150, 175], kneeR: [150, 175],
      footL: [180, 230], footR: [180, 230],
      bench: true,
      dumbbell: { cx: 60, cy: 110 }
    },
    skull_bot: {
      head: [40, 170, 12], hips: [120, 175],
      shoulderL: [60, 170], shoulderR: [60, 170],
      elbowL: [60, 140], elbowR: [60, 140],
      handL: [40, 165], handR: [40, 165],
      kneeL: [150, 175], kneeR: [150, 175],
      footL: [180, 230], footR: [180, 230],
      bench: true,
      dumbbell: { cx: 40, cy: 165 }
    },
    // GENERIC LUNGE
    lunge_top: {
      head: [100, 50, 12], hips: [100, 145],
      shoulderL: [88, 75], shoulderR: [112, 75],
      elbowL: [78, 130], elbowR: [122, 130],
      handL: [70, 165], handR: [130, 165],
      kneeL: [88, 200], kneeR: [112, 200],
      footL: [82, 258], footR: [118, 258]
    },
    lunge_bot: {
      head: [100, 80, 12], hips: [100, 165],
      shoulderL: [88, 105], shoulderR: [112, 105],
      elbowL: [78, 145], elbowR: [122, 145],
      handL: [70, 175], handR: [130, 175],
      kneeL: [60, 230], kneeR: [140, 200],
      footL: [60, 258], footR: [160, 258]
    }
  }
};

// Default mappings (cover any exercise via fallback to category)
const POSE_MAP = {
  bb_squat: ["squat_top", "squat_bot"],
  bb_front_squat: ["squat_top", "squat_bot"],
  db_goblet: ["goblet_top", "goblet_bot"],
  bw_squat: ["squat_top", "squat_bot"],
  bb_deadlift: ["dl_top", "dl_bot"],
  bb_rdl: ["rdl_top", "rdl_bot"],
  db_rdl: ["rdl_top", "rdl_bot"],
  bb_bench: ["bench_top", "bench_bot"],
  db_press: ["bench_top", "bench_bot"],
  bb_ohp: ["ohp_bot", "ohp_top"],
  db_ohp: ["ohp_bot", "ohp_top"],
  db_lateral: ["lateral_down", "lateral_up"],
  db_rear_fly: ["rearfly_down", "rearfly_up"],
  bb_row: ["row_down", "row_up"],
  db_row: ["row_down", "row_up"],
  bb_curl: ["curl_down", "curl_up"],
  db_curl: ["curl_down", "curl_up"],
  db_hammer: ["curl_down", "curl_up"],
  db_skullcrush: ["skull_top", "skull_bot"],
  db_shrug: ["shrug_down", "shrug_up"],
  db_calf: ["calf_down", "calf_up"],
  bb_hipthrust: ["hipthrust_down", "hipthrust_up"],
  pu_pullup: ["pullup_down", "pullup_up"],
  pu_chinup: ["pullup_down", "pullup_up"],
  pu_dip: ["dip_top", "dip_bot"],
  pu_legraise: ["legraise_down", "legraise_up"],
  pu_kneeraise: ["legraise_down", "legraise_up"],
  pu_lsit: ["lsit_pose", "lsit_pose"],
  bw_pushup: ["pushup_top", "pushup_bot"],
  bw_diamond: ["pushup_top", "pushup_bot"],
  bw_plank: ["plank_pose", "plank_pose"],
  bw_glutebridge: ["bridge_down", "bridge_up"],
  bw_calf: ["calf_down", "calf_up"],
  bw_situp: ["situp_down", "situp_up"],
  bw_russian: ["russian_left", "russian_right"],
  bw_superman: ["superman_down", "superman_up"],
  bb_lunge: ["lunge_top", "lunge_bot"],
  db_lunge: ["lunge_top", "lunge_bot"],
  bw_lunge: ["lunge_top", "lunge_bot"]
};

// Form cues + mistakes per exercise (curated)
const FORM_GUIDE = {
  bb_squat: {
    cues: [
      "Bar rests on upper back (traps), not neck",
      "Feet shoulder-width, toes slightly out",
      "Brace core, chest up — initiate by pushing hips back",
      "Knees track over toes, drop hips to parallel or below",
      "Drive through heels — push the floor away"
    ],
    mistakes: ["Knees caving inward", "Heels lifting", "Chest collapsing forward", "Bouncing out of the bottom"],
    tempo: "3 sec down · 1 sec pause · 1 sec up"
  },
  bb_front_squat: {
    cues: ["Bar racked across front delts/clavicles, elbows HIGH", "Stay upright — proud chest", "Drop straight down between heels", "Drive elbows up the whole time"],
    mistakes: ["Elbows dropping", "Hips shooting up first", "Heels lifting"],
    tempo: "Controlled descent · drive up"
  },
  bb_deadlift: {
    cues: ["Bar over mid-foot, shins ~1 inch from bar", "Hinge at hips — push butt back, soft knee bend", "Neutral spine, chest proud, lats tight (squeeze armpits)", "Push the floor away — bar slides up your shins", "Lock out by squeezing glutes — no hyperextension"],
    mistakes: ["Rounding lower back", "Bar drifting forward", "Jerking off the floor", "Hyperextending at top"],
    tempo: "Reset between every rep — no bouncing"
  },
  bb_rdl: {
    cues: ["Slight knee bend — keep it FIXED", "Push hips straight back, bar slides down thighs", "Stop when you feel hamstring stretch (~mid-shin)", "Drive hips forward to stand up"],
    mistakes: ["Bending knees more on descent", "Rounding back", "Going too low"],
    tempo: "3 sec down · 1 sec up"
  },
  bb_bench: {
    cues: ["Eyes UNDER the bar, feet flat on floor", "Slight arch, shoulder blades pinned back & down", "Bar to lower chest/sternum, elbows ~45°", "Drive chest UP into the bar to press"],
    mistakes: ["Flaring elbows 90°", "Bouncing off chest", "Lifting butt off bench", "Pressing to wrong line"],
    tempo: "2 sec down · pause · explode up"
  },
  bb_ohp: {
    cues: ["Bar at clavicles, elbows just in front of bar", "Squeeze glutes, brace core — NO leg drive", "Press straight up, push head 'through' window at top", "Lock out directly over mid-foot"],
    mistakes: ["Leaning back excessively", "Pressing in front of head", "Half-locking the rep"],
    tempo: "Strict — no bounce"
  },
  bb_row: {
    cues: ["Hinge to ~45°, neutral spine, knees soft", "Pull bar to lower chest/upper abs", "Lead with elbows — drive them past your back", "Squeeze shoulder blades, lower under control"],
    mistakes: ["Standing more upright with each rep", "Yanking with arms only", "Rounding back"],
    tempo: "Pull fast · lower 2 sec"
  },
  bb_curl: {
    cues: ["Elbows pinned to ribs", "Curl from full extension to full contraction", "Squeeze biceps at top — pause 1 sec", "Lower under control"],
    mistakes: ["Swinging hips/shoulders", "Elbows drifting forward", "Cutting range short"],
    tempo: "1 sec up · pause · 2 sec down"
  },
  db_press: {
    cues: ["Same as bench but DBs allow deeper stretch", "DBs over wrists, wrists over elbows", "Press up and slightly together", "Don't clang at top"],
    mistakes: ["Going too heavy too fast", "Letting elbows flare", "Hitting DBs together hard"]
  },
  db_ohp: {
    cues: ["Press from shoulder height with palms forward (or neutral)", "Elbows slightly in front", "Press to lockout — don't touch DBs", "Lower controlled to ear level"],
    mistakes: ["Half reps", "Leaning back", "Wrists bent backward"]
  },
  db_row: {
    cues: ["Hand + knee on bench, flat back", "Pull DB to hip — elbow goes up & back", "Squeeze lat at top", "Lower with full stretch"],
    mistakes: ["Twisting torso to lift more", "Pulling to chest instead of hip"]
  },
  db_curl: { cues: ["Standing, palms forward", "Curl one or both — full ROM", "Supinate at top (twist palm up)", "Slow eccentric"], mistakes: ["Swinging", "Cutting range"] },
  db_hammer: { cues: ["Neutral grip (palms face each other)", "Curl to shoulder", "Targets brachialis + forearms"], mistakes: ["Rotating wrist", "Using momentum"] },
  db_lateral: { cues: ["Slight forward lean, elbows soft", "Raise to shoulder height — lead with elbows", "Pinky slightly higher than thumb", "Slow lower (3 sec)"], mistakes: ["Going too heavy", "Shrugging traps", "Swinging"] },
  db_rear_fly: { cues: ["Bent over ~30°, neutral spine", "Arms slightly bent, lift out to sides", "Squeeze rear delts at top"], mistakes: ["Using lower back", "Going too heavy"] },
  db_skullcrush: { cues: ["Lying flat, DBs above shoulders", "Hinge ONLY at elbows — upper arms stay vertical", "Lower DBs toward forehead/ears", "Extend back up"], mistakes: ["Moving upper arms", "Flaring elbows"] },
  db_goblet: { cues: ["Hold DB at chest with both hands", "Elbows tucked, drop straight down", "Knees track over toes", "Drive through heels"], mistakes: ["Letting elbows hit knees", "Heels lifting"] },
  db_lunge: { cues: ["Step forward into 90/90 position", "Front knee over ankle, back knee tap floor", "Push back up through front heel"], mistakes: ["Knee caving in", "Step too short"] },
  db_rdl: { cues: ["DBs in front of thighs", "Hinge at hips — push butt back", "DBs slide down thighs, feel hamstring stretch", "Drive hips forward to stand"], mistakes: ["Rounding back", "Squatting instead of hinging"] },
  db_shrug: { cues: ["DBs at sides, arms straight", "Lift shoulders STRAIGHT UP toward ears", "Squeeze, hold 1 sec, lower slow"], mistakes: ["Rolling shoulders", "Bending elbows"] },
  db_calf: { cues: ["Stand on edge of step or block", "Drop heels below toes for stretch", "Press up to full point — pause", "Lower slow"], mistakes: ["Bouncing", "Half reps"] },
  bb_lunge: { cues: ["Bar on back like a squat", "Long step forward into 90/90", "Drive through front heel"], mistakes: ["Front knee shooting past toes", "Stepping too short"] },
  bb_hipthrust: { cues: ["Upper back on bench, bar over hips (use pad)", "Feet flat, shins vertical at top", "Drive hips up — squeeze glutes HARD", "Chin tucked"], mistakes: ["Hyperextending lower back", "Feet too far/close"] },
  pu_pullup: { cues: ["Hang full — arms straight (dead hang)", "Pull elbows DOWN & BACK toward your ribs", "Chin clears the bar", "Lower controlled — full extension"], mistakes: ["Kipping/swinging", "Half reps", "Flaring elbows out"] },
  pu_chinup: { cues: ["Underhand grip, shoulder-width", "Same as pull-up but biceps assist more", "Squeeze biceps at top"], mistakes: ["Cutting range", "Swinging"] },
  pu_dip: { cues: ["Lock arms at top, lean slightly forward (chest) or vertical (triceps)", "Lower until shoulders just below elbows", "Press back up to lockout", "Don't shrug at top"], mistakes: ["Going too low (shoulder strain)", "Flaring elbows", "Swinging legs"] },
  pu_legraise: { cues: ["Dead hang, brace core", "Lift legs straight up to ~90°", "Posteriorly tilt pelvis at top (curl hips up)", "Lower SLOW"], mistakes: ["Swinging", "Bending knees (unless doing knee raise)", "Using momentum"] },
  pu_kneeraise: { cues: ["Easier version — bend knees", "Pull knees toward chest", "Curl hips up at top"], mistakes: ["Just hip flexors — no ab curl"] },
  pu_lsit: { cues: ["From dead hang or support", "Legs straight out — parallel to ground", "Hold for time", "Brace HARD"], mistakes: ["Knees bent", "Legs dropping"] },
  bw_pushup: { cues: ["Hands shoulder-width, fingers spread", "Body in straight line head-to-heels (plank)", "Lower until chest hovers above floor", "Elbows ~45° — not flared 90°", "Push the floor away"], mistakes: ["Sagging hips", "Flaring elbows", "Half range"] },
  bw_diamond: { cues: ["Hands close — thumbs/index touch (diamond)", "Same plank line", "Elbows track close to ribs", "Triceps focus"], mistakes: ["Hands too far forward", "Hips sagging"] },
  bw_plank: { cues: ["Forearms on ground, elbows under shoulders", "Body straight — squeeze glutes + abs", "Tuck chin slightly", "Breathe normally"], mistakes: ["Hips up (resting)", "Hips down (sagging)", "Holding breath"] },
  bw_squat: { cues: ["Feet shoulder-width, slight toe-out", "Push hips back, drop straight down", "Knees track over toes", "Stand up tall"], mistakes: ["Knees caving", "Heels lifting"] },
  bw_lunge: { cues: ["Step into 90/90, back knee taps floor lightly", "Push through front heel", "Stay tall"], mistakes: ["Step too short", "Knee crashing on floor"] },
  bw_glutebridge: { cues: ["Lying on back, knees bent, feet flat", "Drive hips up — squeeze glutes hard", "Brief pause at top", "Lower controlled"], mistakes: ["Pushing through toes", "Arching lower back"] },
  bw_calf: { cues: ["Stand tall, press up onto balls of feet", "Hold 1 sec at top", "Lower slow"], mistakes: ["Bouncing"] },
  bw_situp: { cues: ["Knees bent, feet flat", "Curl up — ribs to hips", "Don't yank neck", "Lower controlled"], mistakes: ["Pulling neck", "Using hip flexors only"] },
  bw_russian: { cues: ["Sit balanced, lean back ~45°", "Rotate torso side-to-side", "Touch floor or hold weight", "Feet up = harder"], mistakes: ["Just moving arms — rotate the torso"] },
  bw_superman: { cues: ["Lying face down, arms forward", "Lift arms + legs simultaneously", "Squeeze lower back + glutes", "Don't yank — controlled"], mistakes: ["Hyperextending neck", "Going too fast"] }
};

// Easing
const easeInOut = (t) => t < 0.5 ? 2*t*t : 1 - Math.pow(-2*t + 2, 2) / 2;

const lerp = (a, b, t) => a + (b - a) * t;
const lerpPose = (p1, p2, t) => {
  const out = {};
  for (const k in p1) {
    if (Array.isArray(p1[k])) {
      out[k] = p1[k].map((v, i) => lerp(v, p2[k][i], t));
    } else if (typeof p1[k] === "object") {
      out[k] = {};
      for (const j in p1[k]) {
        if (typeof p1[k][j] === "number") out[k][j] = lerp(p1[k][j], p2[k][j], t);
        else out[k][j] = p1[k][j];
      }
    } else {
      out[k] = p1[k];
    }
  }
  return out;
};

const StickFigure = ({ pose, color }) => {
  const p = pose;
  const stroke = color || "#F5F1E8";
  const sw = 4;
  return (
    <svg viewBox="0 0 220 280" className="hf-svg" preserveAspectRatio="xMidYMid meet">
      {/* Ground */}
      <line x1="0" y1="260" x2="220" y2="260" stroke="rgba(245,241,232,0.3)" strokeDasharray="4 4" strokeWidth="1" />
      {p.bench && <rect x="20" y="170" width="140" height="14" fill="rgba(245,241,232,0.15)" stroke="rgba(245,241,232,0.4)" />}
      {p.bar && (
        <line x1={p.bar.x1} y1={p.bar.y1} x2={p.bar.x2} y2={p.bar.y2} stroke="#FFB800" strokeWidth="5" strokeLinecap="round" />
      )}

      {/* Body — spine = shoulders midpoint to hips */}
      <line x1={(p.shoulderL[0] + p.shoulderR[0]) / 2} y1={(p.shoulderL[1] + p.shoulderR[1]) / 2}
            x2={p.hips[0]} y2={p.hips[1]} stroke={stroke} strokeWidth={sw} strokeLinecap="round" />
      {/* Shoulders */}
      <line x1={p.shoulderL[0]} y1={p.shoulderL[1]} x2={p.shoulderR[0]} y2={p.shoulderR[1]} stroke={stroke} strokeWidth={sw} strokeLinecap="round" />
      {/* Arms */}
      <line x1={p.shoulderL[0]} y1={p.shoulderL[1]} x2={p.elbowL[0]} y2={p.elbowL[1]} stroke={stroke} strokeWidth={sw} strokeLinecap="round" />
      <line x1={p.elbowL[0]} y1={p.elbowL[1]} x2={p.handL[0]} y2={p.handL[1]} stroke={stroke} strokeWidth={sw} strokeLinecap="round" />
      <line x1={p.shoulderR[0]} y1={p.shoulderR[1]} x2={p.elbowR[0]} y2={p.elbowR[1]} stroke={stroke} strokeWidth={sw} strokeLinecap="round" />
      <line x1={p.elbowR[0]} y1={p.elbowR[1]} x2={p.handR[0]} y2={p.handR[1]} stroke={stroke} strokeWidth={sw} strokeLinecap="round" />
      {/* Hips line */}
      <line x1={p.kneeL[0]} y1={p.hips[1]} x2={p.kneeR[0]} y2={p.hips[1]} stroke={stroke} strokeWidth={sw} strokeLinecap="round" />
      {/* Legs */}
      <line x1={p.hips[0] - 6} y1={p.hips[1]} x2={p.kneeL[0]} y2={p.kneeL[1]} stroke={stroke} strokeWidth={sw} strokeLinecap="round" />
      <line x1={p.kneeL[0]} y1={p.kneeL[1]} x2={p.footL[0]} y2={p.footL[1]} stroke={stroke} strokeWidth={sw} strokeLinecap="round" />
      <line x1={p.hips[0] + 6} y1={p.hips[1]} x2={p.kneeR[0]} y2={p.kneeR[1]} stroke={stroke} strokeWidth={sw} strokeLinecap="round" />
      <line x1={p.kneeR[0]} y1={p.kneeR[1]} x2={p.footR[0]} y2={p.footR[1]} stroke={stroke} strokeWidth={sw} strokeLinecap="round" />
      {/* Head */}
      <circle cx={p.head[0]} cy={p.head[1]} r={p.head[2]} fill="none" stroke={stroke} strokeWidth={sw} />

      {/* Barbell */}
      {p.barbell && (
        <g>
          <line x1={p.barbell.x1} y1={p.barbell.y1} x2={p.barbell.x2} y2={p.barbell.y2}
                stroke="#F5F1E8" strokeWidth="5" strokeLinecap="round" />
          {p.barbell.plates && (
            <>
              <rect x={p.barbell.x1 - 4} y={p.barbell.y1 - 14} width="8" height="28" fill="#FFB800" />
              <rect x={p.barbell.x2 - 4} y={p.barbell.y2 - 14} width="8" height="28" fill="#FFB800" />
            </>
          )}
        </g>
      )}
      {/* Dumbbell(s) */}
      {p.dumbbell && (
        <g>
          <rect x={p.dumbbell.cx - 12} y={p.dumbbell.cy - 4} width="24" height="8" fill="#F5F1E8" rx="1" />
          <rect x={p.dumbbell.cx - 16} y={p.dumbbell.cy - 8} width="4" height="16" fill="#FFB800" />
          <rect x={p.dumbbell.cx + 12} y={p.dumbbell.cy - 8} width="4" height="16" fill="#FFB800" />
        </g>
      )}
      {p.dumbbell2 && (
        <g>
          <rect x={p.dumbbell2.cx - 12} y={p.dumbbell2.cy - 4} width="24" height="8" fill="#F5F1E8" rx="1" />
          <rect x={p.dumbbell2.cx - 16} y={p.dumbbell2.cy - 8} width="4" height="16" fill="#FFB800" />
          <rect x={p.dumbbell2.cx + 12} y={p.dumbbell2.cy - 8} width="4" height="16" fill="#FFB800" />
        </g>
      )}
    </svg>
  );
};

const HowToView = ({ exercise, color, onClose }) => {
  const D = window.FITNESS_DATA;
  const guide = FORM_GUIDE[exercise.id] || { cues: ["Form guide coming soon."], mistakes: [], tempo: "" };
  const poseKeys = POSE_MAP[exercise.id] || ["squat_top", "squat_bot"];
  const p1 = STICK.poses[poseKeys[0]];
  const p2 = STICK.poses[poseKeys[1]];

  const [t, setT] = React.useState(0);
  const [playing, setPlaying] = React.useState(true);

  React.useEffect(() => {
    if (!playing) return;
    let raf, start = null;
    const loop = (ts) => {
      if (!start) start = ts;
      const elapsed = (ts - start) / 1400;
      const phase = elapsed % 2;
      const local = phase < 1 ? phase : 2 - phase;
      setT(easeInOut(local));
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, [playing, exercise.id]);

  const currentPose = lerpPose(p1, p2, t);

  return (
    <div className="hf-modal" onClick={onClose}>
      <div className="hf-card" onClick={e => e.stopPropagation()} style={{ "--c": color }}>
        <div className="hf-head">
          <div>
            <div className="hf-equip">{D.equipment.find(e => e.id === exercise.equip)?.label.toUpperCase()} · HOW TO</div>
            <div className="hf-title">{exercise.name.toUpperCase()}</div>
          </div>
          <div className="hf-close" onClick={onClose}>×</div>
        </div>

        <div className="hf-body">
          {/* Animation column */}
          <div className="hf-anim">
            <div className="hf-anim-frame">
              <StickFigure pose={currentPose} color={color} />
            </div>
            <div className="hf-anim-controls">
              <button className="hf-btn" onClick={() => setPlaying(!playing)}>{playing ? "❚❚ PAUSE" : "▶ PLAY"}</button>
              <div className="hf-scrub">
                <input type="range" min="0" max="1" step="0.01" value={t}
                  onChange={(e) => { setPlaying(false); setT(parseFloat(e.target.value)); }} />
              </div>
              <div className="hf-phase">{t < 0.5 ? "↓ ECCENTRIC" : "↑ CONCENTRIC"}</div>
            </div>
            {guide.tempo && <div className="hf-tempo">TEMPO · {guide.tempo}</div>}
          </div>

          {/* Cues column */}
          <div className="hf-info">
            <div className="hf-section">
              <div className="hf-section-head" style={{ color }}>★ FORM CUES</div>
              <ol className="hf-cues">
                {guide.cues.map((c, i) => (
                  <li key={i} className="hf-cue">
                    <span className="hf-cue-n">{String(i+1).padStart(2,"0")}</span>
                    <span className="hf-cue-t">{c}</span>
                  </li>
                ))}
              </ol>
            </div>

            {guide.mistakes && guide.mistakes.length > 0 && (
              <div className="hf-section">
                <div className="hf-section-head hf-section-head--warn">⚠ AVOID</div>
                <ul className="hf-mistakes">
                  {guide.mistakes.map((m, i) => <li key={i}>× {m}</li>)}
                </ul>
              </div>
            )}

            <div className="hf-musc">
              <div className="hf-musc-row">
                <span className="hf-musc-lbl">PRIMARY</span>
                <div className="hf-musc-tags">
                  {exercise.primary.map(m => <span key={m} className="ft-tag-primary">{D.muscles[m].label}</span>)}
                </div>
              </div>
              {exercise.secondary.length > 0 && (
                <div className="hf-musc-row">
                  <span className="hf-musc-lbl">SECONDARY</span>
                  <div className="hf-musc-tags">
                    {exercise.secondary.map(m => <span key={m} className="ft-tag-secondary">{D.muscles[m].label}</span>)}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>

        <div className="hf-footer">
          <div className="hf-foot-note">BEGINNERS · START LIGHT · NAIL FORM BEFORE LOADING</div>
        </div>
      </div>
    </div>
  );
};

window.HowToView = HowToView;
