(function () {
  var formSettings = window.dsproofwpFormSettings || {
    image_max_size_mb: 5,
    video_max_size_mb: 50,
    image_max_count: 5,
    video_max_count: 1,
    image_upload_enabled: true,
    video_upload_enabled: true,
    allowed_image_types: ["jpg", "jpeg", "png", "webp"],
    allowed_video_types: ["mp4", "mov", "webm"],
    recaptcha_enabled: false,
    recaptcha_site_key: "",
    recaptcha_secret_key_set: false,
    i18n: {
      unsupported_type: "Unsupported or disabled file type.",
      mixed_media:
        "Only one type of media (images or videos) is allowed per review. Mixed media was ignored.",
      large_images:
        "Some images exceeded the maximum size limit of 5MB and were ignored.",
      large_videos:
        "Some videos exceeded the maximum size limit of 50MB and were ignored.",
      max_images_limit:
        "You can only upload up to 5 image(s). Extra images were ignored.",
      max_videos_limit:
        "You can only upload up to 1 video(s). Extra videos were ignored.",
      submit_rating: "Please submit at least one rating before submitting.",
      recaptcha_required: "Please complete the reCAPTCHA challenge.",
    },
  };

  var isCaptchaRequired =
    formSettings.recaptcha_enabled &&
    formSettings.recaptcha_site_key &&
    formSettings.recaptcha_site_key.trim() !== "" &&
    formSettings.recaptcha_secret_key_set;

  if (isCaptchaRequired) {
    var SCRIPT_ID = "google-recaptcha-script";
    if (!document.getElementById(SCRIPT_ID)) {
      window.dsproofwpRenderRecaptcha = function () {
        if (typeof window.grecaptcha !== "undefined") {
          window.grecaptcha.render("dsproofwp-recaptcha-container", {
            sitekey: formSettings.recaptcha_site_key.trim(),
            callback: function (token) {
              var tokenInput = document.getElementById(
                "dsproofwp-recaptcha-token",
              );
              if (tokenInput) {
                tokenInput.value = token;
              }
            },
            "expired-callback": function () {
              var tokenInput = document.getElementById(
                "dsproofwp-recaptcha-token",
              );
              if (tokenInput) {
                tokenInput.value = "";
              }
            },
            "error-callback": function () {
              var tokenInput = document.getElementById(
                "dsproofwp-recaptcha-token",
              );
              if (tokenInput) {
                tokenInput.value = "";
              }
            },
          });
        }
      };

      var script = document.createElement("script");
      script.id = SCRIPT_ID;
      script.src =
        "https://www.google.com/recaptcha/api.js?onload=dsproofwpRenderRecaptcha&render=explicit";
      script.async = true;
      script.defer = true;
      document.head.appendChild(script);
    }
  }

  function setStars(container) {
    var stars = container.querySelectorAll(".dsproofwp-star");
    var input = container.parentNode.querySelector(".dsproofwp-rating-value");
    stars.forEach(function (star) {
      star.addEventListener("click", function () {
        input.value = this.dataset.value;
        stars.forEach(
          function (item, index) {
            item.classList.toggle("active", index < this.dataset.value);
          }.bind(this),
        );
      });
    });
  }

  document.querySelectorAll(".dsproofwp-stars").forEach(setStars);

  function setupCharacterCount(textarea) {
    var counterSpan = textarea.parentNode.querySelector(
      ".dsproofwp-char-counter",
    );
    if (!counterSpan) {
      return;
    }
    textarea.addEventListener("input", function () {
      counterSpan.textContent =
        "Character count: " + textarea.value.length + "/1000";
    });
  }
  document
    .querySelectorAll(".dsproofwp-review-text textarea")
    .forEach(setupCharacterCount);

  function setupFilePreview(card) {
    var fileField = card.querySelector(".dsproofwp-file-field");
    var previewContainer = card.querySelector(".dsproofwp-file-preview");
    if (!fileField || !previewContainer) {
      return;
    }

    // Initialize custom property to store files
    fileField.dsproofwpFiles = [];

    fileField.addEventListener("change", function () {
      var rawFiles = Array.from(fileField.files);
      if (rawFiles.length === 0) {
        return;
      }

      // 1. Determine allowed type from existing files or first new file
      var allowedType = null;
      if (fileField.dsproofwpFiles.length > 0) {
        var firstExt = fileField.dsproofwpFiles[0].name
          .split(".")
          .pop()
          .toLowerCase();
        if (
          formSettings.allowed_image_types.includes(firstExt) ||
          fileField.dsproofwpFiles[0].type.startsWith("image/")
        ) {
          allowedType = "image";
        } else {
          allowedType = "video";
        }
      } else {
        var firstFile = rawFiles[0];
        var isFirstImage = false;
        var isFirstVideo = false;

        var firstExt = firstFile.name.split(".").pop().toLowerCase();
        if (
          formSettings.allowed_image_types.includes(firstExt) ||
          firstFile.type.startsWith("image/")
        ) {
          isFirstImage = true;
        } else if (
          formSettings.allowed_video_types.includes(firstExt) ||
          firstFile.type.startsWith("video/")
        ) {
          isFirstVideo = true;
        }

        if (isFirstImage && formSettings.image_upload_enabled) {
          allowedType = "image";
        } else if (isFirstVideo && formSettings.video_upload_enabled) {
          allowedType = "video";
        } else {
          alert(formSettings.i18n.unsupported_type);
          fileField.value = "";
          return;
        }
      }

      var maxCount =
        allowedType === "image"
          ? formSettings.image_max_count
          : formSettings.video_max_count;
      var maxSizeMb =
        allowedType === "image"
          ? formSettings.image_max_size_mb
          : formSettings.video_max_size_mb;
      var maxSizeBytes = maxSizeMb * 1024 * 1024;

      var validNewFiles = [];
      var filteredByMixedType = false;
      var filteredBySize = false;

      rawFiles.forEach(function (file) {
        var ext = file.name.split(".").pop().toLowerCase();
        var isImage =
          formSettings.allowed_image_types.includes(ext) ||
          file.type.startsWith("image/");
        var isVideo =
          formSettings.allowed_video_types.includes(ext) ||
          file.type.startsWith("video/");

        var currentType = isImage ? "image" : isVideo ? "video" : null;

        if (currentType !== allowedType) {
          filteredByMixedType = true;
          return;
        }

        if (file.size > maxSizeBytes) {
          filteredBySize = true;
          return;
        }

        // Prevent duplicate file names/sizes from being added
        var isDuplicate = fileField.dsproofwpFiles.some(function (existing) {
          return (
            existing.name === file.name &&
            existing.size === file.size &&
            existing.lastModified === file.lastModified
          );
        });
        if (isDuplicate) {
          return;
        }

        validNewFiles.push(file);
      });

      var warningMessages = [];
      if (filteredByMixedType) {
        warningMessages.push(formSettings.i18n.mixed_media);
      }
      if (filteredBySize) {
        warningMessages.push(
          allowedType === "image"
            ? formSettings.i18n.large_images
            : formSettings.i18n.large_videos,
        );
      }

      var totalFiles = fileField.dsproofwpFiles.concat(validNewFiles);

      if (totalFiles.length > maxCount) {
        totalFiles = totalFiles.slice(0, maxCount);
        warningMessages.push(
          allowedType === "image"
            ? formSettings.i18n.max_images_limit
            : formSettings.i18n.max_videos_limit,
        );
      }

      if (warningMessages.length > 0) {
        alert(warningMessages.join("\n"));
      }

      // Revoke old object URLs
      previewContainer.querySelectorAll("[data-url]").forEach(function (el) {
        var url = el.getAttribute("data-url");
        if (url) {
          URL.revokeObjectURL(url);
        }
      });

      fileField.dsproofwpFiles = totalFiles;
      renderPreviews();

      // Reset input value so selection of same files again triggers change event
      fileField.value = "";
    });

    function renderPreviews() {
      previewContainer.innerHTML = "";

      fileField.dsproofwpFiles.forEach(function (file, index) {
        var url = URL.createObjectURL(file);
        var isVideo = file.type.startsWith("video/");

        var cardEl = document.createElement("div");
        cardEl.className = "dsproofwp-preview-card";
        cardEl.setAttribute("data-url", url);

        var mediaWrapper = document.createElement("div");
        mediaWrapper.className = "dsproofwp-preview-media-wrapper";

        if (isVideo) {
          var video = document.createElement("video");
          video.src = url;
          video.controls = false;
          mediaWrapper.appendChild(video);
        } else {
          var img = document.createElement("img");
          img.src = url;
          img.alt = file.name;
          mediaWrapper.appendChild(img);
        }

        var actions = document.createElement("div");
        actions.className = "dsproofwp-preview-actions";

        var badge = document.createElement("span");
        badge.className = "dsproofwp-preview-badge";
        badge.textContent = isVideo ? "video" : "image";

        var deleteBtn = document.createElement("button");
        deleteBtn.type = "button";
        deleteBtn.className = "dsproofwp-preview-delete-btn";
        deleteBtn.setAttribute("aria-label", "Remove media");
        deleteBtn.innerHTML =
          '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2M10 11v6M14 11v6"/></svg>';

        deleteBtn.addEventListener("click", function () {
          URL.revokeObjectURL(url);
          fileField.dsproofwpFiles.splice(index, 1);
          renderPreviews();
        });

        actions.appendChild(badge);
        actions.appendChild(deleteBtn);

        cardEl.appendChild(mediaWrapper);
        cardEl.appendChild(actions);

        previewContainer.appendChild(cardEl);
      });
    }
  }
  document
    .querySelectorAll(".dsproofwp-product-card")
    .forEach(setupFilePreview);

  document
    .querySelector(".dsproofwp-review-form")
    .addEventListener("submit", function (e) {
      // Populate all file inputs with their accumulated DataTransfer files right before submission
      document
        .querySelectorAll(".dsproofwp-product-card")
        .forEach(function (card) {
          var fileField = card.querySelector(".dsproofwp-file-field");
          if (
            fileField &&
            fileField.dsproofwpFiles &&
            fileField.dsproofwpFiles.length > 0
          ) {
            var dt = new DataTransfer();
            fileField.dsproofwpFiles.forEach(function (file) {
              dt.items.add(file);
            });
            fileField.files = dt.files;
          }
        });

      // Validate reCAPTCHA if required
      if (isCaptchaRequired) {
        var tokenInput = document.getElementById("dsproofwp-recaptcha-token");
        if (!tokenInput || !tokenInput.value) {
          e.preventDefault();
          alert(formSettings.i18n.recaptcha_required);
          return;
        }
      }

      var hasOne = false;
      document
        .querySelectorAll(".dsproofwp-rating-value")
        .forEach(function (input) {
          if (parseInt(input.value, 10) > 0) {
            hasOne = true;
          }
        });
      if (!hasOne) {
        e.preventDefault();
        alert(formSettings.i18n.submit_rating);
      }
    });
})();
