---
interface Props {
  strength?: number; // 磁性强度，1-10之间
  className?: string;
  radius?: number; // 影响半径（像素）
  smoothing?: number; // 平滑程度 (0-1)
}

const { 
  strength = 5,
  className = "",
  radius = 150,
  smoothing = 0.15
} = Astro.props;

const magnetId = `magnetic-${Math.random().toString(36).substring(2, 11)}`;
---

<div id={magnetId} class={`magnetic-element relative ${className}`}>
  <div class="magnetic-content relative inline-block z-10">
    <slot />
  </div>
</div>

<style>
  .magnetic-element {
    display: inline-block;
    transform-style: preserve-3d;
    position: relative;
  }
  
  .magnetic-content {
    position: relative;
    display: inline-block;
    transition: transform 0.1s cubic-bezier(0.165, 0.84, 0.44, 1);
  }
</style>

<script define:vars={{ magnetId, strength, radius, smoothing }}>
  document.addEventListener('DOMContentLoaded', () => {
    const magneticElement = document.getElementById(magnetId);
    if (!magneticElement) return;
    
    const magneticContent = magneticElement.querySelector('.magnetic-content');
    if (!magneticContent) return;
    
    // 计算最大移动距离（基于强度）
    const maxDistance = strength * 3;
    
    let isHovered = false;
    let rafId = null;
    
    // 鼠标移动距离
    let mouseX = 0;
    let mouseY = 0;
    
    // 当前位置
    let currentX = 0;
    let currentY = 0;
    
    const lerp = (start, end, t) => {
      return start * (1 - t) + end * t;
    };
    
    const updatePosition = () => {
      if (!isHovered) {
        // 如果没有悬停，逐渐回到原位
        currentX = lerp(currentX, 0, smoothing);
        currentY = lerp(currentY, 0, smoothing);
        
        // 如果足够接近原点，就停止动画
        if (Math.abs(currentX) < 0.1 && Math.abs(currentY) < 0.1) {
          currentX = 0;
          currentY = 0;
          cancelAnimationFrame(rafId);
          rafId = null;
          magneticContent.style.transform = '';
          return;
        }
      } else {
        // 如果悬停中，平滑过渡到目标位置
        currentX = lerp(currentX, mouseX, smoothing);
        currentY = lerp(currentY, mouseY, smoothing);
      }
      
      // 应用变换
      magneticContent.style.transform = `translate3D(${currentX}px, ${currentY}px, 0)`;
      
      // 继续动画
      rafId = requestAnimationFrame(updatePosition);
    };
    
    // 鼠标进入
    magneticElement.addEventListener('mouseenter', () => {
      isHovered = true;
      if (!rafId) {
        rafId = requestAnimationFrame(updatePosition);
      }
    });
    
    // 鼠标移动
    magneticElement.addEventListener('mousemove', (e) => {
      if (!isHovered) return;
      
      const rect = magneticElement.getBoundingClientRect();
      
      // 计算鼠标相对元素中心的位置
      const centerX = rect.left + rect.width / 2;
      const centerY = rect.top + rect.height / 2;
      
      // 鼠标距离中心的距离
      const distX = e.clientX - centerX;
      const distY = e.clientY - centerY;
      
      // 计算总距离
      const distance = Math.sqrt(distX * distX + distY * distY);
      
      // 如果鼠标在影响半径内
      if (distance < radius) {
        // 计算移动百分比（越接近中心，移动越大）
        const percent = (radius - distance) / radius;
        
        // 应用强度系数，计算最终移动距离
        mouseX = distX * percent * (maxDistance / radius);
        mouseY = distY * percent * (maxDistance / radius);
      } else {
        mouseX = 0;
        mouseY = 0;
      }
    });
    
    // 鼠标离开
    magneticElement.addEventListener('mouseleave', () => {
      isHovered = false;
    });
    
    // 页面卸载时清除动画帧
    window.addEventListener('beforeunload', () => {
      if (rafId) {
        cancelAnimationFrame(rafId);
      }
    });
  });
</script> 