/**
 * Leave Stoper - Exit Intent and Inactivity Detection (Niwa Interface version)
 * Updated selectors: za-* -> niwa-*
 * Uses Niwa.MorphController.open() to open chat
 * No jQuery dependency.
 */

(function(){
    'use strict';

    var F = window.NiwaAIFrontend || {};

    // Exit if Leave Stoper is not enabled or config is missing
    if (!window.NiwaAI || !window.NiwaAI.leave_stoper || !window.NiwaAI.leave_stoper.enabled) {
        return;
    }

    var config = window.NiwaAI.leave_stoper;
    var STORAGE_KEY = 'niwa_ai_leave_stoper_cooldown';

    var hasTriggered = false;
    var exitIntentBound = false;
    var inactivityTimer = null;
    var lastActivity = Date.now();
    var exitIntentThreshold = 80;

    function track(eventType, meta, options) {
        if (window.Niwa && window.Niwa.Utils && typeof window.Niwa.Utils.trackFrontendEvent === 'function') {
            window.Niwa.Utils.trackFrontendEvent(eventType, {
                source: 'leave_stoper',
                meta: meta || {}
            }, options || null);
        }
    }

    function markLeaveStoperActive(triggerType) {
        try {
            sessionStorage.setItem('niwa_ai_leave_stoper_active', '1');
            sessionStorage.setItem('niwa_ai_leave_stoper_trigger_type', triggerType || config.trigger_type || '');
            sessionStorage.setItem('niwa_ai_leave_stoper_triggered_at', String(Date.now()));
        } catch (e) { /* ignore */ }
    }

    function clearLeaveStoperState() {
        try {
            sessionStorage.removeItem('niwa_ai_leave_stoper_active');
            sessionStorage.removeItem('niwa_ai_leave_stoper_trigger_type');
            sessionStorage.removeItem('niwa_ai_leave_stoper_triggered_at');
        } catch (e) { /* ignore */ }
    }

    function isMobileDevice() {
        return window.matchMedia('(max-width: 767px)').matches;
    }

    function isInCooldown() {
        if (config.test_mode) return false;
        try {
            var raw = sessionStorage.getItem(STORAGE_KEY);
            if (!raw) return false;

            var now = Date.now();
            var data = JSON.parse(raw);
            var expiresAt = data && parseInt(data.expires_at, 10);

            if (!expiresAt || expiresAt <= now) {
                sessionStorage.removeItem(STORAGE_KEY);
                return false;
            }

            return true;
        } catch (e) {
            try { sessionStorage.removeItem(STORAGE_KEY); } catch (err) { /* ignore */ }
            return false;
        }
    }

    function setCooldown() {
        if (config.test_mode) return;

        try {
            var minutes = parseInt(config.cooldown_minutes, 10);
            if (!minutes || minutes < 1) minutes = 30;

            sessionStorage.setItem(STORAGE_KEY, JSON.stringify({
                triggered_at: Date.now(),
                expires_at: Date.now() + (minutes * 60 * 1000)
            }));
        } catch (e) { /* ignore */ }
    }

    function canTrigger() {
        if (hasTriggered) return false;
        if (config.disable_on_mobile && isMobileDevice()) return false;
        if (isInCooldown()) return false;
        return true;
    }

    function openChat() {
        // Use new Niwa module system
        if (window.Niwa && window.Niwa.MorphController) {
            if (window.Niwa.MorphController.isOpen()) return true;
            window.Niwa.MorphController.open();
            return true;
        }

        // Fallback to niwaAI global
        if (window.niwaAI && typeof window.niwaAI.openChat === 'function') {
            window.niwaAI.openChat();
            return true;
        }

        return false;
    }

    function findChatBody() {
        return document.querySelector('.niwa-morph__body')
            || document.querySelector('.niwa-center__body');
    }

    function escapeHtml(unsafe) {
        if (typeof unsafe !== 'string') return '';
        return unsafe
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function sendLeaveStoperMessage(triggerType) {
        var retryCount = 0;
        var maxRetries = 10;

        function attemptSendMessage() {
            var chatBody = findChatBody();

            if (!chatBody && retryCount < maxRetries) {
                retryCount++;
                setTimeout(attemptSendMessage, 200);
                return;
            }

            if (!chatBody) {
                if (window.Niwa && window.Niwa.MessageRenderer) {
                    window.Niwa.MessageRenderer.hideTyping();
                }
                return;
            }

            // Show typing indicator
            if (window.Niwa && window.Niwa.MessageRenderer) {
                window.Niwa.MessageRenderer.showTyping();
            }

            sendMessageToBody(chatBody);
        }

        function sendMessageToBody(chatBody) {
            setTimeout(function() {
                // Hide typing
                if (window.Niwa && window.Niwa.MessageRenderer) {
                    window.Niwa.MessageRenderer.hideTyping();
                }

                // Build message content
                var messageContent = '';

                // Add media if available
                if (config.media && config.media.url) {
                    if (config.media.type === 'image') {
                        messageContent += '<img src="' + escapeHtml(config.media.url)
                            + '" alt="' + escapeHtml(config.media.alt || '')
                            + '" style="max-width: 100%; height: auto; border-radius: 8px; margin-bottom: 8px; display: block;" />';
                    } else if (config.media.type === 'video') {
                        messageContent += '<video controls style="max-width: 100%; height: auto; border-radius: 8px; margin-bottom: 8px; display: block;">'
                            + '<source src="' + escapeHtml(config.media.url) + '" type="' + escapeHtml(config.media.mime_type) + '">'
                            + 'Your browser does not support the video tag.</video>';
                    }
                }

                if (config.message_text) {
                    if (messageContent) messageContent += '<br>';
                    messageContent += escapeHtml(config.message_text);
                }

                if (!messageContent) {
                    messageContent = 'Hey! Before you go, is there anything I can help you with?';
                }

                // Use MessageRenderer if available
                if (window.Niwa && window.Niwa.MessageRenderer) {
                    // For rich messages (with media), we build DOM directly
                    if (config.media && config.media.url) {
                        var msgDiv = document.createElement('div');
                        msgDiv.className = 'niwa-message niwa-message--bot';

                        var avatarDiv = document.createElement('div');
                        avatarDiv.className = 'niwa-message__avatar';
                        var avatarUrl = (window.NiwaAI && window.NiwaAI.avatar_url)
                            ? window.NiwaAI.avatar_url
                            : ((window.NiwaAI && window.NiwaAI.default_avatar_url)
                                ? window.NiwaAI.default_avatar_url
                                : ((window.NiwaAI && window.NiwaAI.pluginURL)
                                    ? window.NiwaAI.pluginURL + 'assets/img/niwa-admin-personal-assistant.png'
                                    : ''));
                        if (avatarUrl) {
                            var avatarImg = document.createElement('img');
                            avatarImg.src = avatarUrl;
                            avatarImg.alt = 'Niwa';
                            avatarImg.width = 28;
                            avatarImg.height = 28;
                            avatarDiv.appendChild(avatarImg);
                        }
                        msgDiv.appendChild(avatarDiv);

                        var contentWrapper = document.createElement('div');
                        var bubbleDiv = document.createElement('div');
                        bubbleDiv.className = 'niwa-message__bubble';

                        // Build safe media DOM
                        if (config.media.type === 'image') {
                            var img = document.createElement('img');
                            img.src = config.media.url;
                            img.alt = config.media.alt || '';
                            img.style.cssText = 'max-width: 100%; height: auto; border-radius: 8px; margin-bottom: 8px; display: block;';
                            bubbleDiv.appendChild(img);
                        } else if (config.media.type === 'video') {
                            var video = document.createElement('video');
                            video.controls = true;
                            video.style.cssText = 'max-width: 100%; height: auto; border-radius: 8px; margin-bottom: 8px; display: block;';
                            var source = document.createElement('source');
                            source.src = config.media.url;
                            source.type = config.media.mime_type || 'video/mp4';
                            video.appendChild(source);
                            bubbleDiv.appendChild(video);
                        }

                        if (config.message_text) {
                            if (config.media) bubbleDiv.appendChild(document.createElement('br'));
                            bubbleDiv.appendChild(document.createTextNode(config.message_text));
                        }

                        contentWrapper.appendChild(bubbleDiv);
                        msgDiv.appendChild(contentWrapper);
                        chatBody.appendChild(msgDiv);

                        // Scroll
                        if (window.Niwa.ScrollBehavior) {
                            window.Niwa.ScrollBehavior.scrollToBottom(chatBody);
                            setTimeout(function() { window.Niwa.ScrollBehavior.scrollToBottom(chatBody); }, 150);
                        }

                        track('leave_stoper_message_shown', {
                            trigger_type: triggerType || config.trigger_type || '',
                            has_media: !!(config.media && config.media.url)
                        });

                        // Scroll after media load
                        var mediaNodes = bubbleDiv.querySelectorAll('img, video');
                        for (var i = 0; i < mediaNodes.length; i++) {
                            mediaNodes[i].addEventListener('load', function() {
                                if (window.Niwa.ScrollBehavior) {
                                    setTimeout(function() { window.Niwa.ScrollBehavior.scrollToBottom(chatBody); }, 250);
                                }
                            });
                        }
                    } else {
                        // Simple text message
                        window.Niwa.MessageRenderer.addMessage(
                            config.message_text || 'Hey! Before you go, is there anything I can help you with?',
                            'bot',
                            { source: 'LeaveStoper' }
                        );

                        track('leave_stoper_message_shown', {
                            trigger_type: triggerType || config.trigger_type || '',
                            has_media: false
                        });
                    }
                }
            }, 1000);
        }

        setTimeout(attemptSendMessage, config.open_delay || 0);
    }

    function triggerLeaveStoper(triggerType) {
        if (!canTrigger()) return;

        hasTriggered = true;
        setCooldown();
        markLeaveStoperActive(triggerType);
        track('leave_stoper_triggered', {
            trigger_type: triggerType || config.trigger_type || '',
            test_mode: !!config.test_mode
        });

        if (openChat()) {
            sendLeaveStoperMessage(triggerType);
        }
    }

    // Exit intent detection
    function handleExitIntent(e) {
        var toElement = e.relatedTarget || e.toElement;
        var clientY = typeof e.clientY === 'number' ? e.clientY : mouseY;
        var clientX = typeof e.clientX === 'number' ? e.clientX : 0;
        var isLeavingWindow = !toElement;
        var isNearTopEdge = clientY <= exitIntentThreshold || mouseY <= exitIntentThreshold;
        var isNearTopCorner = clientY <= exitIntentThreshold
            && (clientX <= 0 || clientX >= window.innerWidth - 1);
        var isExitIntent = clientY <= 0 || (isLeavingWindow && isNearTopEdge) || isNearTopCorner;

        if (isExitIntent) {
            if (config.trigger_type === 'exit_intent' || config.trigger_type === 'both') {
                triggerLeaveStoper('exit_intent');
            }
        }
    }

    var mouseY = 0;

    function trackMousePosition(e) {
        mouseY = e.clientY;
    }

    function updateActivity() {
        lastActivity = Date.now();
        if (inactivityTimer) clearTimeout(inactivityTimer);

        if (config.trigger_type === 'inactivity' || config.trigger_type === 'both') {
            inactivityTimer = setTimeout(function() {
                triggerLeaveStoper('inactivity');
            }, config.inactivity_timeout * 1000);
        }
    }

    function initLeaveStoper() {
        if (config.reset_on_page_load) {
            clearLeaveStoperState();
        }

        if (config.test_mode) {
            try {
                sessionStorage.removeItem(STORAGE_KEY);
                hasTriggered = false;
            } catch (e) { /* ignore */ }
            clearLeaveStoperState();
        }

        if (config.trigger_type === 'exit_intent' || config.trigger_type === 'both') {
            setTimeout(function() {
                document.addEventListener('mouseout', handleExitIntent, { passive: true });
                document.addEventListener('mouseleave', handleExitIntent, { passive: true });
                document.addEventListener('mousemove', trackMousePosition, { passive: true });
                exitIntentBound = true;
            }, 2000);
        }

        if (config.trigger_type === 'inactivity' || config.trigger_type === 'both') {
            var events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart', 'click'];
            for (var i = 0; i < events.length; i++) {
                document.addEventListener(events[i], updateActivity, { passive: true });
            }
            updateActivity();
        }

        window.addEventListener('beforeunload', function() {
            if (exitIntentBound) {
                document.removeEventListener('mouseout', handleExitIntent);
                document.removeEventListener('mouseleave', handleExitIntent);
                document.removeEventListener('mousemove', trackMousePosition);
            }
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initLeaveStoper);
    } else {
        initLeaveStoper();
    }

})();
