<script type="module">
  (function() {
    
    function initArtalk() {
      const el = document.getElementById('artalk_container');
      if (!el) return;

      // artalk 邮件通知链接携带 ?atk_comment=<id> / #atk-comment-<id> 定位目标，
      // 命中时跳过视口懒加载立即初始化，让 Artalk 自身的 list-goto 逻辑完成定位。
      const hasAtkTarget = /[?&]atk_comment=\d+/.test(window.location.search) || /#atk-comment-\d+/.test(window.location.hash);
      
      function load_artalk() {
        utils.css('<%- url_for('/css/comments/artalk.css') %>?v=<%- stellar_info('version') %>');
        utils.css('<%- theme.comments.artalk.css %>');
        utils.js('<%- theme.comments.artalk.js %>', {defer: true}).then(function () {
          // 监听 Artalk 事件
          // FIXME: Artalk开启了懒加载会导致评论输入预览框里的图也变成data-src，导致看不到图
          // Artalk.use((ctx) => {
          //   ctx.on('list-loaded', () => window.lazyLoadInstance?.update())
          // })
          // 邮件通知链接以 ?atk_comment=<id> 定位，Artalk 在 list-loaded 时才重新读取 URL，
          // 固定延时清理会与之竞态（#598）。先把评论 id 改写到 hash（Artalk 读取优先级高于 query），
          // 同时立即移除 atk_comment 查询参数，避免其 hash 监听干扰目录定位；
          // atk_notify_key 保留到 list-loaded 完成定位与已读回执后再清理。
          const atkComment = window.location.search.match(/[?&]atk_comment=(\d+)/);
          if (atkComment && !/#atk-comment-\d+/.test(window.location.hash)) {
            const params = new URLSearchParams(window.location.search);
            const notifyKey = params.get('atk_notify_key');
            const query = notifyKey ? '?atk_notify_key=' + encodeURIComponent(notifyKey) : '';
            window.history.replaceState(null, '', window.location.pathname + query + '#atk-comment-' + atkComment[1]);
          }
          const path = el.getAttribute('comment_id') ?? decodeURI(window.location.pathname);
          const artalk = Artalk.init({
            el: '#artalk_container',
            pageKey: path,
            pageTitle: '<%= page.title %>',
            server: '<%= theme.comments.artalk.server %>',
            site: '<%= theme.comments.artalk.site %>',
            darkMode: '<%= theme.comments.artalk.darkMode %>',
            <% if (theme.comments.artalk.imageUploader?.api) { %>
            imgUploader: function(file) {
              let headers = new Headers();
              headers.set('Accept', 'application/json');
              <% if (theme.comments.artalk.imageUploader?.token) { %>
                headers.set('Authorization', '<%- theme.comments.artalk.imageUploader?.token %>')
              <% } %>
              let formData = new FormData();
              formData.append('file', file);
              return fetch('<%- theme.comments.artalk.imageUploader?.api %>',{
                method: 'POST',
                body: formData,
                headers: headers
                }).then((resp) => resp.json())
                  .then((resp) => resp.<%- theme.comments.artalk.imageUploader?.resp %>)
              },
            <% } %>
          });
          // list-loaded 时 Artalk 已读取 atk_comment / atk_notify_key 并触发定位与已读回执，
          // 此时再清理残留的 ?atk_* 参数，避免固定延时与异步加载竞态（#598）。
          if (hasAtkTarget && window.location.search.indexOf('atk_') !== -1) {
            artalk.on('list-loaded', function () {
              window.setTimeout(function () {
                window.history.replaceState(null, '', window.location.pathname + window.location.hash);
              }, 0);
            });
          }
        });
      }
      
      util.viewportLazyload(el, load_artalk, !hasAtkTarget);
    }
    
    // Initialize on page load
    initArtalk();
  })();
</script>
