/**
 * Help text for restriction message fields that fall back to the shared
 * default message, with a link to where that message is edited.
 *
 * Member Access rules use it inside the admin app. The Restricted Content
 * block and the per-post Access Restriction dialog pass the URL from their own
 * runtime data, since they run in the post editor.
 *
 * @package ArraySubs
 */

import React from "react";
import { createInterpolateElement } from "@wordpress/element";
import { __ } from "@wordpress/i18n";
import { buildUrl } from "@libs/url";
import "./default-message-help.scss";

export const CONTENT_GATE_ROUTE = "/settings/content-gate";
export const DEFAULT_MESSAGE_SECTION = "default-message";

/**
 * Admin app URL of the Content Gate page, opened at the default message.
 *
 * @return {string} Absolute admin URL.
 */
export const getDefaultMessageUrl = () => {
  const adminUrl =
    window.arraySubs?.env?.wpAdminUrl || `${window.location.origin}/wp-admin/`;

  return `${buildUrl(`${adminUrl}admin.php`, {
    page: "arraysubs-mainadmin",
  })}#${CONTENT_GATE_ROUTE}?section=${DEFAULT_MESSAGE_SECTION}`;
};

// Opens in a new tab so unsaved editor changes are kept. The arrow is text,
// like WordPress's ExternalLink, so the sentence's closing period cannot wrap
// onto a line of its own after it.
const NewTabLink = ({ href, children }) => (
  <a
    className="arraysubs-default-message-help__link"
    href={href}
    target="_blank"
    rel="noopener noreferrer"
  >
    {children}
    <span className="arraysubs-default-message-help__icon" aria-hidden="true">
      &#8599;
    </span>
    <span className="screen-reader-text">
      {__("(opens in a new tab)", "arraysubs")}
    </span>
  </a>
);

/**
 * @param {Object} props
 * @param {string} [props.url] Content Gate URL; defaults to the admin app URL.
 */
const DefaultMessageHelp = ({ url }) =>
  createInterpolateElement(
    __(
      "Leave empty to use the default message from <link>ArraySubs → Settings → Content Gate</link>.",
      "arraysubs",
    ),
    {
      link: <NewTabLink href={url || getDefaultMessageUrl()} />,
    },
  );

export default DefaultMessageHelp;
