(function () {
  if (!window.retellClientJsSdk || !window.retellClientJsSdk.RetellWebClient) {
    return;
  }

  var wrap = document.getElementById("retell-btn-wrap");
  var btn = document.getElementById("retell-btn");
  var label = document.getElementById("retell-label");

  if (!wrap || !btn) {
    return;
  }

  var config = window.storevoiceaiCallWidget || {};
  var i18n = config.i18n || {};
  var LABELS = {
    idle: i18n.callUs || "Call us",
    connecting: i18n.connecting || "Connecting…",
    active: i18n.endCall || "Tap to end call",
  };

  function setState(name) {
    wrap.className = name === "idle" ? "" : name;
    if (label) label.textContent = LABELS[name] || LABELS.idle;
  }

  function hideWidget() {
    document.body.classList.add("storevoiceai-minutes-exhausted");
    wrap.hidden = true;
  }

  var active = false;
  var client = new window.retellClientJsSdk.RetellWebClient();

  client.on("call_started", function () {
    active = true;
    setState("active");
  });

  client.on("call_ended", function () {
    active = false;
    setState("idle");
  });

  client.on("error", function (e) {
    console.error("Retell error:", e);
    active = false;
    setState("idle");
  });

  btn.addEventListener("click", function () {
    if (active) {
      try {
        client.stopCall();
      } catch (e) {
        console.error("stopCall error:", e);
      }
      active = false;
      setState("idle");
      btn.disabled = false;
      return;
    }

    setState("connecting");
    btn.disabled = true;

    fetch(config.ajax_url, {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: new URLSearchParams({
        action: "storevoiceai_create_call",
        nonce: config.nonce,
      }),
    })
      .then(function (res) {
        if (!res.ok) {
          return res.text().then(function (body) {
            var detail = body ? ": " + body.slice(0, 300) : "";
            throw new Error("Call request failed (" + res.status + " " + res.statusText + ")" + detail);
          });
        }
        return res.json();
      })
      .then(function (json) {
        if (!json.success) {
          console.error("Call failed:", json.data);
          var isMinutesExhausted =
            json.data && json.data.code === "minutes_exhausted";

          var message =
            isMinutesExhausted
              ? "You've run out of call minutes. Please top up to continue."
              : (json.data && json.data.message) || "Failed to start call";

          if (isMinutesExhausted) {
            hideWidget();
          }

          if (
            window.StoreVoiceAINotice &&
            typeof window.StoreVoiceAINotice.show === "function" &&
            window.jQuery
          ) {
            window.StoreVoiceAINotice.show({
              target: window.jQuery(wrap),
              type: "error",
              message: message,
              position: "before",
              autoDismiss: false,
            });
          } else {
            console.log(message);
          }

          setState("idle");
          return;
        }

        return client.startCall({
          accessToken: json.data.access_token,
        });
      })
      .catch(function (err) {
        console.error("Request error:", err);
        setState("idle");
      })
      .finally(function () {
        btn.disabled = false;
      });
  });
})();
