/**
 * SimplyIN Payment - CCIframe Manager
 * Handles CCIframe library loading and card input management for 3D Secure payments
 */
define([
    'jquery',
    'mage/translate'
], function ($, $t) {
    'use strict';

    return {
        /**
         * CCIframe instance
         */
        cc: null,

        /**
         * Library load status
         */
        isLoaded: false,

        /**
         * Created input components
         */
        components: {},

        /**
         * Integrator ID for initialization
         */
        integratorId: null,

        /**
         * Iframe URL for library loading
         */
        iframeUrl: null,

        /**
         * Style configuration for card inputs
         */
        styleConfig: {
            fonts: [{
                family: "Inter",
                src: "url(https://fonts.gstatic.com/s/inter/v18/UcCo3FwrK3iLTcviYwYZ8UA3.woff2) format('woff2')",
                style: "normal",
                weight: "100 900"
            }],
            styles: {
                base: {
                    color: "rgba(0, 0, 0, 0.8)",
                    fontFamily: "Inter",
                    fontSize: "14px"
                }
            }
        },

        /**
         * Load CCIframe library dynamically
         * @param {string} iframeUrl - URL to load CCIframe script from
         * @returns {Promise} - Resolves when library is loaded
         */
        loadLibrary: function (iframeUrl) {
            var self = this;
            this.iframeUrl = iframeUrl;

            return new Promise(function (resolve, reject) {
                // Check if already loaded
                if (window.CCIframe) {
                    self.isLoaded = true;
                    resolve();
                    return;
                }

                // Check if script is already being loaded
                var existingScript = document.querySelector('script[src="' + iframeUrl + '"]');
                if (existingScript) {
                    // Wait for existing script to load
                    existingScript.addEventListener('load', function () {
                        self.isLoaded = true;
                        resolve();
                    });
                    existingScript.addEventListener('error', function () {
                        reject(new Error($t('Failed to load CCIframe library')));
                    });
                    return;
                }

                // Create and load script
                var script = document.createElement('script');
                script.src = iframeUrl;
                script.async = true;

                script.onload = function () {
                    if (window.CCIframe) {
                        self.isLoaded = true;
                        resolve();
                    } else {
                        reject(new Error($t('CCIframe library not available after load')));
                    }
                };

                script.onerror = function () {
                    reject(new Error($t('Failed to load CCIframe library from: ') + iframeUrl));
                };

                document.head.appendChild(script);
            });
        },

        /**
         * Initialize CCIframe with integrator ID
         * @param {string} integratorId - Integrator ID from API
         * @returns {boolean} - True if initialization successful
         */
        initialize: function (integratorId) {
            if (!window.CCIframe) {
                console.error('CCIframe library not loaded');
                return false;
            }

            if (!integratorId) {
                console.error('Integrator ID is required');
                return false;
            }

            try {
                this.integratorId = integratorId;
                this.cc = CCIframe({ integratorId: integratorId });
                return true;
            } catch (e) {
                console.error('Failed to initialize CCIframe:', e);
                return false;
            }
        },

        /**
         * Create secure input components for card fields
         * @param {Object} containerIds - Object with container IDs for each field
         * @param {Object} customStyleConfig - Optional custom style configuration
         * @returns {boolean} - True if components created successfully
         */
        createInputComponents: function (containerIds, customStyleConfig) {
            if (!this.cc) {
                console.error('CCIframe not initialized');
                return false;
            }

            var styleConfig = customStyleConfig || this.styleConfig;

            try {
                // Create card number component
                if (containerIds.cardNumber) {
                    this.components.cardNumber = this.cc.createComponent(
                        'cardNumber',
                        containerIds.cardNumber,
                        styleConfig
                    );
                }

                // Create card holder component (optional)
                if (containerIds.cardHolder) {
                    this.components.cardHolder = this.cc.createComponent(
                        'cardHolder',
                        containerIds.cardHolder,
                        styleConfig
                    );
                }

                // Create expiry date component
                if (containerIds.expiry) {
                    this.components.expiry = this.cc.createComponent(
                        'cardExp',
                        containerIds.expiry,
                        styleConfig
                    );
                }

                // Create CVV component
                if (containerIds.cvv) {
                    this.components.cvv = this.cc.createComponent(
                        'cardCvv',
                        containerIds.cvv,
                        styleConfig
                    );
                }

                return true;
            } catch (e) {
                console.error('Failed to create CCIframe components:', e);
                return false;
            }
        },

        /**
         * Create token from card data
         * @returns {Promise} - Resolves with token data or rejects with error
         */
        createToken: function () {
            var self = this;

            return new Promise(function (resolve, reject) {
                if (!self.cc) {
                    reject(new Error($t('CCIframe not initialized')));
                    return;
                }

                self.cc.createToken().then(function (result) {
                    if (result && result.oneTimeToken) {
                        resolve({
                            oneTimeToken: result.oneTimeToken,
                            last4digits: result.last4digits || '',
                            organization: result.organization || '',
                            first6digits: result.first6digits || '',
                            expiryMonth: result.expiryMonth || '',
                            expiryYear: result.expiryYear || ''
                        });
                    } else {
                        reject(new Error($t('Invalid token response from CCIframe')));
                    }
                }).catch(function (error) {
                    console.error('CCIframe createToken error:', error);
                    
                    var errorMessage = $t('Card validation failed');
                    if (error && error.message) {
                        if (error.message.includes('400')) {
                            errorMessage = $t('Invalid card data. Please check your card details.');
                        } else if (error.message.includes('network')) {
                            errorMessage = $t('Network error. Please check your connection.');
                        } else {
                            errorMessage = error.message;
                        }
                    }
                    
                    reject(new Error(errorMessage));
                });
            });
        },

        /**
         * Destroy CCIframe components and clean up
         */
        destroy: function () {
            this.components = {};
            this.cc = null;
            this.integratorId = null;
        },

        /**
         * Check if CCIframe is ready
         * @returns {boolean}
         */
        isReady: function () {
            return this.isLoaded && this.cc !== null;
        },

        /**
         * Get card brand icon URL based on organization
         * @param {string} organization - Card organization (visa, mastercard, etc.)
         * @returns {string} - Icon URL
         */
        getCardBrandIcon: function (organization) {
            var baseUrl = require.toUrl('Simplyin_Payment/images/');
            var brandIcons = {
                'visa': 'visa.svg',
                'mastercard': 'mastercard.svg',
                'maestro': 'maestro.svg',
                'amex': 'amex.svg',
                'discover': 'discover.svg',
                'diners': 'diners.svg',
                'jcb': 'jcb.svg'
            };

            var iconFile = brandIcons[organization.toLowerCase()] || 'card-default.svg';
            return baseUrl + iconFile;
        }
    };
});
