<?php include __DIR__ . '/../partials/_header.php'; ?>
<div class="container" style="max-width:800px;margin:20px auto;">
  <h2>Recortar y ajustar avatar</h2>
  <p>Sube una imagen y ajusta el recorte cuadrado. Tamaño final: 256×256.</p>

  <div class="card" style="padding:16px;">
    <input id="fileInput" type="file" accept="image/*" style="margin-bottom:12px;">
    <div id="cropStage" style="width:400px;height:400px;border:1px solid #ddd;position:relative;overflow:hidden;background:#f7f7f7;">
      <img id="img" style="position:absolute; top:0; left:0; user-select:none; -webkit-user-drag: none; display:none;">
      <div style="position:absolute; inset:0; box-shadow:0 0 0 9999px rgba(0,0,0,.35); pointer-events:none;"></div>
    </div>
    <div style="margin-top:10px;display:flex;gap:12px;align-items:center;">
      <label>Zoom</label>
      <input id="zoom" type="range" min="0.5" max="3" step="0.01" value="1" style="flex:1;">
      <button id="btnSave" class="btn btn-primary" disabled>Guardar recorte</button>
      <a href="<?php echo htmlspecialchars(base_url('/profile')); ?>" class="btn ghost">Cancelar</a>
    </div>
    <canvas id="canvas" width="256" height="256" style="display:none;"></canvas>
  </div>
</div>
<script>
(function(){
  const file = document.getElementById('fileInput');
  const img = document.getElementById('img');
  const stage = document.getElementById('cropStage');
  const zoom = document.getElementById('zoom');
  const canvas = document.getElementById('canvas');
  const ctx = canvas.getContext('2d');
  const save = document.getElementById('btnSave');

  let scale = 1, isDown = false, startX=0, startY=0, imgX=0, imgY=0, imgW=0, imgH=0, naturalW=0, naturalH=0;

  function fitImage() {
    if (!naturalW || !naturalH) return;
    const box = 400;
    const k = Math.max(box/naturalW, box/naturalH);
    scale = k; zoom.value = Math.max(0.5, Math.min(3, k));
    imgW = naturalW * scale; imgH = naturalH * scale;
    imgX = (box - imgW)/2; imgY = (box - imgH)/2;
    applyTransform();
  }

  function applyTransform() {
    img.style.transform = `translate(${imgX}px, ${imgY}px) scale(${scale})`;
    img.style.transformOrigin = 'top left';
  }

  function clampPosition(){
    const box = 400;
    const viewW = naturalW * scale, viewH = naturalH * scale;
    // ensure the square 400 is fully covered
    if (viewW <= box) imgX = (box - viewW)/2; else { if (imgX > 0) imgX = 0; if (imgX + viewW < box) imgX = box - viewW; }
    if (viewH <= box) imgY = (box - viewH)/2; else { if (imgY > 0) imgY = 0; if (imgY + viewH < box) imgY = box - viewH; }
  }

  file.addEventListener('change', (e)=>{
    const f = e.target.files[0];
    if (!f) return;
    const url = URL.createObjectURL(f);
    img.onload = ()=>{
      naturalW = img.naturalWidth; naturalH = img.naturalHeight;
      img.style.display='block';
      img.style.transform = 'none';
      scale = 1; imgX = 0; imgY = 0;
      fitImage();
    };
    img.src = url;
    save.disabled = false;
  });

  zoom.addEventListener('input', ()=>{
    const box = 400;
    scale = parseFloat(zoom.value);
    imgW = naturalW * scale; imgH = naturalH * scale;
    clampPosition();
    applyTransform();
  });

  stage.addEventListener('mousedown', (e)=>{ isDown = true; startX = e.clientX - imgX; startY = e.clientY - imgY; });
  window.addEventListener('mouseup', ()=> isDown = false);
  window.addEventListener('mousemove', (e)=>{
    if (!isDown) return;
    imgX = e.clientX - startX; imgY = e.clientY - startY;
    clampPosition(); applyTransform();
  });

  save.addEventListener('click', async ()=>{
    if (!naturalW || !naturalH) return;
    // render to 256x256
    ctx.clearRect(0,0,256,256);
    const box = 400;
    // compute source rect relative to image
    const sx = (0 - imgX) / scale;
    const sy = (0 - imgY) / scale;
    const sSize = 400 / scale;
    ctx.imageSmoothingQuality = 'high';
    ctx.drawImage(img, sx, sy, sSize, sSize, 0, 0, 256, 256);
    const dataUrl = canvas.toDataURL('image/png');

    // POST to /profile/avatar as avatar_data
    const fd = new FormData();
    fd.append('_csrf', '<?php echo htmlspecialchars(csrf_token()); ?>');
    fd.append('avatar_data', dataUrl);

    const resp = await fetch('<?php echo htmlspecialchars(base_url('/profile/avatar')); ?>', {
      method: 'POST',
      body: fd,
      credentials: 'same-origin'
    });
    if (resp.redirected) {
      window.location.href = resp.url;
    } else {
      // try to parse error or just go back to profile
      window.location.href = '<?php echo htmlspecialchars(base_url('/profile')); ?>';
    }
  });
})();
</script>
<?php include __DIR__ . '/../partials/_footer.php'; ?>
