/**
 * In v2, the installtion code was this:
 *
 *  <script type="text/javascript" id="hyvor-talk-script">
    var HYVOR_TALK_WEBSITE = 1; // DO NOT CHANGE THIS
    var HYVOR_TALK_CONFIG = {
      url: false, // Replace "false" with the CANONICAL URL of the webpage
      id: false // Replace "false" with the UNIQUE ID of the webpage
    }
  </script>
  <script type="text/javascript" src="//talk.hyvor.com/web-api/embed"></script>
 *
 * This script replaces it with a minimal v3 code
 */

function loadHyvorTalk() {
    // first, add the v3 script
    const script = document.createElement("script");
    script.type = "module";
    const instance = window.HYVOR_TALK_INSTANCE || "https://talk.hyvor.com";
    script.src = instance + "/embed/embed.js";
    script.async = true;
    document.head.appendChild(script);

    // then, add the <hyvor-talk-comments> tag
    const wrap = document.getElementById("hyvor-talk-view");
    const htScript = document.getElementById("hyvor-talk-script");
    const comments = document.createElement("hyvor-talk-comments");

    // website-id
    const websiteId = window.HYVOR_TALK_WEBSITE;
    if (!websiteId) {
        console.error("HYVOR_TALK_WEBSITE is not defined");
        return;
    }
    comments.setAttribute("website-id", websiteId);

    const config = window.HYVOR_TALK_CONFIG || {};

    // page-id
    if (config.id) {
        comments.setAttribute("page-id", config.id);
    }

    // sso
    if (config.sso) {
        comments.setAttribute("sso-user", config.sso.userData);
        comments.setAttribute("sso-hash", config.sso.hash);
    }

    // testing
    if (window.HYVOR_TALK_INSTANCE) {
        comments.setAttribute("instance", window.HYVOR_TALK_INSTANCE);
    }

    if (wrap) wrap.appendChild(comments);
    else if (htScript) htScript.parentElement?.insertBefore(comments, htScript);
}

loadHyvorTalk();
