// Script da tela "reset_passowrd_selfie.html" (etapa 2: selfie + finalizar).
(function () {
  function showAlert(title, text) {
    try { alert(title + '\n\n' + text); } catch (e) {}
  }

  function showBanner(msg) {
    var el = document.getElementById('errorBanner');
    if (!el) return;
    el.textContent = msg;
    el.classList.remove('hidden');
  }

  function run() {
    var pendingRaw = '';
    try { pendingRaw = sessionStorage.getItem('rp_reset_pending') || ''; } catch (e) {}
    if (!pendingRaw) {
      showAlert('Atenção', 'A etapa 1 não foi concluída. Informe senha e CPF primeiro.');
      window.location.href = 'reset_passowrd.html';
      return;
    }

    var pending = null;
    try { pending = JSON.parse(pendingRaw); } catch (e) {}
    if (!pending || !pending.cpf || !pending.new_password || !pending.confirm_password) {
      showAlert('Atenção', 'Dados da etapa 1 inválidos. Refaça o processo.');
      window.location.href = 'reset_passowrd.html';
      return;
    }

    var camVideo = document.getElementById('camVideo');
    var previewShot = document.getElementById('previewShot');
    var camPlaceholder = document.getElementById('camPlaceholder');
    var btnCapture = document.getElementById('btnCapture');
    var btnGallery = document.getElementById('btnGallery');
    var btnFlip = document.getElementById('btnFlip');
    var btnRetake = document.getElementById('btnRetake');
    var galleryInput = document.getElementById('galleryInput');
    var btnConfirm = document.getElementById('btnConfirm');
    var btnBack = document.getElementById('btnBack');
    var btnLocRetry = document.getElementById('btnLocRetry');
    var geoLat = null;
    var geoLng = null;
    var geoAcc = null;
    var addressLine = '';

    var capCanvas = document.createElement('canvas');
    var capturedBlob = null;
    var stream = null;
    var facingMode = 'user';

    function updateConfirm() {
      var ok = !!capturedBlob && geoLat != null && geoLng != null;
      btnConfirm.disabled = !ok;
      if (ok) {
        btnConfirm.classList.remove('bg-primary/40', 'cursor-not-allowed');
        btnConfirm.classList.add('bg-primary', 'hover:bg-primary/90', 'active:scale-[0.98]', 'cursor-pointer');
      } else {
        btnConfirm.classList.add('bg-primary/40', 'cursor-not-allowed');
        btnConfirm.classList.remove('bg-primary', 'hover:bg-primary/90', 'active:scale-[0.98]', 'cursor-pointer');
      }
    }

    function stopCam() {
      if (stream) {
        stream.getTracks().forEach(function (t) { t.stop(); });
        stream = null;
      }
      if (camVideo) camVideo.srcObject = null;
    }

    function getUserMediaCompat(constraints) {
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        return navigator.mediaDevices.getUserMedia(constraints);
      }
      var legacy = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
      if (legacy) {
        return new Promise(function (resolve, reject) {
          legacy.call(navigator, constraints, resolve, reject);
        });
      }
      return Promise.reject(new Error('getUserMedia não suportado'));
    }

    function startCam() {
      if (!camVideo) return;
      stopCam();
      getUserMediaCompat({ video: { facingMode: { ideal: facingMode }, width: { ideal: 1280 }, height: { ideal: 720 } }, audio: false })
        .then(function (s) {
          stream = s;
          camVideo.srcObject = s;
          if (camPlaceholder) camPlaceholder.classList.add('hidden');
          return camVideo.play().catch(function () {});
        })
        .catch(function () {
          showBanner('Não foi possível abrir a câmera. Você pode usar a galeria.');
          if (camPlaceholder) camPlaceholder.classList.remove('hidden');
        });
    }

    function applyGeoSuccess(pos) {
      geoLat = pos.coords.latitude;
      geoLng = pos.coords.longitude;
      geoAcc = pos.coords.accuracy;
      var locText = document.getElementById('locText');
      if (locText) {
        locText.textContent = geoLat.toFixed(6) + ', ' + geoLng.toFixed(6) + ' (±' + Math.round(geoAcc) + ' m)';
      }
      reverseGeocode(geoLat, geoLng);
      updateConfirm();
    }

    function applyGeoError(msg) {
      geoLat = null;
      geoLng = null;
      geoAcc = null;
      addressLine = '';
      var locText = document.getElementById('locText');
      if (locText) locText.textContent = 'Localização indisponível.';
      if (btnLocRetry) btnLocRetry.classList.remove('hidden');
      updateConfirm();
      showBanner(msg || 'Não foi possível obter localização.');
    }

    function loadGeolocation() {
      if (btnLocRetry) btnLocRetry.classList.add('hidden');
      if (!navigator.geolocation) {
        applyGeoError('GPS não disponível neste dispositivo.');
        return;
      }
      navigator.geolocation.getCurrentPosition(
        applyGeoSuccess,
        function () { applyGeoError('Ative localização/GPS para finalizar a redefinição.'); },
        { enableHighAccuracy: true, timeout: 30000, maximumAge: 0 }
      );
    }

    function reverseGeocode(lat, lon) {
      var url = 'https://nominatim.openstreetmap.org/reverse?lat=' + encodeURIComponent(lat) + '&lon=' + encodeURIComponent(lon) + '&format=json';
      fetch(url, { headers: { 'Accept-Language': 'pt-BR' } })
        .then(function (r) { return r.json(); })
        .then(function (j) {
          if (j && j.display_name) {
            addressLine = String(j.display_name);
            var locText = document.getElementById('locText');
            if (locText) locText.textContent = addressLine;
          }
        })
        .catch(function () {});
    }

    function showPreviewFromBlob(blob) {
      capturedBlob = blob;
      var url = URL.createObjectURL(blob);
      previewShot.onload = function () { try { URL.revokeObjectURL(url); } catch (e) {} };
      previewShot.src = url;
      previewShot.classList.remove('hidden');
      if (btnRetake) btnRetake.classList.remove('hidden');
      stopCam();
      if (camPlaceholder) camPlaceholder.classList.add('hidden');
      updateConfirm();
    }

    function captureFromVideo() {
      if (!camVideo || !camVideo.videoWidth) {
        showAlert('Atenção', 'A câmera ainda não está pronta.');
        return;
      }
      var w = camVideo.videoWidth;
      var h = camVideo.videoHeight;
      capCanvas.width = w;
      capCanvas.height = h;
      var ctx = capCanvas.getContext('2d');
      ctx.translate(w, 0);
      ctx.scale(-1, 1);
      ctx.drawImage(camVideo, 0, 0, w, h);
      ctx.setTransform(1, 0, 0, 1, 0, 0);
      capCanvas.toBlob(function (blob) {
        if (!blob) {
          showAlert('Atenção', 'Falha ao capturar selfie.');
          return;
        }
        showPreviewFromBlob(blob);
      }, 'image/jpeg', 0.92);
    }

    function submitFinal() {
      if (!capturedBlob) {
        showAlert('Atenção', 'Capture a selfie antes de finalizar.');
        return;
      }
      var RESET_API_URL = (function () {
        try {
          var custom = localStorage.getItem('PASSWORD_RESET_SELFIE_API_URL');
          if (custom && /^https?:\/\//i.test(custom)) return custom;
        } catch (e) {}
        if (typeof registroProGetPasswordResetWithSelfieApiUrl === 'function') {
          return registroProGetPasswordResetWithSelfieApiUrl();
        }
        return '';
      })();
      if (!RESET_API_URL) {
        showAlert('Erro', 'Configuração da API ausente (js/api-config.js).');
        return;
      }

      btnConfirm.disabled = true;
      var oldHtml = btnConfirm.innerHTML;
      btnConfirm.innerHTML = 'Finalizando...';

      var fd = new FormData();
      fd.append('cpf', String(pending.cpf || ''));
      fd.append('new_password', String(pending.new_password || ''));
      fd.append('confirm_password', String(pending.confirm_password || ''));
      fd.append('security_token', String(pending.security_token || ''));
      fd.append('selfie', capturedBlob, 'selfie.jpg');
      fd.append('latitude', String(geoLat != null ? geoLat : ''));
      fd.append('longitude', String(geoLng != null ? geoLng : ''));
      fd.append('location_accuracy', String(geoAcc != null ? geoAcc : ''));
      fd.append('address_line', addressLine || '');
      if (pending.tenant_slug) fd.append('tenant_slug', String(pending.tenant_slug));

      fetch(RESET_API_URL, { method: 'POST', headers: { Accept: 'application/json' }, body: fd })
        .then(function (r) {
          return r.json().catch(function () { return null; }).then(function (j) {
            return { ok: r.ok, json: j };
          });
        })
        .then(function (res) {
          if (res.ok && res.json && res.json.ok && res.json.changed) {
            try { sessionStorage.removeItem('rp_reset_pending'); } catch (e) {}
            window.location.href = 'senha_alterada_sucesso.html';
            return;
          }
          var msg = (res.json && res.json.error) ? res.json.error : 'Não foi possível redefinir a senha.';
          showAlert('Atenção', msg);
          btnConfirm.disabled = false;
          btnConfirm.innerHTML = oldHtml;
          updateConfirm();
        })
        .catch(function () {
          showAlert('Erro', 'Falha de conexão ao finalizar redefinição.');
          btnConfirm.disabled = false;
          btnConfirm.innerHTML = oldHtml;
          updateConfirm();
        });
    }

    btnCapture.addEventListener('click', captureFromVideo);
    btnGallery.addEventListener('click', function () { galleryInput.click(); });
    galleryInput.addEventListener('change', function () {
      var f = galleryInput.files && galleryInput.files[0];
      if (!f) return;
      if (!/^image\//.test(f.type)) {
        showAlert('Atenção', 'Escolha uma imagem válida.');
        galleryInput.value = '';
        return;
      }
      var r = new FileReader();
      r.onload = function () {
        var img = new Image();
        img.onload = function () {
          capCanvas.width = img.naturalWidth;
          capCanvas.height = img.naturalHeight;
          var ctx = capCanvas.getContext('2d');
          ctx.drawImage(img, 0, 0);
          capCanvas.toBlob(function (blob) {
            if (blob) showPreviewFromBlob(blob);
          }, 'image/jpeg', 0.92);
        };
        img.src = r.result;
      };
      r.readAsDataURL(f);
      galleryInput.value = '';
    });
    btnFlip.addEventListener('click', function () {
      facingMode = facingMode === 'user' ? 'environment' : 'user';
      startCam();
    });
    btnRetake.addEventListener('click', function () {
      capturedBlob = null;
      previewShot.classList.add('hidden');
      previewShot.removeAttribute('src');
      btnRetake.classList.add('hidden');
      updateConfirm();
      startCam();
    });
    btnConfirm.addEventListener('click', submitFinal);
    if (btnLocRetry) btnLocRetry.addEventListener('click', loadGeolocation);
    btnBack.addEventListener('click', function () {
      window.location.href = 'reset_passowrd.html';
    });

    updateConfirm();
    startCam();
    loadGeolocation();
    window.addEventListener('beforeunload', stopCam);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', run, { once: true });
  } else {
    run();
  }
})();
