/**
 * Login as User — User Profile Heading Button
 *
 * Injects a "Login as {name}" button next to the h1 heading
 * on wp-admin/user-edit.php and wp-admin/profile.php.
 */
import domReady from "@wordpress/dom-ready";
import { __, sprintf } from "@wordpress/i18n";

const BUTTON_ID = "arraysubs-login-as-user-heading-link";
const MEMBER_DETAILS_BUTTON_ID = "arraysubspro-member-details-heading-link";

const createLoginAsUserButton = ({ url, displayName, isAvailable, reason }) => {
  const button = document.createElement(isAvailable ? "a" : "button");

  button.id = BUTTON_ID;
  button.className = "page-title-action arraysubs-login-as-user-heading-link";

  if (isAvailable) {
    button.href = url;
  } else {
    button.type = "button";
    button.disabled = true;
    button.classList.add("arraysubs-login-as-user-heading-link--disabled");
    if (reason) {
      button.title = reason;
      button.setAttribute("aria-label", reason);
    }
  }

  /* translators: %s: user display name */
  button.textContent = sprintf(__("Login as %s", "arraysubs"), displayName);

  return button;
};

domReady(() => {
  const data = window.arraySubsLoginAsUser;

  if (!data?.displayName || document.getElementById(BUTTON_ID)) {
    return;
  }

  const mountButton = () => {
    if (document.getElementById(BUTTON_ID)) {
      return true;
    }

    const memberDetailsButton = document.getElementById(
      MEMBER_DETAILS_BUTTON_ID,
    );
    const heading = document.querySelector(".wrap > h1");
    const target = memberDetailsButton || heading;

    if (!target) {
      return false;
    }

    target.insertAdjacentElement(
      "afterend",
      createLoginAsUserButton({
        url: data.loginUrl,
        displayName: data.displayName || "",
        isAvailable: !!data.isAvailable,
        reason: data.reason || "",
      }),
    );

    return !!memberDetailsButton;
  };

  const mountedBesideMemberDetails = mountButton();

  if (mountedBesideMemberDetails) {
    return;
  }

  let attempts = 0;
  const interval = window.setInterval(() => {
    attempts += 1;

    const loginButton = document.getElementById(BUTTON_ID);
    const memberDetailsButton = document.getElementById(
      MEMBER_DETAILS_BUTTON_ID,
    );

    if (loginButton && memberDetailsButton) {
      memberDetailsButton.insertAdjacentElement("afterend", loginButton);
      window.clearInterval(interval);
      return;
    }

    if (attempts >= 12) {
      window.clearInterval(interval);
    }
  }, 50);
});
