// pose-detect.jsx — framing-detection hooks
//
// Two hooks here:
//   useFraming({angleKey, active})  → live state about whether the subject fits the guide
//   useDeviceLevel()                 → real gyroscope reading (no mock)
//
// useFraming does NOT detect the person. Until 2026-11-11 it played a fake
// progression ("in frame" → "a small step closer" → "locked") and the capture
// screen then took the photo by itself, whether or not anyone was framed
// (Marit: "it says it is scanning before you press the button"). Now it only
// reports what is really measured: the light (exposure). The photographer
// presses the button herself.
//
// To replace the mock with real detection, swap the body of `useFraming` for one
// of:
//   • Android native: ML Kit Pose Detection in the CameraX analyzer, post detected
//     keypoints (left/right shoulder, left/right hip) into the hook via setState.
//   • PWA fallback:   TensorFlow.js MoveNet over a <video> stream, same idea.
//
// The UI never cares which backend feeds it; it just reacts to the state shape.

const { useState: useF, useEffect: useFE, useRef: useFR } = React;

// Tuneable timings for the mock progression. In a real backend these are wall-clock
// observations of detection confidence; here we fake a believable curve.
const LOCK_HOLD_TO_AUTO_MS = 1500;  // kept for old references; there is no auto-capture any more

// Exposure thresholds, measured on average pixel luminance (0..255). Below
// TOO_DARK = too dim for a usable scan; above TOO_BRIGHT = blown highlights
// or overexposed. Sampled twice a second on a 16-pixel-wide downscaled
// snapshot of the live preview — cheap and indistinguishable from the
// luminance you'd get from a real ISP exposure meter for our purposes.
const TOO_DARK_LUMA    = 28;
const TOO_BRIGHT_LUMA  = 230;
const LUMA_SAMPLE_INTERVAL_MS = 500;
// No "light is too one-sided" check any more (Marit 2026-11-12: it came up
// on every other photo for no reason). It compared the brightest and darkest
// parts of the WHOLE picture, so a window, a lamp or dark furniture in view
// was enough, however well she herself was lit.
//
// Dark / bright only count once the camera has settled (it adjusts its
// exposure for a moment after every restart, and it restarts for every
// photo) and when it lasts: 4 samples in a row, about 2 seconds.
const SETTLE_MS     = 1500;
const STREAK_NEEDED = 4;

function useFraming({ angleKey, active, videoRef }) {
  const streakRef = useFR({ kind: 'ok', n: 0 });
  const startRef  = useFR(0);
  const [s, setS] = useF({
    inFrame:  false,      // subject visible in viewport
    distance: null,       // 'too_far' | 'too_close' | 'ok' | null
    locked:   false,      // subject fits guide, centered, pose stable
    lockMs:   0,          // ms the lock has been held (for auto-capture trigger)
    exposure: 'ok',       // 'too_dark' | 'too_bright' | 'ok'
    luma:     null,       // last measured avg luminance, for debugging
  });

  // Reset per angle. No person detection: inFrame stays true so the shutter
  // always works, distance is never guessed, and nothing ever "locks".
  useFE(() => {
    setS({ inFrame: true, distance: 'ok', locked: false, lockMs: 0, exposure: 'ok', luma: null });
  }, [angleKey, active]);

  // Real luminance sampling from the live video. Reads a small downscaled
  // snapshot every 500ms; if the average luminance falls outside our
  // [TOO_DARK_LUMA, TOO_BRIGHT_LUMA] band, we surface that as exposure.
  // Doesn't block the lock progression — a too-dark or too-bright lock can
  // still happen, the banner just tells the customer why the shot would be
  // unusable for the AI sculptor.
  useFE(() => {
    if (!active || !videoRef || !videoRef.current) return;
    startRef.current  = Date.now();
    streakRef.current = { kind: 'ok', n: 0 };
    let canceled = false;
    let canvas;  // reused across ticks
    let g;
    const sample = () => {
      if (canceled) return;
      const v = videoRef.current;
      if (!v || !v.videoWidth) return;
      try {
        if (!canvas) {
          canvas = document.createElement('canvas');
          canvas.width  = 16;
          canvas.height = Math.max(1, Math.round(16 * v.videoHeight / v.videoWidth));
          g = canvas.getContext('2d', { willReadFrequently: true });
        }
        if (!g) return;
        g.drawImage(v, 0, 0, canvas.width, canvas.height);
        const data = g.getImageData(0, 0, canvas.width, canvas.height).data;
        let total = 0, count = 0;
        for (let i = 0; i < data.length; i += 4) {
          // Rec.709 luma weights, integer-friendly.
          total += 0.2126 * data[i] + 0.7152 * data[i + 1] + 0.0722 * data[i + 2];
          count++;
        }
        const avg = count ? total / count : 0;

        let raw = 'ok';
        if (avg < TOO_DARK_LUMA)        raw = 'too_dark';
        else if (avg > TOO_BRIGHT_LUMA) raw = 'too_bright';
        const st = streakRef.current;
        if (st.kind === raw) st.n++; else { st.kind = raw; st.n = 1; }
        const settled  = Date.now() - startRef.current > SETTLE_MS;
        const exposure = raw !== 'ok' && settled && st.n >= STREAK_NEEDED ? raw : 'ok';

        setS((p) =>
          (p.exposure === exposure && Math.abs((p.luma ?? 0) - avg) < 2)
            ? p
            : { ...p, exposure, luma: Math.round(avg) });
      } catch (err) {
        // Cross-origin video or no frames yet — silently skip this tick.
      }
    };
    const id = setInterval(sample, LUMA_SAMPLE_INTERVAL_MS);
    sample();
    return () => { canceled = true; clearInterval(id); };
  }, [active, angleKey, videoRef]);

  return s;
}

// Read DeviceOrientation. Returns {levelOk, supported, tiltLR, tiltFB}.
//   beta  ≈ 90  when phone is vertical (portrait, screen facing user)
//   gamma ≈ 0   when phone is not tilted left/right
// We allow ±8° left/right and ±12° front/back before flagging.
// Movement meter (Marit 2026-11-12: "schudden geeft niet de melding
// onscherp"): how fast the phone turned in the last moments, in degrees per
// second, from the motion sensor (or, without it, from the change in
// orientation). Shaking the phone while the photo is taken shows up here
// even when the picture itself is hard to judge.
(function () {
  if (typeof window === 'undefined' || window.bewegingsMeter) return;
  const metingen = []; // [tijd, graden per seconde]
  const schokken = []; // [tijd, m/s2]: moving back and forth, without turning
  const bewaar = (v, lijst = metingen) => {
    const nu = performance.now();
    lijst.push([nu, v]);
    while (lijst.length && nu - lijst[0][0] > 2000) lijst.shift();
  };
  let viaMotion = false;
  let vorigeG = null;
  window.addEventListener('devicemotion', (e) => {
    // Shaking is mostly moving back and forth (Marit 2026-11-12: "flink
    // geshaked, maar alsnog komt ie erdoor"), so the acceleration counts too.
    const a = e.acceleration;
    if (a && (a.x != null || a.y != null || a.z != null)) {
      bewaar(Math.hypot(a.x || 0, a.y || 0, a.z || 0), schokken);
    } else if (e.accelerationIncludingGravity) {
      // Without a separate value: the change from one measurement to the next.
      const g = e.accelerationIncludingGravity;
      if (vorigeG) bewaar(Math.hypot((g.x || 0) - vorigeG.x, (g.y || 0) - vorigeG.y, (g.z || 0) - vorigeG.z), schokken);
      vorigeG = { x: g.x || 0, y: g.y || 0, z: g.z || 0 };
    }
    const r = e.rotationRate;
    if (!r || (r.alpha == null && r.beta == null && r.gamma == null)) return;
    viaMotion = true;
    bewaar(Math.hypot(r.alpha || 0, r.beta || 0, r.gamma || 0));
  }, true);
  let vorige = null;
  window.addEventListener('deviceorientation', (e) => {
    if (viaMotion || e.beta == null) return;
    const nu = performance.now();
    if (vorige && nu > vorige.t) {
      const dt = (nu - vorige.t) / 1000;
      bewaar(Math.hypot((e.beta - vorige.b) / dt, ((e.gamma || 0) - vorige.g) / dt));
    }
    vorige = { t: nu, b: e.beta, g: e.gamma || 0 };
  }, true);
  window.bewegingsMeter = {
    // Fastest turn in the last `ms` milliseconds; null without a sensor.
    max(ms = 400) {
      const nu = performance.now();
      const recent = metingen.filter(([t]) => nu - t <= ms);
      return recent.length ? Math.max(...recent.map(([, v]) => v)) : null;
    },
    // Strongest acceleration (m/s2, without gravity) in the last `ms`; null without a sensor.
    maxVersnelling(ms = 400) {
      const nu = performance.now();
      const recent = schokken.filter(([t]) => nu - t <= ms);
      return recent.length ? Math.max(...recent.map(([, v]) => v)) : null;
    },
  };
})();

function useDeviceLevel() {
  const [state, setState] = useF({ levelOk: true, supported: false, tiltLR: 0, tiltFB: 0, pointsUp: false });
  const askedRef = useFR(false);

  useFE(() => {
    if (typeof window === 'undefined' || !window.DeviceOrientationEvent) {
      setState((p) => ({ ...p, supported: false }));
      return;
    }
    const handler = (e) => {
      const lr = Math.abs(e.gamma || 0);
      const beta = e.beta == null ? 90 : e.beta;
      const fb = Math.abs(beta - 90);
      // Stricter since 2026-11-12 (was 8 and 12 degrees): even 10 degrees of
      // tilt visibly changes her proportions from 2.5 m. beta above 90 = the
      // top of the phone leans towards the photographer, the lens points up.
      setState({
        supported: true,
        tiltLR: lr, tiltFB: fb, pointsUp: beta > 90,
        levelOk: lr < 5 && fb < 5,
      });
    };

    // iOS Safari requires explicit permission. Ask once on first user gesture.
    const maybeRequest = async () => {
      if (askedRef.current) return;
      askedRef.current = true;
      if (DeviceOrientationEvent && typeof DeviceOrientationEvent.requestPermission === 'function') {
        try { await DeviceOrientationEvent.requestPermission(); } catch (e) { /* user denied, fine */ }
      }
      // The movement meter uses the motion sensor too (same permission on iOS).
      if (window.DeviceMotionEvent && typeof DeviceMotionEvent.requestPermission === 'function') {
        try { await DeviceMotionEvent.requestPermission(); } catch (e) { /* fine */ }
      }
      window.addEventListener('deviceorientation', handler, true);
    };
    // Try silently first; if events never arrive we'll wait for a tap.
    window.addEventListener('deviceorientation', handler, true);
    const gestureHandler = () => maybeRequest();
    window.addEventListener('touchstart', gestureHandler, { once: true });

    return () => {
      window.removeEventListener('deviceorientation', handler, true);
      window.removeEventListener('touchstart', gestureHandler);
    };
  }, []);

  return state;
}

Object.assign(window, { useFraming, useDeviceLevel, LOCK_HOLD_TO_AUTO_MS });
