/**
 * Shois Chat Button — Tracker
 *
 * Tracks impressions and clicks via navigator.sendBeacon
 * to the REST API. GDPR safe — no PII stored, only aggregated counts.
 *
 * @package ShoisChatButton
 */
(function () {
    'use strict';

    /**
     * SCBTracker class.
     *
     * @param {Object} config The shcb_config object.
     */
    function SCBTracker(config) {
        this.config = config;
        this.endpoint = config.rest_url + '/analytics/track';
        this.nonce = config.nonce || '';
        this.sessionKey = 'shcb_tracked_' + (config.template_id || 0);
        this.tracked = {};
    }

    /**
     * Send a tracking event to the REST API.
     *
     * @param {string} eventType   Event type identifier.
     * @param {Object} extraData   Additional event data.
     */
    SCBTracker.prototype.send = function (eventType, extraData) {
        var data = {
            event_type: eventType,
            template_id: this.config.template_id || 0,
            page_url: window.location.href,
            device_type: this.getDeviceType(),
            timestamp: new Date().toISOString(),
        };

        if (extraData) {
            for (var key in extraData) {
                if (extraData.hasOwnProperty(key)) {
                    data[key] = extraData[key];
                }
            }
        }

        var body = JSON.stringify(data);

        // Use sendBeacon for non-blocking, reliable delivery.
        if (navigator.sendBeacon) {
            var blob = new Blob([body], { type: 'application/json' });
            navigator.sendBeacon(this.endpoint, blob);
        } else {
            // Fallback: use fetch.
            try {
                fetch(this.endpoint, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': this.nonce,
                    },
                    body: body,
                    keepalive: true,
                });
            } catch (e) {
                // Silently fail — analytics should never break the widget.
            }
        }
    };

    /**
     * Track an impression event. Fires once per session.
     */
    SCBTracker.prototype.trackImpression = function () {
        // Prevent duplicate impressions in the same session.
        if (sessionStorage) {
            var key = this.sessionKey + '_imp';
            if (sessionStorage.getItem(key)) {
                return;
            }
            sessionStorage.setItem(key, '1');
        }

        // Use IntersectionObserver if available.
        var self = this;
        var widget = document.getElementById('shcb-widget');

        if (!widget) {
            return;
        }

        if ('IntersectionObserver' in window) {
            var observer = new IntersectionObserver(
                function (entries) {
                    entries.forEach(function (entry) {
                        if (entry.isIntersecting && entry.intersectionRatio >= 0.5) {
                            // Wait 500ms to confirm visibility.
                            setTimeout(function () {
                                self.send('impression');
                            }, 500);
                            observer.disconnect();
                        }
                    });
                },
                { threshold: 0.5 }
            );
            observer.observe(widget);
        } else {
            // Fallback: track immediately.
            this.send('impression');
        }
    };

    /**
     * Track button click (popup opened). Fires once per session.
     */
    SCBTracker.prototype.trackButtonClick = function () {
        if (sessionStorage) {
            var key = this.sessionKey + '_btn_click';
            if (sessionStorage.getItem(key)) {
                return;
            }
            sessionStorage.setItem(key, '1');
        }
        this.send('click');
    };

    /**
     * Track a specific platform link click (the real conversion). Fires once per platform per session.
     *
     * @param {string} platformId Platform identifier.
     * @param {string} agentId    Agent identifier.
     */
    SCBTracker.prototype.trackPlatformClick = function (platformId, agentId) {
        if (sessionStorage) {
            var key = this.sessionKey + '_plat_' + platformId + '_' + (agentId || '');
            if (sessionStorage.getItem(key)) {
                return; // Fire third-party events even if already tracked internally? 
                // Let's just track once per session for our own analytics too, but third party might want all clicks.
                // For now, let's limit everything to once per session to prevent spam.
            }
            sessionStorage.setItem(key, '1');
        } else {
            // Fallback Debounce: prevent double-fires within 500ms if no sessionStorage.
            var dkey = 'platform_' + platformId + '_' + (agentId || '');
            if (this.tracked[dkey]) return;
            this.tracked[dkey] = true;
            var self = this;
            setTimeout(function () { delete self.tracked[dkey]; }, 500);
        }

        this.send('platform_click', {
            platform_id: platformId,
            agent_id: agentId || '',
        });

        // Fire third-party tracking events.
        this.fireThirdPartyEvents(platformId, agentId);
    };

    /**
     * Track popup close without conversion.
     */
    SCBTracker.prototype.trackPopupClose = function () {
        this.send('popup_close');
    };

    /**
     * Fire third-party analytics events (GA4, FB Pixel, GTM).
     *
     * @param {string} platformId Platform identifier.
     * @param {string} agentId    Agent identifier.
     */
    SCBTracker.prototype.fireThirdPartyEvents = function (platformId, agentId) {
        var integrations = this.config.integrations || {};

        // Google Analytics 4.
        if (integrations.ga4 && typeof gtag === 'function') {
            gtag('event', 'chat_widget_click', {
                event_category: 'Shois Chat Button',
                event_label: platformId,
                agent_name: agentId || '',
            });
        }

        // Facebook Pixel.
        if (integrations.fb_pixel && typeof fbq === 'function') {
            fbq('track', 'Contact', {
                content_name: platformId,
                content_category: 'Chat Widget',
            });
        }

        // Google Tag Manager dataLayer.
        if (integrations.gtm && window.dataLayer) {
            window.dataLayer.push({
                event: 'shcb_platform_click',
                shcb_platform: platformId,
                shcb_agent: agentId || '',
            });
        }
    };

    /**
     * Detect device type.
     *
     * @return {string} "mobile", "tablet", or "desktop".
     */
    SCBTracker.prototype.getDeviceType = function () {
        var ua = navigator.userAgent;
        var width = window.innerWidth;

        if (/Mobi|Android/i.test(ua) && width < 768) {
            return 'mobile';
        }
        if (/iPad|Android/i.test(ua) && width >= 768 && width < 1024) {
            return 'tablet';
        }
        if (width < 768) {
            return 'mobile';
        }
        if (width < 1024) {
            return 'tablet';
        }
        return 'desktop';
    };

    // Export to global scope for widget.js.
    window.SCBTracker = SCBTracker;
})();
