/**
 * Mobile Banking Application
 * Base JavaScript Functionality
 */

(function() {
    'use strict';

    // DOM Ready
    document.addEventListener('DOMContentLoaded', function() {
        
        // Initialize loader
        initLoader();
        
        // Initialize dark mode
        initDarkMode();
        
        // Initialize sidebar
        initSidebar();
        
        // Initialize form controls
        initFormControls();
        
        // Initialize toast notifications
        initToast();
        
        // Initialize carousels
        initCarousels();
        
        // Initialize tooltips
        initTooltips();
        
        // Initialize go back buttons
        initGoBack();
        
        // Initialize file uploads
        initFileUpload();
        
        // Initialize searchbox
        initSearchbox();
        
        // Initialize notification close buttons
        initNotifications();
    });

    /**
     * Loader functionality
     */
    function initLoader() {
        var loader = document.getElementById('loader');
        if (loader) {
            setTimeout(function() {
                loader.setAttribute('class', 'loader hidden');
                setTimeout(function() {
                    loader.style.display = 'none';
                }, 300);
            }, 500);
        }
    }

    /**
     * Dark Mode Toggle
     */
    function initDarkMode() {
        var pageBody = document.querySelector('body');
        var darkModeSwitch = document.querySelectorAll('.dark-mode-switch');
        var checkDarkModeStatus = localStorage.getItem('FinappDarkMode');

        // Check if dark mode was previously enabled
        if (checkDarkModeStatus === '1' || checkDarkModeStatus === 1) {
            pageBody.classList.add('dark-mode');
            updateDarkModeSwitch(true);
        }

        // Dark mode toggle event
        darkModeSwitch.forEach(function(el) {
            el.addEventListener('change', function() {
                var isDark = pageBody.classList.contains('dark-mode');
                if (isDark) {
                    pageBody.classList.remove('dark-mode');
                    localStorage.setItem('FinappDarkMode', '0');
                    updateDarkModeSwitch(false);
                } else {
                    pageBody.classList.add('dark-mode');
                    localStorage.setItem('FinappDarkMode', '1');
                    updateDarkModeSwitch(true);
                }
            });
        });

        function updateDarkModeSwitch(isEnabled) {
            darkModeSwitch.forEach(function(el) {
                el.checked = isEnabled;
            });
        }
    }

    /**
     * Sidebar Panel
     */
    function initSidebar() {
        var sidebarPanel = document.getElementById('sidebarPanel');
        if (sidebarPanel) {
            // Sidebar is handled by Bootstrap offcanvas
        }
    }

    /**
     * Form Controls - Input animations
     */
    function initFormControls() {
        var formControls = document.querySelectorAll('.form-group .form-control');
        
        formControls.forEach(function(el) {
            // Focus event
            el.addEventListener('focus', function() {
                this.parentElement.classList.add('not-empty');
            });

            // Blur event
            el.addEventListener('blur', function() {
                if (this.value.length === 0) {
                    this.parentElement.classList.remove('not-empty');
                }
            });

            // Keyup event
            el.addEventListener('keyup', function() {
                if (this.value.length > 0) {
                    this.parentElement.classList.add('not-empty');
                } else {
                    this.parentElement.classList.remove('not-empty');
                }
            });

            // Check if already has value
            if (el.value.length > 0) {
                el.parentElement.classList.add('not-empty');
            }
        });

        // Clear input buttons
        var clearInputs = document.querySelectorAll('.clear-input');
        clearInputs.forEach(function(el) {
            el.addEventListener('click', function() {
                var parent = this.parentElement;
                var input = parent.querySelector('.form-control');
                if (input) {
                    input.value = '';
                    input.focus();
                    parent.classList.remove('not-empty');
                }
            });
        });
    }

    /**
     * Toast Notifications
     */
    function initToast() {
        // Close toast buttons
        var toastCloseButtons = document.querySelectorAll('.toast-box .close-button');
        toastCloseButtons.forEach(function(el) {
            el.addEventListener('click', function(e) {
                e.preventDefault();
                closeToastBox();
            });
        });

        // Tap to close toast
        var toastTapToClose = document.querySelectorAll('.toast-box.tap-to-close');
        toastTapToClose.forEach(function(el) {
            el.addEventListener('click', function() {
                closeToastBox();
            });
        });
    }

    /**
     * Close all toast boxes
     */
    window.closeToastBox = function() {
        var toastBoxes = document.querySelectorAll('.toast-box');
        toastBoxes.forEach(function(el) {
            el.classList.remove('show');
        });
    };

    /**
     * Show toast notification
     */
    window.toastbox = function(id, duration) {
        var toast = document.getElementById(id);
        if (toast) {
            closeToastBox();
            setTimeout(function() {
                toast.classList.add('show');
            }, 100);
            
            if (duration) {
                duration = duration + 100;
                setTimeout(function() {
                    closeToastBox();
                }, duration);
            }
        }
    };

    /**
     * Notification boxes
     */
    function initNotifications() {
        var notificationCloseButtons = document.querySelectorAll('.notification-box .close-button');
        var notificationTapToClose = document.querySelectorAll('.notification-box.tap-to-close .notification-dialog');

        notificationCloseButtons.forEach(function(el) {
            el.addEventListener('click', function(e) {
                e.preventDefault();
                closeNotificationBox();
            });
        });

        notificationTapToClose.forEach(function(el) {
            el.addEventListener('click', function() {
                closeNotificationBox();
            });
        });
    }

    /**
     * Close notification boxes
     */
    window.closeNotificationBox = function() {
        var notificationBoxes = document.querySelectorAll('.notification-box');
        notificationBoxes.forEach(function(el) {
            el.classList.remove('show');
        });
    };

    /**
     * Show notification
     */
    window.notification = function(id, duration) {
        var notif = document.getElementById(id);
        if (notif) {
            closeNotificationBox();
            setTimeout(function() {
                notif.classList.add('show');
            }, 100);
            
            if (duration) {
                duration = duration + 100;
                setTimeout(function() {
                    closeNotificationBox();
                }, duration);
            }
        }
    };

    /**
     * Initialize Carousels (Splide)
     */
    function initCarousels() {
        // Single carousel
        if (typeof Splide !== 'undefined') {
            document.querySelectorAll('.carousel-single').forEach(function(el) {
                new Splide(el, {
                    perPage: 1,
                    rewind: true,
                    type: 'loop',
                    gap: 0,
                    arrows: false,
                    pagination: false
                }).mount();
            });

            // Multiple carousel
            document.querySelectorAll('.carousel-multiple').forEach(function(el) {
                new Splide(el, {
                    perPage: 3,
                    rewind: true,
                    type: 'loop',
                    gap: 16,
                    padding: 16,
                    arrows: false,
                    pagination: false,
                    breakpoints: {
                        768: { perPage: 1 },
                        991: { perPage: 2 }
                    }
                }).mount();
            });

            // Small carousel
            document.querySelectorAll('.carousel-small').forEach(function(el) {
                new Splide(el, {
                    perPage: 9,
                    rewind: false,
                    type: 'loop',
                    gap: 16,
                    padding: 16,
                    arrows: false,
                    pagination: false,
                    breakpoints: {
                        768: { perPage: 4 },
                        991: { perPage: 7 }
                    }
                }).mount();
            });

            // Full carousel
            document.querySelectorAll('.carousel-full').forEach(function(el) {
                new Splide(el, {
                    perPage: 1,
                    rewind: false,
                    type: 'loop',
                    gap: 16,
                    padding: 16,
                    arrows: false,
                    pagination: true
                }).mount();
            });

            // Slider
            document.querySelectorAll('.carousel-slider').forEach(function(el) {
                new Splide(el, {
                    perPage: 16,
                    rewind: false,
                    type: 'slide',
                    gap: 16,
                    padding: 16,
                    arrows: false,
                    pagination: false,
                    breakpoints: {
                        768: { perPage: 4 },
                        991: { perPage: 7 },
                        1200: { perPage: 11 }
                    }
                }).mount();
            });

            // Story block
            document.querySelectorAll('.story-block').forEach(function(el) {
                new Splide(el, {
                    perPage: 4,
                    rewind: true,
                    type: 'loop',
                    gap: 16,
                    padding: 16,
                    arrows: false,
                    pagination: false,
                    breakpoints: {
                        768: { perPage: 2 },
                        991: { perPage: 3 }
                    }
                }).mount();
            });
        }
    }

    /**
     * Initialize Bootstrap Tooltips
     */
    function initTooltips() {
        if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip) {
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            tooltipTriggerList.map(function(el) {
                return new bootstrap.Tooltip(el);
            });
        }
    }

    /**
     * Go Back Button
     */
    function initGoBack() {
        var goBackButtons = document.querySelectorAll('.goBack');
        goBackButtons.forEach(function(el) {
            el.addEventListener('click', function(e) {
                e.preventDefault();
                window.history.go(-1);
            });
        });
    }

    /**
     * File Upload Preview
     */
    function initFileUpload() {
        var uploadComponents = document.querySelectorAll('.custom-file-upload');
        uploadComponents.forEach(function(el) {
            var uploadId = '#' + el.id;
            var fileInput = document.querySelector(uploadId + ' input[type="file"]');
            var label = document.querySelector(uploadId + ' .file-upload-wrapper');
            var labelText = document.querySelector(uploadId + ' .close-button');
            
            if (fileInput && labelText) {
                var defaultText = labelText.innerHTML;
                
                fileInput.addEventListener('change', function(e) {
                    var fileName = this.value.split('\\').pop();
                    if (fileName) {
                        if (label) {
                            label.classList.add('uploaded');
                            var tmppath = URL.createObjectURL(e.target.files[0]);
                            label.style.backgroundImage = 'url(' + tmppath + ')';
                        }
                        labelText.innerHTML = fileName;
                    } else {
                        if (label) {
                            label.classList.remove('uploaded');
                        }
                        labelText.innerHTML = defaultText;
                    }
                });
            }
        });
    }

    /**
     * Searchbox Toggle
     */
    function initSearchbox() {
        var searchboxToggles = document.querySelectorAll('.toggle-searchbox');
        searchboxToggles.forEach(function(el) {
            el.addEventListener('click', function() {
                var searchbox = document.getElementById('searchbox');
                if (searchbox) {
                    var isOpen = searchbox.classList.contains('show');
                    if (isOpen) {
                        searchbox.classList.remove('show');
                    } else {
                        searchbox.classList.add('show');
                        var input = searchbox.querySelector('.form-control');
                        if (input) {
                            input.focus();
                        }
                    }
                }
            });
        });
    }

    /**
     * PWA Add to Home Screen (Optional)
     */
    window.AddtoHome = function(delay, enableStorage) {
        if (!enableStorage) {
            showAddToHome(delay);
        } else {
            var addToHomeStatus = localStorage.getItem('FinappAddtoHome');
            if (addToHomeStatus !== '1' && addToHomeStatus !== 1) {
                localStorage.setItem('FinappAddtoHome', 0);
                showAddToHome(delay);
            }
        }
    };

    function showAddToHome(delay) {
        var isStandalone = window.matchMedia('(display-mode: standalone)').matches;
        if (!navigator.standalone && !isStandalone) {
            setTimeout(function() {
                var iosModal = document.getElementById('ios-add-to-home-screen');
                var androidModal = document.getElementById('android-add-to-home-screen');
                
                var isIos = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
                var isAndroid = /android/i.test(navigator.userAgent);
                
                if (isIos && iosModal && typeof bootstrap !== 'undefined') {
                    new bootstrap.Modal(iosModal).show();
                } else if (isAndroid && androidModal && typeof bootstrap !== 'undefined') {
                    new bootstrap.Modal(androidModal).show();
                }
            }, delay);
        }
    }

    /**
     * Cookies Box
     */
    window.CookiesBox = function(delay) {
        var cookiesStatus = localStorage.getItem('FinappCookies');
        if (cookiesStatus !== '1' && cookiesStatus !== 1) {
            var cookiesBox = document.querySelector('.offcanvas.cookiesbox');
            if (cookiesBox && typeof bootstrap !== 'undefined') {
                var bsOffcanvas = new bootstrap.Offcanvas(cookiesBox);
                if (delay) {
                    setTimeout(function() {
                        bsOffcanvas.show();
                    }, delay);
                } else {
                    bsOffcanvas.show();
                }
            }
        }
    };

    // Accept cookies button
    var acceptCookiesButtons = document.querySelectorAll('.accept-cookies');
    acceptCookiesButtons.forEach(function(el) {
        el.addEventListener('click', function() {
            localStorage.setItem('FinappCookies', '1');
        });
    });

})();
