/**
 * SimplyIN Payment - Success Page 3DS Handler
 * Handles payment status polling after 3D Secure return
 * Design matches WooCommerce/PrestaShop confirmation page
 */
define([
    'jquery',
    'Simplyin_Payment/js/model/ajax-client',
    'Simplyin_Payment/js/model/session-storage-manager',
    'domReady!'
], function ($, ajaxClient, sessionStorageManager) {
    'use strict';

    var handler = {
        baseUrl: '',
        translations: {},

        /**
         * Clear the full Simply.IN client-side session (terminal states only).
         * Reuses the shared clearAll() so we never duplicate the key list, and
         * also drops the 3DS sessionStorage/cookie handoff so nothing lingers
         * after a completed / failed order until the tab is closed.
         */
        clearSimplyinSession: function () {
            try {
                sessionStorageManager.clearAll();
            } catch (e) {
                console.warn('SimplyIn Success: Failed to clear storage:', e);
            }
            this.clear3DSSession();
        },
        
        // SVG icons for different states (with colors)
        icons: {
            clock: '<path fill="#f59e0b" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"/>',
            success: '<path fill="#22c55e" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>',
            error: '<circle cx="12" cy="12" r="10" fill="#ef4444"/><path d="M15 9l-6 6m0-6l6 6" stroke="white" stroke-width="2" stroke-linecap="round" fill="none"/>',
            warning: '<path fill="#f59e0b" d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>'
        },
        
        /**
         * Initialize the 3DS handler on success page
         * @param {Object} config - Configuration object with baseUrl and translations
         */
        init: function (config) {
            // Store config
            if (config && config.baseUrl) {
                this.baseUrl = config.baseUrl;
            } else if (window.SIMPLYIN_BASE_URL) {
                this.baseUrl = window.SIMPLYIN_BASE_URL;
            }
            
            if (config && config.translations) {
                this.translations = config.translations;
            }
            
            // Check if returning from 3DS
            var sessionData = this.check3DSSession();
            
            if (sessionData) {
                this.handleReturn(sessionData);
            }
            
            return this;
        },

        /**
         * Check for 3DS session data
         */
        check3DSSession: function () {
            try {
                // First try sessionStorage
                var sessionDataStr = sessionStorage.getItem('simplyin_3ds_session');
                
                // If not in sessionStorage, try cookie
                if (!sessionDataStr) {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = cookies[i].trim();
                        if (cookie.indexOf('simplyin_3ds_session=') === 0) {
                            sessionDataStr = decodeURIComponent(cookie.substring('simplyin_3ds_session='.length));
                            break;
                        }
                    }
                }
                
                if (!sessionDataStr) {
                    return null;
                }
                
                var sessionData = JSON.parse(sessionDataStr);
                
                // Check if session is still valid (30 minutes)
                var elapsed = Date.now() - sessionData.timestamp;
                if (elapsed > 30 * 60 * 1000) {
                    this.clear3DSSession();
                    return null;
                }
                
                return sessionData;
            } catch (e) {
                console.error('SimplyIn Success: Failed to check 3DS session:', e);
                return null;
            }
        },

        /**
         * Clear 3DS session data
         */
        clear3DSSession: function () {
            try {
                sessionStorage.removeItem('simplyin_3ds_session');
                document.cookie = 'simplyin_3ds_session=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/';
            } catch (e) {
                console.warn('SimplyIn Success: Failed to clear 3DS session:', e);
            }
        },

        /**
         * Build API URL correctly
         */
        buildApiUrl: function (endpoint) {
            var baseUrl = this.baseUrl || window.SIMPLYIN_BASE_URL || '';
            
            if (baseUrl) {
                if (baseUrl.charAt(baseUrl.length - 1) !== '/') {
                    baseUrl += '/';
                }
                if (endpoint.charAt(0) === '/') {
                    endpoint = endpoint.substring(1);
                }
                return baseUrl + endpoint;
            }
            
            // Fallback: extract base URL from current location
            var pathname = window.location.pathname;
            baseUrl = window.location.origin;
            
            var checkoutIndex = pathname.indexOf('/checkout');
            if (checkoutIndex !== -1) {
                var storePath = pathname.substring(0, checkoutIndex);
                baseUrl = window.location.origin + storePath;
            }
            
            if (baseUrl.charAt(baseUrl.length - 1) !== '/') {
                baseUrl += '/';
            }
            
            if (endpoint.charAt(0) === '/') {
                endpoint = endpoint.substring(1);
            }
            
            return baseUrl + endpoint;
        },

        /**
         * Handle return from 3DS
         */
        handleReturn: function (sessionData) {
            // Show status container
            this.showStatusBox();
            
            // Update provider logo if available in session data
            if (sessionData.providerLogoUrl) {
                this.updateProviderLogo(sessionData.providerLogoUrl, sessionData.providerName);
            }
            
            // Update payment method display with logo and name from session
            this.updatePaymentMethod(
                sessionData.paymentMethod || 'card',
                sessionData.paymentMethodName,
                sessionData.paymentMethodLogoUrl
            );
            
            // Show processing state
            this.updateStatus('processing', 
                this.translations.waitConfirmation || 'Please wait for confirmation',
                this.translations.verifying || 'Verifying payment status...'
            );
            
            // Clear the session data
            this.clear3DSSession();
            
            // Start polling for payment status
            if (sessionData.paymentId || sessionData.magentoOrderId) {
                this.pollPaymentStatus(sessionData.paymentId, sessionData.authToken, sessionData.magentoOrderId);
            } else {
                // No payment ID - show success
                this.updateStatus('success',
                    this.translations.success || 'Payment completed successfully!',
                    this.translations.successSub || 'Your order has been confirmed.'
                );
                this.clearSimplyinSession();
            }
        },

        /**
         * Update provider logo dynamically
         */
        updateProviderLogo: function (logoUrl, providerName) {
            var providerLogo = $('#simplyin-provider-logo');
            if (providerLogo.length && logoUrl) {
                providerLogo.attr('src', logoUrl);
                if (providerName) {
                    providerLogo.attr('alt', providerName);
                }
            }
        },

        /**
         * Show the status box
         */
        showStatusBox: function () {
            var container = $('#simplyin-payment-status');
            if (container.length) {
                container.show();
            }
        },

        /**
         * Update payment method display
         * @param {string} method - Payment method type (card, blik, etc.)
         * @param {string} methodName - Display name from API
         * @param {string} methodLogoUrl - Logo URL from API
         */
        updatePaymentMethod: function (method, methodName, methodLogoUrl) {
            var methodNameEl = $('#simplyin-method-name');
            var methodLogo = $('#simplyin-method-logo');
            
            // Update method name - use API name if available, otherwise translate
            if (methodName) {
                methodNameEl.text(methodName);
            } else if (method === 'blik') {
                methodNameEl.text(this.translations.blik || 'BLIK');
            } else {
                methodNameEl.text(this.translations.card || 'Card');
            }
            
            // Update method logo - use API logo if available
            if (methodLogoUrl) {
                methodLogo.attr('src', methodLogoUrl);
                methodLogo.attr('alt', methodName || method);
                methodLogo.show();
            } else {
                // Hide logo if no URL provided
                methodLogo.hide();
            }
        },

        /**
         * Update status display
         */
        updateStatus: function (status, mainMessage, subMessage) {
            var statusBox = $('.simplyin-payment-status-box');
            var statusIcon = $('#simplyin-status-icon');
            var statusMain = $('#simplyin-status-main');
            var statusSub = $('#simplyin-status-sub');
            var spinner = $('#simplyin-status-spinner');
            
            // Remove all status classes
            statusBox.removeClass('status-processing status-success status-error status-warning');
            
            // Update icon and class based on status
            switch (status) {
                case 'success':
                    statusBox.addClass('status-success');
                    statusIcon.html(this.icons.success);
                    spinner.addClass('hidden');
                    break;
                case 'error':
                    statusBox.addClass('status-error');
                    statusIcon.html(this.icons.error);
                    spinner.addClass('hidden');
                    break;
                case 'warning':
                    statusBox.addClass('status-warning');
                    statusIcon.html(this.icons.warning);
                    spinner.addClass('hidden');
                    break;
                case 'processing':
                default:
                    statusBox.addClass('status-processing');
                    statusIcon.html(this.icons.clock);
                    spinner.removeClass('hidden');
                    break;
            }
            
            // Update messages
            if (mainMessage) {
                statusMain.text(mainMessage);
            }
            if (subMessage) {
                statusSub.text(subMessage);
            }
        },

        /**
         * Poll payment status
         */
        pollPaymentStatus: function (paymentId, authToken, magentoOrderId) {
            var attempts = 0;
            var maxAttempts = 30;
            var pollInterval = 2000;
            var self = this;
            
            var poll = function () {
                attempts++;
                
                ajaxClient.postSilent('simplyin/api/checkPaymentStatus', {
                    paymentId: paymentId,
                    authToken: authToken,
                    orderId: magentoOrderId
                }).done(function (response) {
                    if (response.success && response.status) {
                        var status = response.status.toUpperCase();
                        
                        if (status === 'COMPLETED' || status === 'SUCCESS' || status === 'PAID') {
                            self.updateStatus('success',
                                self.translations.success || 'Payment completed successfully!',
                                self.translations.successSub || 'Your order has been confirmed.'
                            );
                            self.clearSimplyinSession();
                        } else if (status === 'FAILED' || status === 'CANCELLED' || status === 'REJECTED') {
                            self.updateStatus('error',
                                self.translations.failed || 'Payment failed',
                                response.errorMessage || self.translations.failedSub || 'Your order has been created but requires payment.'
                            );
                            self.clearSimplyinSession();
                        } else if (status === 'PENDING' && attempts < maxAttempts) {
                            setTimeout(poll, pollInterval);
                        } else {
                            // Payment is still pending after max attempts
                            self.updateStatus('warning',
                                self.translations.pending || 'Payment is being processed',
                                self.translations.pendingSub || 'You will receive a confirmation email once the payment is verified.'
                            );
                        }
                    } else {
                        if (attempts < maxAttempts) {
                            setTimeout(poll, pollInterval);
                        } else {
                            self.updateStatus('warning',
                                self.translations.pending || 'Payment is being processed',
                                self.translations.pendingSub || 'You will receive a confirmation email once the payment is verified.'
                            );
                        }
                    }
                }).fail(function () {
                    if (attempts < maxAttempts) {
                        setTimeout(poll, pollInterval);
                    } else {
                        self.updateStatus('warning',
                            self.translations.pending || 'Payment is being processed',
                            self.translations.pendingSub || 'You will receive a confirmation email once the payment is verified.'
                        );
                    }
                });
            };
            
            poll();
        }
    };

    // Return a function that accepts config from x-magento-init
    return function (config) {
        handler.init(config);
        return handler;
    };
});
