/**
 * InPost Universal Popup - Visual Feedback & Loading States
 * Rozszerzenie dla głównego pliku inpost-universal-popup.js
 * 
 * @version 1.0.0
 * @author InPost Integration Team
 * @created 2026-01-20
 * 
 * Funkcje:
 * - Loading progress bar
 * - Zoom hints & tooltips
 * - Search status messages
 * - Map skeleton loaders
 * - Real-time feedback
 */

(function() {
    'use strict';

    // Sprawdź czy główny skrypt jest załadowany (z retry mechanism)
    // PROBLEM: Sprawdzenie było zbyt wcześnie - skrypty ładują się asynchronicznie
    // ROZWIĄZANIE: Retry mechanism z setTimeout
    function checkMainScript() {
        if (typeof window.IntroPopup !== 'undefined') {
            return true;
        }
        return false;
    }
    
    // Retry mechanism - sprawdź ponownie po 100ms, 200ms, 500ms
    let retryCount = 0;
    const maxRetries = 3;
    const retryDelays = [100, 200, 500];
    
    function waitForMainScript() {
        if (checkMainScript()) {
            initVisualFeedback();
            return;
        }
        
        if (retryCount < maxRetries) {
            setTimeout(waitForMainScript, retryDelays[retryCount]);
            retryCount++;
        } else {
            // Po 3 próbach - sprawdź jeszcze raz na document.ready
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', function() {
                    setTimeout(function() {
                        if (!checkMainScript()) {
                            window.PS_DEBUG&&console.warn('[InPost Visual] Main InPost script (IntroPopup) not loaded after retries. Some features may not work.');
                        } else {
                            initVisualFeedback();
                        }
                    }, 500);
                });
            } else {
                // DOM już załadowany - ostatnia próba
                setTimeout(function() {
                    if (!checkMainScript()) {
                        window.PS_DEBUG&&console.warn('[InPost Visual] Main InPost script (IntroPopup) not loaded. Some features may not work.');
                    } else {
                        initVisualFeedback();
                    }
                }, 500);
            }
        }
    }
    
    function initVisualFeedback() {
        // Główny kod modułu tutaj
        if (typeof window.IntroPopup === 'undefined') {
            return;
        }

        // ====================
        // 1. PROGRESS BAR PODCZAS ŁADOWANIA API
        // ====================
    
    const LoadingIndicator = {
        // Stwórz progress bar
        create: function() {
            const existingBar = document.getElementById('inpostLoadingBar');
            if (existingBar) return;

            const html = `
                <div id="inpostLoadingBar" class="inpost-loading-bar">
                    <div class="inpost-loading-progress" style="width: 0%"></div>
                    <span class="inpost-loading-text">Ładowanie punktów...</span>
                </div>
            `;

            const container = document.getElementById('inpostPopupContainer');
            if (container) {
                container.insertAdjacentHTML('afterbegin', html);
            }
        },

        // Aktualizuj progress
        update: function(percentage, text) {
            const progressBar = document.querySelector('.inpost-loading-progress');
            const loadingText = document.querySelector('.inpost-loading-text');

            if (progressBar) {
                progressBar.style.width = Math.min(100, Math.max(0, percentage)) + '%';
            }

            if (loadingText && text) {
                loadingText.textContent = text;
            }
        },

        // Ukryj po zakończeniu
        hide: function() {
            const bar = document.getElementById('inpostLoadingBar');
            if (bar) {
                bar.style.opacity = '0';
                setTimeout(() => {
                    if (bar.parentNode) {
                        bar.parentNode.removeChild(bar);
                    }
                }, 300);
            }
        },

        // Pokaż ponownie
        show: function() {
            this.create();
            const bar = document.getElementById('inpostLoadingBar');
            if (bar) {
                bar.style.opacity = '1';
            }
        }
    };

    // ====================
    // 2. ZOOM HINTS (Wizualne podpowiedzi)
    // ====================
    
    const ZoomHints = {
        shown: false,
        timeout: null,

        show: function() {
            if (this.shown) return;

            const html = `
                <div id="inpostZoomHint" class="inpost-zoom-hint">
                    <span class="zoom-icon">🔍</span>
                    <span class="zoom-text">
                        Powiększ mapę:<br>
                        <strong>Ctrl + scroll</strong> lub <strong>pinch</strong>
                    </span>
                </div>
            `;

            const mapContainer = document.getElementById('inpostMap');
            if (mapContainer) {
                mapContainer.insertAdjacentHTML('afterbegin', html);
                this.shown = true;

                // Auto-hide po 5 sekundach
                this.timeout = setTimeout(() => {
                    this.hide();
                }, 5000);
            }
        },

        hide: function() {
            const hint = document.getElementById('inpostZoomHint');
            if (hint) {
                hint.style.opacity = '0';
                setTimeout(() => {
                    if (hint.parentNode) {
                        hint.parentNode.removeChild(hint);
                    }
                    this.shown = false;
                }, 300);
            }

            if (this.timeout) {
                clearTimeout(this.timeout);
                this.timeout = null;
            }
        },

        // Pokaż po pierwszym otwarciu mapy
        showOnce: function() {
            if (!localStorage.getItem('parcselect_zoom_hint_shown')) {
                this.show();
                localStorage.setItem('parcselect_zoom_hint_shown', 'true');
            }
        }
    };

    // ====================
    // 3. SEARCH STATUS MESSAGES
    // ====================
    
    const SearchStatus = {
        container: null,

        init: function() {
            const searchInput = document.getElementById('inpostSearchInput');
            if (!searchInput) return;

            // Stwórz kontener dla statusu
            const html = `
                <div id="inpostSearchStatus" class="inpost-search-status">
                    <span class="status-icon"></span>
                    <span class="status-text"></span>
                </div>
            `;

            searchInput.parentNode.insertAdjacentHTML('afterend', html);
            this.container = document.getElementById('inpostSearchStatus');
        },

        show: function(type, message) {
            if (!this.container) this.init();
            if (!this.container) return;

            const iconMap = {
                'searching': '🔍',
                'success': '✅',
                'warning': '⚠️',
                'error': '❌',
                'sorting': '📍'
            };

            const icon = this.container.querySelector('.status-icon');
            const text = this.container.querySelector('.status-text');

            if (icon) icon.textContent = iconMap[type] || '';
            if (text) text.textContent = message;

            this.container.className = 'inpost-search-status inpost-search-status-' + type;
            this.container.style.display = 'flex';
        },

        hide: function() {
            if (this.container) {
                this.container.style.display = 'none';
            }
        }
    };

    // ====================
    // 4. MAP SKELETON LOADER
    // ====================
    
    const SkeletonLoader = {
        create: function() {
            const html = `
                <div id="inpostMapSkeleton" class="inpost-map-skeleton">
                    <div class="skeleton-header"></div>
                    <div class="skeleton-map">
                        <div class="skeleton-marker"></div>
                        <div class="skeleton-marker"></div>
                        <div class="skeleton-marker"></div>
                    </div>
                    <div class="skeleton-list">
                        <div class="skeleton-item"></div>
                        <div class="skeleton-item"></div>
                        <div class="skeleton-item"></div>
                    </div>
                </div>
            `;

            const container = document.getElementById('inpostPopupContainer');
            if (container) {
                container.insertAdjacentHTML('afterbegin', html);
            }
        },

        remove: function() {
            const skeleton = document.getElementById('inpostMapSkeleton');
            if (skeleton && skeleton.parentNode) {
                skeleton.parentNode.removeChild(skeleton);
            }
        }
    };

    // ====================
    // 5. TOAST NOTIFICATIONS
    // ====================
    
    const Toast = {
        show: function(message, type = 'info', duration = 3000) {
            const id = 'inpostToast_' + Date.now();
            const typeClass = 'inpost-toast-' + type;

            const html = `
                <div id="${id}" class="inpost-toast ${typeClass}">
                    ${message}
                </div>
            `;

            document.body.insertAdjacentHTML('beforeend', html);
            const toast = document.getElementById(id);

            // Animate in
            setTimeout(() => {
                toast.classList.add('inpost-toast-show');
            }, 10);

            // Auto remove
            setTimeout(() => {
                toast.classList.remove('inpost-toast-show');
                setTimeout(() => {
                    if (toast.parentNode) {
                        toast.parentNode.removeChild(toast);
                    }
                }, 300);
            }, duration);
        },

        success: function(message) {
            this.show('✅ ' + message, 'success');
        },

        error: function(message) {
            this.show('❌ ' + message, 'error');
        },

        info: function(message) {
            this.show('ℹ️ ' + message, 'info');
        },

        warning: function(message) {
            this.show('⚠️ ' + message, 'warning');
        }
    };

    // ====================
    // 6. CONNECTION STATUS MONITOR
    // ====================
    
    const ConnectionMonitor = {
        init: function() {
            window.addEventListener('online', () => {
                Toast.success('Połączenie z internetem przywrócone');
            });

            window.addEventListener('offline', () => {
                Toast.error('Brak połączenia z internetem');
            });
        }
    };

    // ====================
    // EXPOSE PUBLICZNE API
    // ====================
    
    window.InPostVisual = {
        LoadingIndicator: LoadingIndicator,
        ZoomHints: ZoomHints,
        SearchStatus: SearchStatus,
        SkeletonLoader: SkeletonLoader,
        Toast: Toast,
        ConnectionMonitor: ConnectionMonitor
    };

    // Auto-init
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            ConnectionMonitor.init();
            SearchStatus.init();
        });
    } else {
        ConnectionMonitor.init();
        SearchStatus.init();
    }

        window.PS_DEBUG&&console.log('[InPost Visual] Visual feedback system loaded ✅');
    }
    
    // Rozpocznij sprawdzanie głównego skryptu
    waitForMainScript();

})();
