/* ═══════════════════════════════════════════════════════
   lib/cropper · Avatar crop modal (touch + mouse)
═══════════════════════════════════════════════════════ */

function showCropModal(file, onCrop, opts = {}) {
  const SIZE = opts.canvasSize || 260;
  const OUT = opts.outputSize || 256;
  const overlay = document.createElement('div');
  overlay.style.cssText = `
    position: fixed; inset: 0; z-index: 99999;
    background: rgba(4,8,4,.94);
    display: flex; align-items: center; justify-content: center; flex-direction: column;
    padding: 20px; backdrop-filter: blur(10px);`;
  const canvas = document.createElement('canvas');
  canvas.width = SIZE; canvas.height = SIZE;
  canvas.style.cssText = 'border-radius:50%;border:3px solid rgba(212,175,55,.6);cursor:grab;touch-action:none;display:block;background:#000;';
  const ctx = canvas.getContext('2d');
  const img = new Image();
  let imgX = 0, imgY = 0, imgScale = 1, dragging = false, lastX = 0, lastY = 0, pinchDist = 0;
  function draw() {
    ctx.clearRect(0, 0, SIZE, SIZE);
    ctx.save();
    ctx.beginPath(); ctx.arc(SIZE/2, SIZE/2, SIZE/2, 0, Math.PI*2); ctx.clip();
    ctx.drawImage(img, imgX, imgY, img.width * imgScale, img.height * imgScale);
    ctx.restore();
  }
  function clamp() {
    const w = img.width * imgScale, h = img.height * imgScale;
    if (imgX > 0) imgX = 0;
    if (imgY > 0) imgY = 0;
    if (imgX + w < SIZE) imgX = SIZE - w;
    if (imgY + h < SIZE) imgY = SIZE - h;
  }
  const reader = new FileReader();
  reader.onload = e => {
    img.onload = () => {
      const minS = Math.max(SIZE / img.width, SIZE / img.height);
      imgScale = minS;
      imgX = (SIZE - img.width * imgScale) / 2;
      imgY = (SIZE - img.height * imgScale) / 2;
      clamp(); draw();
    };
    img.src = e.target.result;
  };
  reader.readAsDataURL(file);

  canvas.addEventListener('mousedown', e => { dragging = true; lastX = e.clientX; lastY = e.clientY; e.preventDefault(); });
  document.addEventListener('mousemove', e => {
    if (!dragging) return;
    imgX += e.clientX - lastX; imgY += e.clientY - lastY;
    lastX = e.clientX; lastY = e.clientY; clamp(); draw();
  });
  document.addEventListener('mouseup', () => dragging = false);
  canvas.addEventListener('touchstart', e => {
    if (e.touches.length === 1) { dragging = true; lastX = e.touches[0].clientX; lastY = e.touches[0].clientY; }
    else if (e.touches.length === 2) {
      pinchDist = Math.hypot(e.touches[0].clientX - e.touches[1].clientX, e.touches[0].clientY - e.touches[1].clientY);
    }
    e.preventDefault();
  }, { passive: false });
  canvas.addEventListener('touchmove', e => {
    if (e.touches.length === 1 && dragging) {
      imgX += e.touches[0].clientX - lastX; imgY += e.touches[0].clientY - lastY;
      lastX = e.touches[0].clientX; lastY = e.touches[0].clientY;
    } else if (e.touches.length === 2) {
      const d = Math.hypot(e.touches[0].clientX - e.touches[1].clientX, e.touches[0].clientY - e.touches[1].clientY);
      const minS = Math.max(SIZE / img.width, SIZE / img.height);
      imgScale = Math.min(Math.max(imgScale * (d / pinchDist), minS), minS * 4);
      pinchDist = d;
    }
    clamp(); draw(); e.preventDefault();
  }, { passive: false });
  canvas.addEventListener('touchend', () => dragging = false);

  const cancelB = document.createElement('button');
  cancelB.textContent = 'Cancelar';
  cancelB.style.cssText = 'flex:1;background:rgba(255,255,255,.06);border:1px solid rgba(212,175,55,.18);color:#aaa;padding:11px;border-radius:10px;font-size:14px;cursor:pointer;font-family:inherit;';
  const saveB = document.createElement('button');
  saveB.textContent = '✓ Usar foto';
  saveB.style.cssText = 'flex:1;background:linear-gradient(135deg,#d4af37,#8a6f1f);border:0;color:#0d0d08;padding:11px;border-radius:10px;font-size:14px;font-weight:700;cursor:pointer;font-family:inherit;';
  cancelB.addEventListener('click', () => document.body.removeChild(overlay));
  saveB.addEventListener('click', () => {
    const out = document.createElement('canvas');
    out.width = OUT; out.height = OUT;
    const octx = out.getContext('2d');
    octx.beginPath(); octx.arc(OUT/2, OUT/2, OUT/2, 0, Math.PI*2); octx.clip();
    const ratio = OUT / SIZE;
    octx.drawImage(img, imgX * ratio, imgY * ratio, img.width * imgScale * ratio, img.height * imgScale * ratio);
    document.body.removeChild(overlay);
    onCrop(out.toDataURL('image/jpeg', 0.85));
  });

  const title = document.createElement('div');
  title.textContent = 'Posicione a foto';
  title.style.cssText = "color:#e8c96a;font-size:16px;font-weight:700;margin-bottom:12px;font-family:'Cinzel',serif;letter-spacing:.1em;text-transform:uppercase;";
  const btnRow = document.createElement('div');
  btnRow.style.cssText = 'display:flex;gap:12px;margin-top:16px;width:100%;max-width:280px;';
  btnRow.appendChild(cancelB); btnRow.appendChild(saveB);
  const hint = document.createElement('div');
  hint.textContent = 'Arraste para ajustar · Pince para zoom';
  hint.style.cssText = 'color:rgba(212,175,55,.5);font-size:11px;margin-top:10px;';

  overlay.appendChild(title);
  overlay.appendChild(canvas);
  overlay.appendChild(hint);
  overlay.appendChild(btnRow);
  document.body.appendChild(overlay);
}

window.showCropModal = showCropModal;
