if (typeof jQuery === 'undefined') {
    console.error('jQuery is not loaded. LinkCentral may not work correctly.');
}

(function($) {
    'use strict';

    // Import WordPress i18n function
    const { __ } = wp.i18n;

    $(document).ready(function() {
        // Form validation for adding/editing links
        $('#post').on('submit', function(e) {
            var destinationUrl = $('#linkcentral_destination_url').val();
            var customSlug = $('#post_name').val();
            var title = $('#title').val();

            if (!title) {
                e.preventDefault();
                alert(__('Please fill in all required fields (title, slug, and destination URL).', 'linkcentral'));
                $('#title').focus();
                return false;
            }

            if (!destinationUrl || !customSlug) {
                e.preventDefault();
                alert(__('Please fill in all required fields (title, slug, and destination URL).', 'linkcentral'));
                return false;
            }

            if (!isValidUrl(destinationUrl)) {
                e.preventDefault();
                alert(__('Please enter a valid destination URL. Supports HTTP/HTTPS URLs, custom schemes (tel:, mailto:, myapp://), and relative paths (/path).', 'linkcentral'));
                return false;
            }
        });

        // Handle Enter key press to publish *new* links instead of saving them as draft
        if (typeof linkcentral_admin.is_new_link !== 'undefined' && linkcentral_admin.is_new_link) {
            $('#post').on('keydown', function(e) {
                if (e.key === 'Enter' && !$(e.target).is('textarea')) {
                    e.preventDefault();
                    $('#publish').click();
                }
            });
        }

        // Custom URL slug generator with AJAX check
        $('#title').on('blur', function() {
            var title = $(this).val();
            if (title && !$('#post_name').val()) {
                var slug = title.toLowerCase().replace(/[^a-z0-9\/]+/g, '-').replace(/^-+|-+$/g, '');
                checkSlug(slug);
            }
        });

        // Check slug availability when custom slug field changes or loses focus
        $('#post_name').on('blur change', function() {
            var slug = $(this).val();
            if (slug) {
                checkSlug(slug);
            }
        });

        // Generate random slug functionality
        $(document).on('click', '.linkcentral-generate-slug-button', function() {
            generateRandomSlug();
        });

        function checkSlug(slug) {
            var postId = $('#post_ID').val() || 0;
            $.ajax({
                url: linkcentral_admin.ajax_url,
                type: 'POST',
                data: {
                    action: 'linkcentral_check_slug',
                    nonce: linkcentral_admin.nonce,
                    slug: slug,
                    post_id: postId
                },
                success: function(response) {
                    if (response.success) {
                        $('#post_name').val(response.data.unique_slug);
                    } else {
                        alert(response.data.message);
                    }
                },
                error: function() {
                    alert('Error checking slug.');
                }
            });
        }

        function generateRandomSlug() {
            var $button = $('.linkcentral-generate-slug-button');
            var $slugField = $('#post_name');
            var postId = $('#post_ID').val() || 0;

            // Generate random 5-character alphanumeric string
            var randomSlug = generateRandomString(5);

            // Set loading state
            $button.addClass('loading').prop('disabled', true);

            // Use the existing checkSlug AJAX endpoint to ensure uniqueness
            $.ajax({
                url: linkcentral_admin.ajax_url,
                type: 'POST',
                data: {
                    action: 'linkcentral_check_slug',
                    nonce: linkcentral_admin.nonce,
                    slug: randomSlug,
                    post_id: postId
                },
                success: function(response) {
                    if (response.success) {
                        $slugField.val(response.data.unique_slug);
                    } else {
                        alert(response.data.message);
                    }
                },
                error: function() {
                    alert(__('Error generating random slug.', 'linkcentral'));
                },
                complete: function() {
                    // Remove loading state
                    $button.removeClass('loading').prop('disabled', false);
                }
            });
        }

        function generateRandomString(length) {
            var chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
            var result = '';
            for (var i = 0; i < length; i++) {
                result += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            return result;
        }

        // Copy short URL to clipboard
        $('.linkcentral-copy-url').on('click', function(e) {
            e.preventDefault();
            var shortUrl = $(this).data('url');
            copyToClipboard(shortUrl);
            updateButtonText($(this), __('Copied!', 'linkcentral'), __('Copy', 'linkcentral'));
        });

        // Remove 'Pending Review' option
        if (typeof linkcentral_post_type !== 'undefined' && linkcentral_post_type == 'linkcentral_link') {
            // Remove 'Pending Review' from status dropdown
            $('#post-status-select option[value="pending"]').remove();
        }

        // Copy URL functionality
        $('#linkcentral-copy-url').on('click', function() {
            var $hiddenInput = $('#linkcentral_disable_slug_prefix');
            var isPrefixDisabled = $hiddenInput.val() === '1';
            var slug = $('#post_name').val();
            var fullUrl;

            if (isPrefixDisabled) {
                // Prefix is disabled, use home URL + slug directly
                var $prefixElement = $('#linkcentral-url-prefix');
                var homeUrl = $prefixElement.data('home-url'); // Use data attribute for clean URL
                fullUrl = homeUrl + slug;
            } else {
                // Prefix is enabled, use the full prefix URL
                var baseUrl = $('#linkcentral-url-prefix').text().trim();
                fullUrl = baseUrl + slug;
            }

            copyToClipboard(fullUrl);
            updateButtonText($(this), __('Copied!', 'linkcentral'));
        });

        // Copy shortcode functionality (if it exists in HTML)
        $('.linkcentral-copy-shortcode').on('click', function(e) {
            e.preventDefault();
            var shortcode = $(this).data('shortcode');
            copyToClipboard(shortcode);
            updateButtonText($(this), __('Copied!', 'linkcentral'), __('Copy Shortcode', 'linkcentral'));
        });

        // Toggle CSS classes visibility
        if(linkcentral_admin.can_use_premium_code__premium_only){
            $('#linkcentral_css_classes_option').on('change', function() {
                if ($(this).val() === 'default') {
                    $('#linkcentral_custom_css_classes').hide();
                } else {
                    $('#linkcentral_custom_css_classes').show();
                }
            });
        }

        // Administrative note functionality
        $('.linkcentral-edit-note').on('click', function(e) {
            e.preventDefault();
            $('.linkcentral-note-display').hide();
            $('.linkcentral-note-edit').show();
        });

        $('.linkcentral-cancel-edit').on('click', function() {
            $('.linkcentral-note-edit').hide();
            $('.linkcentral-note-display').show();
        });

        $('.linkcentral-save-note').on('click', function() {
            var newNote = $('#linkcentral_note').val();
            $('.linkcentral-note-text').text(newNote);
            $('.linkcentral-note-edit').hide();
            $('.linkcentral-note-display').show();
        });

        // Slug prefix toggle functionality - simple click on slug part only
        $('.linkcentral-slug-toggle').on('click', function(e) {
            e.preventDefault();
            var $slugToggle = $(this);
            var $hiddenInput = $('#linkcentral_disable_slug_prefix');
            
            var isDisabled = $hiddenInput.val() === '1';
            var slugText = $slugToggle.data('slug');
            
            if (isDisabled) {
                // Enable prefix - show normal slug
                $hiddenInput.val('0');
                $slugToggle.removeClass('linkcentral-slug-disabled');
            } else {
                // Disable prefix - gray out but keep visible
                $hiddenInput.val('1');
                $slugToggle.addClass('linkcentral-slug-disabled');
            }
        });

        

        

        // Handle truncated URL clicks - show tooltip
        $(document).on('click', '.linkcentral-truncated-url', function(e) {
            e.preventDefault();
            e.stopPropagation();

            // Hide any existing tooltips
            $('.linkcentral-url-tooltip').remove();

            // Create tooltip with full URL
            var fullUrl = $(this).data('full-url');
            var $tooltip = $('<div class="linkcentral-url-tooltip">' + escapeHtml(fullUrl) + '</div>');

            // Position above element
            var offset = $(this).offset();
            var height = $(this).outerHeight();
            $tooltip.css({
                left: offset.left,
                top: offset.top + height + 5
            });

            // Add to page and show
            $('body').append($tooltip);
            setTimeout(function() { $tooltip.addClass('show'); }, 10);

            // Hide on click elsewhere (but not inside tooltip)
            setTimeout(function() {
                var hideTooltip = function(e) {
                    // Don't close if clicking inside the tooltip
                    if (!$(e.target).closest('.linkcentral-url-tooltip').length) {
                        $tooltip.remove();
                        $(document).off('click', hideTooltip);
                    }
                };
                $(document).on('click', hideTooltip);
            }, 100);
        });

    });


    // Helper function to validate URLs - more forgiving to support various link types
    function isValidUrl(url) {
        url = url.trim();
        
        // Empty URLs are invalid
        if (!url) {
            return false;
        }
        
        // URLs that are too long are probably invalid
        if (url.length > 2048) {
            return false;
        }
        
        // Check for standard HTTP/HTTPS URLs first
        try {
            new URL(url);
            return true;
        } catch (e) {
            // Continue to other checks if URL constructor fails
        }
        
        // Check for custom schemes (like myapp://, tel:, mailto:, etc.)
        if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)) {
            return true;
        }
        
        // Check for relative paths starting with /
        if (/^\/[^\s]*$/.test(url)) {
            return true;
        }
        
        // If none of the above patterns match, it's probably invalid
        return false;
    }

    // Function to handle per-page changes on links overview page
    window.linkcentralChangePerPage = function(perPage) {
        const url = new URL(window.location);
        url.searchParams.set('per_page', perPage);
        url.searchParams.set('paged', '1');
        window.location.href = url.toString();
    };

    // Helper function to copy text to clipboard
    function copyToClipboard(text) {
        var $temp = $("<input>");
        $("body").append($temp);
        $temp.val(text).select();
        document.execCommand("copy");
        $temp.remove();
    }

    // Helper function to update button text temporarily
    function updateButtonText($button, tempText, originalText) {
        var original = originalText || $button.text();
        $button.text(tempText);
        setTimeout(function() {
            $button.text(original);
        }, 2000);
    }

    // Helper function to escape HTML for security
    function escapeHtml(text) {
        var map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }

})(jQuery);