import $ from "jquery";
import { InplaceInputLabels } from "@lib/inplace-input-labels";
import Scroll from "@assets/js/lib/scroll";
import { InobyModule } from "./lib/inoby-module";
import { InobyFunctions } from "./lib/inoby-functions";
import { PostFiltering } from "./lib/post-filtering";

class AppModule extends InobyModule {
  run() {
    this.hookNewsletterSubmit();
    this.hookLinksWithKeepSearchRole();
  }

  hookNewsletterSubmit() {
    // Newsletter subscribe
    $('form[id^="newsletter_form"]').on("submit", (e) => {
      e.preventDefault();
      const form = e.currentTarget as HTMLFormElement;
      
      // Get reCAPTCHA token if configured
      const recaptchaSiteKey = window.inoby_vars?.recaptcha?.site_key;
      
      if (recaptchaSiteKey && window.grecaptcha) {
        // Execute reCAPTCHA v3
        window.grecaptcha.ready(() => {
          window.grecaptcha!
            .execute(recaptchaSiteKey, { action: "newsletter_subscribe" })
            .then((token: string) => {
              // Add token to form data
              const formData = new FormData(form);
              formData.append("recaptcha_token", token);
              
              // Convert FormData to object for wpSendData
              const data = Object.fromEntries(formData.entries());
              
              form.classList.add("loading");
              InobyFunctions.wpSendData("inoby_newsletter_subscribe", data)
                .done(() => {
                  $(form).removeClass("fail").addClass("success");
                  $(form).find("input").val("").prop("checked", false);
                })
                .fail((response) => {
                  console.warn("newsletter subscribe fail", response);
                  $(form).removeClass("success").addClass("fail");
                  setTimeout(() => $(form).removeClass("fail"), 5000);
                })
                .always(() => {
                  form.classList.remove("loading");
                });
            })
            .catch((error: any) => {
              console.error("reCAPTCHA error:", error);
              $(form).removeClass("success").addClass("fail");
              setTimeout(() => $(form).removeClass("fail"), 5000);
            });
        });
      } else {
        // No reCAPTCHA configured, submit normally
        InobyFunctions.wpSendForm("inoby_newsletter_subscribe", form)
          .done(() => {
            $(form).removeClass("fail").addClass("success");
            $(form).find("input").val("").prop("checked", false);
          })
          .fail((response) => {
            console.warn("newsletter subscribe fail", response);
            $(form).removeClass("success").addClass("fail");
            setTimeout(() => $(form).removeClass("fail"), 5000);
          });
      }
    });
  }

  hookLinksWithKeepSearchRole() {
    $("a[rel~=keep-search]").on("click", (e) => {
      const link = e.currentTarget as HTMLAnchorElement;
      if (link?.href) {
        e.preventDefault();
        window.location.href = `${link.href}${window.location.search}`;
      }
    });
  }
}

new AppModule().runOnReady();
new InplaceInputLabels().runOnReady();
new Scroll().runOnReady();

window.inoby_post_filter = new PostFiltering();
window.inoby_post_filter.runOnReady();
