// ─── Recortador de avatar (encuadre cuadrado, arrastrar + zoom) ───────────
// Flujo: el usuario sube/elige una foto → este modal deja encuadrar un
// CUADRADO (arrastrar para mover, slider para zoom). Al guardar produce una
// imagen 512×512 que se usa en todos los avatares (círculos) y en el carnet.
// Además guarda la imagen original + el encuadre {z, cx, cy} para poder
// reabrir y reajustar después sin perder calidad.

const LS_AVATAR_SRC = 'rodando.avatarSrc';     // imagen fuente (reescalada)
const LS_AVATAR_XFORM = 'rodando.avatarXform'; // encuadre { z, cx, cy } en px de la fuente

function loadAvatarSrc() { try { return localStorage.getItem(LS_AVATAR_SRC) || ''; } catch (e) { return ''; } }
function loadAvatarXform() {
  try { return JSON.parse(localStorage.getItem(LS_AVATAR_XFORM) || 'null'); } catch (e) { return null; }
}
function saveAvatarMeta(src, xform) {
  try {
    if (src) localStorage.setItem(LS_AVATAR_SRC, src); else localStorage.removeItem(LS_AVATAR_SRC);
    if (xform) localStorage.setItem(LS_AVATAR_XFORM, JSON.stringify(xform)); else localStorage.removeItem(LS_AVATAR_XFORM);
  } catch (e) {}
}
function removeAvatar() {
  if (window.saveAvatar) window.saveAvatar('');
  saveAvatarMeta('', null);
}

// Abre el recortador. src = dataURL fuente; xform = encuadre previo (o null).
function openAvatarCropper(src, xform) {
  if (!src) return;
  window.dispatchEvent(new CustomEvent('rodando-open-cropper', { detail: { src, xform: xform || null } }));
}
// Reabre el recortador sobre la foto actual para reajustar el encuadre.
function reencuadrarAvatar() {
  const src = loadAvatarSrc();
  if (!src) return;
  openAvatarCropper(src, loadAvatarXform());
}

// Selección de archivo → reescala la fuente → abre el recortador.
function pickAvatarFileToCrop() {
  const inp = document.createElement('input');
  inp.type = 'file'; inp.accept = 'image/*';
  inp.onchange = () => {
    const f = inp.files && inp.files[0];
    if (!f) return;
    const r = new FileReader();
    r.onload = async () => {
      let src = r.result;
      // Reescala la fuente para no reventar el almacenamiento (máx 1024px lado).
      if (window.downscaleDataURL) {
        try { src = await window.downscaleDataURL(r.result, 1024, 0.85); } catch (e) {}
      }
      openAvatarCropper(src, null);
    };
    r.readAsDataURL(f);
  };
  inp.click();
}

const MAX_ZOOM = 4;

function AvatarCropperHost() {
  const [state, setState] = React.useState(null); // { src, xform }
  const [img, setImg] = React.useState(null);      // HTMLImageElement cargado
  const [z, setZ] = React.useState(1);
  const [center, setCenter] = React.useState({ cx: 0, cy: 0 }); // px de la fuente
  const dragRef = React.useRef(null);
  const FRAME = 264;

  React.useEffect(() => {
    const onOpen = (e) => setState(e.detail);
    window.addEventListener('rodando-open-cropper', onOpen);
    return () => window.removeEventListener('rodando-open-cropper', onOpen);
  }, []);

  // Carga la imagen fuente cuando se abre.
  React.useEffect(() => {
    if (!state) { setImg(null); return; }
    const im = new Image();
    im.onload = () => {
      setImg(im);
      const minDim = Math.min(im.naturalWidth, im.naturalHeight);
      const xf = state.xform;
      if (xf && Number.isFinite(xf.z)) {
        setZ(Math.min(MAX_ZOOM, Math.max(1, xf.z)));
        setCenter({ cx: xf.cx, cy: xf.cy });
      } else {
        setZ(1);
        setCenter({ cx: im.naturalWidth / 2, cy: im.naturalHeight / 2 });
      }
    };
    im.src = state.src;
  }, [state]);

  if (!state) return null;

  const close = () => setState(null);

  // Geometría derivada del estado actual.
  const geo = (() => {
    if (!img) return null;
    const natW = img.naturalWidth, natH = img.naturalHeight;
    const minDim = Math.min(natW, natH);
    const sSize = minDim / z;
    let sx = center.cx - sSize / 2;
    let sy = center.cy - sSize / 2;
    sx = Math.max(0, Math.min(natW - sSize, sx));
    sy = Math.max(0, Math.min(natH - sSize, sy));
    const scale = FRAME / sSize;
    return { natW, natH, sSize, sx, sy, scale };
  })();

  const onPointerDown = (e) => {
    if (!geo) return;
    e.currentTarget.setPointerCapture && e.currentTarget.setPointerCapture(e.pointerId);
    dragRef.current = { x: e.clientX, y: e.clientY, cx: center.cx, cy: center.cy };
  };
  const onPointerMove = (e) => {
    if (!dragRef.current || !geo) return;
    const dx = e.clientX - dragRef.current.x;
    const dy = e.clientY - dragRef.current.y;
    setCenter({
      cx: dragRef.current.cx - dx / geo.scale,
      cy: dragRef.current.cy - dy / geo.scale
    });
  };
  const onPointerUp = (e) => {
    dragRef.current = null;
    if (e.currentTarget.releasePointerCapture) try { e.currentTarget.releasePointerCapture(e.pointerId); } catch (er) {}
  };

  const onZoom = (e) => {
    const nz = Number(e.target.value);
    setZ(nz); // el centro se mantiene; geo reclampa los bordes
  };

  const guardar = () => {
    if (!img || !geo) { close(); return; }
    const OUT = 512;
    const canvas = document.createElement('canvas');
    canvas.width = OUT; canvas.height = OUT;
    const ctx = canvas.getContext('2d');
    ctx.imageSmoothingQuality = 'high';
    ctx.drawImage(img, geo.sx, geo.sy, geo.sSize, geo.sSize, 0, 0, OUT, OUT);
    let out;
    try { out = canvas.toDataURL('image/jpeg', 0.9); } catch (e) { out = state.src; }
    const cx = geo.sx + geo.sSize / 2;
    const cy = geo.sy + geo.sSize / 2;
    if (window.saveAvatar) window.saveAvatar(out);
    saveAvatarMeta(state.src, { z, cx, cy });
    close();
  };

  const imgStyle = geo ? {
    position: 'absolute',
    width: geo.natW * geo.scale,
    height: geo.natH * geo.scale,
    left: -geo.sx * geo.scale,
    top: -geo.sy * geo.scale,
    maxWidth: 'none',
    userSelect: 'none', pointerEvents: 'none', display: 'block'
  } : {};

  const T = window.TOKENS;
  return (
    <div onClick={close} style={{
      position: 'fixed', inset: 0, zIndex: 1300, background: 'rgba(11,28,48,0.66)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '24px 16px',
      backdropFilter: 'blur(3px)'
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', maxWidth: 340, background: T.surface, borderRadius: 18,
        boxShadow: '0 26px 64px rgba(11,28,48,0.4)', overflow: 'hidden'
      }}>
        <div style={{ padding: '16px 18px 4px' }}>
          <div style={{ fontSize: 17, fontWeight: 800, color: T.text, letterSpacing: '-0.01em' }}>Ajusta tu foto</div>
          <div style={{ fontSize: 12.5, color: T.textMuted, marginTop: 2 }}>Arrastra para mover · desliza para acercar</div>
        </div>

        {/* Marco de recorte */}
        <div style={{ padding: '14px 0 4px', display: 'flex', justifyContent: 'center' }}>
          <div
            onPointerDown={onPointerDown}
            onPointerMove={onPointerMove}
            onPointerUp={onPointerUp}
            onPointerCancel={onPointerUp}
            style={{
              position: 'relative', width: FRAME, height: FRAME, overflow: 'hidden',
              borderRadius: 14, background: T.primaryDark, cursor: 'grab', touchAction: 'none'
            }}>
            {img && <img src={state.src} alt="" style={imgStyle} draggable={false} />}
            {/* Guía circular (cómo se verá en los avatares) */}
            <div style={{
              position: 'absolute', inset: 0, pointerEvents: 'none',
              boxShadow: `inset 0 0 0 9999px rgba(11,28,48,0.0)`,
            }}>
              <div style={{
                position: 'absolute', inset: 0, borderRadius: '50%',
                boxShadow: '0 0 0 9999px rgba(11,28,48,0.42)',
                border: '1.5px solid rgba(255,255,255,0.85)'
              }} />
            </div>
          </div>
        </div>

        {/* Zoom */}
        <div style={{ padding: '6px 22px 4px', display: 'flex', alignItems: 'center', gap: 12 }}>
          <span style={{ fontSize: 18, fontWeight: 700, color: T.textMuted, width: 12, textAlign: 'center', lineHeight: 1 }}>−</span>
          <input type="range" min={1} max={MAX_ZOOM} step={0.01} value={z} onChange={onZoom}
            style={{ flex: 1, accentColor: T.primary, cursor: 'pointer' }} />
          <span style={{ fontSize: 18, fontWeight: 700, color: T.textMuted, width: 12, textAlign: 'center', lineHeight: 1 }}>+</span>
        </div>

        {/* Acciones */}
        <div style={{ padding: '12px 18px 18px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <button onClick={close} style={{
            padding: '12px', borderRadius: 11, cursor: 'pointer', fontFamily: 'inherit',
            background: 'transparent', border: `1px solid ${T.borderInput}`, color: T.text, fontSize: 13.5, fontWeight: 700
          }}>Cancelar</button>
          <button onClick={guardar} style={{
            padding: '12px', borderRadius: 11, cursor: 'pointer', fontFamily: 'inherit',
            background: T.primary, border: 'none', color: '#fff', fontSize: 13.5, fontWeight: 700
          }}>Guardar foto</button>
        </div>
      </div>
    </div>);
}

Object.assign(window, {
  AvatarCropperHost, openAvatarCropper, reencuadrarAvatar, pickAvatarFileToCrop,
  loadAvatarSrc, loadAvatarXform, removeAvatar
});
