jQuery(document).ready(function($) {
    var defaultText = $('.mkm-dspb-meta-container').data('default-text');
    
    function htmlToSocialText(html) {
        if (!html) return '';
        var text = String(html);
        text = text.replace(/\[[^\]]+\]/g, '');
        text = text.replace(/<!--[\s\S]*?-->/g, '');
        text = text.replace(/<li[^>]*>\s*/gi, '\n• ');
        text = text.replace(/\s*<\/li>/gi, '');
        text = text.replace(/<br\s*\/?>/gi, '\n');
        text = text.replace(/<\/(p|div|h[1-6]|table|tr|blockquote|section|article)>\s*/gi, '\n\n');
        text = text.replace(/<(p|div|h[1-6]|table|tr|blockquote|section|article)[^>]*>/gi, '');
        text = text.replace(/<\/(ul|ol)>\s*/gi, '\n');
        text = text.replace(/<(ul|ol)[^>]*>/gi, '');
        var tmp = document.createElement('DIV');
        tmp.innerHTML = text;
        text = tmp.textContent || tmp.innerText || '';
        var lines = text.split('\n');
        var cleanLines = [];
        for (var i = 0; i < lines.length; i++) {
            cleanLines.push(lines[i].trim());
        }
        return cleanLines.join('\n').replace(/\n{3,}/g, '\n\n').trim();
    }

    function truncateForTwitter(text, postUrl) {
        if (!text || text.length <= 280) return text;
        var url = postUrl || '';
        var textBefore = text;
        var availableLen = 280 - 3;

        if (url && text.indexOf(url) !== -1) {
            var urlPos = text.lastIndexOf(url);
            textBefore = text.substring(0, urlPos).trim();
            availableLen = 280 - url.length - 5;
        }

        if (availableLen > 20) {
            var sub = textBefore.substring(0, availableLen);
            var lastDot = sub.lastIndexOf('.');
            var lastExcl = sub.lastIndexOf('!');
            var lastQ = sub.lastIndexOf('?');
            var lastPunct = Math.max(lastDot, lastExcl, lastQ);

            if (lastPunct > 40) {
                var cleanText = sub.substring(0, lastPunct + 1);
                return url ? (cleanText + '\n\n' + url) : cleanText;
            }

            var lastSpace = sub.lastIndexOf(' ');
            if (lastSpace > 40) {
                var cleanText = sub.substring(0, lastSpace) + '...';
                return url ? (cleanText + '\n\n' + url) : cleanText;
            }
            var cleanText = sub + '...';
            return url ? (cleanText + '\n\n' + url) : cleanText;
        }
        return text.substring(0, 277) + '...';
    }

    function replaceTags(text, service) {
        if (!text) return '';
        var postUrl = mkmDspbPublisher.postUrl || '';
        var postShortlink = mkmDspbPublisher.postShortlink || postUrl;
        var postTitle = mkmDspbPublisher.postTitle || '';
        var postExcerpt = mkmDspbPublisher.postExcerpt || '';
        var provider = mkmDspbPublisher.shortenerProvider || 'none';

        var isTwitter = (service === 'twitter' || service === 'tw');
        var linkUrl = (isTwitter && provider !== 'none') ? postShortlink : postUrl;

        // Clean up common user typos like #post_excerpt, #post_title, #post_link
        if (text.indexOf('#post_excerpt') !== -1) {
            if (text.indexOf('{excerpt}') !== -1 || text.indexOf('{post_excerpt}') !== -1) {
                text = text.replace(/#post_excerpt/g, '');
            } else {
                text = text.replace(/#post_excerpt/g, '{excerpt}');
            }
        }
        if (text.indexOf('#post_title') !== -1) {
            if (text.indexOf('{title}') !== -1 || text.indexOf('{post_title}') !== -1) {
                text = text.replace(/#post_title/g, '');
            } else {
                text = text.replace(/#post_title/g, '{title}');
            }
        }
        if (text.indexOf('#post_link') !== -1) {
            if (text.indexOf('{link}') !== -1 || text.indexOf('{post_link}') !== -1) {
                text = text.replace(/#post_link/g, '');
            } else {
                text = text.replace(/#post_link/g, '{link}');
            }
        }

        text = text.replace(/\{link\}/g, linkUrl);
        text = text.replace(/\{post_link\}/g, linkUrl);
        text = text.replace(/\{shortlink\}/g, postShortlink);
        text = text.replace(/\{title\}/g, postTitle);
        text = text.replace(/\{post_title\}/g, postTitle);
        text = text.replace(/\{excerpt\}/g, postExcerpt);
        text = text.replace(/\{post_excerpt\}/g, postExcerpt);
        text = text.replace(/\{yoast_desc\}/g, postExcerpt);
        text = text.replace(/\{aioseo_desc\}/g, postExcerpt);

        text = text.replace(/#post_excerpt/g, '');
        text = text.replace(/#post_title/g, '');
        text = text.replace(/#post_link/g, '');
        text = text.replace(/\{post_excerpt\}/g, '');
        text = text.replace(/\{post_title\}/g, '');
        text = text.replace(/\{post_link\}/g, '');
        return htmlToSocialText(text);
    }

    // Function to update preview cards dynamically
    function updatePreviews() {
        var postUrl = mkmDspbPublisher.postUrl;
        
        // 1. Facebook
        if ($('#mkm_dspb_fb_text').length) {
            var fbText = $('#mkm_dspb_fb_text').val() || defaultText;
            fbText = replaceTags(fbText, 'facebook');
            $('#mkm-dspb-card-fb .mkm-dspb-card-text').text(fbText);
        }

        // 2. Instagram
        if ($('#mkm_dspb_ig_text').length) {
            var igText = $('#mkm_dspb_ig_text').val() || defaultText;
            igText = replaceTags(igText, 'instagram');
            $('#mkm-dspb-card-ig .mkm-dspb-card-text').text(igText);
        }

        // 3. LinkedIn
        if ($('#mkm_dspb_li_text').length) {
            var liText = $('#mkm_dspb_li_text').val() || defaultText;
            liText = replaceTags(liText, 'linkedin');
            $('#mkm-dspb-card-li .mkm-dspb-card-text').text(liText);
        }

        // 4. Google Business
        if ($('#mkm_dspb_gmb_text').length) {
            var gmbText = $('#mkm_dspb_gmb_text').val() || defaultText;
            gmbText = replaceTags(gmbText, 'googlebusiness');
            $('#mkm-dspb-card-gmb .mkm-dspb-card-text').text(gmbText);
        }

        // 5. X (Twitter)
        if ($('#mkm_dspb_tw_text').length) {
            var twText = $('#mkm_dspb_tw_text').val() || defaultText;
            twText = replaceTags(twText, 'twitter');

            var twLen = twText.length;
            if ($('#mkm_dspb_tw_char_counter').length) {
                if (twLen > 280) {
                    $('#mkm_dspb_tw_char_counter').css('color', '#d63638').html('<strong>' + twLen + ' / 280 (verrà troncato pulito a 280)</strong>');
                } else {
                    $('#mkm_dspb_tw_char_counter').css('color', '#666').text(twLen + ' / 280');
                }
            }

            var displayTwText = (twLen > 280) ? truncateForTwitter(twText, postUrl) : twText;
            $('#mkm-dspb-card-tw .mkm-dspb-card-text').text(displayTwText);
        }
    }

    // Insert tag pill at cursor position
    $(document).on('click', '.mkm-dspb-tag-pill', function(e) {
        e.preventDefault();
        var targetId = $(this).data('target');
        var tag = $(this).data('tag');
        var $textarea = $('#' + targetId);

        if ($textarea.length) {
            var el = $textarea[0];
            var start = el.selectionStart || 0;
            var end = el.selectionEnd || 0;
            var val = $textarea.val();

            var newVal = val.substring(0, start) + tag + val.substring(end);
            $textarea.val(newVal);

            el.selectionStart = el.selectionEnd = start + tag.length;
            $textarea.focus();

            updatePreviews();
        }
    });

    // Attach typing and change listeners
    $('#mkm_dspb_fb_text, #mkm_dspb_ig_text, #mkm_dspb_li_text, #mkm_dspb_gmb_text, #mkm_dspb_tw_text').on('keyup change input', updatePreviews);
    $('#mkm_dspb_fb_comment, #mkm_dspb_ig_comment, #mkm_dspb_li_comment').on('keyup change input', updatePreviews);
    $('#mkm_dspb_fb_move_link, #mkm_dspb_ig_move_link, #mkm_dspb_li_move_link').on('change', updatePreviews);
    
    updatePreviews(); // Run initially

    // Preview tab switching
    $('.mkm-dspb-preview-tab-btn').on('click', function(e) {
        e.preventDefault();
        var target = $(this).data('target');

        // Reset buttons
        $('.mkm-dspb-preview-tab-btn').removeClass('active');

        // Activate selected button
        $(this).addClass('active');

        // Toggle form tab visibility
        $('.mkm-dspb-form-tab').hide();
        $('#mkm-dspb-form-' + target).show();

        // Toggle card visibility
        $('.mkm-dspb-preview-card').hide();
        $('#mkm-dspb-card-' + target).show();
    });

    // AJAX Publish to Buffer
    $('#mkm_dspb_btn_share').on('click', function(e) {
        e.preventDefault();
        
        var $btn = $(this);
        var $feedback = $('#mkm_dspb_feedback');
        
        var channels = [];
        $('input[name="mkm_dspb_share_channels[]"]:checked').each(function() {
            channels.push($(this).val());
        });
        
        var shareNow = $('input[name="mkm_dspb_share_now"]').is(':checked') ? 1 : 0;
        
        if (channels.length === 0) {
            $feedback.css('color', '#d63638').text(mkmDspbPublisher.selectChannelMsg);
            return;
        }
        
        $btn.prop('disabled', true).text(mkmDspbPublisher.sendingMsg);
        $feedback.css('color', '#666').text(mkmDspbPublisher.connectingMsg);
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'mkm_dspb_manual_share',
                post_id: mkmDspbPublisher.postId,
                channels: channels,
                share_now: shareNow,
                fb_text: $('#mkm_dspb_fb_text').length ? $('#mkm_dspb_fb_text').val() : '',
                fb_move: $('#mkm_dspb_fb_move_link').length && $('#mkm_dspb_fb_move_link').is(':checked') ? 1 : 0,
                fb_comm: $('#mkm_dspb_fb_comment').length ? $('#mkm_dspb_fb_comment').val() : '',
                ig_text: $('#mkm_dspb_ig_text').length ? $('#mkm_dspb_ig_text').val() : '',
                ig_move: $('#mkm_dspb_ig_move_link').length && $('#mkm_dspb_ig_move_link').is(':checked') ? 1 : 0,
                ig_comm: $('#mkm_dspb_ig_comment').length ? $('#mkm_dspb_ig_comment').val() : '',
                li_text: $('#mkm_dspb_li_text').length ? $('#mkm_dspb_li_text').val() : '',
                li_move: $('#mkm_dspb_li_move_link').length && $('#mkm_dspb_li_move_link').is(':checked') ? 1 : 0,
                li_comm: $('#mkm_dspb_li_comment').length ? $('#mkm_dspb_li_comment').val() : '',
                gmb_text: $('#mkm_dspb_gmb_text').length ? $('#mkm_dspb_gmb_text').val() : '',
                tw_text: $('#mkm_dspb_tw_text').length ? $('#mkm_dspb_tw_text').val() : '',
                nonce: mkmDspbPublisher.nonce
            },
            success: function(response) {
                $btn.prop('disabled', false).text(mkmDspbPublisher.btnText);
                if (response.success) {
                    $feedback.css('color', '#46b450').html(response.data.message);
                } else {
                    $feedback.css('color', '#d63638').text(response.data.message);
                }
            },
            error: function() {
                $btn.prop('disabled', false).text(mkmDspbPublisher.btnText);
                $feedback.css('color', '#d63638').text(mkmDspbPublisher.errorMsg);
            }
        });
    });

});
