// ============================================================================
// ENTERPRISE WMS - ADVANCED UI INTERACTIONS
// Notifications, animations, dynamic features, state management
// ============================================================================

(function (window) {
    'use strict';

    const EnterpriseUI = {
        // Configuration
        config: {
            notificationBellId: 'notificationBell',
            notificationBadgeId: 'notificationBadge',
            notificationCountId: 'notificationCount',
            animationDuration: 300,
            toastDuration: 4000
        },

        // Initialize
        init: function () {
            this.setupNotifications();
            this.setupAnimations();
            this.setupFormValidation();
            this.setupTableInteractions();
            this.setupDropdownEnhancements();
            console.log('Enterprise UI initialized');
        },

        // ====================================================================
        // NOTIFICATIONS
        // ====================================================================

        setupNotifications: function () {
            const self = this;
            const notificationBell = document.getElementById(this.config.notificationBellId);

            if (notificationBell) {
                // Mark as read when clicked
                notificationBell.addEventListener('click', function () {
                    self.updateNotificationBadge(0);
                });
            }

            // Listen for new notifications (for future integration)
            window.addEventListener('notification:new', function (e) {
                self.addNotification(e.detail);
            });
        },

        updateNotificationBadge: function (count) {
            const badge = document.getElementById(this.config.notificationBadgeId);
            const countEl = document.getElementById(this.config.notificationCountId);

            if (badge) {
                if (count === 0) {
                    badge.style.display = 'none';
                } else {
                    badge.textContent = count > 9 ? '9+' : count;
                    badge.style.display = 'flex';
                }
            }

            if (countEl) {
                countEl.textContent = count === 0 ? 'No' : count;
            }
        },

        addNotification: function (notification) {
            // notification = { icon, color, title, text, time }
            const template = `
                <a href="#" class="enterprise-notification-item">
                    <div class="enterprise-notification-icon ${notification.color || 'bg-info'}">
                        <i class="${notification.icon || 'fas fa-bell'}"></i>
                    </div>
                    <div class="enterprise-notification-content">
                        <div class="enterprise-notification-title">${notification.title}</div>
                        <div class="enterprise-notification-text">${notification.text}</div>
                        <small class="enterprise-notification-time">just now</small>
                    </div>
                </a>
            `;

            const list = document.querySelector('.enterprise-notification-list');
            if (list) {
                const div = document.createElement('div');
                div.innerHTML = template;
                list.insertBefore(div.firstElementChild, list.firstChild);
            }
        },

        showToast: function (message, type = 'info', duration = null) {
            duration = duration || this.config.toastDuration;

            const toast = document.createElement('div');
            toast.className = `alert alert-${type} m-3`;
            toast.setAttribute('role', 'alert');
            toast.textContent = message;
            toast.style.animation = 'slideIn 0.3s ease';

            document.body.appendChild(toast);

            setTimeout(() => {
                toast.style.animation = 'fadeIn 0.3s ease reverse';
                setTimeout(() => toast.remove(), 300);
            }, duration);
        },

        // ====================================================================
        // ANIMATIONS
        // ====================================================================

        setupAnimations: function () {
            // Observe elements for fade-in animation on scroll
            if ('IntersectionObserver' in window) {
                const observer = new IntersectionObserver((entries) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            entry.target.style.animation = 'fadeIn 0.5s ease forwards';
                            observer.unobserve(entry.target);
                        }
                    });
                }, { threshold: 0.1 });

                document.querySelectorAll('.card, .enterprise-kpi-card').forEach(el => {
                    observer.observe(el);
                });
            }
        },

        // ====================================================================
        // FORM VALIDATION
        // ====================================================================

        setupFormValidation: function () {
            const forms = document.querySelectorAll('form[data-validate="true"]');
            forms.forEach(form => {
                form.addEventListener('submit', function (e) {
                    if (!form.checkValidity()) {
                        e.preventDefault();
                        e.stopPropagation();
                    }
                    form.classList.add('was-validated');
                });
            });
        },

        validateForm: function (formId) {
            const form = document.getElementById(formId);
            if (!form) return false;

            if (!form.checkValidity()) {
                form.classList.add('was-validated');
                return false;
            }
            return true;
        },

        // ====================================================================
        // TABLE INTERACTIONS
        // ====================================================================

        setupTableInteractions: function () {
            const self = this;

            // Row selection with checkbox
            const checkboxes = document.querySelectorAll('table input[type="checkbox"]');
            checkboxes.forEach(checkbox => {
                checkbox.addEventListener('change', function () {
                    const row = this.closest('tr');
                    if (this.checked) {
                        row.style.backgroundColor = 'rgba(0, 82, 204, 0.05)';
                    } else {
                        row.style.backgroundColor = '';
                    }
                });
            });

            // Select all checkbox
            const selectAllCheckbox = document.querySelector('th input[type="checkbox"]');
            if (selectAllCheckbox) {
                selectAllCheckbox.addEventListener('change', function () {
                    const checkboxes = document.querySelectorAll('tbody input[type="checkbox"]');
                    checkboxes.forEach(checkbox => {
                        checkbox.checked = this.checked;
                        checkbox.dispatchEvent(new Event('change'));
                    });
                });
            }

            // Sortable columns
            const sortableHeaders = document.querySelectorAll('th[data-sortable="true"]');
            sortableHeaders.forEach(header => {
                header.style.cursor = 'pointer';
                header.addEventListener('click', function () {
                    self.sortTable(this);
                });
            });
        },

        sortTable: function (header) {
            // Placeholder for table sorting logic
            const table = header.closest('table');
            const direction = header.classList.contains('sort-asc') ? 'desc' : 'asc';

            document.querySelectorAll('th[data-sortable="true"]').forEach(th => {
                th.classList.remove('sort-asc', 'sort-desc');
            });

            header.classList.add(`sort-${direction}`);
        },

        // ====================================================================
        // DROPDOWN ENHANCEMENTS
        // ====================================================================

        setupDropdownEnhancements: function () {
            // Close dropdown when clicking outside
            document.addEventListener('click', function (e) {
                const dropdowns = document.querySelectorAll('.enterprise-dropdown-menu');
                dropdowns.forEach(dropdown => {
                    if (!dropdown.closest('.enterprise-navbar-item').contains(e.target)) {
                        dropdown.classList.remove('show');
                    }
                });
            });

            // Open dropdown with proper positioning
            const dropdownToggles = document.querySelectorAll('[data-bs-toggle="dropdown"]');
            dropdownToggles.forEach(toggle => {
                toggle.addEventListener('click', function (e) {
                    e.preventDefault();
                    const menu = this.nextElementSibling;
                    if (menu && menu.classList.contains('enterprise-dropdown-menu')) {
                        menu.classList.toggle('show');
                    }
                });
            });
        },

        // ====================================================================
        // UTILITIES
        // ====================================================================

        setLoading: function (elementId, isLoading = true) {
            const element = document.getElementById(elementId);
            if (!element) return;

            if (isLoading) {
                element.disabled = true;
                const originalText = element.innerHTML;
                element.dataset.originalText = originalText;
                element.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Loading...';
            } else {
                element.disabled = false;
                element.innerHTML = element.dataset.originalText || 'Submit';
            }
        },

        formatCurrency: function (value) {
            return new Intl.NumberFormat('id-ID', {
                style: 'currency',
                currency: 'IDR',
                minimumFractionDigits: 0
            }).format(value);
        },

        formatDate: function (date) {
            return new Intl.DateTimeFormat('id-ID', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            }).format(new Date(date));
        },

        debounce: function (func, wait) {
            let timeout;
            return function (...args) {
                clearTimeout(timeout);
                timeout = setTimeout(() => func.apply(this, args), wait);
            };
        },

        // ====================================================================
        // CONFIRMATION DIALOG
        // ====================================================================

        confirm: function (message, onConfirm, onCancel = null) {
            if (window.confirm(message)) {
                if (typeof onConfirm === 'function') onConfirm();
            } else {
                if (typeof onCancel === 'function') onCancel();
            }
        },

        // ====================================================================
        // STATE MANAGEMENT
        // ====================================================================

        setState: function (key, value) {
            try {
                localStorage.setItem(`ships-wms-${key}`, JSON.stringify(value));
            } catch (e) {
                console.warn('Could not save state:', e);
            }
        },

        getState: function (key, defaultValue = null) {
            try {
                const item = localStorage.getItem(`ships-wms-${key}`);
                return item ? JSON.parse(item) : defaultValue;
            } catch (e) {
                console.warn('Could not get state:', e);
                return defaultValue;
            }
        },

        clearState: function (key) {
            try {
                localStorage.removeItem(`ships-wms-${key}`);
            } catch (e) {
                console.warn('Could not clear state:', e);
            }
        }
    };

    // Auto-initialize when DOM is ready
    document.addEventListener('DOMContentLoaded', function () {
        EnterpriseUI.init();
    });

    // Expose to window for external use
    window.EnterpriseUI = EnterpriseUI;

})(window);