'use strict';
// ═══════════════════════════════════════════════
// js/webcam.js — webcam capture modal
// ═══════════════════════════════════════════════

let _wcStream = null;
let _wcEntryId = null;
let _wcField = null;
let _wcCaptured = false;

async function webcamOpen(entryId, field) {
  _wcEntryId = entryId;
  _wcField = field;
  _wcCaptured = false;
  try {
    _wcStream = await navigator.mediaDevices.getUserMedia({
      video: { width: { ideal: 1280 }, height: { ideal: 720 }, facingMode: 'user' },
      audio: false
    });
    const v = document.getElementById('webcamVideo');
    v.srcObject = _wcStream;
    v.style.display = '';
    document.getElementById('webcamCanvas').style.display = 'none';
    document.getElementById('webcamCaptureBtn').style.display = '';
    document.getElementById('webcamRetakeBtn').style.display = 'none';
    document.getElementById('webcamUseBtn').style.display = 'none';
    document.getElementById('webcamCaption').textContent =
      `Capturing: ${field} view - position yourself and click Capture`;
    _wcSetupGhost(entryId, field);
    // Sync the sizing-guide overlay with the user's saved preference
    const guideOn = localStorage.getItem('frj_sizing_guide') !== '0';
    const guideEl = document.getElementById('webcamSizingGuide');
    const guideToggle = document.getElementById('webcamSizingGuideToggle');
    if (guideEl) guideEl.style.display = guideOn ? '' : 'none';
    if (guideToggle && !guideToggle._wcWired) {
      guideToggle.checked = guideOn;
      guideToggle.addEventListener('change', () => {
        const on = guideToggle.checked;
        localStorage.setItem('frj_sizing_guide', on ? '1' : '0');
        if (guideEl) guideEl.style.display = on ? '' : 'none';
      });
      guideToggle._wcWired = true;
    } else if (guideToggle) {
      guideToggle.checked = guideOn;
    }
    document.getElementById('webcamModal').classList.add('open');
  } catch(e) {
    toast('Camera access denied or unavailable', true);
    console.warn('Webcam error:', e);
  }
}

// ── Ghost overlay ──────────────────────────────────────────────────────────────
// Shows the most recent earlier photo from the same slot as a translucent layer
// over the live video, so each new shot can match the previous framing. This is
// what makes compare and timeline photos actually comparable.
let _wcGhostRetryTimer = null;

function _wcSetupGhost(entryId, field) {
  const ghost = document.getElementById('webcamGhost');
  const wrap = document.getElementById('webcamGhostToggleWrap');
  const tog = document.getElementById('webcamGhostToggle');
  if (!ghost || !wrap) return;
  const prop = ({ front: 'imgFront' })[field] || field;
  let prevKey = null;
  try {
    const cur = typeof getEntry === 'function' ? getEntry(entryId) : null;
    const prev = (typeof getEntries === 'function' ? getEntries() : [])
      .filter(e => e.id !== entryId && e[prop] && (!cur?.date || e.date <= cur.date))
      .sort((a, b) => b.date.localeCompare(a.date))[0];
    prevKey = prev ? prev[prop] : null;
  } catch (e) { /* no ghost available */ }

  const ghostOn = localStorage.getItem('frj_ghost_overlay') !== '0';
  const apply = () => {
    const src = prevKey && typeof imgURL === 'function' ? imgURL(prevKey) : null;
    if (src) {
      ghost.src = src;
      ghost.style.display = ghostOn && tog?.checked !== false ? '' : 'none';
      wrap.style.display = 'inline-flex';
    } else {
      ghost.src = '';
      ghost.style.display = 'none';
      wrap.style.display = 'none';
    }
    return !!src;
  };
  clearTimeout(_wcGhostRetryTimer);
  if (!apply() && prevKey) {
    // Blob not in the image cache yet -- imgURL kicks off the async load; retry once
    _wcGhostRetryTimer = setTimeout(apply, 700);
  }
  if (tog) {
    tog.checked = ghostOn;
    if (!tog._wcWired) {
      tog.addEventListener('change', () => {
        localStorage.setItem('frj_ghost_overlay', tog.checked ? '1' : '0');
        if (ghost.src) ghost.style.display = tog.checked ? '' : 'none';
      });
      tog._wcWired = true;
    }
  }
}

function webcamCapture() {
  const v = document.getElementById('webcamVideo');
  const c = document.getElementById('webcamCanvas');
  if (!v.videoWidth) { toast('No video stream', true); return; }
  c.width = v.videoWidth;
  c.height = v.videoHeight;
  c.getContext('2d').drawImage(v, 0, 0);
  c.style.display = '';
  v.style.display = 'none';
  _wcCaptured = true;
  document.getElementById('webcamCaptureBtn').style.display = 'none';
  document.getElementById('webcamRetakeBtn').style.display = '';
  document.getElementById('webcamUseBtn').style.display = '';
  document.getElementById('webcamCaption').textContent = 'Preview - retake or use this photo';
}

function webcamRetake() {
  _wcCaptured = false;
  const v = document.getElementById('webcamVideo');
  const c = document.getElementById('webcamCanvas');
  v.style.display = '';
  c.style.display = 'none';
  document.getElementById('webcamCaptureBtn').style.display = '';
  document.getElementById('webcamRetakeBtn').style.display = 'none';
  document.getElementById('webcamUseBtn').style.display = 'none';
  document.getElementById('webcamCaption').textContent =
    `Capturing: ${_wcField} view - position yourself and click Capture`;
}

async function webcamUse() {
  const c = document.getElementById('webcamCanvas');
  c.toBlob(async rawBlob => {
    if (!rawBlob) { toast('Failed to capture image', true); return; }
    const blob = await compressImage(rawBlob);
    const entry = getEntry(_wcEntryId);
    if (!entry) { webcamClose(); return; }
    const fieldMap = { imgFront: 'imgFront', front: 'imgFront' };
    const prop = fieldMap[_wcField] || _wcField;
    const oldKey = entry[prop] || null;
    const eid = _wcEntryId;
    webcamClose();
    if (typeof _ptOpen === 'function') _ptOpen(blob, eid, prop, oldKey);
  }, 'image/jpeg', 0.9);
}

function webcamClose() {
  clearTimeout(_wcGhostRetryTimer);
  if (_wcStream) {
    _wcStream.getTracks().forEach(t => t.stop());
    _wcStream = null;
  }
  const v = document.getElementById('webcamVideo');
  if (v) { v.srcObject = null; }
  document.getElementById('webcamModal').classList.remove('open');
  _wcCaptured = false;
  _wcEntryId = null;
  _wcField = null;
}
