/* eslint-disable react/prop-types */
/**
 * Cursor · cursor custom estilo editorial.
 *
 * - Punto cobre 6px que sigue al mouse con precisión
 * - Anillo navy 32px con lerp suave (lag perceptible)
 * - Estados:
 *     default   · anillo 32px sutil
 *     link      · anillo se reduce y el punto crece (sobre <a>, <button>)
 *     view      · anillo crece a 80px y muestra "VER" (sobre images cards)
 *     next      · anillo crece y muestra "→"  (sobre carruseles)
 *     drag      · sobre marquees con scroll
 * - Hidden en dispositivos táctiles (pointer: coarse)
 *
 * Activación: cualquier elemento con [data-cursor="link"|"view"|"next"|"drag"].
 */

const { useEffect: uE_Cur, useRef: uR_Cur, useState: uS_Cur } = React;

function Cursor() {
  const dotRef  = uR_Cur(null);
  const ringRef = uR_Cur(null);
  const [variant, setVariant] = uS_Cur('default');
  const [label,   setLabel]   = uS_Cur('');
  const [visible, setVisible] = uS_Cur(false);

  uE_Cur(() => {
    if (window.matchMedia('(pointer: coarse)').matches) return;

    // ocultar cursor nativo en interactivos
    document.body.classList.add('has-custom-cursor');

    const target = { x: window.innerWidth / 2, y: window.innerHeight / 2 };
    const ring   = { x: target.x, y: target.y };
    let raf;

    const onMove = (e) => {
      target.x = e.clientX;
      target.y = e.clientY;
      if (!visible) setVisible(true);
      if (dotRef.current) {
        dotRef.current.style.transform = `translate3d(${e.clientX - 3}px, ${e.clientY - 3}px, 0)`;
      }
    };

    const tick = () => {
      ring.x += (target.x - ring.x) * 0.18;
      ring.y += (target.y - ring.y) * 0.18;
      if (ringRef.current) {
        ringRef.current.style.transform =
          `translate3d(${ring.x - 18}px, ${ring.y - 18}px, 0)`;
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);

    const onOver = (e) => {
      const el = e.target.closest('[data-cursor]');
      if (el) {
        const v = el.getAttribute('data-cursor');
        const customLabel = el.getAttribute('data-cursor-label');
        setVariant(v);
        if (customLabel) setLabel(customLabel);
        else if (v === 'view') setLabel('VER');
        else if (v === 'next') setLabel('→');
        else setLabel('');
      } else {
        const interactive = e.target.closest('a, button, label, input, select, textarea, [role="button"], [role="tab"]');
        setVariant(interactive ? 'link' : 'default');
        setLabel('');
      }
    };

    const onLeave = () => setVisible(false);
    const onEnter = () => setVisible(true);

    window.addEventListener('mousemove', onMove, { passive: true });
    window.addEventListener('mouseover', onOver);
    window.addEventListener('mouseout', (e) => { if (!e.relatedTarget) onLeave(); });
    document.addEventListener('mouseleave', onLeave);
    document.addEventListener('mouseenter', onEnter);

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseover', onOver);
      document.removeEventListener('mouseleave', onLeave);
      document.removeEventListener('mouseenter', onEnter);
      document.body.classList.remove('has-custom-cursor');
    };
  }, []);

  const ringStyle = (() => {
    const base = {
      ...curStyles.ring,
      opacity: visible ? 1 : 0,
    };
    if (variant === 'link') {
      return { ...base, width: 56, height: 56, marginLeft: -10, marginTop: -10,
               background: 'rgba(168, 107, 45, 0.12)', borderColor: 'rgba(168, 107, 45, 0.65)' };
    }
    if (variant === 'view' || variant === 'next') {
      return { ...base, width: 84, height: 84, marginLeft: -24, marginTop: -24,
               background: 'rgba(33, 52, 64, 0.92)', borderColor: 'transparent',
               color: '#fff' };
    }
    if (variant === 'drag') {
      return { ...base, width: 64, height: 64, marginLeft: -14, marginTop: -14,
               background: 'rgba(33, 52, 64, 0.92)', borderColor: 'transparent', color: '#fff' };
    }
    return base;
  })();

  return (
    <React.Fragment>
      <div ref={ringRef} style={ringStyle} aria-hidden="true">
        {(variant === 'view' || variant === 'next' || variant === 'drag') && label && (
          <span style={curStyles.label}>{label}</span>
        )}
      </div>
      <div ref={dotRef} style={{
        ...curStyles.dot,
        opacity: visible ? 1 : 0,
        background: variant === 'link' ? 'var(--color-copper-fallback)' : 'var(--color-navy-deep)',
      }} aria-hidden="true" />
    </React.Fragment>
  );
}

const curStyles = {
  ring: {
    position: 'fixed', top: 0, left: 0,
    width: 36, height: 36,
    borderRadius: 999,
    border: '1.5px solid rgba(33, 52, 64, 0.45)',
    pointerEvents: 'none',
    zIndex: 99999,
    transition: 'width 280ms cubic-bezier(0.16, 1, 0.3, 1), height 280ms cubic-bezier(0.16, 1, 0.3, 1), margin 280ms cubic-bezier(0.16, 1, 0.3, 1), background 200ms ease-out, border-color 200ms ease-out, opacity 200ms ease-out',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    fontFamily: 'var(--font-sans)',
    fontSize: 11,
    fontWeight: 700,
    letterSpacing: '0.18em',
    willChange: 'transform',
  },
  dot: {
    position: 'fixed', top: 0, left: 0,
    width: 6, height: 6,
    borderRadius: 999,
    background: 'var(--color-navy-deep)',
    pointerEvents: 'none',
    zIndex: 100000,
    transition: 'opacity 200ms ease-out, background 200ms ease-out, transform 60ms linear',
    willChange: 'transform',
  },
  label: { textTransform: 'uppercase' },
};

const curMQ = document.createElement('style');
curMQ.textContent = `
  @media (pointer: fine) {
    body.has-custom-cursor,
    body.has-custom-cursor * { cursor: none !important; }
  }
  @media (pointer: coarse) {
    body.has-custom-cursor { cursor: auto !important; }
  }
`;
document.head.appendChild(curMQ);

window.Cursor = Cursor;
