(function($) {
    function filterCards() {
        const q = $('#lm-search-input').val().toLowerCase();
        $('#lm-articles-grid .lm-article-card').each(function() {
            const title = $(this).find('.lm-article-card__title').text().toLowerCase();
            const excerpt = $(this).find('.lm-article-card__excerpt').text().toLowerCase();
            const match = title.includes(q) || excerpt.includes(q);
            $(this).toggle(match);
        });
    }

    function openModal(post) {
        const modal = $('#lm-post-modal');
        modal.find('.lm-modal__title').text(post.title || '');
        let meta = '';
        if (post.publishedAt) {
            meta += '<p><strong>' + new Date(post.publishedAt).toLocaleDateString() + '</strong></p>';
        }
        if (post.author) {
            meta += '<p>' + post.author + '</p>';
        }
        let tags = '';
        if (post.tags && post.tags.length) {
            tags = '<p><em>' + post.tags.slice(0, 5).join(', ') + '</em></p>';
        }
        const body = meta + (post.excerpt ? '<div class="lm-modal__excerpt">' + post.excerpt + '</div>' : '') + (post.html || '');
        modal.find('.lm-modal__body').html(body);
        modal.show();
    }

    function closeModal() {
        $('#lm-post-modal').hide();
    }

    function fetchPost(slug, lang) {
        if (!slug) return;
        const modal = $('#lm-post-modal');
        modal.find('.lm-modal__body').html('<p>' + launchmindDashboard.strings.loading + '</p>');
        modal.show();
        $.ajax({
            url: launchmindDashboard.ajaxUrl,
            method: 'GET',
            data: {
                action: 'launchmind_get_post',
                nonce: launchmindDashboard.nonce,
                slug: slug,
                lang: lang
            }
        }).done(function(resp) {
            if (resp && resp.success && resp.data && resp.data.post) {
                openModal(resp.data.post);
            } else {
                modal.find('.lm-modal__body').html('<p>' + (resp.data && resp.data.message ? resp.data.message : launchmindDashboard.strings.error) + '</p>');
            }
        }).fail(function() {
            modal.find('.lm-modal__body').html('<p>' + launchmindDashboard.strings.error + '</p>');
        });
    }

    function bindArticles() {
        $('#lm-search-input').on('input', filterCards);
        $('#lm-articles-grid').on('click', '.lm-article-card__view', function(e) {
            e.preventDefault();
            const card = $(this).closest('.lm-article-card');
            fetchPost(card.data('slug'), card.data('lang'));
        });
    }

    function bindModal() {
        $(document).on('click', '.lm-modal__close, .lm-modal__close-btn, .lm-modal__overlay', function() {
            closeModal();
        });
        $(document).on('keyup', function(e) {
            if (e.key === 'Escape') closeModal();
        });
    }

    function bindActions() {
        $('#lm-refresh-btn').on('click', function() { location.reload(); });

        $('#lm-test-connection').on('click', function() {
            const result = $('#lm-test-result');
            result.show().text(launchmindDashboard.strings.loading);
            $.post(launchmindDashboard.ajaxUrl, {
                action: 'launchmind_test_connection',
                nonce: launchmindDashboard.nonce
            }).done(function(resp) {
                if (resp.success) {
                    result.text(resp.data && resp.data.message ? resp.data.message : 'OK');
                } else {
                    result.text(resp.data && resp.data.message ? resp.data.message : launchmindDashboard.strings.error);
                }
            }).fail(function() {
                result.text(launchmindDashboard.strings.error);
            });
        });

        $('#lm-clear-cache').on('click', function() {
            const result = $('#lm-test-result');
            result.show().text(launchmindDashboard.strings.loading);
            $.post(launchmindDashboard.ajaxUrl, {
                action: 'launchmind_clear_cache',
                nonce: launchmindDashboard.nonce
            }).done(function(resp) {
                if (resp.success) {
                    result.text(resp.data && resp.data.message ? resp.data.message : 'Cache cleared');
                } else {
                    result.text(resp.data && resp.data.message ? resp.data.message : launchmindDashboard.strings.error);
                }
            }).fail(function() {
                result.text(launchmindDashboard.strings.error);
            });
        });
    }

    $(function() {
        bindArticles();
        bindModal();
        bindActions();
    });
})(jQuery);
