jQuery(document).ready(function ($) {
  "use strict";

  // Configuration
  const config = {
    nonce: window.ncpcFreeReviewData?.nonce || "",
    ajaxUrl: window.ncpcFreeReviewData?.ajaxUrl || "",
  };

  // Classe principale pour gérer les reviews
  class NcpcFreeReviewHandler {
    constructor() {
      this.init();
    }

    init() {
      this.bindEvents();
    }

    bindEvents() {
      // Event pour "Noter maintenant"
      $(document).on("click", ".ncpc-free-rate-now", (e) => {
        this.handleRateNow($(e.currentTarget));
      });

      // Events pour les boutons de dismiss
      $(document).on(
        "click",
        ".ncpc-free-rate-dismiss, .ncpc-free-rate-dismiss-link",
        (e) => {
          e.preventDefault();
          this.handleDismiss($(e.currentTarget));
        }
      );
    }

    handleRateNow($element) {
      // Animation de feedback
      this.animateStars();

      // Marquer comme fait après un délai
      setTimeout(() => {
        this.sendDismissRequest("done");
      }, 1000);
    }

    handleDismiss($element) {
      const dismissType = $element.data("action");
      const $widget = $("#ncpc-free-notation-widget");

      // Animation de sortie
      $widget.addClass("ncpc-free-dismissing");

      setTimeout(() => {
        $widget.fadeOut(300, () => {
          $widget.remove();
        });
      }, 200);

      // Envoyer la requête
      this.sendDismissRequest(dismissType);
    }

    animateStars() {
      const $stars = $(".ncpc-free-stars");
      $stars.css({
        transform: "scale(1.2)",
        transition: "transform 0.3s ease",
      });

      setTimeout(() => {
        $stars.css("transform", "scale(1)");
      }, 300);
    }

    sendDismissRequest(dismissType) {
      if (!config.nonce || !config.ajaxUrl) {
        console.warn("NCPC Free: Missing AJAX request configuration");
        return;
      }

      $.ajax({
        url: config.ajaxUrl,
        type: "POST",
        data: {
          action: "ncpc_free_dismiss_review",
          dismiss_type: dismissType,
          nonce: config.nonce,
        },
        success: (response) => {
          console.log("NCPC Free: Review status updated");
        },
        error: (xhr, status, error) => {
          console.error("NCPC Free: Update error:", error);
        },
      });
    }
  }

  // Animation CSS additionnelle
  $("<style>")
    .text(
      `
        .ncpc-free-dismissing {
            transform: translateX(100%);
            opacity: 0;
            transition: all 0.3s ease-out !important;
        }
        
        .ncpc-free-stars {
            cursor: pointer;
        }
        
        .ncpc-free-notation-widget:hover {
            transform: translateY(-1px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.2);
            transition: all 0.3s ease;
        }
    `
    )
    .appendTo("head");

  // Initialiser
  new NcpcFreeReviewHandler();
});
