/**
 * Weglot per-language audio column handler.
 *
 * Handles generate / delete clicks for language-specific audio rows on the
 * post list screen. Expects window.mementorTTSML to be localized by PHP.
 *
 * @package Mementor_TTS
 */
(function($) {
    'use strict';

    window.processingLangPosts = window.processingLangPosts || {};

    var langNames = {
        'nb': 'NO', 'no': 'NO', 'nn': 'NO',
        'en': 'EN', 'sv': 'SV', 'da': 'DA', 'fi': 'FI',
        'de': 'DE', 'fr': 'FR', 'es': 'ES', 'it': 'IT',
        'pt': 'PT', 'nl': 'NL', 'pl': 'PL', 'ru': 'RU',
        'ja': 'JA', 'zh': 'ZH', 'ko': 'KO'
    };

    function getLangLabel(code) {
        return langNames[code] || String(code || '').toUpperCase();
    }

    function notify(message, type) {
        if (typeof window.mementorTTSShowNotification === 'function') {
            window.mementorTTSShowNotification(message, type || 'success');
        } else if (type === 'error') {
            alert(message);
        }
    }

    function handleMLGenerateClick(e) {
        e.preventDefault();
        e.stopPropagation();

        var $btn     = $(this);
        var postId   = $btn.data('post-id');
        var lang     = $btn.data('lang');
        var fileLang = $btn.data('file-lang') || lang;
        var key      = postId + '-' + lang;

        if (window.processingLangPosts[key]) {
            return;
        }
        window.processingLangPosts[key] = true;

        var $row = $btn.closest('.mementor-tts-ml-row');
        $row.addClass('processing');
        var originalContent = $row.html();

        $row.html(
            '<span class="mementor-tts-ml-lang">' + getLangLabel(lang) + '</span>' +
            '<span class="dashicons dashicons-update mementor-tts-spin"></span>'
        );

        $.ajax({
            url: window.mementorTTSML.ajaxUrl,
            type: 'POST',
            data: {
                action: 'mementor_tts_generate_language_audio',
                post_id: postId,
                language: lang,
                nonce: window.mementorTTSML.nonce
            },
            success: function(response) {
                $row.removeClass('processing');

                if (response.success) {
                    var audioUrl = response.data.audio_url;

                    var downloadUrl = window.mementorTTSML.ajaxUrl +
                        '?action=mementor_tts_download_audio' +
                        '&post_id=' + encodeURIComponent(postId) +
                        '&language=' + encodeURIComponent(fileLang) +
                        '&nonce=' + encodeURIComponent(window.mementorTTSML.downloadNonce);
                    var downloadFilename = 'tts-' + postId + '-' + fileLang + '.mp3';

                    $row.html(
                        '<span class="mementor-tts-ml-lang">' + getLangLabel(lang) + '</span>' +
                        '<a href="#" class="mementor-tts-play-button" data-audio-url="' + audioUrl + '" title="Play audio"><img src="' + window.mementorTTSML.playIconUrl + '" alt="Play" class="mementor-tts-play-icon" /></a>' +
                        '<a href="' + downloadUrl + '" class="mementor-tts-download-button" download="' + downloadFilename + '" title="Download audio"><img src="' + window.mementorTTSML.downloadIconUrl + '" alt="Download" /></a>' +
                        '<a href="#" class="mementor-tts-ml-generate-btn mementor-tts-regenerate" data-post-id="' + postId + '" data-lang="' + lang + '" data-file-lang="' + fileLang + '" title="Regenerate audio"><img src="' + window.mementorTTSML.redoIconUrl + '" alt="Regenerate" /></a>' +
                        '<a href="#" class="mementor-tts-ml-delete-btn" data-post-id="' + postId + '" data-lang="' + lang + '" data-file-lang="' + fileLang + '" title="Delete audio"><img src="' + window.mementorTTSML.deleteIconUrl + '" alt="Delete" /></a>'
                    );

                    notify((window.mementorTTSML.successMessage || 'Audio generated!') + ' (' + getLangLabel(lang) + ')', 'success');
                } else {
                    $row.html(originalContent);
                    // Surface the dedicated "not enough credits" modal when the
                    // SaaS returned 402, so users get the top-up / upgrade CTAs.
                    if (response.data && response.data.error === 'credits_exhausted' &&
                        window.mementorTTSModalUtils &&
                        typeof window.mementorTTSModalUtils.showCreditsExhausted === 'function') {
                        var info = response.data.credits_info || {};
                        window.mementorTTSModalUtils.showCreditsExhausted(
                            info.remaining || 0,
                            info.required || 0,
                            info.limit || 0
                        );
                    } else {
                        var errorMsg = (response.data && response.data.message) ? response.data.message : 'Error generating audio';
                        notify(errorMsg, 'error');
                    }
                }
                delete window.processingLangPosts[key];
            },
            error: function(xhr, status, error) {
                $row.removeClass('processing');
                $row.html(originalContent);
                notify('Error generating audio: ' + error, 'error');
                delete window.processingLangPosts[key];
            }
        });
    }

    function handleMLDeleteClick(e) {
        e.preventDefault();
        e.stopPropagation();

        var $btn     = $(this);
        var postId   = $btn.data('post-id');
        var lang     = $btn.data('lang');
        var fileLang = $btn.data('file-lang') || lang;
        var key      = postId + '-' + lang;

        if (window.processingLangPosts[key]) {
            return;
        }

        if (!confirm(window.mementorTTSML.deleteConfirm || 'Are you sure you want to delete this audio file?')) {
            return;
        }

        window.processingLangPosts[key] = true;

        var $row = $btn.closest('.mementor-tts-ml-row');
        $row.addClass('processing');
        var originalContent = $row.html();

        $row.html(
            '<span class="mementor-tts-ml-lang">' + getLangLabel(lang) + '</span>' +
            '<span class="dashicons dashicons-update mementor-tts-spin"></span>'
        );

        $.ajax({
            url: window.mementorTTSML.ajaxUrl,
            type: 'POST',
            data: {
                action: 'mementor_tts_delete_language_audio',
                post_id: postId,
                language: fileLang,
                nonce: window.mementorTTSML.nonce
            },
            success: function(response) {
                $row.removeClass('processing');

                if (response.success) {
                    $row.html(
                        '<span class="mementor-tts-ml-lang">' + getLangLabel(lang) + '</span>' +
                        '<a href="#" class="mementor-tts-ml-generate-btn mementor-tts-ml-create" data-post-id="' + postId + '" data-lang="' + lang + '" data-file-lang="' + fileLang + '" title="Generate audio"><img src="' + window.mementorTTSML.createIconUrl + '" alt="Generate" class="mementor-tts-create-icon" /></a>' +
                        '<span class="mementor-tts-ml-slot"></span>' +
                        '<span class="mementor-tts-ml-slot"></span>' +
                        '<span class="mementor-tts-ml-slot"></span>'
                    );
                    notify(window.mementorTTSML.deleteSuccessMessage || 'Audio deleted!', 'success');
                } else {
                    $row.html(originalContent);
                    var errorMsg = (response.data && response.data.message) ? response.data.message : 'Error deleting audio';
                    notify(errorMsg, 'error');
                }
                delete window.processingLangPosts[key];
            },
            error: function(xhr, status, error) {
                $row.removeClass('processing');
                $row.html(originalContent);
                notify('Error deleting audio: ' + error, 'error');
                delete window.processingLangPosts[key];
            }
        });
    }

    $(document).ready(function() {
        $(document).on('click', '.mementor-tts-ml-generate-btn', handleMLGenerateClick);
        $(document).on('click', '.mementor-tts-ml-delete-btn',   handleMLDeleteClick);
    });

})(jQuery);
