jQuery(document).ready(function($) {
    // Early exit if the finder form doesn't exist on the page
    if (!$('#didak-finder-form').length) {
        return;
    }

    // Constants
    const MAX_HISTORY_ITEMS = 10;
    const STORAGE_KEY = 'didakFinderSearchHistory';
    const BASE64_PLACEHOLDER = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';

    // State variables
    let openWindows = {
        processing: false
    };
    let currentResults = [];
    let popupOpenTime = null;
    let popupCloseTimer = null;

    // DOM Elements
    const $clearButton = $('#didak-finder-clear');
    const $clearContainer = $('#didak-finder-clear-container');
    const $input = $('#didak-finder-input');
    const $form = $('#didak-finder-form');
    const $results = $('#didak-finder-results');
    const $loading = $('#didak-finder-loading');
    const $submit = $('#didak-finder-submit');
    const $popupButtons = $('#didak-finder-popup-buttons');

    // Utility Functions
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // Search History Functions
    function loadSearchHistory() {
        try {
            const history = localStorage.getItem(STORAGE_KEY);
            return history ? JSON.parse(history) : [];
        } catch (e) {
            console.warn('Error loading search history:', e);
            return [];
        }
    }

    function saveSearchHistory(history) {
        try {
            localStorage.setItem(STORAGE_KEY, JSON.stringify(history));
            updateDatalist(history);
        } catch (e) {
            console.warn('Error saving search history:', e);
        }
    }

    function updateDatalist(history) {
        const $datalist = $('#search-history-list');
        $datalist.empty();
        history.forEach(term => {
            $datalist.append($('<option>', { value: term }));
        });
    }

    function addToSearchHistory(term) {
        if (!term || term.trim().length === 0) return;
        
        term = term.trim();
        let history = loadSearchHistory();
        history = history.filter(item => item.toLowerCase() !== term.toLowerCase());
        history.unshift(term);
        history = history.slice(0, MAX_HISTORY_ITEMS);
        saveSearchHistory(history);
    }

    function clearSearchHistory() {
        saveSearchHistory([]);
        $('#search-history-list').empty();
    }

    function initializeSearchHistory() {
        const history = loadSearchHistory();
        if (history && history.length > 0) {
            updateDatalist(history);
        }
        
        if ($input.length) {
            const searchValue = $input.val();
            if (searchValue) {
                $('#search-history-list').toggle(searchValue.trim().length >= 2);
            }
        }
    }

    // Window Management Functions
    function safeWindowOpen(url, name, features) {
        try {
            const newWindow = window.open(url, name, features);
            if (newWindow === null) {
                console.warn('Popup blev blokeret af browseren');
                window.location.href = url;
            }
            return newWindow;
        } catch (error) {
            console.error('Fejl ved åbning af vindue:', error);
            window.location.href = url;
            return null;
        }
    }

    function handlePopupOpen(url) {
        if (openWindows.popup && !openWindows.popup.closed) {
            try {
                openWindows.popup.close();
            } catch (e) {
                console.warn('Kunne ikke lukke eksisterende popup:', e);
            }
        }
        
        const popupSize = getPopupSize();
        const popupPosition = getPopupPosition(
            parseInt(popupSize.width), 
            parseInt(popupSize.height)
        );
        
        const features = [
            'width=' + popupSize.width,
            'height=' + popupSize.height,
            'menubar=no',
            'toolbar=no',
            'location=yes',
            'status=no',
            'resizable=yes',
            'scrollbars=yes'
        ];

        features.push(...popupPosition.split(','));
        
        try {
            const popup = window.open(url, 'DidakFinderPopup', features.join(','));
            
            if (popup === null) {
                handleNewTabOpen(url);
                return;
            }
            
            openWindows.popup = popup;
            popupOpenTime = new Date().getTime();

            if (popup) {
                popup.focus();
            }
            
            if (didakFinderPopupButtons.enabled === '1') {
                showPopupButtons(currentResults);
            }

            $(window).off('blur.popupHandler').on('blur.popupHandler', handleWindowBlur);
            
        } catch (e) {
            console.warn('Fejl ved åbning af popup:', e);
            handleNewTabOpen(url);
        }
    }

    function handleNewWindowOpen(url) {
        const windowName = didakFinderResultTarget.window_type === '_blank' ? 
            `DidakFinder${Date.now()}` : 'DidakFinderResults';
        
        let features = [];
        
        if (didakFinderResultTarget.reuse_popup_size === '1') {
            const popupSize = getPopupSize();
            const popupPosition = getPopupPosition(
                parseInt(popupSize.width), 
                parseInt(popupSize.height)
            );
            
            features.push(`width=${popupSize.width}`);
            features.push(`height=${popupSize.height}`);
            features.push(popupPosition);
        } else {
            let width = didakFinderResultTarget.custom_width;
            let height = didakFinderResultTarget.custom_height;
            
            if (didakFinderResultTarget.custom_width_unit === '%') {
                width = Math.round((window.screen.width * parseInt(width)) / 100);
            }
            if (didakFinderResultTarget.custom_height_unit === '%') {
                height = Math.round((window.screen.height * parseInt(height)) / 100);
            }
            
            features.push(`width=${width}`);
            features.push(`height=${height}`);
            
            const position = getPopupPosition(width, height);
            features.push(position);
        }
        
        features.push(
            'menubar=no',
            'toolbar=no',
            'location=yes',
            'status=no',
            'resizable=yes',
            'scrollbars=yes'
        );
        
        try {
            if (didakFinderResultTarget.window_type !== '_blank' && 
                openWindows[windowName] && 
                !openWindows[windowName].closed) {
                try {
                    openWindows[windowName].close();
                } catch (e) {
                    console.warn('Kunne ikke lukke eksisterende vindue:', e);
                }
            }
            
            const newWindow = window.open(url, windowName, features.join(','));
            
            if (newWindow === null) {
                handleNewTabOpen(url);
                return;
            }
            
            openWindows[windowName] = newWindow;
            newWindow.focus();
            
        } catch (e) {
            console.warn('Fejl ved åbning af nyt vindue:', e);
            handleNewTabOpen(url);
        }
    }

    function handleNewTabOpen(url) {
        const a = document.createElement('a');
        a.href = url;
        a.target = '_blank';
        a.rel = 'noopener';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }

    function handleResultClick(event, url) {
        event.preventDefault();
        event.stopPropagation();

        if (!url) {
            console.error('Ingen URL angivet for resultat');
            return;
        }

        try {
            if (openWindows.processing) {
                return;
            }
            openWindows.processing = true;

            setTimeout(() => {
                switch (didakFinderResultTarget.type) {
                    case 'popup':
                        handlePopupOpen(url);
                        break;
                    case 'window':
                        handleNewWindowOpen(url);
                        break;
                    case 'tab':
                        handleNewTabOpen(url);
                        break;
                    case 'same':
                        window.location.href = url;
                        break;
                    default:
                        console.warn('Ukendt måltype:', didakFinderResultTarget.type);
                        window.location.href = url;
                }
                openWindows.processing = false;
            }, 100);
        } catch (e) {
            console.error('Fejl ved håndtering af resultat-klik:', e);
            window.location.href = url;
            openWindows.processing = false;
        }
    }

    function handleWindowBlur() {
        if (openWindows.popup && !openWindows.popup.closed) {
            const currentTime = new Date().getTime();
            if (currentTime - popupOpenTime > 2000) {
                closePopup();
                hidePopupButtonsAfterDelay();
            } else {
                openWindows.popup.focus();
            }
        }
    }

    function closePopup() {
        if (openWindows.popup && !openWindows.popup.closed) {
            openWindows.popup.close();
        }
        openWindows.popup = null;
        $(window).off('blur.popupHandler');
    }

    function hidePopupButtonsAfterDelay() {
        clearTimeout(popupCloseTimer);
        popupCloseTimer = setTimeout(function() {
            $popupButtons.hide();
        }, 45000);
    }

    // Form submission handler
    $form.on('submit', function(e) {
        e.preventDefault();
        const searchQuery = $input.val();
        const dropdownSelection = $('#didak-finder-dropdown').val();

        if (searchQuery.trim()) {
            addToSearchHistory(searchQuery);
        }

        $submit.addClass('loading');
        $loading.show();

        $.ajax({
            url: didak_finder_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'didak_finder_search',
                nonce: didak_finder_ajax.nonce,
                search_query: searchQuery,
                dropdown_selection: dropdownSelection
            },
            success: function(response) {
                if (response.success) {
                    currentResults = response.data;
                    displayResults(currentResults);
                    fetchImages(currentResults);
                } else {
                    $results.html('<p>No results found.</p>');
                }
                toggleClearButton();
            },
            error: function() {
                $results.html('<p>An error occurred. Please try again.</p>');
                toggleClearButton();
            },
            complete: function() {
                $submit.removeClass('loading');
                $loading.hide();
            }
        });
    });

    // Event Handlers
    $input.on('input', function() {
        const value = $(this).val().trim();
        $('#search-history-list').toggle(value.length >= 2);
    });

    $input.on('change', function() {
        if ($(this).val().trim()) {
            $form.submit();
        }
    });

    $clearButton.on('click', function() {
        clearResults();
        clearSearchHistory();
        $input.val('');
    });

    // Remove existing click handler and add new one
    $(document).off('click', '.didak-finder-result');
    $(document).on('click', '.didak-finder-result', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        const $link = $(this).find('.didak-finder-result-link');
        const url = $link.attr('href');
        
        if (!url || $(this).data('processing')) {
            return;
        }
        
        $(this).data('processing', true);
        
        setTimeout(() => {
            handleResultClick(e, url);
            $(this).data('processing', false);
        }, 100);
    });

    function displayResults(results) {
        $results.empty();

        results.forEach(function(result) {
            const $resultDiv = $('<div class="didak-finder-result"></div>');
            let resultHtml = '<a href="' + result.url + '" class="didak-finder-result-link" target="_blank">';
            
            resultHtml += '<div class="didak-finder-result-image-container">';
            if (result.show_image || result.predefined_image) {
                const placeholderSrc = result.placeholder_image || BASE64_PLACEHOLDER;
                resultHtml += '<img src="' + placeholderSrc + '" class="didak-finder-result-image" ' +
                    'data-url="' + result.url + '" data-image-number="' + result.image_number + '" ' +
                    'alt="Result image" onerror="this.onerror=null;this.src=\'' + BASE64_PLACEHOLDER + '\';">';
            }
            resultHtml += '</div>';
            
            resultHtml += '<div class="didak-finder-result-info">' + result.info_text + '</div>' +
                '<div class="didak-finder-result-search">' + didakFinderLabels.search + ' ' + result.search_query + '</div>';
            
            if (result.dropdown) {
                resultHtml += '<div class="didak-finder-result-category">' + didakFinderLabels.category + ' ' + result.dropdown + '</div>';
            }
            
            resultHtml += '<div class="didak-finder-result-source">' + didakFinderLabels.source + ' ' + result.source + '</div>' +
                '</a>';
            
            $resultDiv.html(resultHtml);
            $results.append($resultDiv);
        });

        handleMobileImageVisibility();
        handleMobileResultButtonWidth();
        setupAccessibility();
    }

    function showPopupButtons(results) {
        $popupButtons.empty();

        results.forEach(function(result) {
            const $button = $('<button class="didak-finder-popup-button"></button>');
            
            if (result.show_image || result.predefined_image) {
                const imageSrc = result.predefined_image || result.placeholder_image || BASE64_PLACEHOLDER;
                $button.append('<img src="' + imageSrc + '" alt="Result image" style="height: 40px; width: auto;">');
            }
            
            $button.append('<span class="popup-button-info">' + result.info_text + '</span>')
                 .append('<span class="popup-button-source">' + result.source + '</span>');

            $button.on('click', function() {
                handleResultClick({ preventDefault: () => {}, stopPropagation: () => {} }, result.url);
            });

            $popupButtons.append($button);
        });

        const baseStyles = {
            'background-color': didakFinderPopupButtons.backgroundColor,
            'color': didakFinderPopupButtons.textColor,
            'height': didakFinderPopupButtons.height,
            'top': didakFinderPopupButtons.position === 'top' ? '0' : 'auto',
            'bottom': didakFinderPopupButtons.position === 'bottom' ? '0' : 'auto',
            'z-index': parseInt(didakFinderPopupZIndex) + 1
        };

        const buttonStyles = {
            'background-color': didakFinderPopupButtons.buttonBackgroundColor,
            'color': didakFinderPopupButtons.buttonTextColor,
            'font-size': didakFinderPopupButtons.buttonTextSize,
            'padding': didakFinderPopupButtons.buttonPadding,
            'border-color': didakFinderPopupButtons.buttonBorderColor,
            'border-width': didakFinderPopupButtons.buttonBorderWidth,
            'border-style': 'solid',
            'border-radius': didakFinderPopupButtons.buttonBorderRadius
        };

        $popupButtons.css(baseStyles).show()
            .find('.didak-finder-popup-button').css(buttonStyles);
    }

    function fetchImages(results) {
        results.forEach(function(result, index) {
            if (result.show_image || result.predefined_image) {
                setTimeout(function() {
                    const $img = $('.didak-finder-result').eq(index).find('.didak-finder-result-image');
                    
                    if (result.show_image) {
                        $.ajax({
                            url: didak_finder_ajax.ajax_url,
                            type: 'POST',
                            data: {
                                action: 'didak_finder_get_image',
                                nonce: didak_finder_ajax.nonce,
                                url: result.url,
                                image_number: result.image_number
                            },
                            success: function(response) {
                                if (response.success && response.data.image_url) {
                                    $img.attr('src', response.data.image_url);
                                } else if (result.predefined_image) {
                                    $img.attr('src', result.predefined_image);
                                }
                            },
                            error: function() {
                                if (result.predefined_image) {
                                    $img.attr('src', result.predefined_image);
                                }
                            }
                        });
                    } else if (result.predefined_image) {
                        $img.attr('src', result.predefined_image);
                    }
                }, result.image_load_delay);
            }
        });
    }

    function getPopupSize() {
        let width = didakFinderPopupSize.width + didakFinderPopupSize.width_unit;
        let height = didakFinderPopupSize.height + didakFinderPopupSize.height_unit;
        
        if (didakFinderPopupSize.width_unit === '%') {
            width = Math.round((window.screen.width * parseInt(didakFinderPopupSize.width)) / 100) + 'px';
        }
        if (didakFinderPopupSize.height_unit === '%') {
            height = Math.round((window.screen.height * parseInt(didakFinderPopupSize.height)) / 100) + 'px';
        }
        
        return { width, height };
    }

    function getPopupPosition(popupWidth, popupHeight) {
        let left, top;
        const screenWidth = window.screen.width;
        const screenHeight = window.screen.height;

        switch (didakFinderPopupPosition) {
            case 'top-left':
                left = 0; top = 0;
                break;
            case 'top-center':
                left = (screenWidth - popupWidth) / 2; top = 0;
                break;
            case 'top-right':
                left = screenWidth - popupWidth; top = 0;
                break;
            case 'center-left':
                left = 0; top = (screenHeight - popupHeight) / 2;
                break;
            case 'center-right':
                left = screenWidth - popupWidth; top = (screenHeight - popupHeight) / 2;
                break;
            case 'bottom-left':
                left = 0; top = screenHeight - popupHeight;
                break;
            case 'bottom-center':
                left = (screenWidth - popupWidth) / 2; top = screenHeight - popupHeight;
                break;
            case 'bottom-right':
                left = screenWidth - popupWidth; top = screenHeight - popupHeight;
                break;
            default: // center
                left = (screenWidth - popupWidth) / 2; top = (screenHeight - popupHeight) / 2;
        }
        return `left=${Math.round(left)},top=${Math.round(top)}`;
    }

    function handleMobileImageVisibility() {
        $('.didak-finder-result-image-container').toggle(
            !(didak_finder_ajax.hide_images_mobile === '1' && window.innerWidth <= 767)
        );
    }

    function handleMobileResultButtonWidth() {
        if (window.innerWidth <= 767) {
            const mobileWidth = didak_finder_ajax.result_button_mobile_width.value + 
                              didak_finder_ajax.result_button_mobile_width.unit;
            $('.didak-finder-result').css('width', mobileWidth);
        } else {
            $('.didak-finder-result').css('width', '');
        }
    }

    function clearResults() {
        $results.empty();
        currentResults = [];
        toggleClearButton();
        $popupButtons.hide();
    }

    function toggleClearButton() {
        $clearButton.toggle($results.children().length > 0);
    }

    function setupAccessibility() {
        $('.didak-finder-result')
            .attr({
                'tabindex': '0',
                'role': 'button',
                'aria-label': function() {
                    const $result = $(this);
                    return [
                        $result.find('.didak-finder-result-info').text(),
                        $result.find('.didak-finder-result-search').text(),
                        $result.find('.didak-finder-result-category').text(),
                        $result.find('.didak-finder-result-source').text()
                    ].filter(Boolean).join(', ');
                }
            });
    }

    // Initialize
    function initialize() {
        initializeSearchHistory();
        $clearContainer.show();
        toggleClearButton();

        $(window).on({
            'resize': function() {
                handleMobileImageVisibility();
                handleMobileResultButtonWidth();
            },
            'focus': function() {
                if (openWindows.popup && openWindows.popup.closed) {
                    hidePopupButtonsAfterDelay();
                    openWindows.popup = null;
                    openWindows.processing = false;
                }
            },
            'unload': function() {
                Object.values(openWindows).forEach(window => {
                    if (window && !window.closed && typeof window.close === 'function') {
                        window.close();
                    }
                });
            },
            'scroll': function() {
                if ($popupButtons.is(':visible') && didakFinderPopupButtons.position === 'top') {
                    $popupButtons.css('top', $(window).scrollTop() + 'px');
                }
            }
        });

        // Keyboard accessibility
        $(document).on('keypress', '.didak-finder-result', function(e) {
            if (e.which === 13 || e.which === 32) {
                e.preventDefault();
                const $link = $(this).find('.didak-finder-result-link');
                const url = $link.attr('href');
                if (url) {
                    handleResultClick(e, url);
                }
            }
        });

        // Handle Enter key in input field
        $input.on('keypress', function(e) {
            if (e.which === 13) {
                e.preventDefault();
                $form.submit();
            }
        });
    }

    // Start initialization
    initialize();
});