// screens-capture.jsx — the capture moment: per-angle framing guide with live feedback,
// countdown, review, retake. Pairs with pose-detect.jsx for detection state.

const { useState, useEffect, useRef } = React;

// ── Camera stream hook ───────────────────────────────────────
// Acquires the rear-camera MediaStream while `active` is true and exposes it
// via a <video> ref. Exposes `grab()` that snapshots the current frame as a
// JPEG File for the upload pipeline. Falls back gracefully on permission
// denial or no-camera devices; CaptureScreen then uses a placeholder so the
// rest of the flow still works.
function useCameraStream({ active }) {
  const videoRef  = useRef(null);
  const streamRef = useRef(null);
  const [error,   setError]   = useState(null);
  const [ready,   setReady]   = useState(false);

  useEffect(() => {
    if (!active) {
      // Drop the stream when we leave the aim phase so the LED off-light
      // matches the user's expectation, and to free the camera for other
      // apps if they background us.
      if (streamRef.current) {
        streamRef.current.getTracks().forEach((t) => t.stop());
        streamRef.current = null;
      }
      setReady(false);
      return;
    }
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      setError('camera-unsupported');
      return;
    }
    let cancelled = false;
    (async () => {
      try {
        // Ask for the highest practical resolution the back camera can give.
        // Phones typically negotiate down to what they support — modern
        // mid-range up to 4K, older drops to 1920×1080. We use min:1920 to
        // refuse anything dramatically worse, ideal 3840 to pull up where
        // possible. More pixels per cm on the full-body capture means more
        // detail for the 3D service to work with even though the body fills less of
        // the frame than a tight portrait would.
        const stream = await navigator.mediaDevices.getUserMedia({
          video: {
            facingMode: { ideal: 'environment' },
            width:  { min: 1920, ideal: 3840 },
            height: { min: 1080, ideal: 2160 },
          },
          audio: false,
        });
        if (cancelled) {
          stream.getTracks().forEach((t) => t.stop());
          return;
        }
        streamRef.current = stream;
        if (videoRef.current) {
          videoRef.current.srcObject = stream;
          // Some Chrome versions need an explicit play() in TWA context.
          try { await videoRef.current.play(); } catch (e) { /* autoplay policy, fine */ }
        }
        setReady(true);
      } catch (e) {
        if (cancelled) return;
        const name = (e && e.name) || '';
        if (name === 'NotAllowedError' || name === 'SecurityError') setError('permission-denied');
        else if (name === 'NotFoundError')                          setError('no-camera');
        else                                                         setError(name || 'camera-error');
      }
    })();
    return () => {
      cancelled = true;
      if (streamRef.current) {
        streamRef.current.getTracks().forEach((t) => t.stop());
        streamRef.current = null;
      }
      setReady(false);
    };
  }, [active]);

  // Snapshot the current video frame into a JPEG File. Returns null if the
  // stream isn't live yet, so callers can fall back to placeholder generation.
  const grab = () => {
    const v = videoRef.current;
    if (!v || !v.videoWidth) return Promise.resolve(null);
    const c = document.createElement('canvas');
    c.width  = v.videoWidth;
    c.height = v.videoHeight;
    const g = c.getContext('2d');
    if (!g) return Promise.resolve(null);
    g.drawImage(v, 0, 0, c.width, c.height);
    return new Promise((resolve) => {
      c.toBlob(
        (blob) => {
          if (!blob) { resolve(null); return; }
          resolve(new File([blob], `frame-${Date.now()}.jpg`, { type: 'image/jpeg' }));
        },
        'image/jpeg',
        0.92
      );
    });
  };

  return { videoRef, ready, error, grab };
}

// Earlier versions generated a placeholder JPEG when the camera never came
// up, so the upload pipeline still had a File to send. That produced scans
// made of blank images: they cost credits at the 3D service and showed up in
// the studio as a scan that did not exist (seen 1 October 2026). We now stop
// and tell the customer instead.

// Default ANGLES (kept for backwards compatibility). The runtime version,
// resolved through resolveAngles(ctx), looks up SCAN_MODE_COPY based on
// ctx.capture.scanMode so the capture screen wording matches what the
// customer just picked on the Overview screen.
const ANGLES = [
  { key: 'front', label: 'Front',      instruct: 'Stand face-on, belly centred',  turn: '0°',
    nextInstruct: 'Now turn a quarter to your right' },
  { key: 'right', label: 'Right side', instruct: 'Quarter-turn to the right',      turn: '90°',
    nextInstruct: 'Now turn to face the wall' },
  { key: 'back',  label: 'Back',       instruct: 'Turn to face the wall',          turn: '180°',
    nextInstruct: 'Now turn a quarter further, to your left side' },
  { key: 'left',  label: 'Left side',  instruct: 'Quarter-turn to the left',       turn: '270°',
    nextInstruct: 'Lovely, that is everything' },
];

// Pull the angle wording from the SCAN_MODE_COPY table set up in
// screens-onboarding.jsx, falling back to the ANGLES default if the table
// (or the mode) is unavailable.
// Capture set (2026-11-11): four body photos, front, right, back and left,
// all from ONE spot about 1.5 m away (Marit 2026-11-12, was 2.5 m: 1.5 m
// gave better detail) with the phone upright at her hip
// height (since 2026-11-12, was belly height), her whole body in every
// photo; only she turns. Same distance and
// framing in every photo gives the 3D service a consistent scale. Then two
// close-ups of her hands, left and right, with her hands in the same place
// (Marit 2026-11-12, instead of one photo from under the belly): detail for
// the digital team; they do not go to the 3D service. Not when her hands are
// behind her head: those come off with the head.
//
const BODY_KEYS = ['front', 'right', 'back', 'left'];
const HAND_KEYS = ['hand_left', 'hand_right'];
function captureSequence(armPose) {
  return [...BODY_KEYS, ...(armPose === 'back' ? [] : HAND_KEYS)].map((k) => ({ key: k, locationIdx: 0 }));
}
const TURN_LABEL = { front: '0°', right: '90°', back: '180°', left: '270°', hand_left: 'close-up', hand_right: 'close-up' };

// The label 'Back' (the photo of her back) shares its English text with the
// back button, which is 'Terug' in Dutch. The photo label gets its own key;
// without a translation the original label shows.
function fotoLabel(label) {
  if (label !== 'Back') return t(label);
  const v = t('Back (photo)');
  return v === 'Back (photo)' ? label : v;
}

function resolveAngles(ctx) {
  const mode    = (ctx && ctx.capture && ctx.capture.scanMode) || 'standing';
  const armPose = (ctx && ctx.capture && ctx.capture.armPose)  || 'belly';
  const table = (typeof window !== 'undefined' && window.SCAN_MODE_COPY) || null;
  if (!table || !table[mode]) return ANGLES.map((a) => ({ ...a, label: fotoLabel(a.label), instruct: t(a.instruct), nextInstruct: t(a.nextInstruct) }));
  const copy    = table[mode];
  const armCopy = (typeof window !== 'undefined' && window.ARM_POSE_COPY && window.ARM_POSE_COPY[armPose]) || null;
  const armSuffix = armCopy ? ' ' + t(armCopy.angleSuffix) : '';

  const items = captureSequence(armPose)
    .filter(({ key }) => copy.angles[key])
    .map(({ key, locationIdx }) => {
      const isUnder  = HAND_KEYS.includes(key);
      const baseHint = isUnder ? t(copy.angles[key].hint) : t(copy.angles[key].hint) + armSuffix;
      return {
        key,
        locationIdx,
        label:    fotoLabel(copy.angles[key].label),
        instruct: baseHint,
        turn:     TURN_LABEL[key] || '',
        isUnder,
        takeIdx:  0,
      };
    });

  items.forEach((item, i) => {
    const next = items[i + 1];
    if (!next) {
      item.nextInstruct = t('Lovely, that is everything');
      return;
    }
    if (next.key === 'hand_left') {
      item.nextInstruct = t('Now two close-ups of her hands. She keeps them exactly where they are');
      return;
    }
    item.nextInstruct = t(copy.angles[item.key]?.next ?? '');
  });

  return items;
}

// ── per-angle silhouettes ────────────────────────────────────
// Each one is an SVG drawn into a 150×380 viewport so the same outline
// can show: dashed-rose (waiting), dashed-gold (lock), solid-gold-glow (firing).
function AngleSilhouette({ angleKey, color, dashed = true, glow = false }) {
  const stroke = color;
  const fill   = 'none';
  const dash   = dashed ? '6 6' : '0';
  const filter = glow ? `drop-shadow(0 0 14px ${color})` : 'none';

  let head = null, body = null;
  switch (angleKey) {
    case 'front':
      // Tight front crop: head down to the KNEES only. Belly protrudes wide
      // to read as clearly pregnant — peak extends to ~x=17/x=133 on a 150px
      // viewport (about 77% of total width at the widest point).
      head = <circle cx="75" cy="44" r="30" fill={fill} stroke={stroke} strokeWidth="2.5" strokeDasharray={dash} />;
      body = <path d="M 46 88 C 39 103, 35 119, 34 133 C 31 143, 27 154, 25 166
                       C 17 186, 16 212, 26 235 C 31 247, 35 256, 37 268
                       C 38 274, 39 281, 40 288 C 41 320, 42 352, 43 380
                       L 62 380 C 63 352, 64 320, 65 291 L 75 270 L 85 291
                       C 86 320, 87 352, 88 380 L 107 380
                       C 108 352, 109 320, 110 288 C 111 281, 112 274, 113 268
                       C 115 256, 119 247, 124 235 C 134 212, 133 186, 125 166
                       C 123 154, 119 143, 116 133 C 115 119, 111 103, 104 88
                       C 93 64, 57 64, 46 88 Z"
                   fill={fill} stroke={stroke} strokeWidth="2.5" strokeDasharray={dash} strokeLinejoin="round" />;
      break;
    case 'right':
      // Side profile. Belly peak at x=126 — a clear rounded dome shape.
      // Left (back) uses scale(-1,1) so this path serves both sides.
      head = <ellipse cx="68" cy="44" rx="22" ry="28" fill={fill} stroke={stroke} strokeWidth="2.5" strokeDasharray={dash} />;
      body = <path d="M 57 84 C 49 110, 44 142, 48 172 C 44 202, 45 232, 53 252
                       C 54 300, 55 340, 56 380 L 90 380
                       C 89 340, 88 300, 87 252 C 86 243, 86 236, 87 227
                       C 104 210, 126 190, 126 166 C 126 154, 122 144, 113 135
                       C 108 125, 110 112, 102 100 C 97 90, 86 83, 81 86
                       C 74 80, 63 80, 57 84 Z"
                   fill={fill} stroke={stroke} strokeWidth="2.5" strokeDasharray={dash} strokeLinejoin="round" />;
      break;
    case 'back':
      // Full standing figure, head to feet — the back is the pose anchor
      // (our AI needs the whole skeleton), so the proportions are smaller
      // and the feet sit just inside the bottom of the frame. No belly or
      // breasts: nothing of that shows from behind.
      head = (
        <g>
          <circle cx="75" cy="30" r="21" fill={fill} stroke={stroke} strokeWidth="2.5" strokeDasharray={dash} />
          {/* small hair line so it reads as "back of head" */}
          <path d="M 61 20 Q 75 12, 89 20" fill="none" stroke={stroke} strokeWidth="2.5" strokeDasharray={dash} strokeLinecap="round" />
        </g>
      );
      body = (
        <path d="M 55 56 C 47 82, 42 110, 42 138 C 42 162, 46 184, 54 200
                 C 56 205, 57 210, 58 216 C 59 250, 60 286, 61 312
                 C 60 336, 60 358, 59 368 C 59 374, 57 376, 55 376
                 L 55 380 L 73 380 C 73 372, 73 350, 72 312
                 L 74 226 L 75 220 L 76 226 L 78 312
                 C 77 350, 77 372, 77 380 L 95 380 L 95 376
                 C 93 376, 91 374, 91 368 C 90 358, 90 336, 89 312
                 C 90 286, 91 250, 92 216 C 93 210, 94 205, 96 200
                 C 104 184, 108 162, 108 138 C 108 110, 103 82, 95 56
                 C 87 38, 63 38, 55 56 Z"
              fill={fill} stroke={stroke} strokeWidth="2.5" strokeDasharray={dash} strokeLinejoin="round" />
      );
      break;
    case 'left':
      // Mirror of the right tight profile around the vertical centre line so
      // the belly + breast bump to the left. One transform keeps it perfectly
      // symmetric with 'right' instead of maintaining a second path.
      head = null;
      body = (
        <g transform="translate(150,0) scale(-1,1)">
          <ellipse cx="68" cy="44" rx="22" ry="28" fill={fill} stroke={stroke} strokeWidth="2.5" strokeDasharray={dash} />
          <path d="M 58 86 C 50 112, 46 144, 50 172 C 47 202, 48 230, 56 250
                   C 57 298, 58 340, 59 380 L 92 380
                   C 91 340, 90 298, 89 250 C 88 242, 88 236, 89 228
                   C 103 210, 114 188, 104 162 C 101 152, 99 146, 98 140
                   C 106 130, 109 116, 101 102 C 96 92, 86 86, 82 88
                   C 75 82, 64 82, 58 86 Z"
                fill={fill} stroke={stroke} strokeWidth="2.5" strokeDasharray={dash} strokeLinejoin="round" />
        </g>
      );
      break;
    case 'front_detail':
      // Extra front close-up: same tight head-to-knees crop as the regular
      // front shot. It is a second front photo for resolution, framed the
      // same way, so it shares the front silhouette exactly.
      head = <circle cx="75" cy="44" r="30" fill={fill} stroke={stroke} strokeWidth="2.5" strokeDasharray={dash} />;
      body = <path d="M 47 90 C 41 104, 38 118, 38 132 C 36 140, 34 150, 33 162
                       C 26 180, 26 205, 36 226 C 41 236, 44 244, 46 256
                       C 47 262, 48 268, 49 274 C 50 312, 51 346, 52 380
                       L 70 380 C 71 346, 72 312, 73 280 L 75 270 L 77 280
                       C 78 312, 79 346, 80 380 L 98 380
                       C 99 346, 100 312, 101 274 C 102 268, 103 262, 104 256
                       C 106 244, 109 236, 114 226 C 124 205, 124 180, 117 162
                       C 116 150, 114 140, 112 132 C 112 118, 109 104, 103 90
                       C 94 68, 56 68, 47 90 Z"
                   fill={fill} stroke={stroke} strokeWidth="2.5" strokeDasharray={dash} strokeLinejoin="round" />;
      break;
    case 'hand_right':
    case 'hand_left': {
      // Flat-hand silhouette, palm-down. Fingers CLOSED together (single
      // rounded block, not spread), thumb sits free and slightly away from
      // the rest. Same 150×380 viewport as the body silhouettes so the
      // capture-frame UI stays consistent. Left-hand variant mirrors.
      const mirrored = angleKey === 'hand_left';
      const tf = mirrored ? 'translate(150,0) scale(-1,1)' : undefined;
      head = null;
      body = (
        <g transform={tf}>
          {/* palm + wrist + closed-finger block as one continuous outline.
              Top edge sits at y=64 with a soft round so the four fingertips
              read as a single closed shape. Wrist tapers down to y=320. */}
          <path d="M 56 64
                   C 50 60, 122 60, 116 64
                   L 116 200
                   C 116 220, 122 240, 122 268
                   C 122 300, 110 320, 92 320
                   L 60 320
                   C 42 320, 30 300, 30 268
                   C 30 240, 36 220, 36 200
                   L 36 152
                   C 36 156, 36 156, 36 152 Z"
                fill={fill} stroke={stroke} strokeWidth="2.5" strokeDasharray={dash} strokeLinejoin="round" strokeLinecap="round" />
          {/* thumb sticking out to the side, clear gap from the fingers */}
          <path d="M 36 180
                   C 18 178, 6 162, 12 142
                   C 18 124, 38 122, 50 138
                   L 50 196"
                fill={fill} stroke={stroke} strokeWidth="2.5" strokeDasharray={dash} strokeLinecap="round" strokeLinejoin="round" />
        </g>
      );
      break;
    }
    case 'belly_under': {
      // Phone held under the belly, pointing upward. Shows the underside of
      // the bump (large oval) with navel centre and the upper thighs visible.
      head = null;
      body = (
        <g>
          <ellipse cx="75" cy="172" rx="58" ry="74" fill={fill} stroke={stroke} strokeWidth="2.5" strokeDasharray={dash} />
          <circle cx="75" cy="155" r="9" fill={fill} stroke={stroke} strokeWidth="2" strokeDasharray={dash} />
          <ellipse cx="35" cy="328" rx="20" ry="44" fill={fill} stroke={stroke} strokeWidth="2" strokeDasharray={dash} />
          <ellipse cx="115" cy="328" rx="20" ry="44" fill={fill} stroke={stroke} strokeWidth="2" strokeDasharray={dash} />
        </g>
      );
      break;
    }
    default:
      head = <circle cx="75" cy="34" r="30" fill={fill} stroke={stroke} strokeWidth="2.5" strokeDasharray={dash} />;
      body = <rect x="32" y="72" width="86" height="282" rx="40" fill={fill} stroke={stroke} strokeWidth="2.5" strokeDasharray={dash} />;
  }

  // Each figure draws at its natural extent inside the 150×380 viewport:
  // the tight angles (front/right/left/front_detail) are head-to-knees with
  // the thighs running off the bottom (frame cuts at the knees, no shins or
  // feet); the back is the full head-to-feet figure. The caller scales the
  // SVG to fill the framing box, so the knees (tight) or feet (back) land at
  // the bottom of the guide.
  return (
    <svg viewBox="0 0 150 380" width="100%" height="100%" preserveAspectRatio="xMidYMid meet"
         style={{ filter, display: 'block', transition: 'filter .25s ease' }}>
      {head}
      {body}
    </svg>
  );
}

// ── framing guide overlay ────────────────────────────────────
// frameState: 'seeking' | 'in-frame' | 'locked' | 'firing'
function FramingGuide({ angleKey, frame, midLabel = 'her hips' }) {
  let color = 'rgba(236,231,218,.55)';
  let glow  = false;
  let dashed = true;
  if (frame === 'in-frame') color = 'rgba(212,165,154,.95)';
  if (frame === 'locked')   { color = '#cbb273'; glow = true; }
  if (frame === 'firing')   { color = '#e5cf88'; glow = true; dashed = false; }
  // All four body photos are taken the same way since 2026-11-11 (Marit):
  // from one spot about 1.5 m away, phone upright at her hip height, her
  // whole body in the photo. Before, three photos were head-to-knees from
  // about 1 m and the back from further away: up close the belly and hands
  // were magnified and every photo had a different scale, which gave the 3D service
  // odd proportions and strange hands. The frame is a loose guide (no exact
  // silhouette to fit into): she just has to be inside it.
  //
  // Size and place (Marit 2026-11-12): the frame is the size of her body from
  // about 1.5 m (was 2.5 m; 1.5 m gave better detail). A phone camera sees
  // about 2 m high there. With the phone upright at her hip height her hips
  // sit on the middle line, her head about 0.75 m above it and her feet about
  // 0.95 m below it: so the frame starts at about 11% from the top and ends
  // just above the bottom. If her hips are not on the line, the phone is too
  // high or too low, not tilted.
  const isBody      = ['front', 'right', 'back', 'left', 'front_detail'].includes(angleKey);
  const topLabel    = t('her head inside');
  const bottomLabel = t('her feet inside');
  const frameTop    = '11%';
  const frameBottom = '3%';

  return (
    <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
      {/* faint thirds grid */}
      {[1, 2].map((i) => (
        <div key={'v' + i} style={{ position: 'absolute', top: 0, bottom: 0, left: `${i * 33.3}%`, width: 1, background: 'rgba(236,231,218,.08)' }} />
      ))}
      {[1, 2].map((i) => (
        <div key={'h' + i} style={{ position: 'absolute', left: 0, right: 0, top: `${i * 33.3}%`, height: 1, background: 'rgba(236,231,218,.08)' }} />
      ))}
      {/* CROP FRAME: corner brackets + bottom bar + label. The bottom marks
          where the shot stops (her knees on the tight shots, her feet on the
          full-body back). Tight shots sit a little lower (frameTop) so the
          partner does not try to fit the whole body in. The bar stays clear
          of the shutter UI (hint + 76px button + padding ≈ bottom 17%). The
          captured photo is the full video frame regardless; this only
          governs the visible guide. */}
      {isBody && (
        <div style={{ position: 'absolute', top: frameTop, bottom: frameBottom, left: '14%', right: '14%', pointerEvents: 'none' }}>
          {[
            { top: 0,    left: 0,    borderTop: true,  borderLeft: true  },
            { top: 0,    right: 0,   borderTop: true,  borderRight: true },
            { bottom: 0, left: 0,    borderBottom: true, borderLeft: true },
            { bottom: 0, right: 0,   borderBottom: true, borderRight: true },
          ].map((c, i) => (
            <div key={i} style={{
              position: 'absolute',
              width: 28, height: 28,
              top: c.top, bottom: c.bottom, left: c.left, right: c.right,
              borderTop:    c.borderTop    ? `2.5px solid ${color}` : undefined,
              borderBottom: c.borderBottom ? `2.5px solid ${color}` : undefined,
              borderLeft:   c.borderLeft   ? `2.5px solid ${color}` : undefined,
              borderRight:  c.borderRight  ? `2.5px solid ${color}` : undefined,
              filter: glow ? `drop-shadow(0 0 8px ${color})` : 'none',
              transition: 'border-color .25s, filter .25s',
            }} />
          ))}
          <div style={{ position: 'absolute', top: -2, left: '50%', transform: 'translateX(-50%)',
            fontSize: 9, letterSpacing: '.18em', textTransform: 'uppercase',
            color: 'rgba(236,231,218,.55)', background: 'rgba(20,22,15,.7)',
            padding: '3px 8px', borderRadius: 4, whiteSpace: 'nowrap' }}>
            {topLabel}
          </div>
          <div style={{ position: 'absolute', bottom: 5, left: '50%', transform: 'translateX(-50%)',
            fontSize: 9, letterSpacing: '.18em', textTransform: 'uppercase',
            color: 'rgba(236,231,218,.55)', background: 'rgba(20,22,15,.7)',
            padding: '3px 8px', borderRadius: 4, whiteSpace: 'nowrap' }}>
            {bottomLabel}
          </div>
        </div>
      )}
      {/* silhouette. For body shots it fills the SAME box as the crop frame
          (top frameTop / bottom frameBottom / left+right 14%) so the figure's
          bottom — her knees on the tight crops, her feet on the full-body
          back shot — lands exactly on the bottom bar.
          Hand close-ups keep the centred, fixed-size placement. */}
      {isBody ? (
        // A faint vertical line keeps her roughly in the middle; the
        // horizontal middle line is where her hips go (the centre of the lens).
        <>
          <div style={{ position: 'absolute', top: `calc(${frameTop} + 26px)`, bottom: `calc(${frameBottom} + 26px)`, left: '50%', width: 0,
            borderLeft: `1px dashed ${color}`, opacity: .3, pointerEvents: 'none' }} />
          <div style={{ position: 'absolute', top: '50%', left: '14%', right: '14%', height: 0,
            borderTop: `1.5px dashed ${color}`, opacity: .7, pointerEvents: 'none' }} />
          <div style={{ position: 'absolute', top: '50%', right: '14%', transform: 'translate(0, -50%)',
            fontSize: 9, letterSpacing: '.18em', textTransform: 'uppercase',
            color: 'rgba(236,231,218,.7)', background: 'rgba(20,22,15,.7)',
            padding: '3px 8px', borderRadius: 4, whiteSpace: 'nowrap', pointerEvents: 'none' }}>
            {t(midLabel)}
          </div>
        </>
      ) : (angleKey === 'hand_left' || angleKey === 'hand_right') ? (
        // Hand close-up: a plain square in the middle, the hand fills it.
        // (The old outline with three circles was confusing, Marit 2026-11-12.)
        <div style={{ position: 'absolute', top: '24%', bottom: '30%', left: '9%', right: '9%', pointerEvents: 'none' }}>
          {[
            { top: 0, left: 0, borderTop: true, borderLeft: true },
            { top: 0, right: 0, borderTop: true, borderRight: true },
            { bottom: 0, left: 0, borderBottom: true, borderLeft: true },
            { bottom: 0, right: 0, borderBottom: true, borderRight: true },
          ].map((c, i) => (
            <div key={i} style={{
              position: 'absolute', width: 28, height: 28,
              top: c.top, bottom: c.bottom, left: c.left, right: c.right,
              borderTop:    c.borderTop    ? `2.5px solid ${color}` : undefined,
              borderBottom: c.borderBottom ? `2.5px solid ${color}` : undefined,
              borderLeft:   c.borderLeft   ? `2.5px solid ${color}` : undefined,
              borderRight:  c.borderRight  ? `2.5px solid ${color}` : undefined,
            }} />
          ))}
          <div style={{ position: 'absolute', top: -2, left: '50%', transform: 'translateX(-50%)',
            fontSize: 9, letterSpacing: '.18em', textTransform: 'uppercase',
            color: 'rgba(236,231,218,.55)', background: 'rgba(20,22,15,.7)',
            padding: '3px 8px', borderRadius: 4, whiteSpace: 'nowrap' }}>
            {angleKey === 'hand_left' ? t('her left hand') : t('her right hand')}
          </div>
        </div>
      ) : (
        <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ width: 150, height: 380 }}>
            <AngleSilhouette angleKey={angleKey} color={color} dashed={dashed} glow={glow} />
          </div>
        </div>
      )}
    </div>
  );
}

// ── rotation overlay between shots ──────────────────────────
function RotationOverlay({ from, to, instruct, onDone, hold = false }) {
  // Every turn waits for a tap (Marit 2026-11-19: after 1.5 s the instruction
  // was gone before anyone had read it). The button says what happens next.
  const fromDeg = { front: 0, right: 90, back: 180, left: 270 }[from] || 0;
  const toDeg   = { front: 0, right: 90, back: 180, left: 270 }[to]   || 0;
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 5, display: 'flex',
      alignItems: 'center', justifyContent: 'center',
      background: 'rgba(11,12,8,.72)', backdropFilter: 'blur(4px)',
      animation: 'fadein .25s ease both',
    }}>
      <style>{`@keyframes rotIcon-${from}-${to} { from { transform: rotate(${fromDeg}deg);} to { transform: rotate(${toDeg}deg);} }`}</style>
      <div style={{ textAlign: 'center', padding: '0 36px' }}>
        <div style={{ width: 140, height: 140, margin: '0 auto', position: 'relative' }}>
          <svg viewBox="0 0 140 140" width="140" height="140" style={{
            transformOrigin: '70px 70px',
            animation: `rotIcon-${from}-${to} 1.2s cubic-bezier(.6,.05,.3,1) .15s both`,
          }}>
            <circle cx="70" cy="70" r="58" fill="none" stroke="rgba(212,165,154,.4)" strokeWidth="1.5" strokeDasharray="3 5" />
            {/* fixed arrow at top showing camera direction */}
            <path d="M 70 6 L 64 16 L 76 16 Z" fill="rgba(236,231,218,.85)" />
            {/* simple person silhouette in the middle */}
            <circle cx="70" cy="56" r="9" fill="#ece7da" />
            <path d="M 56 70 C 56 66, 62 65, 70 65 C 78 65, 84 66, 84 70
                     L 86 96 C 86 106, 82 112, 78 116 L 62 116 C 58 112, 54 106, 54 96 Z" fill="#ece7da" />
          </svg>
        </div>
        <div className="eyebrow" style={{ marginTop: 22, color: 'var(--gold-soft)' }}>
          {hold ? t('Move to a new spot') : t('Next angle')}
        </div>
        <h3 style={{ fontFamily: 'var(--serif)', fontWeight: 500, fontSize: 26, color: 'var(--paper)', margin: '10px 0 0', lineHeight: 1.25 }}>
          {instruct}
        </h3>
        {(
          <button onClick={onDone} style={{
            marginTop: 26, padding: '13px 30px', borderRadius: 999, border: 'none',
            background: '#e5cf88', color: '#1a1c14', fontSize: 15, fontWeight: 700,
            cursor: 'pointer', boxShadow: '0 8px 26px rgba(229,207,136,.35)',
          }}>
            {hold ? t('We are in the new spot, continue') : String(to).startsWith('hand_') ? t('We are close, continue') : t('She turned, next photo')}
          </button>
        )}
      </div>
    </div>
  );
}


function CaptureScreen({ ctx }) {
  const [shot, setShot]                 = useState(0);
  const [phase, setPhase]               = useState('aim');      // aim | count | review | rotating
  const [count, setCount]               = useState(3);
  const [flash, setFlash]               = useState(false);
  const [reviewFailed, setReviewFailed] = useState(false);
  const [toast, setToast]               = useState(null);
  const [holdStill, setHoldStill]       = useState(false);
  const [prevAngleKey, setPrevAngleKey] = useState(null);
  const [reviewFrame, setReviewFrame]   = useState(null);       // dataURL of last grabbed frame, for review tile
  // Lower hand too low (below the belly, near the pubic area)? Checked on the
  // front photo with the "hands on belly" pose, on the phone itself
  // (hand-check.js). null = no check or no answer; never a guess.
  const [handOordeel, setHandOordeel]   = useState(null);       // null | 'bezig' | 'goed' | 'te_laag'
  // The review analysis (Marit 2026-11-12): outline, pose points, head and a
  // real sharpness check. undefined = busy, null = could not tell.
  const [analyse, setAnalyse]           = useState(undefined);
  // Sharpness of the body photos kept so far in this scan (for scherpGrens).
  const scherpteEerderRef = useRef([]);
  // Did the phone move while the photo was taken? (motion sensor)
  const [bewogen, setBewogen]           = useState(false);
  const [beweging, setBeweging]         = useState(null);       // { draai, versnelling, model } for the test mode and the server
  const [modelBewogen, setModelBewogen] = useState(false);      // she moved while the photo was taken
  const handenOpBuik = ((ctx && ctx.capture && ctx.capture.armPose) || 'belly') === 'belly';
  // The pose model also blurs the head in the review (always, not only for the hand check).
  useEffect(() => { if (window.handCheck) { window.handCheck.voorladen(); window.handCheck.voorladenVideo(); } }, []);
  const [plekGezien, setPlekGezien]     = useState(false);      // "find your spot" read before the first photo
  // Distance measured live from her pose (Marit 2026-11-19): null = nobody found.
  const [afstand, setAfstand]           = useState(null);
  const [uitlegOpen, setUitlegOpen]     = useState(false);      // full instruction for this photo, on tap
  const capturedFileRef = useRef(null);
  // Per-mode angle list (resolved once per render). `ANGLES` stays for the
  // default mode + RotationOverlay's compass-direction lookup.
  const angles    = resolveAngles(ctx);
  const approved  = shot;
  const angle     = angles[shot];
  const plekUitleg = shot === 0 && !plekGezien && phase === 'aim';
  useEffect(() => { setUitlegOpen(false); }, [shot]);

  // Real camera stream while aiming. Stops + restarts as we move between
  // angles and back from review/retake.
  const cameraActive = phase === 'aim' || phase === 'count';
  const camera       = useCameraStream({ active: cameraActive });
  // Hand close-up: clear view only when just the hand is in the frame.
  const isHandFoto   = HAND_KEYS.includes(angle.key);
  const lichaamZicht = useLichaamInBeeld(camera.videoRef, isHandFoto && camera.ready && (phase === 'aim' || phase === 'count'));
  const handHelder   = isHandFoto && !lichaamZicht;

  // Live detection state. The mock progression sits in pose-detect.jsx; that's
  // the single seam to swap in real ML Kit / MoveNet later.
  const detectActive = phase === 'aim';
  const det          = useFraming({ angleKey: angle.key, active: detectActive, videoRef: camera.videoRef });
  const level        = useDeviceLevel();

  const frameState = (() => {
    if (phase === 'count')                                                return 'firing';
    // Bad exposure blocks the 'locked' state so silent auto-capture cannot
    // fire on a pitch-black or blown-out frame. The customer sees the
    // exposure hint and corrects the light before we shoot.
    // Gold = what we really measure is fine: the phone is held straight and
    // the light is good. Whether she is in the frame, the photographer sees.
    // Hand close-ups: holding the phone straight does not matter there.
    if (camera.ready && (level.levelOk || angle.isUnder) && det.exposure === 'ok') return 'locked';
    return 'seeking';
  })();
  const ready = frameState === 'locked';

  const vibrate = (p) => { try { navigator.vibrate && navigator.vibrate(p); } catch (e) {} };

  // True once a shutter press produced nothing because the camera is not
  // running. Shown as a blocking message; the customer cannot continue with
  // empty photos.
  const [cameraBlocked, setCameraBlocked] = useState(false);

  // No auto-capture: the photo is only taken when the photographer presses
  // the button (Marit 2026-11-11). Before, it fired by itself after a few
  // seconds of holding the phone straight, framed or not.

  // Countdown driver. The shutter "fires" when n reaches 0: we grab the
  // current video frame, flash, then jump to the review sheet.
  useEffect(() => {
    if (phase !== 'count') return;
    setCount(3);
    vibrate(18);
    let n = 3;
    const id = setInterval(async () => {
      n -= 1;
      if (n > 0) { setCount(n); vibrate(18); return; }
      clearInterval(id);
      vibrate([0, 32, 40, 32]);
      setFlash(true);
      setTimeout(() => setFlash(false), 220);

      // Grab the live frame. No camera means no photo: we stop here rather
      // than sending something blank.
      // Shake check: the fastest turn of the phone just before and at the shot.
      const draai = window.bewegingsMeter ? window.bewegingsMeter.max(450) : null;
      const versnelling = window.bewegingsMeter && window.bewegingsMeter.maxVersnelling ? window.bewegingsMeter.maxVersnelling(450) : null;
      const model = BODY_KEYS.includes(angle.key) ? modelBeweging(700) : null;
      setBeweging({ draai, versnelling, model });
      setBewogen((draai != null && draai > BEWEGING_MAX) || (versnelling != null && versnelling > VERSNELLING_MAX));
      setModelBewogen(model != null && model > MODEL_BEWEGING_MAX);
      const file = await camera.grab();
      if (!file) {
        capturedFileRef.current = null;
        setCameraBlocked(true);
        setHoldStill(false);
        setPhase('aim');
        return;
      }
      capturedFileRef.current = file;
      if (handenOpBuik && angle.key === 'front' && window.handCheck) {
        setHandOordeel('bezig');
        window.handCheck.teLaag(file).then((r) => setHandOordeel(r ? (r.teLaag ? 'te_laag' : 'goed') : null));
      } else {
        setHandOordeel(null);
      }
      try { setReviewFrame(URL.createObjectURL(file)); } catch (e) { setReviewFrame(null); }
      setAnalyse(undefined);
      if (window.handCheck && window.handCheck.analyse) {
        const key = angle.key;
        const eerder = BODY_KEYS.includes(key) ? scherpteEerderRef.current.slice() : [];
        window.handCheck.analyse(file).then((a) => {
          if (!a) { setAnalyse(null); return; }
          if (a.scherpte == null) { setAnalyse(a); return; }
          const grens = scherpGrens(key, eerder);
          setAnalyse({ ...a, scherp: a.scherpte >= grens, grens });
        });
      } else setAnalyse(null);

      setReviewFailed(false);
      setHoldStill(false);
      setPhase('review');
    }, 820);
    return () => clearInterval(id);
  }, [phase]);

  // Stage the most recently grabbed photo into the cross-screen store.
  // (angle, locationIdx) is the unique key — same angle at different
  // locations are kept side by side, not overwritten.
  const stageCapture = (angleKey, takeIdx = 0, locationIdx = 0) => {
    if (!ctx || !ctx.capture) return;
    const file = capturedFileRef.current;
    if (!file) { setCameraBlocked(true); return; }
    ctx.capture.photos = (ctx.capture.photos || [])
      .filter((p) => !(p.angle === angleKey && (p.order_idx ?? 0) === takeIdx && (p.location_idx ?? 0) === locationIdx));
    const foto = { angle: angleKey, file, order_idx: takeIdx, location_idx: locationIdx };
    // Measurements, sent along with the photo to tune the limits (Marit 2026-11-12).
    const rond = (v) => (v == null ? null : Math.round(v * 100) / 100);
    foto.meting = {
      scherpte: analyse ? rond(analyse.scherpte) : null,
      scherp: analyse ? analyse.scherp : null,
      scherp_grens: analyse && analyse.grens != null ? Math.round(analyse.grens * 100) / 100 : null,
      draai: rond(beweging && beweging.draai), versnelling: rond(beweging && beweging.versnelling),
      model: beweging && beweging.model != null ? Math.round(beweging.model * 10000) / 10000 : null,
      bewogen, model_bewogen: modelBewogen, sensor: !!(beweging && (beweging.draai != null || beweging.versnelling != null)),
    };
    // Her face is made unrecognisable before anything is sent (Marit
    // 2026-11-12). Only the four body photos: the hand close-ups have no face.
    // The upload waits for this (foto.klaar).
    if (BODY_KEYS.includes(angleKey) && window.handCheck && window.handCheck.vervaagHoofd) {
      foto.klaar = window.handCheck.vervaagHoofd(file).then((r) => { foto.file = r.file; foto.hoofd_vervaagd = r.vervaagd; });
    }
    ctx.capture.photos.push(foto);
  };

  const approve = () => {
    if (BODY_KEYS.includes(angle.key) && analyse && analyse.scherpte != null) scherpteEerderRef.current.push(analyse.scherpte);
    stageCapture(angle.key, angle.takeIdx ?? 0, angle.locationIdx ?? 0);
    // Free the temporary object URL from the review tile, no longer needed.
    if (reviewFrame) { try { URL.revokeObjectURL(reviewFrame); } catch (e) {} setReviewFrame(null); }
    if (shot >= angles.length - 1) { ctx.go('details'); return; }
    const next = shot + 1;
    setToast(t('{n} of {totaal} captured', { n: next, totaal: angles.length }));
    setTimeout(() => setToast(null), 1500);
    setPrevAngleKey(angle.key);
    setShot(next);
    setPhase('rotating');
  };

  const retake = () => {
    setReviewFailed(false);
    if (reviewFrame) { try { URL.revokeObjectURL(reviewFrame); } catch (e) {} setReviewFrame(null); }
    capturedFileRef.current = null;
    setPhase('aim');
  };

  // Too close (measured, not guessed): the shutter waits until he steps back.
  const teDichtbij = afstand === 'te_dichtbij' && BODY_KEYS.includes(angle.key) && phase === 'aim' && !plekUitleg;
  const onShutter = () => {
    if (teDichtbij) { vibrate([0, 60, 60, 60]); return; }
    if (phase === 'aim' && !plekUitleg) setPhase('count');
  };

  // Ready to shoot (Marit 2026-11-19: the hints stayed at the bottom, so it
  // was not clear when to tap): phone straight, light fine, and the distance
  // not measured as wrong. Then the button turns green.
  const GROEN = '#3fae6a';
  const klaar = phase === 'aim' && !plekUitleg && ready && !teDichtbij
    && !(afstand === 'te_ver' && BODY_KEYS.includes(angle.key));
  const hint = (() => {
    if (phase === 'count')                                  return t('Hold still...');
    // Exposure beats every other state — a too-dark or too-bright frame is
    // useless regardless of pose.
    if (det.exposure === 'too_dark')                         return t('Too dark, find more light or move closer to a window');
    if (det.exposure === 'too_bright')                       return t('Too bright, dim the light or step out of direct sun');
    // Differentiate front-back tilt (camera too high / too low / pointing up
    // or down) from left-right tilt (rotated around its long axis). Front-
    // back tilt is what made the back-angle look like she was photographed
    // from a chair — that needs an explicit "drop to her belly height" hint.
    // Tilting distorts her shape most: pointing down gives short legs and a
    // big upper body, pointing up the other way round. Say which way.
    if (!angle.isUnder && level.supported && level.tiltFB >= 5 && level.pointsUp)   return t('The phone points up. Hold it straight upright and raise it to her hips');
    if (!angle.isUnder && level.supported && level.tiltFB >= 5)                     return t('The phone points down. Hold it straight upright and lower it to her hips');
    if (!angle.isUnder && level.supported && !level.levelOk)                        return t('Hold the phone straight, no left or right tilt');
    // Distance from the live pose points (afstandUit). Only what we measure.
    if (teDichtbij)                                          return t('Too close. Step back until her head and feet are inside');
    if (afstand === 'te_ver' && BODY_KEYS.includes(angle.key)) return t('A little too far. Take one step closer');
    if (klaar && BODY_KEYS.includes(angle.key))              return t('Ready. Tap the green button');
    if (isHandFoto && !handHelder)                           return t('Come closer, about 30 cm, until only her hand is in view');
    if (angle.key === 'hand_left')                           return t('Close up: her left hand fills the frame, hands where they were');
    if (angle.key === 'hand_right')                          return t('Close up: her right hand fills the frame, hands where they were');
    return t('Phone upright at her hips, step back until she fits the frame. Then tap');
  })();

  // Not ready: a quiet grey button. Ready: green.
  const shutterBorder = klaar ? GROEN : 'rgba(236,231,218,.55)';
  const shutterFill   = phase === 'count' ? 'var(--rose)' : klaar ? GROEN : 'rgba(236,231,218,.35)';

  return (
    <div className="scr scr--dark" style={{ background: '#13160f' }}>
      {/* Camera feed as a scanning device, not a photo (Marit 2026-11-12:
          "livebeeld ook blur en een filter, maar je moet nog wel duidelijk de
          positie kunnen zien"): grey, softly blurred so skin, face and
          intimate detail fall away, with extra contrast so her outline and
          pose stay clear, and a brand tint with scan lines on top. A little
          sharper for the hand close-ups. CSS only: the photo itself is taken
          sharp. */}
      <video ref={camera.videoRef} autoPlay playsInline muted
        style={{
          position: 'absolute', inset: 0, width: '100%', height: '100%',
          objectFit: 'cover', background: '#0e0f0a',
          opacity: camera.ready && phase !== 'review' && phase !== 'rotating' ? 1 : 0,
          filter: handHelder ? 'none'
            : String(angle.key || '').startsWith('hand_')
            ? 'grayscale(1) blur(3px) contrast(1.35) brightness(0.92)'
            : 'grayscale(1) blur(6px) contrast(1.6) brightness(0.9)',
          transition: 'opacity .25s, filter .3s',
        }} />
      {camera.ready && (phase === 'aim' || phase === 'count') && BODY_KEYS.includes(angle.key) && (
        <LiveOmtrek videoRef={camera.videoRef} scant={phase === 'count'} onAfstand={setAfstand} />
      )}
      {camera.ready && phase !== 'review' && phase !== 'rotating' && !handHelder && (
        <>
          <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 1, background: 'var(--rose)', mixBlendMode: 'color', opacity: 0.38 }} />
          <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 1, background: 'repeating-linear-gradient(0deg, transparent, transparent 3px, rgba(0,0,0,.10) 3px, rgba(0,0,0,.10) 4px)' }} />
        </>
      )}
      {/* The scan look (raster, sweep, "Scanning") only once the button is
          pressed, during the countdown. Before, it ran while still aiming and
          suggested the app was already scanning (Marit 2026-11-11). */}
      {phase === 'count' && camera.ready && (
        <>
          {/* Horizontal raster overlay — mimics scanner CCD line structure */}
          <div style={{
            position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 2,
            background: 'repeating-linear-gradient(0deg, transparent, transparent 3px, rgba(0,0,0,.08) 3px, rgba(0,0,0,.08) 4px)',
          }} />
          {/* Sweep beam: 80px tall, bright gold line at the leading edge with a
              glowing wake above it. Bounces top-to-bottom continuously. */}
          <div style={{
            position: 'absolute', left: 0, right: 0, top: 0, height: 80,
            background: 'linear-gradient(180deg, transparent 0%, rgba(229,207,136,.06) 50%, rgba(229,207,136,.32) 82%, rgba(245,220,110,.95) 96%, rgba(255,240,140,1) 100%)',
            boxShadow: '0 6px 30px 12px rgba(229,207,136,.35)',
            animation: 'scan-sweep 2.5s ease-in-out infinite alternate',
            pointerEvents: 'none', zIndex: 3,
          }} />
          {/* Scanning badge — bottom-right, above shutter */}
          <div style={{
            position: 'absolute', bottom: 118, right: 20, zIndex: 4,
            display: 'flex', alignItems: 'center', gap: 6,
            padding: '5px 11px 5px 9px', borderRadius: 6,
            background: 'rgba(14,15,10,.78)',
            border: '1px solid rgba(229,207,136,.24)',
            fontSize: 10, letterSpacing: '.14em', fontWeight: 700,
            color: 'rgba(229,207,136,.82)', textTransform: 'uppercase',
            pointerEvents: 'none',
          }}>
            <span style={{
              width: 6, height: 6, borderRadius: '50%', flexShrink: 0,
              background: 'rgba(229,207,136,.9)',
              animation: 'scan-dot 1s ease-in-out infinite alternate',
              display: 'inline-block',
            }} />
            {t('Scanning')}
          </div>
        </>
      )}
      {(!camera.ready || phase === 'review' || phase === 'rotating') && (
        <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(120% 80% at 50% 38%, #2a2c20 0%, #1a1c14 55%, #0e0f0a 100%)' }} />
      )}
      {/* Soft top + bottom vignette so the framing guide stays legible
          regardless of the camera scene's brightness. */}
      <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', background: 'linear-gradient(180deg, rgba(0,0,0,.45) 0%, transparent 22% 72%, rgba(0,0,0,.55) 100%)' }} />

      {/* No camera, no scan. Without a live frame the photos would be blank,
          so we stop the flow here and say what to do. */}
      {(cameraBlocked || camera.error) && (
        <div style={{ position: 'absolute', inset: 0, zIndex: 20, background: 'rgba(14,15,10,.92)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
          <div style={{ maxWidth: 340, textAlign: 'center' }}>
            <div style={{ fontSize: 30, marginBottom: 10 }}>📷</div>
            <h2 style={{ fontSize: 19, fontWeight: 700, marginBottom: 10, color: 'var(--on-dark)' }}>
              {t('We cannot reach your camera')}
            </h2>
            <p style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--on-dark-mute)', marginBottom: 8 }}>
              {camera.error === 'no-camera'
                ? t('This device does not seem to have a camera. Please continue on your phone.')
                : t('Allow camera access and try again.')}
            </p>
            <p style={{ fontSize: 13, lineHeight: 1.6, color: 'var(--on-dark-mute)', marginBottom: 18 }}>
              {t('If you opened this from inside another app, such as Instagram or Facebook, open it in Chrome or Safari instead. Those apps block the camera.')}
            </p>
            <button
              type="button"
              onClick={() => { setCameraBlocked(false); try { location.reload(); } catch (e) {} }}
              style={{ padding: '11px 22px', borderRadius: 999, border: '1px solid rgba(236,231,218,.3)', background: 'transparent', color: 'var(--on-dark)', fontSize: 14, fontWeight: 600, cursor: 'pointer' }}
            >
              {t('Try again')}
            </button>
          </div>
        </div>
      )}

      {phase !== 'review' && phase !== 'rotating' && (
        <FramingGuide angleKey={angle.key} frame={frameState}
          midLabel={ctx && ctx.capture && ctx.capture.scanMode === 'seated' ? 'her middle' : 'her hips'} />
      )}

      {/* top status */}
      <div style={{ position: 'relative', padding: '8px 20px 0' }}>
        <TopBar onBack={() => ctx.back()} dark onHelp={ctx.onHelp} />
        <div style={{ display: 'flex', gap: 7, justifyContent: 'center', marginTop: 2 }}>
          {angles.map((a, i) => (
            <div key={`${a.key}-${a.takeIdx ?? 0}-${a.locationIdx ?? 0}`} style={{
              flex: 1, maxWidth: 56, height: 4, borderRadius: 999,
              background: i < approved ? 'var(--rose)' : i === shot ? 'rgba(236,231,218,.65)' : 'rgba(236,231,218,.2)',
              transition: 'background .3s',
            }} />
          ))}
        </div>
      </div>

      {/* Which photo this is, in one short line under the progress bar. The
          full instruction opens on a tap, so the frame stays clear. */}
      {phase !== 'review' && phase !== 'rotating' && !plekUitleg && (
        <div style={{ position: 'relative', textAlign: 'center', marginTop: 8, zIndex: 3 }} className="fadein" key={angle.key}>
          <button type="button" onClick={() => setUitlegOpen((o) => !o)} style={{
            display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 14px', borderRadius: 999, cursor: 'pointer',
            background: 'rgba(20,22,15,.6)', border: '1px solid rgba(236,231,218,.16)', backdropFilter: 'blur(4px)', color: 'var(--on-dark)',
          }}>
            <span className="serif-num" style={{ color: 'var(--gold-soft)', fontSize: 16 }}>{String(shot + 1).padStart(2, '0')}</span>
            <span style={{ fontWeight: 700, fontSize: 14 }}>{angle.label}</span>
            <span style={{ fontSize: 12, color: 'var(--on-dark-mute)' }}>{uitlegOpen ? t('close') : t('how?')}</span>
          </button>
          {/* Hand close-ups (Marit 2026-11-19): which hand and how close, big. */}
          {phase === 'aim' && isHandFoto && (
            <div style={{ marginTop: 8 }}>
              <div style={{ fontSize: 26, fontWeight: 800, color: '#fff', textShadow: '0 2px 12px rgba(0,0,0,.6)', letterSpacing: '.02em' }}>
                {angle.key === 'hand_left' ? t('LEFT HAND') : t('RIGHT HAND')}
              </div>
              <span style={{ display: 'inline-block', marginTop: 4, padding: '5px 14px', borderRadius: 999, fontSize: 16, fontWeight: 700,
                background: handHelder ? 'rgba(46,125,70,.85)' : 'rgba(20,22,15,.75)', color: '#fff', border: '1px solid rgba(236,231,218,.25)' }}>
                {handHelder ? t('30 cm, good') : t('30 cm away, come closer')}
              </span>
            </div>
          )}
          {/* Always in view: the distance (Marit 2026-11-19). Green when the
              measured distance is right. */}
          {phase === 'aim' && BODY_KEYS.includes(angle.key) && !teDichtbij && (
            <div style={{ marginTop: 6 }}>
              <span style={{
                display: 'inline-block', padding: '5px 12px', borderRadius: 999, fontSize: 13, fontWeight: 700,
                background: afstand === 'goed' ? 'rgba(46,125,70,.85)' : 'rgba(20,22,15,.7)',
                color: '#fff', border: '1px solid rgba(236,231,218,.2)',
              }}>
                {afstand === 'goed' ? t('Good distance') : afstand === 'te_ver' ? t('One step closer') : t('1.5 m away, 2 big steps')}
              </span>
            </div>
          )}
          {uitlegOpen && (
            <div onClick={() => setUitlegOpen(false)} style={{
              margin: '8px 20px 0', padding: '12px 14px', borderRadius: 14, textAlign: 'left',
              background: 'rgba(20,22,15,.86)', border: '1px solid rgba(236,231,218,.16)', backdropFilter: 'blur(6px)',
              fontSize: 13.5, lineHeight: 1.5, color: 'var(--on-dark)',
            }}>
              {angle.instruct}
              {!['hand_left', 'hand_right'].includes(angle.key) && (
                <div style={{ marginTop: 6, color: 'var(--on-dark-mute)', fontSize: 12.5 }}>
                  {t('About 1.5 metres away, phone upright at her hip height, her hips on the middle line. You stay on the same spot for all four photos.')}
                </div>
              )}
            </div>
          )}
        </div>
      )}

      {/* Before the first photo: where to stand. There was no distance
          guidance at all before (Marit 2026-11-11). */}
      {plekUitleg && (
        <div style={{ position: 'absolute', inset: 0, zIndex: 6, display: 'flex', alignItems: 'center', justifyContent: 'center',
          background: 'rgba(11,12,8,.8)', backdropFilter: 'blur(4px)', padding: '0 26px' }} className="fadein">
          <div style={{ maxWidth: 360, color: 'var(--on-dark)' }}>
            <div className="eyebrow" style={{ color: 'var(--gold-soft)' }}>{t('Before the first photo')}</div>
            {/* Most people do not read (Marit 2026-11-19): the distance is the
                one thing that has to land, so it comes first and big. */}
            <h3 style={{ fontFamily: 'var(--serif)', fontWeight: 500, fontSize: 34, color: 'var(--paper)', margin: '10px 0 4px', lineHeight: 1.1 }}>
              {t('2 big steps away.')}
            </h3>
            <div style={{ fontSize: 17, color: '#e5cf88', fontWeight: 700, marginBottom: 16 }}>{t('1.5 metres. Never closer.')}</div>
            {[
              ['Phone at her hip height', 'Held straight upright. Kneeling down makes it easier.'],
              ['Feet do not fit?', 'Step back. Never tilt the phone.'],
              ['Stay on this spot', 'For all four photos. Only she turns.'],
            ].map(([kop, tekst], i) => (
              <div key={i} style={{ display: 'flex', gap: 12, marginBottom: 12 }}>
                <span className="serif-num" style={{ color: 'var(--gold-soft)', fontSize: 18, lineHeight: 1.2, flex: '0 0 auto' }}>{i + 1}</span>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 15 }}>{t(kop)}</div>
                  <div style={{ fontSize: 13.5, color: 'var(--on-dark-mute)', lineHeight: 1.45 }}>{t(tekst)}</div>
                </div>
              </div>
            ))}
            <button type="button" onClick={() => setPlekGezien(true)} style={{
              marginTop: 10, width: '100%', padding: '14px 20px', borderRadius: 999, border: 'none',
              background: '#e5cf88', color: '#1a1c14', fontSize: 15, fontWeight: 700, cursor: 'pointer',
            }}>
              {t('We are 2 steps apart')}
            </button>
          </div>
        </div>
      )}

      {/* Too close: impossible to miss, in the middle of the screen (Marit
          2026-11-19). No reading needed: an arrow and three words. */}
      {teDichtbij && (
        <div style={{ position: 'absolute', inset: 0, zIndex: 5, display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
          <div className="fadein" style={{ textAlign: 'center', padding: '22px 26px', borderRadius: 24, background: 'rgba(150,40,30,.82)', color: '#fff', boxShadow: '0 10px 40px rgba(0,0,0,.45)', maxWidth: 300 }}>
            <svg width="64" height="64" viewBox="0 0 64 64" aria-hidden="true" style={{ display: 'block', margin: '0 auto 6px' }}>
              <path d="M32 8 L32 52 M14 34 L32 54 L50 34" fill="none" stroke="#fff" strokeWidth="6" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
            <div style={{ fontSize: 30, fontWeight: 800, letterSpacing: '.02em', lineHeight: 1.1 }}>{t('Too close')}</div>
            <div style={{ fontSize: 19, fontWeight: 600, marginTop: 6 }}>{t('Take 2 big steps back')}</div>
          </div>
        </div>
      )}
      {/* countdown */}
      {phase === 'count' && (
        <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
          <div key={count} className="serif-num" style={{
            fontSize: 132, color: 'var(--paper)', textShadow: '0 4px 30px rgba(0,0,0,.5)',
            animation: 'cnt .82s ease both',
          }}>{count}</div>
        </div>
      )}

      <div className="grow" />

      {/* shutter / hint */}
      {phase !== 'review' && phase !== 'rotating' && (
        <div style={{ position: 'relative', padding: '0 26px 26px', textAlign: 'center' }}>
          <p style={{ fontSize: klaar ? 15 : 13, fontWeight: klaar ? 700 : 400, color: klaar ? '#7fdc9f' : 'var(--on-dark-mute)', margin: '0 0 4px', minHeight: 18, transition: 'color .3s' }}>
            {hint}
          </p>
          <div style={{ height: 10 }} />
          <button onClick={onShutter} aria-label={t('Capture')}
            disabled={phase === 'count' || !camera.ready}
            style={{
              width: 76, height: 76, borderRadius: 999, margin: '0 auto',
              cursor: (phase === 'count' || !camera.ready) ? 'default' : 'pointer',
              border: `4px solid ${shutterBorder}`,
              background: 'transparent', padding: 4, display: 'flex',
              transition: 'border-color .3s, opacity .3s, transform .15s, box-shadow .3s',
              opacity: phase === 'count' ? .5 : camera.ready ? 1 : .55,
              transform: klaar ? 'scale(1.08)' : 'scale(1)',
              boxShadow: klaar ? '0 0 30px rgba(63,174,106,.65)' : 'none',
            }}>
            <span style={{
              flex: 1, borderRadius: 999, background: shutterFill,
              transition: 'background .25s',
            }} />
          </button>
        </div>
      )}

      {/* flash */}
      {flash && <div style={{ position: 'absolute', inset: 0, background: '#fff', animation: 'flash .22s ease both' }} />}

      {/* toast checkpoint */}
      {toast && (
        <div style={{ position: 'absolute', top: 92, left: '50%', transform: 'translateX(-50%)', display: 'flex', alignItems: 'center', gap: 8, padding: '9px 16px', borderRadius: 999, background: 'var(--ink)', color: 'var(--paper)', fontSize: 13.5, fontWeight: 600, boxShadow: '0 10px 30px rgba(0,0,0,.4)', animation: 'scr-in .3s ease both', zIndex: 7 }}>
          <span style={{ display: 'flex', color: 'var(--rose)' }}><IcCheck size={16} /></span> {toast}
        </div>
      )}

      {/* rotation overlay between shots */}
      {phase === 'rotating' && (() => {
        const prevA = angles[(shot - 1 + angles.length) % angles.length];
        return (
          <RotationOverlay
            from={prevAngleKey || 'front'}
            to={angle.key}
            instruct={prevA.nextInstruct}
            hold={false}
            onDone={() => setPhase('aim')}
          />
        );
      })()}

      {/* review sheet */}
      {phase === 'review' && (
        <ReviewSheet angle={angle} failed={reviewFailed} onApprove={approve} onRetake={retake} idx={shot} total={angles.length} frameSrc={reviewFrame} analyse={analyse} bewogen={bewogen} modelBewogen={modelBewogen} beweging={beweging}
          handTeLaag={handOordeel === 'te_laag'} />
      )}
    </div>
  );
}

// ── Pose analysis view (Marit 2026-11-12) ─────────────────────
// "Only her pose matters; it should not feel naked or intimate to send in."
// The photo is shown dimmed, grey and softly blurred, still clearly a photo.
// On top: the outline of her body in glowing blue, red dots blinking on her
// joints, and the head pixelated. The sharpness is checked by the app (see
// ReviewSheet), so nobody has to judge it through the filter. Display only:
// the photo that is uploaded stays as taken (apart from the blurred face).
// Until the analysis is ready, a heavily blurred version shows, never the
// bare photo.
// Faster than this (degrees per second) just before the shot = the phone
// moved (Marit 2026-11-12). Held still by hand is usually under 15.
const BEWEGING_MAX = 20; // was 35; still in scan 9 (12-11): 2.6 to 5.5
// Moving back and forth: stronger than this (m/s2, without gravity) = moved.
// Held still by hand is usually under 0.5.
const VERSNELLING_MAX = 0.9; // was 1.5; still in scan 9: 0.14 to 0.37
// Did SHE move? (Marit 2026-11-12: "het gaat om het model dat beweegt").
// While aiming and counting down the app follows her pose for the blue
// outline; the last 0.7 s are kept in window.houdingSpoor. Her shoulders,
// hips and knees in the first half are compared with the second half: the
// middle shift, as a share of her height. Standing still stays well under
// this; swaying or stepping goes over it.
// Was 2.5%: far too lenient (Marit 12-11: "echt heel veel gevoeliger"); standing
// still in scan 9 gave 0.3 to 0.5%.
const MODEL_BEWEGING_MAX = 0.01;
const SPOOR_PUNTEN = [11, 12, 23, 24, 25, 26];
function modelBeweging(ms = 700) {
  const nu = performance.now();
  const spoor = (window.houdingSpoor || []).filter((s) => nu - s.t <= ms && s.p);
  if (spoor.length < 4) return null;
  const midden = (spoor[0].t + spoor[spoor.length - 1].t) / 2;
  const eerst = spoor.filter((s) => s.t <= midden), daarna = spoor.filter((s) => s.t > midden);
  if (!eerst.length || !daarna.length) return null;
  const ok = (q) => q && (q.visibility == null || q.visibility > 0.5);
  const gem = (lijst, i) => {
    const z = lijst.map((s) => ({ q: s.p[i], a: s.aspect })).filter((v) => ok(v.q));
    if (!z.length) return null;
    return { x: z.reduce((t, v) => t + v.q.x * v.a, 0) / z.length, y: z.reduce((t, v) => t + v.q.y, 0) / z.length };
  };
  // Her height in the picture: shoulders to ankles, or shoulders to hips x 2.6.
  const p = spoor[spoor.length - 1].p;
  const sy = ok(p[11]) && ok(p[12]) ? (p[11].y + p[12].y) / 2 : null;
  const ey = ok(p[27]) && ok(p[28]) ? (p[27].y + p[28].y) / 2 : null;
  const hy = ok(p[23]) && ok(p[24]) ? (p[23].y + p[24].y) / 2 : null;
  const hoogte = sy != null && ey != null ? ey - sy : sy != null && hy != null ? (hy - sy) * 2.6 : null;
  if (!hoogte || hoogte <= 0.05) return null;
  const v = SPOOR_PUNTEN.map((i) => { const a = gem(eerst, i), b = gem(daarna, i); return a && b ? Math.hypot(a.x - b.x, a.y - b.y) : null; })
    .filter((x) => x != null).sort((a, b) => a - b);
  if (v.length < 3) return null;
  return v[Math.floor(v.length / 2)] / hoogte;
}

// Test mode with the measurements on screen: open the app with ?meten=1.
try {
  if (new URLSearchParams(window.location.search).get('meten') === '1') sessionStorage.setItem('meten', '1');
} catch (e) {}
function meetStand() { try { return sessionStorage.getItem('meten') === '1'; } catch (e) { return false; } }
const POSE_PUNTEN = [11, 12, 13, 14, 15, 16, 23, 24, 25, 26, 27, 28];
const BLAUW = '120, 196, 255';

function AnalyseFoto({ src, label, analyse, skelet = true }) {
  const basisRef = useRef(null);
  const lagenRef = useRef(null);
  const [maat, setMaat] = useState(null); // { W, H } once the base is drawn
  useEffect(() => {
    let stop = false;
    setMaat(null);
    (async () => {
      const img = new Image();
      try {
        await new Promise((klaar, mis) => { img.onload = klaar; img.onerror = mis; img.src = src; });
      } catch (e) { return; }
      if (stop) return;
      const H = 640;
      const W = Math.max(1, Math.round((img.naturalWidth / img.naturalHeight) * H));
      const c = basisRef.current;
      if (!c) return;
      c.width = W; c.height = H;
      const ctx = c.getContext('2d');
      ctx.filter = 'grayscale(1) blur(2.5px) brightness(.62) contrast(1.15)';
      ctx.drawImage(img, 0, 0, W, H);
      ctx.filter = 'none';
      if (!stop) setMaat({ W, H });
    })();
    return () => { stop = true; };
  }, [src]);

  // Head blur on the base, once the analysis is in.
  useEffect(() => {
    const c = basisRef.current;
    // No head on the hand close-ups: never blur part of a hand there.
    if (!c || !maat || !analyse || !analyse.hoofd || !skelet) return;
    const { W, H } = maat, g = analyse.hoofd;
    const ctx = c.getContext('2d');
    const cx = g.cx * W, cy = g.cy * H, rx = g.rx * W, ry = g.ry * H;
    const x0 = Math.max(0, Math.round(cx - rx)), y0 = Math.max(0, Math.round(cy - ry));
    const bw = Math.min(W - x0, Math.round(rx * 2)), bh = Math.min(H - y0, Math.round(ry * 2));
    if (bw < 4 || bh < 4) return;
    const blok = Math.max(8, Math.round(rx / 3));
    const klein = document.createElement('canvas');
    klein.width = Math.max(1, Math.round(bw / blok)); klein.height = Math.max(1, Math.round(bh / blok));
    klein.getContext('2d').drawImage(c, x0, y0, bw, bh, 0, 0, klein.width, klein.height);
    ctx.save();
    ctx.beginPath(); ctx.ellipse(cx, cy, rx, ry, 0, 0, Math.PI * 2); ctx.clip();
    ctx.imageSmoothingEnabled = false;
    ctx.filter = 'blur(2px)';
    ctx.drawImage(klein, 0, 0, klein.width, klein.height, x0, y0, bw, bh);
    ctx.restore();
  }, [maat, analyse, skelet]);

  // Animated layer: the blue outline breathing, red dots blinking.
  useEffect(() => {
    const c = lagenRef.current;
    if (!c || !maat) return undefined;
    const { W, H } = maat;
    c.width = W; c.height = H;
    const ctx = c.getContext('2d');
    let raf = 0;
    const teken = (t) => {
      raf = requestAnimationFrame(teken);
      ctx.clearRect(0, 0, W, H);
      if (!analyse) return;
      const rand = (analyse.omtrek && analyse.omtrek.rand) || [];
      if (rand.length) {
        const golf = 0.55 + 0.45 * Math.sin(t / 380);
        ctx.fillStyle = `rgba(${BLAUW}, ${0.5 + 0.4 * golf})`;
        ctx.shadowColor = `rgba(${BLAUW}, .9)`;
        ctx.shadowBlur = 6 + 6 * golf;
        const r = Math.max(1.4, H / 380);
        for (let i = 0; i < rand.length; i++) {
          ctx.beginPath(); ctx.arc(rand[i][0] * W, rand[i][1] * H, r, 0, Math.PI * 2); ctx.fill();
        }
        ctx.shadowBlur = 0;
      }
      const p = analyse.p;
      if (skelet && p) {
        const zicht = (i) => p[i] && (p[i].visibility == null || p[i].visibility > 0.4);
        POSE_PUNTEN.forEach((i, k) => {
          if (!zicht(i)) return;
          const aan = 0.5 + 0.5 * Math.sin(t / 220 + k * 1.3);
          const x = p[i].x * W, y = p[i].y * H, r = Math.max(3, H / 120);
          ctx.fillStyle = `rgba(255, 70, 70, ${0.15 + 0.35 * aan})`;
          ctx.beginPath(); ctx.arc(x, y, r * (1.8 + 1.2 * aan), 0, Math.PI * 2); ctx.fill();
          ctx.fillStyle = `rgba(255, 70, 70, ${0.55 + 0.45 * aan})`;
          ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill();
        });
      }
    };
    raf = requestAnimationFrame(teken);
    return () => cancelAnimationFrame(raf);
  }, [maat, analyse, skelet]);

  const laag = { position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'contain', display: 'block' };
  return (
    <div style={{ position: 'absolute', inset: 0 }}>
      {(!maat || analyse === undefined) && (
        <img src={src} alt="" aria-hidden="true"
          style={{ ...laag, filter: 'grayscale(1) blur(22px) brightness(.7)', transform: 'scale(1.08)', zIndex: 2 }} />
      )}
      <canvas ref={basisRef} aria-label={t('{label} captured, shown as a pose analysis', { label })} style={{ ...laag, opacity: maat && analyse !== undefined ? 1 : 0, transition: 'opacity .25s' }} />
      <canvas ref={lagenRef} aria-hidden="true" style={{ ...laag, pointerEvents: 'none' }} />
      <span style={{ position: 'absolute', left: 10, top: 10, zIndex: 3, fontSize: 10.5, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--on-dark, #ece7da)', background: 'rgba(11,12,8,.55)', padding: '4px 8px', borderRadius: 6 }}>
        {analyse === undefined ? t('Analysing...') : t('Pose analysis')}
      </span>
    </div>
  );
}

// How sharp is sharp enough (Marit 2026-11-19: "de derde foto blijft maar
// aangeven too blurry"). The measure counts crisp edges; a bare back has few
// (no face, hands or clothing), so it scores lower while being just as sharp.
// In scan 9: front 7.25, sides 13, back 6.5, with a fixed limit of 5. Now:
// the back has its own lower limit, and once there are earlier photos in this
// scan, a photo only has to reach 60% of their median (never above the fixed
// limit, never below 2.5).
const SCHERP_GRENS = 5;
const SCHERP_GRENS_RUG = 3.5;
function scherpGrens(key, eerder) {
  let grens = key === 'back' ? SCHERP_GRENS_RUG : SCHERP_GRENS;
  if (eerder.length) {
    const r = [...eerder].sort((a, b) => a - b);
    const mediaan = r.length % 2 ? r[(r.length - 1) / 2] : (r[r.length / 2 - 1] + r[r.length / 2]) / 2;
    grens = Math.min(grens, 0.6 * mediaan);
  }
  return Math.max(2.5, grens);
}

// Hand close-ups (Marit 2026-11-19): the filter comes off only when the phone
// is so close that just the hand (and the belly under it) is in view, never
// suddenly a whole body. Body in view = her face, or a shoulder and a hip,
// inside the frame. No answer from the model = keep the filter.
function lichaamInBeeld(p) {
  if (!p || !p.length) return false;
  const binnen = (i) => p[i] && (p[i].visibility == null || p[i].visibility > 0.5)
    && p[i].y >= 0 && p[i].y <= 1 && p[i].x >= 0 && p[i].x <= 1;
  if ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].some(binnen)) return true;
  return [11, 12].some(binnen) && [23, 24].some(binnen);
}

// Follows the live camera for the hand close-ups: true while a body is in
// view (or nothing is known yet), false once only the hand is. Changes after
// 3 readings in a row, so it does not flicker.
function useLichaamInBeeld(videoRef, actief) {
  const [inBeeld, setInBeeld] = useState(true);
  useEffect(() => {
    setInBeeld(true);
    const v = videoRef.current;
    if (!actief || !v || !window.handCheck || !window.handCheck.volg) return undefined;
    let kandidaat = true, reeks = 0, getoond = true;
    const stop = window.handCheck.volg(v, (r) => {
      const a = lichaamInBeeld(r.p);
      if (a === kandidaat) reeks++; else { kandidaat = a; reeks = 1; }
      if (reeks >= 3 && a !== getoond) { getoond = a; setInBeeld(a); }
    });
    return () => { stop(); };
  }, [actief, videoRef]); // eslint-disable-line react-hooks/exhaustive-deps
  return inBeeld;
}

// Distance from the live pose points (Marit 2026-11-19: "sommige mensen
// lezen NIETS"; the partner skipped every instruction and walked up close to
// get her in the frame). Measured on the whole camera frame, which is also
// what the photo captures. Points are 0..1 from the top of the frame.
//   'te_dichtbij'  head or feet fall outside the frame, or she fills it
//   'te_ver'       she is small in the frame
//   'goed'         head to feet inside, a sensible size
//   null           nobody found: say nothing, never guess
// Seen from behind the face points are not visible; then the top of her head
// is estimated from the shoulders and hips.
function afstandUit(p) {
  if (!p || !p.length) return null;
  const zicht = (i) => p[i] && (p[i].visibility == null || p[i].visibility > 0.5);
  const binnen = (i) => zicht(i) && p[i].y >= 0 && p[i].y <= 1 && p[i].x >= 0 && p[i].x <= 1;
  const sch = [11, 12].filter(zicht), heup = [23, 24].filter(zicht);
  if (!sch.length && !heup.length) return null;
  const gem = (ids) => ids.reduce((t, i) => t + p[i].y, 0) / ids.length;
  const kop = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].filter(binnen);
  let top;
  if (kop.length) top = Math.min(...kop.map((i) => p[i].y)) - 0.03;
  else if (sch.length && heup.length) top = gem(sch) - 0.45 * (gem(heup) - gem(sch));
  else return null;
  // Feet: ankles, heels and toes. Predicted below the frame = cut off.
  const voet = [27, 28, 29, 30, 31, 32].filter((i) => p[i]);
  const voetBinnen = voet.filter(binnen);
  const voetBuiten = voet.some((i) => p[i].y > 1.0);
  if (top < 0 || voetBuiten) return 'te_dichtbij';
  // Feet hidden but not cut off (behind a bed, a chair): we cannot tell.
  if (!voetBinnen.length) return null;
  const onder = Math.max(...voetBinnen.map((i) => p[i].y));
  const hoogte = onder - top;
  if (hoogte > 0.92 || onder > 0.985) return 'te_dichtbij';
  if (hoogte < 0.45) return 'te_ver';
  return 'goed';
}

// Live outline (Marit 2026-11-12): while aiming and scanning, the outline of
// the person glows blue over the camera, so it is clear who is being scanned
// and whether she fits the frame. Runs on the phone; nothing is sent.
function LiveOmtrek({ videoRef, scant, onAfstand }) {
  const ref = useRef(null);
  useEffect(() => {
    const v = videoRef.current, c = ref.current;
    if (!v || !c || !window.handCheck || !window.handCheck.volg) return undefined;
    let laatste = { rand: [] };
    window.houdingSpoor = [];
    // Only change the distance after 3 readings in a row (about 0.4 s), so it
    // does not flicker while he walks.
    let kandidaat = null, reeks = 0, getoond;
    const stopVolg = window.handCheck.volg(v, (r) => {
      laatste = r;
      if (onAfstand) {
        const a = afstandUit(r.p);
        if (a === kandidaat) reeks++; else { kandidaat = a; reeks = 1; }
        if (reeks >= 3 && a !== getoond) { getoond = a; onAfstand(a); }
      }
      // Her pose over time, for "did she move" at the moment of the photo.
      if (r.p && v.videoHeight) {
        const nu = performance.now();
        window.houdingSpoor.push({ t: nu, p: r.p, aspect: v.videoWidth / v.videoHeight });
        while (window.houdingSpoor.length && nu - window.houdingSpoor[0].t > 2000) window.houdingSpoor.shift();
      }
    });
    const ctx = c.getContext('2d');
    let raf = 0;
    const teken = (t) => {
      raf = requestAnimationFrame(teken);
      const cw = c.clientWidth, ch = c.clientHeight;
      if (!cw || !ch) return;
      if (c.width !== cw || c.height !== ch) { c.width = cw; c.height = ch; }
      ctx.clearRect(0, 0, cw, ch);
      const vw = v.videoWidth, vh = v.videoHeight;
      if (!vw || !vh || !laatste.rand.length) return;
      // The video is shown with object-fit: cover.
      const sch = Math.max(cw / vw, ch / vh);
      const ox = (cw - vw * sch) / 2, oy = (ch - vh * sch) / 2;
      const golf = 0.55 + 0.45 * Math.sin(t / (scant ? 160 : 420));
      ctx.fillStyle = `rgba(${BLAUW}, ${0.45 + 0.45 * golf})`;
      ctx.shadowColor = `rgba(${BLAUW}, .95)`;
      ctx.shadowBlur = 8 + 8 * golf;
      const r = 1.8;
      for (const [x, y] of laatste.rand) {
        ctx.beginPath(); ctx.arc(ox + x * vw * sch, oy + y * vh * sch, r, 0, Math.PI * 2); ctx.fill();
      }
      ctx.shadowBlur = 0;
    };
    raf = requestAnimationFrame(teken);
    return () => { stopVolg(); cancelAnimationFrame(raf); if (onAfstand) onAfstand(null); };
  }, [videoRef, scant]); // eslint-disable-line react-hooks/exhaustive-deps
  return <canvas ref={ref} aria-hidden="true" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none', zIndex: 2 }} />;
}

function ReviewSheet({ angle, failed, onApprove, onRetake, idx, total, frameSrc, handTeLaag = false, analyse, bewogen = false, modelBewogen = false, beweging = null }) {
  const isHand = String(angle.key || '').startsWith('hand_');
  // The app judges sharpness, not the person: through the filter you cannot
  // see it. Moved phone (motion sensor) or soft edges (image) = not sharp.
  const scherp = bewogen || modelBewogen ? 'wazig'
    : analyse === undefined ? 'bezig' : analyse && analyse.scherp === false ? 'wazig' : analyse && analyse.scherp ? 'scherp' : 'onbekend';
  return (
    <div style={{ position: 'absolute', inset: 0, background: 'rgba(11,12,8,.55)', backdropFilter: 'blur(3px)', display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', zIndex: 6 }}>
      <div className="fadein" style={{ background: 'var(--paper)', borderRadius: '26px 26px 0 0', padding: 22, color: 'var(--ink)' }}>
        <div style={{ width: 38, height: 4, borderRadius: 999, background: 'var(--hairline)', margin: '0 auto 16px' }} />
        {/* The whole photo, but as a "pose analysis" (Marit 2026-11-12): her
            pose stays clear, skin and intimate detail do not, and the head is
            blurred. Only the view: the photo that is sent stays the original. */}
        <div style={{ borderRadius: 16, overflow: 'hidden', position: 'relative', height: '46vh', minHeight: 220, background: '#0e0f0a' }}>
          {frameSrc
            ? <AnalyseFoto src={frameSrc} label={angle.label} analyse={analyse} skelet={!isHand} />
            : <Placeholder label={t('{label} · captured', { label: angle.label.toLowerCase() })} dark />}
          {failed && <div style={{ position: 'absolute', inset: 0, background: 'rgba(8,9,6,.45)' }} />}
        </div>

        {failed ? (
          <>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 16 }}>
              <span className="tag" style={{ background: 'color-mix(in oklch, var(--rose), transparent 84%)', borderColor: 'color-mix(in oklch, var(--rose), transparent 64%)', color: 'var(--rose-deep)' }}>
                <IcSun size={14} /> {t('A little underexposed')}
              </span>
            </div>
            <h3 className="title" style={{ fontSize: 21, marginTop: 12 }}>{t("Let's catch more light.")}</h3>
            <p className="lede" style={{ fontSize: 14.5, marginTop: 6 }}>
              {t("The right side fell into shadow. Turn the subject a touch toward the window, then we'll take this one again.")}
            </p>
            <button className="btn btn--primary" style={{ marginTop: 16 }} onClick={onRetake}>
              <IcRetake size={18} /> {t('Retake this photo')}
            </button>
          </>
        ) : (
          <>
            {handTeLaag ? (
              <>
                {/* The lower hand is below the belly, near the pubic area: retake. */}
                <h3 className="title" style={{ fontSize: 21, marginTop: 16 }}>{t('Her lower hand is too low.')}</h3>
                <p className="lede" style={{ fontSize: 14.5, marginTop: 6 }}>
                  {t('Both hands stay on her belly, the lower hand never below it. Ask her to move it up a little, then take this photo again.')}
                </p>
                <button className="btn btn--accent" style={{ marginTop: 16 }} onClick={onRetake}>
                  <IcRetake size={18} /> {t('Retake this photo')}
                </button>
                <button className="linkbtn" style={{ display: 'block', margin: '12px auto 0' }} onClick={onApprove}>
                  {t('Her hands are fine, keep it')}
                </button>
              </>
            ) : (
              <>
                <div style={{ marginTop: 14 }}>
                  {scherp === 'bezig' && <span className="tag">{t('Checking sharpness...')}</span>}
                  {scherp === 'scherp' && (
                    <span className="tag" style={{ background: 'color-mix(in oklch, #3c8c5a, transparent 85%)', borderColor: 'color-mix(in oklch, #3c8c5a, transparent 60%)', color: '#2f6e47' }}>
                      <IcCheck size={14} /> {t('Sharp')}
                    </span>
                  )}
                  {scherp === 'wazig' && (
                    <span className="tag" style={{ background: 'color-mix(in oklch, var(--rose), transparent 84%)', borderColor: 'color-mix(in oklch, var(--rose), transparent 64%)', color: 'var(--rose-deep)' }}>
                      {t('Not sharp')}
                    </span>
                  )}
                </div>
                {meetStand() && (
                  <p style={{ margin: '8px 0 0', fontSize: 11.5, color: 'var(--ink-mute)', fontFamily: 'ui-monospace, Menlo, monospace' }}>
                    scherpte {analyse && analyse.scherpte != null ? analyse.scherpte : '?'} (min {analyse && analyse.grens != null ? analyse.grens.toFixed(1) : 5}) · draai {beweging && beweging.draai != null ? Math.round(beweging.draai) : 'geen sensor'} (max {BEWEGING_MAX}) · versnelling {beweging && beweging.versnelling != null ? beweging.versnelling.toFixed(2) : 'geen sensor'} (max {VERSNELLING_MAX}) · zij bewoog {beweging && beweging.model != null ? `${(beweging.model * 100).toFixed(1)}%` : '?'} (max {(MODEL_BEWEGING_MAX * 100).toFixed(1)}%)
                  </p>
                )}
                <h3 className="title" style={{ fontSize: 21, marginTop: 10 }}>{scherp === 'wazig' ? (modelBewogen ? t('She moved.') : bewogen ? t('The phone moved.') : t('This one is a little blurry.')) : t('Keep this one?')}</h3>
                <p className="lede" style={{ fontSize: 14.5, marginTop: 6 }}>
                  {scherp === 'wazig'
                    ? (modelBewogen
                      ? t('She moved a little while the photo was taken. Ask her to stand completely still, breathing calmly, until the photo is taken. Then take it again.')
                      : bewogen
                      ? t('The phone moved while the photo was taken, so it may be blurry. Hold it still until the photo is taken, then take it again.')
                      : t('Hold the phone still while it counts down, and make sure there is enough light. Then take it again.'))
                    : isHand
                      ? t('Check that the whole hand is in the photo, all fingers. We check the sharpness for you.')
                      : t('Check that her whole body is in the photo, head to feet. We check the sharpness for you.')}
                </p>
                {scherp === 'wazig' ? (
                  <>
                    <button className="btn btn--accent" style={{ marginTop: 16 }} onClick={onRetake}>
                      <IcRetake size={18} /> {t('Retake this photo')}
                    </button>
                    <button className="linkbtn" style={{ display: 'block', margin: '12px auto 0' }} onClick={onApprove}>
                      {t('Keep it anyway')}
                    </button>
                  </>
                ) : (
                  <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
                    <button className="btn btn--ghost" style={{ flex: 1 }} onClick={onRetake}>
                      <IcRetake size={18} /> {t('Retake')}
                    </button>
                    <button className="btn btn--accent" style={{ flex: 1.4 }} onClick={onApprove}>
                      <IcCheck size={18} /> {idx >= (total || ANGLES.length) - 1 ? t('Finish') : t('Keep & continue')}
                    </button>
                  </div>
                )}
              </>
            )}
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { CaptureScreen, FramingGuide, ReviewSheet, AngleSilhouette, RotationOverlay, ANGLES });
