---
// 可靠的图标组件
// 提供加载状态管理和错误处理

export interface Props {
	icon: string;
	class?: string;
	style?: string;
	size?: "xs" | "sm" | "md" | "lg" | "xl" | "2xl";
	color?: string;
	fallback?: string; // 备用图标或文本
	loading?: "lazy" | "eager";
}

const {
	icon,
	class: className = "",
	style = "",
	size = "md",
	color,
	fallback = "●",
	loading = "lazy",
} = Astro.props;

// 尺寸映射
const sizeClasses = {
	xs: "text-xs",
	sm: "text-sm",
	md: "text-base",
	lg: "text-lg",
	xl: "text-xl",
	"2xl": "text-2xl",
};

const sizeClass = sizeClasses[size] || sizeClasses.md;
const colorStyle = color ? `color: ${color};` : "";
const combinedStyle = `${colorStyle}${style}`;
const combinedClass = `${sizeClass} ${className}`.trim();

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

<span 
  class={`inline-flex items-center justify-center ${combinedClass}`}
  style={combinedStyle}
  data-icon-container={iconId}
>
  <!-- 加载状态指示器 -->
  <span 
    class="icon-loading animate-pulse opacity-50"
    data-loading-indicator
  >
    {fallback}
  </span>
  
  <!-- 实际图标 -->
  <iconify-icon 
    icon={icon}
    class="icon-content opacity-0 transition-opacity duration-200"
    style="color: currentColor;"
    data-icon-element
    loading={loading}
  ></iconify-icon>
</span>

<style>
  .icon-loading {
    min-width: 1em;
    min-height: 1em;
    display: inline-flex;
    align-items: center;
    justify-content: center;
  }
  
  .icon-content {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    color: currentColor;
  }
  
  /* 确保 iconify-icon 能够继承颜色 */
  iconify-icon {
    color: currentColor;
  }
  
  [data-icon-container] {
    position: relative;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 1em;
    min-height: 1em;
  }
  
  [data-icon-container] .icon-loading,
  [data-icon-container] .icon-content {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
</style>