$(document).ready(function () {
  // Print button
  $("#printPerson").on("click", function () {
    window.print();
  });

  // Group interactions (add, change role, remove) are handled by
  // webpack/people/person-group-manager.js — loaded via the
  // people-person-view webpack entry point.

  $("#input-person-properties").on("change", function () {
    var promptBox = $("#prompt-box");
    promptBox.removeClass("mb-3").html("");
    var selected = $("#input-person-properties :selected");
    var pro_prompt = selected.data("pro_prompt");
    var pro_value = selected.data("pro_value");
    if (pro_prompt) {
      promptBox
        .addClass("mb-3")
        .append($("<label></label>").text(pro_prompt))
        .append($('<textarea rows="3" class="form-control" name="PropertyValue"></textarea>').val(pro_value));
    }
  });

  $("#assign-property-btn").click(function (event) {
    let propertyId = "";
    let value = "";
    let dataToSend = $("#assign-property-form").serializeArray();
    $.each(dataToSend, function (key, field) {
      if (field.name === "PropertyId") {
        propertyId = field.value;
      } else if (field.name === "PropertyValue") {
        value = field.value;
      }
    });
    window.CRM.APIRequest({
      method: "POST",
      path: "people/properties/person/" + window.CRM.currentPersonID + "/" + propertyId,
      data: JSON.stringify({ value: value }),
    }).done(function (data) {
      location.reload();
    });
  });

  $(".remove-property-btn").click(function (event) {
    let propertyId = $(this).data("property_id");
    bootbox.confirm(i18next.t("Are you sure you want to unassign this property?"), function (result) {
      if (result) {
        window.CRM.APIRequest({
          method: "DELETE",
          path: "people/properties/person/" + window.CRM.currentPersonID + "/" + propertyId,
        }).done(function (data) {
          location.reload();
        });
      }
    });
  });

  $("#edit-role-btn").click(function (event) {
    event.preventDefault();
    var thisLink = $(this);
    var personId = thisLink.data("person_id");
    var familyRoleId = thisLink.data("family_role_id");
    var familyRole = thisLink.data("family_role");

    $.ajax({
      type: "GET",
      dataType: "json",
      url: window.CRM.root + "/api/persons/roles",
      success: function (data, status, xmlHttpReq) {
        if (data.length) {
          roles = [{ text: familyRole, value: "" }];
          for (var i = 0; i < data.length; i++) {
            if (data[i].OptionId == familyRoleId) {
              continue;
            }

            roles[roles.length] = {
              text: data[i].OptionName,
              value: data[i].OptionId,
            };
          }

          bootbox.prompt({
            title: i18next.t("Change role"),
            inputType: "select",
            inputOptions: roles,
            callback: function (result) {
              if (result) {
                $.ajax({
                  type: "POST",
                  dataType: "json",
                  url: window.CRM.root + "/api/person/" + personId + "/role/" + result,
                  success: function (data, status, xmlHttpReq) {
                    if (data.success) {
                      location.reload();
                    }
                  },
                });
              }
            },
          });
        }
      },
    });
  });

  // Check if MailChimp plugin is active via API and load data if so
  // Only show tab if the person has at least one email (tab content is conditionally rendered in PHP)
  if ($("#mailchimp").length > 0) {
    $.ajax({
      type: "GET",
      dataType: "json",
      url: window.CRM.root + "/plugins/status/mailchimp",
      success: function (pluginData) {
        if (pluginData.success && pluginData.isActive && pluginData.isConfigured) {
          // Show the MailChimp tab and content
          $("#nav-item-mailchimp-container").removeClass("d-none");
          $("#mailchimp").removeClass("d-none");

          // Load the person's MailChimp data
          $.ajax({
            type: "GET",
            dataType: "json",
            url: window.CRM.root + "/plugins/mailchimp/api/person/" + window.CRM.currentPersonID,
            success: function (data) {
              if (!data || data.length === 0) {
                // No email data returned - should not happen if tab is shown
                return;
              }
              for (const emailData of data) {
                let htmlVal = "";
                let emailMD5 = emailData["emailMD5"];
                let lists = emailData["list"] || [];
                for (const list of lists) {
                  let listName = list["name"];
                  let listStatus = list["status"];
                  if (listStatus != 404) {
                    let listOpenRate = (list["stats"]?.["avg_open_rate"] || 0) * 100;
                    htmlVal +=
                      "<li>" +
                      listName +
                      " (" +
                      listStatus +
                      ") - " +
                      listOpenRate.toFixed(2) +
                      "% " +
                      i18next.t("open rate") +
                      "</li>";
                  }
                }
                if (htmlVal === "") {
                  htmlVal = i18next.t("Not Subscribed");
                }
                $("#" + emailMD5).html(htmlVal);
              }
            },
            error: function () {
              // API error - update all loading cells to show error
              // Use data attribute marker instead of localized text check
              $("#mailchimp td[data-loading='true']").each(function () {
                $(this)
                  .removeAttr("data-loading")
                  .html('<span class="text-muted">' + i18next.t("Unable to load") + "</span>");
              });
            },
          });
        }
      },
    });
  }
});
