export class PixelioCartAbandonRecoveryMoreEngagementTracker {
    constructor(eventTracker, callbackNewPage = null) {
        this.eventTracker = eventTracker;
        this.callbackNewPage = callbackNewPage;

        this.startTime = Date.now();
        this.currentUrl = window.location.href;
        this.maxScrollPercent = 0;
        this.hasSentPageEngagement = false;
    }

    init() {
        this.trackPageView();

        jQuery(window).on("scroll", () => {
            this.handleScroll();
        });

        jQuery(window).on("beforeunload", () => {
            this.sendPageEngagementOnce(true);
        });

        setTimeout(() => {
            this.sendPageEngagementOnce();
        }, 15000);
    }

    handleScroll() {
        this.detectNewPage();

        const scrollTop = jQuery(window).scrollTop();
        const docHeight = jQuery(document).height() - jQuery(window).height();

        if (docHeight <= 0) {
            return;
        }

        const scrollPercent = Math.min(100, Math.max(0, (scrollTop / docHeight) * 100));

        if (scrollPercent > this.maxScrollPercent) {
            this.maxScrollPercent = scrollPercent;
        }
    }

    detectNewPage() {
        if (this.currentUrl === window.location.href) {
            return;
        }

        this.sendPageEngagementOnce();

        this.currentUrl = window.location.href;
        this.startTime = Date.now();
        this.maxScrollPercent = 0;
        this.hasSentPageEngagement = false;

        this.trackPageView();

        if (this.callbackNewPage !== null) {
            this.callbackNewPage();
        }
    }

    trackPageView() {
        this.eventTracker.track("page_view", {
            pageUrl: this.currentUrl
        });
    }

    sendPageEngagementOnce(useBeacon = false) {
        if (this.hasSentPageEngagement) {
            return;
        }

        this.hasSentPageEngagement = true;

        this.eventTracker.track("page_engagement", {
            pageUrl: this.currentUrl,
            visitDuration: this.getVisitDuration(),
            scrollPercent: this.getMaxScrollPercent()
        }, useBeacon);
    }

    getVisitDuration() {
        return Math.round((Date.now() - this.startTime) / 1000);
    }

    getMaxScrollPercent() {
        return Math.round(this.maxScrollPercent || 0);
    }
}
