/**
 * ArraySubs Email Placeholders Helper
 *
 * Adds clickable placeholder buttons to WooCommerce email settings page
 * for ArraySubs subscription emails.
 *
 * @package ArraySubs
 * @since 1.0.0
 */

(function () {
  "use strict";

  /**
   * Check if current page is an ArraySubs email settings page
   */
  function isArraySubsEmailPage() {
    const bodyClasses = document.body.className;
    // Check for body class pattern: woocommerce_page_wc-settings-email-arraysubs_*
    return (
      bodyClasses.includes("woocommerce_page_wc-settings") &&
      bodyClasses.includes("arraysubs_")
    );
  }

  /**
   * Extract placeholders from the page's aria-label attributes
   */
  function extractPlaceholdersFromPage() {
    const placeholders = new Set();
    const helpTips = document.querySelectorAll(".woocommerce-help-tip");

    helpTips.forEach(function (tip) {
      const label = tip.getAttribute("aria-label") || "";
      // Match all {placeholder_name} patterns
      const matches = label.match(/\{[a-z_]+\}/g);
      if (matches) {
        matches.forEach(function (match) {
          placeholders.add(match);
        });
      }
    });

    return Array.from(placeholders);
  }

  /**
   * Get placeholder description
   */
  function getPlaceholderDescription(placeholder) {
    const descriptions = {
      "{site_title}": "Website name",
      "{site_address}": "Website address",
      "{site_url}": "Website URL",
      "{store_email}": "Store email address",
      "{customer_name}": "Customer's full name",
      "{customer_first_name}": "Customer's first name",
      "{customer_email}": "Customer's email address",
      "{subscription_id}": "Subscription ID number",
      "{subscription_status}": "Current subscription status",
      "{product_name}": "Subscription product name",
      "{billing_period}": "Billing period (e.g., 'every month')",
      "{next_payment_date}": "Next payment due date",
      "{next_payment_amount}": "Next payment amount",
      "{recurring_amount}": "Recurring payment amount",
      "{last_payment_date}": "Last successful payment date",
      "{last_payment_amount}": "Last payment amount",
      "{trial_end_date}": "Trial expiration date",
      "{expiration_date}": "Subscription expiration date",
      "{my_account_url}": "Link to My Account page",
      "{manage_subscription_url}": "Link to manage subscription",
      "{update_payment_url}": "Link to update payment method",
      "{credit_amount}": "Store credit amount",
      "{new_balance}": "New credit balance after change",
      "{credit_balance}": "Current store credit balance",
      "{credit_source}": "Source of the credit",
      "{order_id}": "Order ID number",
      "{order_url}": "Link to order details",
      "{shop_url}": "Link to shop page",
      "{days_remaining}": "Days until expiration",
      "{skipped_cycles}": "Number of skipped billing cycles",
      "{pause_date}": "Date subscription was paused",
      "{resume_date}": "Date subscription will resume",
    };
    return descriptions[placeholder] || "Email placeholder";
  }

  /**
   * Create placeholder button
   */
  function createPlaceholderButton(placeholder) {
    const btn = document.createElement("button");
    btn.type = "button";
    btn.className = "arraysubs-placeholder-btn button button-secondary";
    btn.textContent = placeholder;
    btn.title = getPlaceholderDescription(placeholder);
    btn.style.cssText =
      "margin: 3px; font-size: 12px; padding: 4px 10px; line-height: 1.4;";

    btn.addEventListener("click", function (e) {
      e.preventDefault();

      // Target the additional_content textarea by default, or last focused input
      const targetInput =
        window.arraysubsLastFocusedInput ||
        document.querySelector('textarea[id$="_additional_content"]') ||
        document.querySelector('input[id$="_subject"]');

      if (targetInput) {
        insertAtCursor(targetInput, placeholder);
        targetInput.focus();
      }
    });

    return btn;
  }

  /**
   * Insert text at cursor position
   */
  function insertAtCursor(input, text) {
    const start = input.selectionStart;
    const end = input.selectionEnd;
    const value = input.value;

    input.value = value.substring(0, start) + text + value.substring(end);
    input.selectionStart = input.selectionEnd = start + text.length;

    // Trigger change event
    input.dispatchEvent(new Event("input", { bubbles: true }));
    input.dispatchEvent(new Event("change", { bubbles: true }));
  }

  /**
   * Track last focused input/textarea
   */
  function trackFocusedInputs() {
    const inputs = document.querySelectorAll(
      '.form-table input[type="text"], .form-table textarea',
    );
    inputs.forEach(function (input) {
      input.addEventListener("focus", function () {
        window.arraysubsLastFocusedInput = input;
      });
    });
  }

  /**
   * Create placeholder panel
   */
  function createPlaceholderPanel(placeholders) {
    const container = document.createElement("div");
    container.className = "arraysubs-placeholders-panel";
    container.style.cssText = `
      background: #f0f6fc;
      border: 1px solid #c3c4c7;
      border-left: 4px solid #2271b1;
      border-radius: 4px;
      padding: 15px 20px;
      margin: 20px 0;
    `;

    const title = document.createElement("h3");
    title.textContent = "📋 Available Placeholders";
    title.style.cssText = "margin: 0 0 8px 0; font-size: 14px; color: #1d2327;";
    container.appendChild(title);

    const description = document.createElement("p");
    description.textContent =
      "Click a placeholder to insert it into the focused field. Click on Subject, Heading, or Additional Content first.";
    description.style.cssText =
      "margin: 0 0 12px 0; font-size: 13px; color: #50575e;";
    container.appendChild(description);

    const btnContainer = document.createElement("div");
    btnContainer.style.cssText = "display: flex; flex-wrap: wrap; gap: 4px;";

    placeholders.forEach(function (placeholder) {
      btnContainer.appendChild(createPlaceholderButton(placeholder));
    });

    container.appendChild(btnContainer);

    return container;
  }

  /**
   * Initialize the placeholder helper
   */
  function init() {
    if (!isArraySubsEmailPage()) {
      return;
    }

    // Extract placeholders from the page
    const placeholders = extractPlaceholdersFromPage();

    if (placeholders.length === 0) {
      return;
    }

    // Find the form table to insert before
    const formTable = document.querySelector(".form-table");
    if (!formTable) {
      return;
    }

    // Create and insert placeholder panel
    const panel = createPlaceholderPanel(placeholders);
    formTable.parentNode.insertBefore(panel, formTable);

    // Track focused inputs
    trackFocusedInputs();
  }

  // Initialize when DOM is ready
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", init);
  } else {
    init();
  }
})();
