---
export interface Props {
  code: string;
  language?: string;
  title?: string;
  showLineNumbers?: boolean;
  className?: string;
  copyable?: boolean;
}

const { 
  code, 
  language = 'javascript', 
  title, 
  showLineNumbers = false, 
  className = '',
  copyable = true 
} = Astro.props;

// 生成唯一ID
const codeId = `code-${Math.random().toString(36).substring(2, 11)}`;
---

<div class={`glass-code-block ${className}`}>
  {title && (
    <div class="code-header">
      <span class="code-title">{title}</span>
      <span class="code-language">{language}</span>
      {copyable && (
        <button class="copy-btn" data-code-id={codeId} title="复制代码">
          <i class="fas fa-copy"></i>
        </button>
      )}
    </div>
  )}
  <div class="code-content">
    <pre class={`language-${language} ${showLineNumbers ? 'line-numbers' : ''}`}><code id={codeId} class={`language-${language}`}>{code}</code></pre>
  </div>
</div>

<script>
  // 动态加载 Prism.js
  function loadPrism() {
    if ((window as any).Prism) return Promise.resolve();
    
    return new Promise<void>((resolve, reject) => {
      // 加载行号插件 CSS（结构样式）
      const lineNumbersCss = document.createElement('link');
      lineNumbersCss.rel = 'stylesheet';
      lineNumbersCss.href = 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/line-numbers/prism-line-numbers.min.css';
      document.head.appendChild(lineNumbersCss);
      
      // 加载核心 JS
      const script = document.createElement('script');
      script.src = 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js';
      script.onload = () => {
        // 加载自动加载插件
        const autoloaderScript = document.createElement('script');
        autoloaderScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js';
        autoloaderScript.onload = () => {
          // 加载行号插件
          const lineNumbersScript = document.createElement('script');
          lineNumbersScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/line-numbers/prism-line-numbers.min.js';
          lineNumbersScript.onload = () => resolve();
          lineNumbersScript.onerror = reject;
          document.head.appendChild(lineNumbersScript);
        };
        autoloaderScript.onerror = reject;
        document.head.appendChild(autoloaderScript);
      };
      script.onerror = reject;
      document.head.appendChild(script);
    });
  }

  // 高亮代码
  function highlightCode() {
    loadPrism().then(() => {
      const prism = (window as any).Prism;
      if (prism && prism.highlightAll) {
        prism.highlightAll();
      }
    }).catch(error => {
      console.warn('Failed to load Prism.js:', error);
    });
  }

  // 复制代码功能
  function initCopyButtons() {
    document.querySelectorAll('.copy-btn').forEach(btn => {
      btn.addEventListener('click', async function(this: HTMLElement) {
        const codeId = this.getAttribute('data-code-id');
        const codeElement = document.getElementById(codeId || '');
        if (!codeElement) return;
        
        const code = codeElement.textContent || '';
        
        try {
          await navigator.clipboard.writeText(code);
          const icon = this.querySelector('i') as HTMLElement;
          const originalClass = icon.className;
          icon.className = 'fas fa-check';
          this.style.color = '#22c55e';
          
          setTimeout(() => {
            icon.className = originalClass;
            this.style.color = '';
          }, 2000);
        } catch (err) {
          console.warn('Failed to copy code:', err);
        }
      });
    });
  }

  // 页面加载完成后初始化
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
      highlightCode();
      initCopyButtons();
    });
  } else {
    highlightCode();
    initCopyButtons();
  }
</script>

<style>
  .glass-code-block {
    background: rgba(255, 255, 255, 0.12);
    backdrop-filter: blur(22px);
    border: 1px solid rgba(148, 163, 184, 0.35);
    border-radius: 1rem;
    margin: 1.5rem 0;
    overflow: hidden;
    box-shadow: 0 10px 36px rgba(15, 23, 42, 0.12);
    transition: all 0.3s ease;
    font-family: 'Maple Mono NF CN', 'FiraCode Nerd Font', 'Fira Code', 'JetBrains Mono', 'Cascadia Code', 'Roboto Mono', 'SFMono-Regular', monospace;
    font-feature-settings: "calt" 1, "ss01" 1;
  }
  
  .glass-code-block:hover {
    background: rgba(255, 255, 255, 0.16);
    border-color: rgba(148, 163, 184, 0.5);
    transform: translateY(-2px);
    box-shadow: 0 14px 44px rgba(15, 23, 42, 0.16);
  }
  
  .code-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0.75rem 1rem;
    background: rgba(59, 130, 246, 0.1);
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
  }
  
  .code-title {
    font-weight: 600;
    color: #1e40af;
    font-size: 0.9rem;
  }
  
  .code-language {
    font-size: 0.8rem;
    color: #1c304e;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    background: rgba(100, 116, 139, 0.156);
    padding: 0.25rem 0.5rem;
    border-radius: 0.25rem;
  }
  
  .copy-btn {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 0.375rem;
    padding: 0.5rem;
    color: #64748b;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 0.9rem;
  }
  
  .copy-btn:hover {
    background: rgba(255, 255, 255, 0.2);
    color: #3b82f6;
    transform: scale(1.05);
  }
  
  .code-content {
    overflow: auto;
    max-height: 500px;
    background: linear-gradient(135deg, rgba(224, 231, 255, 0.42) 0%, rgba(221, 242, 253, 0.32) 100%);
  }
  
  .code-content pre {
    margin: 0;
    padding: 1.5rem 1.5rem 1.5rem 3.5rem;
    background: transparent !important;
    font-size: 0.9rem;
    line-height: 1.6;
    overflow: auto;
    color: #0f172a;
    font-family: 'Maple Mono NF CN', 'FiraCode Nerd Font', 'Fira Code', 'JetBrains Mono', 'Cascadia Code', 'Roboto Mono', monospace;
  }
  
  .code-content code {
    background: transparent !important;
    color: inherit !important;
    font-family: 'Maple Mono NF CN', 'FiraCode Nerd Font', 'Fira Code', 'JetBrains Mono', 'Cascadia Code', 'Roboto Mono', monospace;
    font-variant-ligatures: contextual;
  }
  
  /* 覆盖 Prism 默认样式 */
  .code-content pre[class*="language-"] {
    background: transparent !important;
    box-shadow: none !important;
    border: none !important;
  }
  
  /* 行号样式 */
  :global(.line-numbers .line-numbers-rows) {
    border-right: 1px solid rgba(100, 116, 139, 0.35) !important;
    background: rgba(15, 23, 42, 0.08) !important;
    padding: 1.5rem 0.75rem !important;
    text-align: right !important;
  }
  
  :global(.line-numbers-rows > span:before) {
    color: #334155 !important;
    display: inline-block;
    width: 100%;
    text-align: right;
  }
  
  /* 语法高亮颜色调整 */
  :global(.code-content .token.comment),
  :global(.code-content .token.prolog),
  :global(.code-content .token.doctype),
  :global(.code-content .token.cdata) {
    color: #475569 !important;
    font-style: italic;
  }
  
  :global(.code-content .token.punctuation) {
    color: #1e293b !important;
    font-weight: 500;
  }
  
  :global(.code-content .token.property),
  :global(.code-content .token.tag),
  :global(.code-content .token.boolean),
  :global(.code-content .token.number),
  :global(.code-content .token.constant),
  :global(.code-content .token.symbol),
  :global(.code-content .token.deleted) {
    color: #b45309 !important;
    font-weight: 600;
  }
  
  :global(.code-content .token.selector),
  :global(.code-content .token.attr-name),
  :global(.code-content .token.string),
  :global(.code-content .token.char),
  :global(.code-content .token.builtin),
  :global(.code-content .token.inserted) {
    color: #047857 !important;
  }
  
  :global(.code-content .token.operator),
  :global(.code-content .token.entity),
  :global(.code-content .token.url),
  :global(.language-css .token.string),
  :global(.style .token.string) {
    color: #2563eb !important;
    font-weight: 500;
  }
  
  :global(.code-content .token.atrule),
  :global(.code-content .token.attr-value),
  :global(.code-content .token.keyword) {
    color: #7c3aed !important;
    font-weight: 600;
  }
  
  :global(.code-content .token.function),
  :global(.code-content .token.class-name) {
    color: #db2777 !important;
    font-weight: 600;
  }

  :global(.code-content .token.regex),
  :global(.code-content .token.important),
  :global(.code-content .token.variable) {
    color: #0f766e !important;
  }

  :global(.code-content .token.bold) {
    font-weight: 700;
  }

  :global(.code-content .token.italic) {
    font-style: italic;
  }
  
  /* 响应式设计 */
  @media (max-width: 768px) {
    .code-header {
      padding: 0.5rem 0.75rem;
    }
    
    .code-content pre {
      padding: 1rem;
      font-size: 0.8rem;
    }
    
    .copy-btn {
      padding: 0.375rem;
      font-size: 0.8rem;
    }
  }
  
  /* 滚动条样式 */
  .code-content::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }
  
  .code-content::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.1);
  }
  
  .code-content::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.2);
    border-radius: 3px;
  }
  
  .code-content::-webkit-scrollbar-thumb:hover {
    background: rgba(255, 255, 255, 0.3);
  }
</style>