/**
 * Profile Fields Frontend
 *
 * Handles avatar upload/remove and file field interactions
 * on the WooCommerce My Account > Account Details page.
 *
 * @package ArraySubs
 * @since 1.9.0
 */

import "@scss/customer-portal/profile-fields.scss";

(function () {
  "use strict";

  const config = window.arraySubsProfileFields;

  if (!config) {
    return;
  }

  const { nonce, apiBaseUrl, i18n } = config;

  function getApiUrl(path) {
    const base = apiBaseUrl || "";
    const cleanBase = base.endsWith("/") ? base : `${base}/`;
    const cleanPath = String(path || "").replace(/^\/+/, "");
    return `${cleanBase}${cleanPath}`;
  }

  /**
   * Avatar section handling
   */
  function initAvatar() {
    if (!config.avatarEnabled) {
      return;
    }

    const section = document.getElementById("arraysubs-avatar-section");
    if (!section) {
      return;
    }

    const input = document.getElementById("arraysubs-avatar-input");
    const preview = document.getElementById("arraysubs-avatar-preview");
    const uploadBtn = document.getElementById("arraysubs-avatar-upload-btn");
    const removeBtn = document.getElementById("arraysubs-avatar-remove-btn");
    const status = document.getElementById("arraysubs-avatar-status");

    if (!input || !preview) {
      return;
    }

    input.addEventListener("change", async function () {
      const file = this.files[0];
      if (!file) {
        return;
      }

      const maxBytes = (config.avatarMaxSize || 2) * 1024 * 1024;
      if (file.size > maxBytes) {
        showStatus(i18n.fileTooLarge, "error");
        this.value = "";
        return;
      }

      const ext = file.name.split(".").pop().toLowerCase();
      const allowed = config.avatarTypes || ["jpg", "jpeg", "png", "gif"];
      if (!allowed.includes(ext)) {
        showStatus(i18n.invalidFileType, "error");
        this.value = "";
        return;
      }

      showStatus(i18n.uploading, "info");
      setUploading(true);

      const formData = new FormData();
      formData.append("avatar", file);

      try {
        const response = await fetch(
          getApiUrl("arraysubs/v1/profile-fields/avatar"),
          {
            method: "POST",
            headers: {
              "X-WP-Nonce": nonce,
            },
            body: formData,
          },
        );

        const data = await response.json();

        if (response.ok && data.content && data.content.url) {
          preview.src = data.content.url;
          showStatus("", "");
          updateButtons(true);
        } else {
          showStatus(data.message || i18n.uploadFailed, "error");
        }
      } catch {
        showStatus(i18n.uploadFailed, "error");
      } finally {
        setUploading(false);
        input.value = "";
      }
    });

    if (removeBtn) {
      removeBtn.addEventListener("click", async function () {
        setUploading(true);
        showStatus("", "");

        try {
          const response = await fetch(
            getApiUrl("arraysubs/v1/profile-fields/avatar"),
            {
              method: "DELETE",
              headers: {
                "X-WP-Nonce": nonce,
                "Content-Type": "application/json",
              },
            },
          );

          const data = await response.json();

          if (response.ok && data.content) {
            preview.src = data.content.url || config.gravatarUrl;
            updateButtons(false);
          } else {
            showStatus(data.message || i18n.removeFailed, "error");
          }
        } catch {
          showStatus(i18n.removeFailed, "error");
        } finally {
          setUploading(false);
        }
      });
    }

    function showStatus(message, type) {
      if (!status) return;
      status.textContent = message;
      status.className = "arraysubs-avatar-section__help";
      if (type) {
        status.classList.add(`arraysubs-avatar-section__help--${type}`);
      }
    }

    function setUploading(isUploading) {
      if (uploadBtn) {
        uploadBtn.classList.toggle(
          "arraysubs-avatar-section__upload-btn--loading",
          isUploading,
        );
      }
      if (removeBtn) {
        removeBtn.disabled = isUploading;
      }
      if (input) {
        input.disabled = isUploading;
      }
    }

    function updateButtons(hasAvatar) {
      if (uploadBtn) {
        const labelText = hasAvatar ? i18n.changeAvatar : i18n.uploadAvatar;
        // Update only the text node, preserve the input
        const textNodes = Array.from(uploadBtn.childNodes).filter(
          (n) => n.nodeType === Node.TEXT_NODE,
        );
        if (textNodes.length > 0) {
          textNodes[0].textContent = labelText;
        }
      }

      const actions = document.getElementById("arraysubs-avatar-actions");
      if (!actions) return;

      let currentRemoveBtn = document.getElementById(
        "arraysubs-avatar-remove-btn",
      );

      if (hasAvatar && !currentRemoveBtn) {
        const btn = document.createElement("button");
        btn.type = "button";
        btn.className = "button arraysubs-avatar-section__remove-btn";
        btn.id = "arraysubs-avatar-remove-btn";
        btn.textContent = i18n.removeAvatar;
        actions.appendChild(btn);

        btn.addEventListener("click", async function () {
          setUploading(true);
          try {
            const response = await fetch(
              getApiUrl("arraysubs/v1/profile-fields/avatar"),
              {
                method: "DELETE",
                headers: {
                  "X-WP-Nonce": nonce,
                  "Content-Type": "application/json",
                },
              },
            );
            const data = await response.json();
            if (response.ok && data.content) {
              preview.src = data.content.url || config.gravatarUrl;
              updateButtons(false);
            }
          } catch {
            showStatus(i18n.removeFailed, "error");
          } finally {
            setUploading(false);
          }
        });
      } else if (!hasAvatar && currentRemoveBtn) {
        currentRemoveBtn.remove();
      }
    }
  }

  /**
   * File upload field remove buttons
   */
  function initFileFields() {
    const removeButtons = document.querySelectorAll(
      ".arraysubs-profile-field__remove-file",
    );

    removeButtons.forEach((btn) => {
      btn.addEventListener("click", function () {
        const fieldKey = this.dataset.field;
        if (!fieldKey) return;

        const wrapper = this.closest(".arraysubs-profile-field--upload");
        if (!wrapper) return;

        const currentFile = wrapper.querySelector(
          ".arraysubs-profile-field__current-file",
        );
        if (currentFile) {
          currentFile.style.display = "none";
        }

        let removeInput = wrapper.querySelector(
          `input[name="arraysubs_remove_file_${fieldKey}"]`,
        );
        if (!removeInput) {
          removeInput = document.createElement("input");
          removeInput.type = "hidden";
          removeInput.name = `arraysubs_remove_file_${fieldKey}`;
          removeInput.value = "1";
          wrapper.appendChild(removeInput);
        }
      });
    });
  }

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