---
import { commentConfig } from "@/config";

if (!commentConfig || !commentConfig.giscus) {
	throw new Error("Giscus comments are not configured");
}

const giscus = commentConfig.giscus;
const lightTheme = "light";
const darkTheme = "dark";
---

<script is:inline type="module" src="https://esm.sh/giscus"></script>

<!-- 
  Giscus 官方Web Component用法，兼容Astro静态输出，无需import包，无需NPM依赖！
  参考：https://giscus.app/ 详情配置说明
-->
<giscus-widget
  id="comments"
  repo={giscus.repo}
  repoId={giscus.repoId}
  category={giscus.category}
  categoryId={giscus.categoryId}
  mapping={giscus.mapping}
  strict={giscus.strict}
  reactionsEnabled={giscus.reactionsEnabled}
  emitMetadata={giscus.emitMetadata}
  inputPosition={giscus.inputPosition}
  theme={lightTheme}
  lang={giscus.lang}
  loading={giscus.loading}
/>

<script is:inline define:vars={{ lightTheme, darkTheme }}>
  function updateGiscusTheme() {
    const isDark = document.documentElement.classList.contains('dark');
    const theme = isDark ? darkTheme : lightTheme;
    const widget = document.querySelector('giscus-widget');
    if (widget) {
      widget.setAttribute('theme', theme);
    }
  }

  // Initial update
  updateGiscusTheme();

  // Clean up previous observer if exists
  if (window.giscusThemeObserver) {
    window.giscusThemeObserver.disconnect();
  }

  // Create new observer
  window.giscusThemeObserver = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
        updateGiscusTheme();
      }
    });
  });

  window.giscusThemeObserver.observe(document.documentElement, { attributes: true });
</script>
