jQuery(document).ready(function($) {
    const codeSearchApp = {
        init() {
            this.bindEvents();
        },

        bindEvents() {
            $('#search-form').on('submit', this.handleSearch.bind(this));
            $('#search-results').on('click', '.search-result-item', this.openSearchResult.bind(this));
        },

        handleSearch(e) {
            e.preventDefault();
            
            const query = $('#search-query').val().trim();
            const path = $('#search-path').val();
            const caseSensitive = $('#case-sensitive').is(':checked');

            if (!query) {
                alert('Please enter a search term');
                return;
            }

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'code_editor_search',
                    query: query,
                    path: path,
                    case_sensitive: caseSensitive,
                    security: codeEditorVars.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.displayResults(response.data);
                    } else {
                        console.error(response.data);
                    }
                }
            });
        },

        displayResults(results) {
            const $resultsContainer = $('#search-results').empty();
            
            if (results.length === 0) {
                $resultsContainer.append('<p>No results found</p>');
                return;
            }

            results.forEach(result => {
                const $resultItem = $(`
                    <div class="search-result-item" data-path="${result.path}">
                        <h4>${result.path}</h4>
                        <div class="matches-container"></div>
                    </div>
                `);

                result.matches.forEach(match => {
                    $resultItem.find('.matches-container').append(`
                        <div class="match-item" data-line="${match.line}">
                            <span class="line-number">${match.line}:</span>
                            <span class="match-text">${match.text}</span>
                        </div>
                    `);
                });

                $resultsContainer.append($resultItem);
            });
        },

        openSearchResult(e) {
            const $target = $(e.target).closest('.search-result-item, .match-item');
            const path = $target.closest('.search-result-item').data('path');
            const line = $target.hasClass('match-item') ? $target.data('line') : 1;

            $(document).trigger('codeEditor:openFile', {
                path: path,
                line: line
            });
        }
    };

    codeSearchApp.init();
});