---
import { Image } from "astro:assets";
import * as path from "node:path";
import { coverImageConfig } from "@/config/coverImageConfig";
import { generateApiUrls } from "@/utils/image-utils";
import { url } from "@/utils/url-utils";

const { randomCoverImage } = coverImageConfig;

interface Props {
	id?: string;
	src: string;
	class?: string;
	alt?: string;
	position?: string;
	basePath?: string;
	seed?: string; // 用于生成随机图API的种子（文章slug）
	preview?: boolean; // 是否是预览模式（文章列表页），true为预览模式（小尺寸），false为详情页（大尺寸）
	fallback?: string; // 图片加载失败时的备用图片
}

const {
	id,
	src,
	alt,
	position = "center",
	basePath = "/",
	seed,
	preview = false,
	fallback,
} = Astro.props;
const className = Astro.props.class;

const isLocal = !(
	src.startsWith("/") ||
	src.startsWith("http") ||
	src.startsWith("https") ||
	src.startsWith("data:")
);
const isPublic = src.startsWith("/");

// 检查是否是随机图API（包含query参数v=）
const isRandomApiImage =
	(src.startsWith("http://") || src.startsWith("https://")) &&
	src.includes("?v=");

// TODO temporary workaround for images dynamic import
// https://github.com/withastro/astro/issues/3373
let img: ImageMetadata | null = null;
if (isLocal) {
	const files = import.meta.glob<ImageMetadata>("../../**", {
		import: "default",
	});
	let normalizedPath = path
		.normalize(path.join("../../", basePath, src))
		.replace(/\\/g, "/");
	const file = files[normalizedPath];
	if (!file) {
		console.error(
			`\n[ERROR] Image file not found: ${normalizedPath.replace("../../", "src/")}`,
		);
		img = null; // 设置为 null 而不是继续调用
	} else {
		img = await file();
	}
}
// 如果是随机图API，生成所有API URL列表用于客户端重试
let allApiUrls: string[] = [];
if (
	isRandomApiImage &&
	randomCoverImage.enable &&
	randomCoverImage.apis &&
	randomCoverImage.apis.length > 0
) {
	allApiUrls = generateApiUrls(seed);
}

// 确定fallback图片路径
let fallbackSrc = "";
if (isRandomApiImage) {
	if (randomCoverImage.enable) {
		fallbackSrc = fallback || randomCoverImage.fallback || "";
	}
} else {
	fallbackSrc = fallback || "";
}

// 处理fallback URL
const getFallbackUrl = (src: string): string => {
	if (!src) return "";
	if (src.startsWith("http://") || src.startsWith("https://")) {
		return src;
	}
	if (src.startsWith("/")) {
		return url(src);
	}
	return url(`/${src}`);
};

// 图片样式
const imageClass = "w-full h-full object-cover";
const imageStyle = `object-position: ${position || "center"}; image-rendering: -webkit-optimize-contrast;`;

// 水印配置
const watermark = randomCoverImage.watermark;
const showWatermark =
	isRandomApiImage && randomCoverImage.enable && watermark?.enable;

// 生成水印位置样式和类名
const getWatermarkStyles = (
	pos?: string,
): { classes: string; styles: string } => {
	const position = pos || "bottom-right";
	let classes = "";
	let styles = "";

	switch (position) {
		case "top-left":
			classes = "top-2 left-2";
			break;
		case "top-right":
			classes = "top-2 right-2";
			break;
		case "bottom-left":
			classes = "top-2 left-2 md:top-auto md:bottom-2 md:left-2";
			break;
		case "bottom-right":
			classes = "top-2 right-2 md:top-auto md:bottom-2 md:right-2";
			break;
		case "center":
			classes = "top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2";
			break;
		default:
			classes = "top-2 right-2 md:top-auto md:bottom-2 md:right-2";
	}

	styles = `padding: 0.25rem 0.5rem; border-radius: 0.25rem; font-size: ${watermark?.fontSize || "0.75rem"}; color: ${watermark?.color || "#ffffff"}; background-color: ${watermark?.backgroundColor || "rgba(0, 0, 0, 0.4)"}; opacity: ${watermark?.opacity || 0.6}; pointer-events: none; z-index: 10; white-space: nowrap; user-select: none;`;

	return { classes, styles };
};

const watermarkStyles = showWatermark
	? getWatermarkStyles(watermark?.position)
	: { classes: "", styles: "" };
---

<div id={id} class:list={[
  className,
  'overflow-hidden relative',
  preview ? 'min-h-[150px] md:min-h-0' : 'min-h-[300px]'
]}> 
  <!-- 加载指示器：对所有文章封面图片显示 -->
  {randomCoverImage.enable && randomCoverImage.loading?.enable !== false && (
    <div 
      class="image-loading-indicator absolute inset-0 flex items-center justify-center z-20 transition-opacity duration-300"
      style={`background-color: ${randomCoverImage.loading?.backgroundColor || '#fefefe'};`}
    >
      <img 
        src={url(randomCoverImage.loading?.image || "/assets/images/loading.gif")} 
        alt="Loading..." 
        class="w-24 h-24 md:w-32 md:h-32 opacity-80" 
      />
    </div>
  )}
  
  <!-- 本地图片：使用 Astro Image 组件 -->
  {isLocal && img && (
    <Image 
      src={img} 
      alt={alt || ""} 
      class:list={[
        imageClass,
        preview ? 'random-cover-preview-image' : 'random-cover-full-image'
      ]}
      style={imageStyle}
      width={preview ? 400 : 1200}
      height={preview ? 300 : 800}
      loading="lazy"
      format="webp"
      quality={preview ? 80 : 90}
      widths={preview ? [200, 400, 600] : [800, 1200, 1600, 2000]}
      sizes={preview ? "(max-width: 768px) 100vw, 28vw" : "(max-width: 768px) 100vw, (max-width: 1200px) 90vw, 1200px"}
      onloadstart={`(function(img){
        const container = img.parentElement;
        if (container) {
          const loadingIndicator = container.querySelector('.image-loading-indicator');
          if (loadingIndicator) {
            loadingIndicator.classList.remove('hidden');
            loadingIndicator.style.removeProperty('opacity');
            loadingIndicator.style.removeProperty('display');
          }
        }
      })(this);`}
      onload={`(function(img){
        if (img.naturalWidth > 0 && img.naturalHeight > 0) {
          setTimeout(function() {
            const container = img.parentElement;
            if (container) {
              const loadingIndicator = container.querySelector('.image-loading-indicator');
              if (loadingIndicator) {
                loadingIndicator.style.setProperty('opacity', '0', 'important');
                loadingIndicator.style.setProperty('transition', 'opacity 0.3s ease-out', 'important');
                setTimeout(function() {
                  loadingIndicator.style.setProperty('display', 'none', 'important');
                  loadingIndicator.classList.add('hidden');
                }, 300);
              }
            }
          }, 800);
        }
      })(this);`}
    />
  )}
  
  <!-- 远程图片（包括随机图API和普通远程图片） -->
  {!isLocal && (
    <img 
      src={isPublic ? url(src) : src} 
      alt={alt || ""} 
      class:list={[
        imageClass,
        preview ? 'random-cover-preview-image' : 'random-cover-full-image'
      ]}
      style={imageStyle}
      loading="lazy"
      decoding="async"
      data-preview={preview ? "true" : "false"}
      data-seed={seed || ""}
      data-api-urls={allApiUrls.length > 0 ? JSON.stringify(allApiUrls) : ""}
      data-fallback={fallbackSrc ? getFallbackUrl(fallbackSrc) : ""}
      data-api-index={allApiUrls.length > 0 ? "0" : ""}
      data-enable={isRandomApiImage ? (randomCoverImage.enable ? "true" : "false") : ""}
      data-need-check-fallback="true"
    onloadstart={`(function(img){
      const container = img.parentElement;
      if (container) {
        const loadingIndicator = container.querySelector('.image-loading-indicator');
        if (loadingIndicator) {
          loadingIndicator.classList.remove('hidden');
          loadingIndicator.style.removeProperty('opacity');
          loadingIndicator.style.removeProperty('display');
        }
      }
    })(this);`}
    onload={`(function(img){
      if (img.naturalWidth > 0 && img.naturalHeight > 0) {
        setTimeout(function() {
          const container = img.parentElement;
          if (container) {
            const loadingIndicator = container.querySelector('.image-loading-indicator');
            if (loadingIndicator) {
              loadingIndicator.style.setProperty('opacity', '0', 'important');
              loadingIndicator.style.setProperty('transition', 'opacity 0.3s ease-out', 'important');
              setTimeout(function() {
                loadingIndicator.style.setProperty('display', 'none', 'important');
                loadingIndicator.classList.add('hidden');
              }, 300);
            }
            const watermarkEl = container.querySelector('[data-watermark]');
            if (watermarkEl && watermarkEl.getAttribute('data-watermark-visible') !== 'true') {
              watermarkEl.setAttribute('data-watermark-visible', 'true');
              watermarkEl.classList.remove('opacity-0');
              watermarkEl.classList.add('opacity-100');
              const originalOpacity = watermarkEl.getAttribute('data-original-opacity') || '0.6';
              watermarkEl.style.opacity = originalOpacity;
            }
          }
        }, 800);
      }
    })(this);`}
    onerror={`(function(img){
      try {
        const apiUrls = img.dataset.apiUrls ? JSON.parse(img.dataset.apiUrls) : [];
        let currentIndex = parseInt(img.dataset.apiIndex || '0');
        const isEnabled = img.dataset.enable !== 'false';
        const fallbackUrl = img.dataset.fallback;
        
        if (apiUrls.length > 0 && currentIndex < apiUrls.length - 1) {
          currentIndex = currentIndex + 1;
          img.dataset.apiIndex = currentIndex.toString();
          img.src = apiUrls[currentIndex];
        } 
        else if (isEnabled && fallbackUrl && fallbackUrl.length > 0) {
          const seed = img.dataset.seed;
          if (seed) {
            try {
              localStorage.setItem('api_image_failed_' + seed, 'true');
            } catch (e) {}
          }
          const container = img.parentElement;
          if (container) {
            const watermarkEl = container.querySelector('[data-watermark]');
            if (watermarkEl) {
              watermarkEl.textContent = 'Image API Error';
              watermarkEl.setAttribute('data-error', 'true');
            }
          }
          img.onerror = null;
          img.src = fallbackUrl;
          img.addEventListener('load', function() {
            if (img.naturalWidth > 0 && img.naturalHeight > 0) {
              const container = img.parentElement;
              if (container) {
                const loadingIndicator = container.querySelector('.image-loading-indicator');
                if (loadingIndicator) {
                  loadingIndicator.style.opacity = '0';
                  setTimeout(function() {
                    loadingIndicator.style.display = 'none';
                  }, 300);
                }
                const watermarkEl = container.querySelector('[data-watermark]');
                if (watermarkEl && watermarkEl.getAttribute('data-watermark-visible') !== 'true') {
                  watermarkEl.setAttribute('data-watermark-visible', 'true');
                  watermarkEl.classList.remove('opacity-0');
                  watermarkEl.classList.add('opacity-100');
                  const originalOpacity = watermarkEl.getAttribute('data-original-opacity') || '0.6';
                  watermarkEl.style.opacity = originalOpacity;
                  watermarkEl.style.setProperty('opacity', originalOpacity, 'important');
                }
              }
            }
          }, { once: true });
        } 
        else {
          img.onerror = null;
          img.style.display = 'none';
          const container = img.parentElement;
          if (container) {
            const loadingIndicator = container.querySelector('.image-loading-indicator');
            if (loadingIndicator) {
              loadingIndicator.style.opacity = '0';
              setTimeout(function() {
                loadingIndicator.style.display = 'none';
              }, 300);
            }
          }
        }
      } catch(e) {
        const isEnabled = img.dataset.enable !== 'false';
        const fallbackUrl = img.dataset.fallback;
        const seed = img.dataset.seed;
        if (isEnabled && fallbackUrl && fallbackUrl.length > 0) {
          if (seed) {
            try {
              localStorage.setItem('api_image_failed_' + seed, 'true');
            } catch (e) {}
          }
          const container = img.parentElement;
          if (container) {
            const watermarkEl = container.querySelector('[data-watermark]');
            if (watermarkEl) {
              watermarkEl.textContent = 'Image API Error';
              watermarkEl.setAttribute('data-error', 'true');
            }
          }
          img.onerror = null;
          img.src = fallbackUrl;
        } else {
          img.onerror = null;
          img.style.display = 'none';
          const container = img.parentElement;
          if (container) {
            const loadingIndicator = container.querySelector('.image-loading-indicator');
            if (loadingIndicator) {
              loadingIndicator.style.opacity = '0';
              setTimeout(function() {
                loadingIndicator.style.display = 'none';
              }, 300);
            }
          }
        }
      }
    })(this);`}
    />
  )}
  
  {showWatermark && (
    <div 
      data-watermark="true"
      data-watermark-visible="false"
      data-original-opacity={watermark?.opacity || "0.6"}
      class:list={["absolute", watermarkStyles.classes, "pointer-events-none", "z-10"]}
      style={`${watermarkStyles.styles} opacity: 0 !important;`}
    >
      {watermark?.text || "Random Cover"}
    </div>
  )}
</div>

<style>
  .image-loading-indicator {
    opacity: 1 !important;
    display: flex !important;
    visibility: visible !important;
    z-index: 20;
  }
  
  .image-loading-indicator.hidden {
    opacity: 0 !important;
    display: none !important;
    visibility: hidden !important;
  }
  
  img.random-cover-preview-image,
  img[data-preview="true"] {
    min-height: 150px;
    @media (min-width: 768px) {
      min-height: 0;
    }
    image-rendering: -webkit-optimize-contrast !important;
    image-rendering: auto !important;
    transform: translateZ(0);
    -webkit-transform: translateZ(0);
    will-change: transform;
    backface-visibility: hidden;
    -webkit-backface-visibility: hidden;
    -ms-interpolation-mode: bicubic;
    object-fit: cover !important;
    max-width: 100%;
    max-height: 100%;
    width: 100%;
    height: 100%;
  }
  
  img.random-cover-full-image {
    min-height: 300px;
    image-rendering: -webkit-optimize-contrast !important;
    image-rendering: auto !important;
    transform: translateZ(0);
    -webkit-transform: translateZ(0);
    object-fit: cover !important;
    width: 100%;
    height: 100%;
  }
</style>

<script is:inline>
  (function() {
    function isPageRefresh() {
      try {
        if (window.performance && window.performance.getEntriesByType) {
          const navEntries = window.performance.getEntriesByType('navigation');
          if (navEntries.length > 0) {
            const navType = navEntries[0].type;
            if (navType === 'reload' || navType === 'navigate') {
              return true;
            }
            if (navType === 'back_forward') {
              return false;
            }
          }
        }
        const perf = /** @type {any} */ (window.performance);
        if (perf && perf.navigation) {
          const navType = perf.navigation.type;
          if (navType === perf.navigation.TYPE_RELOAD) {
            return true;
          }
          if (navType === 2) {
            return false;
          }
        }
        const refreshCheckKey = 'random_cover_image_last_init_time';
        const navigationCheckKey = 'random_cover_image_navigation_type';
        const now = Date.now();
        const lastInitTime = sessionStorage.getItem(refreshCheckKey);
        const lastNavType = sessionStorage.getItem(navigationCheckKey);
        
        if (!lastInitTime || (now - parseInt(lastInitTime)) > 10000) {
          sessionStorage.setItem(refreshCheckKey, now.toString());
          sessionStorage.setItem(navigationCheckKey, 'refresh');
          return true;
        }
        
        if (lastNavType === 'back_forward' && (now - parseInt(lastInitTime)) < 5000) {
          return false;
        }
        
        sessionStorage.setItem(refreshCheckKey, now.toString());
        sessionStorage.setItem(navigationCheckKey, 'refresh');
        return true;
      } catch (e) {
        console.warn('Unable to detect page refresh type, clearing cache as fallback', e);
        return true;
      }
    }
    
    function clearApiFailureCache() {
      try {
        const keysToRemove = [];
        for (let i = 0; i < localStorage.length; i++) {
          const key = localStorage.key(i);
          if (key && key.startsWith('api_image_failed_')) {
            keysToRemove.push(key);
          }
        }
        keysToRemove.forEach(function(key) {
          localStorage.removeItem(key);
        });
        if (keysToRemove.length > 0) {
          console.log('Cleared ' + keysToRemove.length + ' API failure records on page refresh');
        }
      } catch (e) {
        console.warn('Failed to clear API failure cache', e);
      }
    }
    
    function checkAndUseFallbackForFailedApis() {
      const allApiImages = document.querySelectorAll('img[data-seed][data-fallback][data-enable="true"]');
      
      allApiImages.forEach(function(img) {
        const seed = img.dataset.seed;
        const fallbackUrl = img.dataset.fallback;
        
        if (seed && fallbackUrl) {
          try {
            const failureKey = 'api_image_failed_' + seed;
            if (localStorage.getItem(failureKey) === 'true') {
              if (img.src !== fallbackUrl && !img.src.includes(fallbackUrl.split('?')[0])) {
                img.src = fallbackUrl;
              }
              const container = img.parentElement;
              if (container) {
                const watermarkEl = container.querySelector('[data-watermark]');
                if (watermarkEl) {
                  watermarkEl.textContent = 'Image API Error';
                  watermarkEl.setAttribute('data-error', 'true');
                  const loadingIndicator = container.querySelector('.image-loading-indicator');
                  if (img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
                    if (loadingIndicator) {
                      loadingIndicator.style.opacity = '0';
                      setTimeout(function() {
                        loadingIndicator.style.display = 'none';
                      }, 300);
                    }
                    watermarkEl.setAttribute('data-watermark-visible', 'true');
                    watermarkEl.classList.remove('opacity-0');
                    watermarkEl.classList.add('opacity-100');
                    const originalOpacity = watermarkEl.getAttribute('data-original-opacity') || '0.6';
                    watermarkEl.style.opacity = originalOpacity;
                    watermarkEl.style.setProperty('opacity', originalOpacity, 'important');
                  } else {
                    img.addEventListener('load', function() {
                      if (img.naturalWidth > 0 && img.naturalHeight > 0) {
                        if (loadingIndicator) {
                          loadingIndicator.style.opacity = '0';
                          setTimeout(function() {
                            loadingIndicator.style.display = 'none';
                          }, 300);
                        }
                        watermarkEl.setAttribute('data-watermark-visible', 'true');
                        watermarkEl.classList.remove('opacity-0');
                        watermarkEl.classList.add('opacity-100');
                        const originalOpacity = watermarkEl.getAttribute('data-original-opacity') || '0.6';
                        watermarkEl.style.opacity = originalOpacity;
                        watermarkEl.style.setProperty('opacity', originalOpacity, 'important');
                      }
                    }, { once: true });
                  }
                }
              }
            }
          } catch (e) {}
        }
      });
    }
    
    function showLoadingIndicator(img) {
      if (!img.dataset.seed && img.dataset.preview !== 'true') {
        return;
      }
      const container = img.closest('[id]') || img.parentElement;
      if (container) {
        const loadingIndicator = container.querySelector('.image-loading-indicator');
        if (loadingIndicator) {
          loadingIndicator.classList.remove('hidden');
          loadingIndicator.style.removeProperty('opacity');
          loadingIndicator.style.removeProperty('display');
        }
      }
    }
    
    function hideLoadingIndicator(img) {
      if (!img.dataset.seed && img.dataset.preview !== 'true') {
        return;
      }
      const container = img.closest('[id]') || img.parentElement;
      if (container) {
        const loadingIndicator = container.querySelector('.image-loading-indicator');
        if (loadingIndicator) {
          setTimeout(function() {
            loadingIndicator.style.setProperty('opacity', '0', 'important');
            loadingIndicator.style.setProperty('transition', 'opacity 0.3s ease-out', 'important');
            setTimeout(function() {
              loadingIndicator.style.setProperty('display', 'none', 'important');
              loadingIndicator.classList.add('hidden');
            }, 300);
          }, 800);
        }
      }
    }
    
    function showWatermark(img) {
      if (!img.complete || img.naturalWidth === 0 || img.naturalHeight === 0) {
        return;
      }
      hideLoadingIndicator(img);
      const container = img.closest('[id]') || img.parentElement;
      if (container) {
        const watermarkEl = container.querySelector('[data-watermark]');
        if (watermarkEl && watermarkEl.getAttribute('data-watermark-visible') !== 'true') {
          watermarkEl.setAttribute('data-watermark-visible', 'true');
          watermarkEl.classList.remove('opacity-0');
          watermarkEl.classList.add('opacity-100');
          const originalOpacity = watermarkEl.getAttribute('data-original-opacity') || '0.6';
          watermarkEl.style.opacity = originalOpacity;
          watermarkEl.style.setProperty('opacity', originalOpacity, 'important');
        }
      }
    }
    
    function optimizePreviewImages() {
      const previewImages = document.querySelectorAll('img[data-preview="true"]');
      previewImages.forEach(function(img) {
        if (!img.complete || img.naturalWidth === 0 || img.naturalHeight === 0) {
          showLoadingIndicator(img);
          img.addEventListener('loadstart', function() {
            showLoadingIndicator(img);
          }, { once: true });
        }
      });
    }
    
    function setupObserver() {
      const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
          mutation.addedNodes.forEach(function(node) {
            if (node.nodeType === Node.ELEMENT_NODE) {
              const element = node;
              const apiImages = [];
              if (element.tagName === 'IMG' && element.dataset.seed && element.dataset.fallback) {
                apiImages.push(element);
              }
              const childApiImages = element.querySelectorAll ? element.querySelectorAll('img[data-seed][data-fallback]') : [];
              childApiImages.forEach(function(img) {
                if (!apiImages.includes(img)) {
                  apiImages.push(img);
                }
              });
              
              apiImages.forEach(function(img) {
                showLoadingIndicator(img);
                if (img.getAttribute('data-need-check-fallback') === 'true') {
                  checkAndUseFallbackForFailedApis();
                  img.removeAttribute('data-need-check-fallback');
                }
                if (img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
                  hideLoadingIndicator(img);
                  showWatermark(img);
                } else {
                  img.addEventListener('loadstart', function() {
                    showLoadingIndicator(img);
                  }, { once: true });
                  img.addEventListener('load', function() {
                    if (img.naturalWidth > 0 && img.naturalHeight > 0) {
                      hideLoadingIndicator(img);
                      showWatermark(img);
                    }
                  }, { once: true });
                  img.addEventListener('error', function() {
                    setTimeout(function() {
                      hideLoadingIndicator(img);
                    }, 500);
                  }, { once: true });
                }
              });
            }
          });
        });
      });
      
      if (document.body) {
        observer.observe(document.body, { childList: true, subtree: true });
      } else {
        document.addEventListener('DOMContentLoaded', function() {
          observer.observe(document.body, { childList: true, subtree: true });
        });
      }
    }
    
    function initializeImages() {
      if (isPageRefresh()) {
        clearApiFailureCache();
      } else {
        checkAndUseFallbackForFailedApis();
      }
      optimizePreviewImages();
      
      const allApiImages = document.querySelectorAll('img[data-seed][data-fallback]');
      allApiImages.forEach(function(img) {
        showLoadingIndicator(img);
        img.addEventListener('loadstart', function() {
          showLoadingIndicator(img);
        }, { once: true });
        
        if (img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
          hideLoadingIndicator(img);
          showWatermark(img);
        } else {
          img.addEventListener('load', function() {
            if (img.naturalWidth > 0 && img.naturalHeight > 0) {
              hideLoadingIndicator(img);
              showWatermark(img);
            }
          }, { once: true });
          img.addEventListener('error', function() {
            setTimeout(function() {
              hideLoadingIndicator(img);
            }, 500);
          }, { once: true });
        }
      });
      
      setupObserver();
    }
    
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', initializeImages);
    } else {
      initializeImages();
    }
    
    // 监听页面可见性变化（从其他页面返回时重新检查）
    document.addEventListener('visibilitychange', function() {
      if (!document.hidden) {
        if (!isPageRefresh()) {
          setTimeout(checkAndUseFallbackForFailedApis, 100);
        }
      }
    });
    
    // 监听popstate事件（浏览器前进/后退）
    window.addEventListener('popstate', function() {
      try {
        sessionStorage.setItem('random_cover_image_navigation_type', 'back_forward');
        sessionStorage.setItem('random_cover_image_last_init_time', Date.now().toString());
      } catch (e) {
        // 忽略错误
      }
      setTimeout(function() {
        checkAndUseFallbackForFailedApis();
      }, 50);
    });
  })();
</script>