---
export interface Props {
  formula: string;
  display?: boolean; // true for block display, false for inline
  className?: string;
}

const { formula, display = false, className = '' } = Astro.props;
---

<div class={`math-formula ${display ? 'display-math' : 'inline-math'} ${className}`}>
  <span class="katex-formula" data-formula={formula}>{formula}</span>
</div>

<script>
  // 动态加载 KaTeX
  function loadKaTeX() {
    if ((window as any).katex) return Promise.resolve();
    
    return new Promise<void>((resolve, reject) => {
      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.href = 'https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.css';
      document.head.appendChild(link);
      
      const script = document.createElement('script');
      script.src = 'https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.js';
      script.onload = () => {
        const autoRenderScript = document.createElement('script');
        autoRenderScript.src = 'https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/contrib/auto-render.min.js';
        autoRenderScript.onload = () => resolve();
        autoRenderScript.onerror = reject;
        document.head.appendChild(autoRenderScript);
      };
      script.onerror = reject;
      document.head.appendChild(script);
    });
  }

  // 渲染数学公式
  function renderMath() {
    loadKaTeX().then(() => {
      const formulas = document.querySelectorAll('.katex-formula');
      formulas.forEach((formula) => {
        const text = formula.getAttribute('data-formula') || formula.textContent;
        const isDisplay = formula.closest('.display-math');
        
        try {
          (window as any).katex.render(text, formula, {
            throwOnError: false,
            displayMode: !!isDisplay
          });
        } catch (error) {
          console.warn('KaTeX rendering error:', error);
          (formula as HTMLElement).textContent = text || '';
        }
      });
    }).catch(error => {
      console.warn('Failed to load KaTeX:', error);
    });
  }

  // 页面加载完成后渲染
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', renderMath);
  } else {
    renderMath();
  }
</script>

<style>
  .math-formula {
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 0.5rem;
    transition: all 0.3s ease;
  }
  
  .inline-math {
    display: inline-block;
    padding: 0.25rem 0.5rem;
    margin: 0 0.25rem;
    border-radius: 0.25rem;
  }
  
  .display-math {
    display: block;
    padding: 1rem;
    margin: 1rem 0;
    text-align: center;
  }
  
  .math-formula:hover {
    background: rgba(255, 255, 255, 0.15);
    border-color: rgba(255, 255, 255, 0.3);
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
  
  .katex-formula {
    color: #2563eb;
    font-weight: 500;
  }
</style>