{{- with site.Params.comments.remark42 -}}
<div id="remark42"></div>
<script>
  var remark42_config = {
    host: '{{ .host }}',
    site_id: '{{ .site_id }}',
    max_shown_comments: 15,
    theme: 'light',
    page_title: '{{ $.Title }}',
    locale: '{{ site.Language.Lang | default "zh" }}',
  };
</script>
<script src="{{ .host }}/web/embed.js"></script>
<script>
  (function () {
    function getRemark42Theme() {
      var stored = localStorage.getItem('color-theme');
      if (stored === 'light' || stored === 'dark') return stored;
      if (stored === 'system') {
        return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
      }
      var defaultTheme = '{{ site.Params.theme.default }}';
      if (defaultTheme === 'light' || defaultTheme === 'dark') return defaultTheme;
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    }

    function setRemark42Theme() {
      var frame = document.querySelector('iframe#remark42-frame');
      if (frame && frame.contentWindow) {
        frame.contentWindow.postMessage(
          { theme: getRemark42Theme() },
          remark42_config.host
        );
      }
    }

    remark42_config.theme = getRemark42Theme();

    window.addEventListener('message', function (e) {
      if (e.data && e.data.remark42) {
        setRemark42Theme();
      }
    });

    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', setRemark42Theme);

    var toggles = document.querySelectorAll('.hextra-theme-toggle-options [data-item]');
    if (toggles) {
      toggles.forEach(function (toggle) {
        toggle.addEventListener('click', function () {
          setTimeout(setRemark42Theme, 200);
        });
      });
    }
  })();
</script>
{{- else -}}
  {{ warnf "remark42 is not configured" }}
{{- end -}}
