// download-button.jsx — DownloadButton + global button ripple effects
// framer-motion → GSAP timeline + CSS keyframes

// ─── DownloadButton ───────────────────────────────────────────────────────────
const DownloadButton = ({
  label      = 'Download',
  doneLabel  = 'Done!',
  duration   = 3200,
  onDownload,
  style      = {},
  className  = '',
}) => {
  const btnRef   = React.useRef(null);
  const fillRef  = React.useRef(null);
  const iconRef  = React.useRef(null);
  const dotRef   = React.useRef(null);
  const labelRef = React.useRef(null);
  const tlRef    = React.useRef(null);
  const [phase, setPhase] = React.useState('idle'); // idle | loading | done

  const handleClick = () => {
    if (phase !== 'idle') return;
    setPhase('loading');
    onDownload?.();

    const tl = gsap.timeline({
      onComplete: () => {
        setPhase('done');
        // Brief done state, then reset
        setTimeout(() => {
          gsap.timeline()
            .to(fillRef.current,  { scaleY: 0, duration: 0.25, ease: 'power2.in' })
            .to(btnRef.current,   { width: 'auto', minWidth: '140px', duration: 0.38, ease: 'power3.inOut' }, '-=0.15')
            .to(iconRef.current,  { opacity: 1, y: 0,   scale: 1, duration: 0.25 }, '-=0.2')
            .to(labelRef.current, { opacity: 1, x: 0,              duration: 0.25 }, '-=0.2')
            .then(() => setPhase('idle'));
        }, 700);
      },
    });
    tlRef.current = tl;

    // Label + icon fade out, button shrinks
    tl.to(labelRef.current, { opacity: 0, x: -6,   duration: 0.22, ease: 'power2.in' }, 0)
      .to(iconRef.current,  { opacity: 0, y: 4, scale: 0.6, duration: 0.22, ease: 'power2.in' }, 0)
      .to(btnRef.current,   { width: 56, minWidth: '56px', duration: 0.38, ease: 'power3.inOut' }, 0.08)
      // Progress fill rises from bottom
      .to(fillRef.current,  { scaleY: 1, duration: duration / 1000, ease: 'none' }, 0.46);
  };

  const accentCircle = {
    position: 'relative',
    width: 48, height: 48,
    borderRadius: '50%',
    background: 'var(--accent)',
    flexShrink: 0,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    overflow: 'hidden',
  };

  const checkIcon = (
    <svg style={{ width: 22, height: 22, color: '#fff', display: 'block' }}
      viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"
      strokeLinecap="round" strokeLinejoin="round">
      <path d="M20 6 9 17l-5-5"/>
    </svg>
  );

  const downloadIcon = (
    <svg style={{ width: 22, height: 22, color: '#fff', display: 'block' }}
      viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"
      strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 19V5m0 14-4-4m4 4 4-4"/>
    </svg>
  );

  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', ...style }}
      className={className}>
      <button
        ref={btnRef}
        onClick={handleClick}
        style={{
          position: 'relative',
          display: 'inline-flex',
          alignItems: 'center',
          width: 'auto', minWidth: '140px',
          height: 56,
          borderRadius: 28,
          border: `2px solid var(--accent)`,
          background: 'transparent',
          cursor: phase === 'idle' ? 'pointer' : 'default',
          padding: 4,
          gap: 0,
          overflow: 'hidden',
          transition: 'border-color 0.2s ease',
        }}
      >
        {/* Accent circle with progress fill + icon */}
        <div style={accentCircle}>
          {/* Dark fill rises from bottom on progress */}
          <div
            ref={fillRef}
            style={{
              position: 'absolute', bottom: 0, left: 0,
              width: '100%', height: '100%',
              background: `color-mix(in oklab, var(--accent) 35%, #000 65%)`,
              transform: 'scaleY(0)',
              transformOrigin: 'bottom',
              borderRadius: 'inherit',
              zIndex: 1,
            }}
          />
          {/* Icon (download → checkmark on done) */}
          <div ref={iconRef} style={{ position: 'relative', zIndex: 2 }}>
            {phase === 'done' ? checkIcon : downloadIcon}
          </div>
        </div>

        {/* Orbiting dot during loading */}
        {phase === 'loading' && (
          <div
            ref={dotRef}
            style={{
              position: 'absolute',
              left: 4 + 24,   // center X of the circle
              top: '50%',
              width: 7, height: 7,
              marginLeft: -3.5, marginTop: -3.5,
              borderRadius: '50%',
              background: 'rgba(255,255,255,0.9)',
              animation: 'dl-orbit 1.4s linear infinite',
              zIndex: 20,
              pointerEvents: 'none',
            }}
          />
        )}

        {/* Text label */}
        <span
          ref={labelRef}
          style={{
            paddingLeft: 12, paddingRight: 14,
            color: 'var(--text)',
            fontSize: '0.92rem', fontWeight: 500,
            whiteSpace: 'nowrap',
          }}
        >
          {phase === 'done' ? doneLabel : label}
        </span>
      </button>
    </div>
  );
};

// ─── Global ripple effect ─────────────────────────────────────────────────────
// Attaches to all .btn-primary, .nav-cta, .pricing-btn-accent, .pkg-cta
const RIPPLE_TARGETS = '.btn-primary, .nav-cta, .pricing-btn-accent, .pricing-btn-default';

const attachRipple = () => {
  document.querySelectorAll(RIPPLE_TARGETS).forEach(btn => {
    if (btn.dataset.ripple) return;
    btn.dataset.ripple = '1';
    btn.classList.add('btn-ripple');
    // Light buttons get dark ripple
    if (btn.classList.contains('nav-cta') || btn.classList.contains('btn-modern-light')) {
      btn.classList.add('btn-ripple-dark');
    }

    btn.addEventListener('click', (e) => {
      const rect  = btn.getBoundingClientRect();
      const wave  = document.createElement('span');
      wave.className = 'btn-ripple-wave';
      wave.style.left = `${e.clientX - rect.left}px`;
      wave.style.top  = `${e.clientY - rect.top}px`;
      btn.appendChild(wave);
      wave.addEventListener('animationend', () => wave.remove());
    });
  });
};

// Re-attach on DOM mutations (React renders new buttons)
const _rippleObserver = new MutationObserver(attachRipple);
_rippleObserver.observe(document.body, { childList: true, subtree: true });
setTimeout(attachRipple, 500);

window.DownloadButton = DownloadButton;
