import { PixelioCartAbandonRecoveryMoreAjaxRequest } from "../../../../frontend/assets/js/components/pixelio_cart_abandon_recovery_more_ajax_request";
import {
	PIXELIOCARTABANDONRECOVERYMOREHIDEIT,
	PIXELIOCARTABANDONRECOVERYMORETHANKSEXITCLASS
} from "../../../../frontend/assets/js/var/pixelio_cart_abandon_recovery_more_variable";
import {PixelioCartAbandonRecoveryMorePopUp} from "./pixelio_cart_abandon_recovery_more_exit_intent_popup";

export class PixelioCartAbandonRecoveryMoreBoughtPopup extends PixelioCartAbandonRecoveryMorePopUp {

	constructor(className, onShowCallback = null, onHideCallback = null, isFrontend = false, positiveCallback = null) {
		super(className, onShowCallback, onHideCallback, isFrontend, positiveCallback , false,false);

		this.popupId = "#pixelio-cart-abandon-recovery-more-bought-message-popup-id";
		jQuery(this.popupId).addClass(PIXELIOCARTABANDONRECOVERYMOREHIDEIT);
		this.ajaxRequest = new PixelioCartAbandonRecoveryMoreAjaxRequest();

		this.initFrontend(isFrontend);
	}

	initFrontend(isFrontend) {
		if (!isFrontend) return;

		this.loadBoughtPopup();
		if (pixelio_ajax.show_bought_popup) {
			// Refresh every 30s
			setInterval(this.loadBoughtPopup.bind(this), 30000);
		}
	}

	loadBoughtPopup() {
		const data = new FormData();
		const productId = this.ajaxRequest.getMetaContentByName("pixelio-product-id");
		data.append("product_id", productId);

		this.ajaxRequest.makeAjaxRequest("pixelio_cart_abandon_recovery_more_check_bought", data, this.updatePopupContent.bind(this));
	}

	updatePopupContent(response) {
		let resp = [];
		try {
			resp = JSON.parse(response.data);
		} catch (e) {
			console.error("Error parsing response.data:", e);
			return;
		}
		if (!resp || resp.length === 0) return;

		const now = Date.now();

		// Récupérer ce qui est déjà vu dans le localStorage
		let alreadySeen = {};
		try {
			const stored = localStorage.getItem("alreadySeen");
			if (stored) {
				alreadySeen = JSON.parse(stored);
			}


		} catch (e) {
			console.error("Error parsing 'alreadySeen' from localStorage:", e);
			alreadySeen = {};
		}



		resp.forEach(item => {
			// Générer une clé unique pour cet item
			const cleaned = String(item.min).replace(/\D/g, '');
			const key = `${item.customer_name}${item.customer_location}${item.product_id}${cleaned}`;

			// Si l’élément n’a pas déjà été vu
			if (!alreadySeen[key]) {
				// Stocker avec timestamp
				alreadySeen[key] = now;
				localStorage.setItem("alreadySeen", JSON.stringify(alreadySeen));

				const $popup = jQuery(this.popupId);

				$popup.removeClass(PIXELIOCARTABANDONRECOVERYMOREHIDEIT);

				// Mettre à jour le contenu du popup
				$popup.find('.rivio-ai-cart-recovery-marketing-email-automation-bought-message-product-image')
					.attr('src', item.product_image);

				$popup.find('.rivio-ai-cart-recovery-marketing-email-automation-bought-product-title')
					.text(item.product_name);

				$popup.find('.rivio-ai-cart-recovery-marketing-email-automation-bought-message-product-description span')
					.text(`${item.customer_name} in ${item.customer_location}`);

				$popup.find('.rivio-ai-cart-recovery-marketing-email-automation-bought-message-product-timestamp span')
					.text(item.min);

				$popup.addClass("pixelio-cart-abandon-recovery-more-show-others-buy-checkbox-animation");
			}
		});

		setTimeout(this.stopBought.bind(this), 10000);
	}
	stopBought(){
		const $popup = jQuery(this.popupId);
		$popup.removeClass("pixelio-cart-abandon-recovery-more-show-others-buy-checkbox-animation");
		$popup.addClass(PIXELIOCARTABANDONRECOVERYMOREHIDEIT);
	}
}
