

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() {
        initFormValidation();
        initEnterToPublishBehavior();
        initSlugGeneration();
        initCopyButtons();
        initCategorySlugAutoPrefixing();
        initAdvancedFieldsToggles();
        initAdminNotes();
        initSlugPrefixToggle();
        
        initTruncatedUrlTooltip();
    });

    function initFormValidation() {
        $('#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;
            }
        });
    }

    function initEnterToPublishBehavior() {
        if (typeof linkcentral_admin.is_new_link === 'undefined' || !linkcentral_admin.is_new_link) {
            return;
        }

        $('#post').on('keydown', function(e) {
            if (e.key === 'Enter' && !$(e.target).is('textarea')) {
                e.preventDefault();
                $('#publish').click();
            }
        });
    }

    function initSlugGeneration() {
        $('#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);
            }
        });

        $('#post_name').on('blur change', function() {
            var slug = $(this).val();
            if (slug) {
                checkSlug(slug);
            }
        });

        $(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;
        }

    }

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

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

    }

    function initCategorySlugAutoPrefixing() {
        if (typeof linkcentral_admin === 'undefined' || !linkcentral_admin.auto_prefix_category) {
            return;
        }

        var previousCategoryCount = $('#linkcentral_categorychecklist input[type="checkbox"]:checked').length +
            ($('#linkcentral_category').val() && $('#linkcentral_category').val() !== '-1' ? 1 : 0);

        $(document).on('change', '#linkcentral_categorychecklist input[type="checkbox"], #linkcentral_category', function() {
            var newCount = $('#linkcentral_categorychecklist input[type="checkbox"]:checked').length +
                ($('#linkcentral_category').val() && $('#linkcentral_category').val() !== '-1' ? 1 : 0);

            if (previousCategoryCount === 0 && newCount === 1) {
                var $slugField = $('#post_name');
                var currentSlug = $slugField.val();

                var categorySlug = $('#linkcentral_categorychecklist input[type="checkbox"]:checked:first').parent('label').text().trim() ||
                    $('#linkcentral_category option:selected').text().trim();

                categorySlug = categorySlug.toLowerCase().replace(/[^a-z0-9\-]+/g, '-').replace(/^-+|-+$/g, '');

                if (categorySlug && (!currentSlug || !currentSlug.startsWith(categorySlug + '/'))) {
                    var newSlug = categorySlug + '/' + (currentSlug || '');
                    $slugField.val(newSlug);

                    var message = '<strong>' + categorySlug + '</strong> ' + __('automatically prepended to slug.', 'linkcentral');

                    var $categoryDiv = $('#linkcentral_categorydiv');
                    var $notification = $categoryDiv.find('.linkcentral-slug-notification');

                    if ($notification.length === 0) {
                        $notification = $('<div class="linkcentral-slug-notification notice notice-info is-dismissible"><p>' + message + '</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button></div>');
                        $categoryDiv.find('.inside').append($notification);

                        $notification.find('.notice-dismiss').on('click', function() {
                            $notification.fadeOut(function() {
                                $notification.remove();
                            });
                        });
                    } else {
                        $notification.find('p').html(message);
                        $notification.show();
                    }

                    checkSlug(newSlug);
                }
            }
            previousCategoryCount = newCount;
        });
    }

    function initAdvancedFieldsToggles() {
        // 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();
                }
            });
        }

        // Toggle Other Attributes visibility
        $('#linkcentral_other_attributes_option').on('change', function() {
            if ($(this).val() === 'default') {
                $('#linkcentral_custom_other_attributes').hide();
            } else {
                $('#linkcentral_custom_other_attributes').show();
            }
        });
    }

    function initAdminNotes() {
        // 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();
        });
    }

    function initSlugPrefixToggle() {
        // 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');
            }
        });
    }

    

    function initTruncatedUrlTooltip() {
        // 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 - supports 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;
        }

        // For http/https schemes, require :// and a non-empty host to avoid accepting values like "https:/" or "https:///"
        // This runs regardless of whether the browser's URL parser considers it valid.
        if (/^https?:/i.test(url)) {
            if (!/^https?:\/\/[^/\s]+/i.test(url)) {
                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);
    }

    function showCopyFeedback($button, tempText, originalText) {
        var $icon = $button.find('.dashicons');
        var originalLabel = originalText || $button.attr('aria-label');

        $button.addClass('linkcentral-copy-url--copied');
        $icon.removeClass('dashicons-admin-page').addClass('dashicons-yes');
        $button.attr('aria-label', tempText).attr('title', tempText);
        setTimeout(function() {
            $button.removeClass('linkcentral-copy-url--copied');
            $icon.removeClass('dashicons-yes').addClass('dashicons-admin-page');
            $button.attr('aria-label', originalLabel).attr('title', originalLabel);
        }, 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);