/**
 * Podcastmaker Admin JS
 * Admin-only script
 *
 * Dynamic data is passed through wp_localize_script as window.PodcastmakerAdminData:
 *   - ajaxUrl        : admin-ajax.php URL
 *   - translateNonce : Podcastmaker_translate_nonce
 *   - titleData      : [{postId, title, date, categories}] - for the list screen
 */
(function () {
    'use strict';

    /* ====================================================
     * 1. Script List Screen (edit-podcastmaker_script)
     * ==================================================== */

    /**
     * Force the Content Preview column to align left
     */
    function forceLeftAlign() {
        var previewCells = document.querySelectorAll('td.column-preview, th.column-preview, .Podcastmaker-content-preview');
        previewCells.forEach(function (cell) {
            cell.style.textAlign = 'left';
            cell.style.direction = 'ltr';
            cell.style.unicodeBidi = 'plaintext';
            cell.style.whiteSpace = 'normal';
            cell.style.overflow = 'visible';
            var children = cell.querySelectorAll('*');
            children.forEach(function (child) {
                child.style.textAlign = 'left';
                child.style.direction = 'ltr';
                child.style.unicodeBidi = 'plaintext';
                child.style.float = 'none';
                child.style.whiteSpace = 'normal';
                child.style.overflowWrap = 'anywhere';
            });
        });
    }

    /**
     * Show the original article title, date, and categories in the title column.
     * (Data is passed via wp_localize_script as PodcastmakerAdminListData.titleData.)
     */
    function replaceTitleColumn() {
        var data = window.PodcastmakerAdminListData || window.PodcastmakerAdminData;
        if (!data || !data.titleData) return;

        data.titleData.forEach(function (item) {
            var row = document.querySelector('tr#post-' + item.postId);
            if (!row) return;

            var titleCell = row.querySelector('.column-title strong a');
            if (titleCell) {
                titleCell.textContent = item.title;
            }

            var titleDiv = row.querySelector('.column-title strong');
            if (titleDiv) {
                var metaInfo = document.createElement('div');
                metaInfo.style.cssText = 'color:#646970; font-size:12px; font-weight:normal; margin-top:4px;';
                metaInfo.textContent = '📅 ' + item.date;
                if (item.categories) {
                    metaInfo.textContent += ' | 🏷️ ' + item.categories;
                }
                titleDiv.parentNode.insertBefore(metaInfo, titleDiv.nextSibling);
            }
        });
    }

    /* ====================================================
     * 2. Settings Page: Model Selector (Gemini API Tab)
     * ==================================================== */

    function initModelSelector() {
        var sidebarItems = document.querySelectorAll('.Podcastmaker-model-sidebar-item');
        var panes = document.querySelectorAll('.Podcastmaker-model-pane');

        if (!sidebarItems.length) return;

        // Sidebar switching
        sidebarItems.forEach(function (item) {
            item.addEventListener('click', function () {
                var targetId = this.getAttribute('data-target');

                sidebarItems.forEach(function (i) { i.classList.remove('active'); });
                panes.forEach(function (p) { p.classList.remove('active'); });

                this.classList.add('active');
                var targetPane = document.getElementById(targetId);
                if (targetPane) targetPane.classList.add('active');
            });
        });

        // Automatically check the matching checkbox when a radio button is selected
        var radios = document.querySelectorAll('.Podcastmaker-radio-default');
        radios.forEach(function (radio) {
            radio.addEventListener('change', function () {
                if (this.checked) {
                    var checkbox = document.getElementById('available_' + this.value);
                    if (checkbox) checkbox.checked = true;
                }
            });
        });
    }

    /* ====================================================
     * 2.1 Settings Page: Vertex Region Matrix
     * ==================================================== */

    function initVertexRegionMatrix() {
        var regionRadios = document.querySelectorAll('.Podcastmaker-region-pill input[type="radio"]');
        var vertexModelRadios = document.querySelectorAll('.Podcastmaker-vertex-radio-default');
        var vertexModelCheckboxes = document.querySelectorAll('.Podcastmaker-vertex-check-available');
        var vertexTtsRadios = document.querySelectorAll('.Podcastmaker-vertex-radio-default-tts');
        var vertexTtsCheckboxes = document.querySelectorAll('.Podcastmaker-vertex-check-available-tts');

        function getRowDefaultRegionInput(row) {
            if (!row) {
                return null;
            }

            return row.querySelector('.Podcastmaker-region-pill input[type="radio"][value="global"]:not(:disabled)') || row.querySelector('.Podcastmaker-region-pill input[type="radio"]:not(:disabled)');
        }

        function syncRegionState(input) {
            var pill = input.closest('.Podcastmaker-region-pill');
            if (!pill) {
                return;
            }

            pill.classList.toggle('is-active', input.checked);
        }

        function syncRegionSummary(details) {
            if (!details) {
                return;
            }

            var selectedRadio = details.querySelector('.Podcastmaker-region-pill input[type="radio"]:checked');
            var status = details.querySelector('.Podcastmaker-region-status');
            if (!status) {
                return;
            }

            var valueElement = status.querySelector('.Podcastmaker-region-status-value');
            if (!selectedRadio) {
                status.classList.add('is-hidden');
                status.classList.remove('is-selected');
                if (valueElement) {
                    valueElement.textContent = '';
                }
                return;
            }

            if (valueElement) {
                valueElement.textContent = selectedRadio.value;
            }

            status.classList.remove('is-hidden');
            status.classList.add('is-selected');
        }

        function isEnabledRegionRadio(input) {
            return input && !input.disabled;
        }

        function syncRegionGroup(row) {
            if (!row) {
                return;
            }

            row.querySelectorAll('.Podcastmaker-region-pill input[type="radio"]').forEach(function (radio) {
                syncRegionState(radio);
            });
        }

        function bindRegionRadios(inputs) {
            inputs.forEach(function (input) {
                if (!isEnabledRegionRadio(input)) {
                    syncRegionState(input);
                    return;
                }

                input.addEventListener('change', function () {
                    var row = input.closest('tr');
                    if (row) {
                        var checkbox = row.querySelector('.Podcastmaker-vertex-check-available, .Podcastmaker-vertex-check-available-tts');
                        if (checkbox && !checkbox.checked) {
                            checkbox.checked = true;
                        }
                        syncRegionGroup(row);
                        row.querySelectorAll('.Podcastmaker-region-card').forEach(function (details) {
                            syncRegionSummary(details);
                        });
                    }
                });
                syncRegionState(input);
            });

            document.querySelectorAll('.Podcastmaker-region-card').forEach(function (details) {
                syncRegionSummary(details);
            });
        }

        function ensureDefaultRegion(row) {
            if (!row) {
                return;
            }

            var selectedRadio = row.querySelector('.Podcastmaker-region-pill input[type="radio"]:checked');
            if (selectedRadio) {
                return;
            }

            var defaultRegion = getRowDefaultRegionInput(row);
            if (defaultRegion) {
                defaultRegion.checked = true;
                syncRegionState(defaultRegion);
                row.querySelectorAll('.Podcastmaker-region-card').forEach(function (details) {
                    syncRegionSummary(details);
                });
            }
        }

        function ensureDefaultModel(preferredValue, radioSelector) {
            var selectedRadio = document.querySelector(radioSelector + ':checked');
            if (selectedRadio) {
                return;
            }

            var defaultRadio = null;
            if (preferredValue) {
                defaultRadio = document.querySelector(radioSelector + '[value="' + preferredValue + '"]');
            }
            if (!defaultRadio) {
                defaultRadio = document.querySelector(radioSelector);
            }
            if (defaultRadio) {
                defaultRadio.checked = true;
            }
        }

        function bindDefaultRadios(radios, checkboxSelector, preferredValue, radioSelector) {
            radios.forEach(function (radio) {
                radio.addEventListener('change', function () {
                    if (!radio.checked) {
                        return;
                    }

                    var row = radio.closest('tr');
                    if (!row) {
                        return;
                    }

                    var checkbox = row.querySelector(checkboxSelector);
                    if (checkbox && !checkbox.checked) {
                        checkbox.checked = true;
                    }

                    ensureDefaultModel(preferredValue, radioSelector);
                    ensureDefaultRegion(row);
                });
            });

            document.querySelectorAll(checkboxSelector).forEach(function (checkbox) {
                checkbox.addEventListener('change', function () {
                    if (!checkbox.checked) {
                        var row = checkbox.closest('tr');
                        if (!row) {
                            return;
                        }

                        var defaultRadio = row.querySelector('input[type="radio"]');
                        if (defaultRadio && defaultRadio.checked) {
                            defaultRadio.checked = false;
                        }
                        return;
                    }

                    var row = checkbox.closest('tr');
                    ensureDefaultModel(preferredValue, radioSelector);
                    ensureDefaultRegion(row);
                });
            });

            document.querySelectorAll(checkboxSelector).forEach(function (checkbox) {
                if (!checkbox.checked) {
                    return;
                }

                var row = checkbox.closest('tr');
                ensureDefaultRegion(row);
            });

            ensureDefaultModel(preferredValue, radioSelector);
        }

        if (regionRadios.length) {
            bindRegionRadios(regionRadios);
        }

        if (vertexModelRadios.length && vertexModelCheckboxes.length) {
            bindDefaultRadios(vertexModelRadios, '.Podcastmaker-vertex-check-available', 'gemini-2.5-flash', '.Podcastmaker-vertex-radio-default');
        }

        if (vertexTtsRadios.length && vertexTtsCheckboxes.length) {
            bindDefaultRadios(vertexTtsRadios, '.Podcastmaker-vertex-check-available-tts', 'gemini-2.5-flash-tts', '.Podcastmaker-vertex-radio-default-tts');
        }
    }

    /* ====================================================
     * 3. Settings Page: Speaker Select (Prompts Tab)
     * ==================================================== */

    function initSpeakerSelect() {
        var options = document.querySelectorAll('.speaker-select-option:not(.disabled)');
        if (!options.length) return;

        options.forEach(function (option) {
            option.addEventListener('click', function () {
                document.querySelectorAll('.speaker-select-option').forEach(function (o) {
                    o.classList.remove('selected');
                });
                this.classList.add('selected');
            });
        });
    }

    /* ====================================================
     * 4. Settings Page: Base Prompt Editor
     * ==================================================== */

    function initBasePromptEditor() {
        var editButton = document.getElementById('Podcastmaker-base-prompt-edit-btn');
        var cancelButton = document.getElementById('Podcastmaker-base-prompt-cancel-btn');
        var saveButton = document.getElementById('Podcastmaker-base-prompt-save-btn');
        var promptEditor = document.getElementById('base_prompt_content');

        if (!editButton || !cancelButton || !saveButton || !promptEditor) {
            return;
        }

        var originalValue = promptEditor.getAttribute('data-original-value') || promptEditor.value || '';

        function enableEditing() {
            promptEditor.readOnly = false;
            promptEditor.focus();
            saveButton.disabled = false;
            cancelButton.disabled = false;
            editButton.disabled = true;
        }

        function disableEditing() {
            promptEditor.readOnly = true;
            promptEditor.value = originalValue;
            saveButton.disabled = true;
            cancelButton.disabled = true;
            editButton.disabled = false;
        }

        editButton.addEventListener('click', function () {
            enableEditing();
        });

        cancelButton.addEventListener('click', function () {
            disableEditing();
        });
    }

    /* ====================================================
     * 5. Settings Page: Prompt Set Editor
     * ==================================================== */

    function initPromptSetEditor() {
        var form = document.getElementById('Podcastmaker-prompt-form');
        var editButton = document.getElementById('Podcastmaker-prompt-edit-btn');
        var cancelButton = document.getElementById('Podcastmaker-prompt-cancel-btn');
        var saveButton = document.getElementById('Podcastmaker-prompt-save-btn');
        var promptName = document.getElementById('prompt_name');
        var promptContent = document.getElementById('prompt_content');

        if (!form || !editButton || !cancelButton || !saveButton || !promptName || !promptContent) {
            return;
        }

        var viewOnly = form.getAttribute('data-view-only') === '1';
        var originalName = promptName.getAttribute('data-original-value') || promptName.value || '';
        var originalContent = promptContent.getAttribute('data-original-value') || promptContent.value || '';

        function enableEditing() {
            if (viewOnly) {
                return;
            }

            promptName.readOnly = false;
            promptContent.readOnly = false;
            promptName.disabled = false;
            promptContent.disabled = false;
            editButton.disabled = true;
            cancelButton.disabled = false;
            saveButton.disabled = false;
            promptName.focus();
        }

        function disableEditing() {
            promptName.readOnly = true;
            promptContent.readOnly = true;
            promptName.value = originalName;
            promptContent.value = originalContent;
            editButton.disabled = viewOnly;
            cancelButton.disabled = true;
            saveButton.disabled = true;
        }

        editButton.addEventListener('click', function () {
            enableEditing();
        });

        cancelButton.addEventListener('click', function () {
            disableEditing();
        });

        disableEditing();
    }

    function initVoicePreviews() {
        var previewTable = document.querySelector('.Podcastmaker-voice-preview-table[data-podcastmaker-assets-url]');

        if (!previewTable) {
            return;
        }

        var assetsUrl = previewTable.getAttribute('data-podcastmaker-assets-url') || '';
        var currentAudio = null;
        var currentButton = null;

        function stopAudio() {
            if (currentAudio) {
                currentAudio.pause();
                currentAudio = null;
            }

            if (currentButton) {
                currentButton.classList.remove('is-playing');
                var currentIcon = currentButton.querySelector('.dashicons');
                if (currentIcon) {
                    currentIcon.classList.remove('dashicons-controls-pause');
                    currentIcon.classList.add('dashicons-controls-play');
                }

                var playingRow = currentButton.closest('tr');
                if (playingRow) {
                    playingRow.classList.remove('is-playing-row');
                }

                currentButton = null;
            }
        }

        previewTable.querySelectorAll('.pm-preview-btn').forEach(function (button) {
            button.addEventListener('click', function (event) {
                event.preventDefault();

                var voiceId = this.getAttribute('data-voice');
                var language = this.getAttribute('data-lang');
                var icon = this.querySelector('.dashicons');

                if (currentAudio && currentButton === this) {
                    stopAudio();
                    return;
                }

                stopAudio();

                currentButton = this;
                currentButton.classList.add('is-playing');

                if (icon) {
                    icon.classList.remove('dashicons-controls-play');
                    icon.classList.add('dashicons-controls-pause');
                }

                var row = this.closest('tr');
                if (row) {
                    row.classList.add('is-playing-row');
                }

                var audioFileUrl = assetsUrl + language + '/' + voiceId + '_' + language + '.mp3';
                currentAudio = new Audio(audioFileUrl);
                currentAudio.play().catch(function () {
                    stopAudio();
                });
                currentAudio.onended = stopAudio;
            });
        });
    }

    /* ====================================================
     * 6. Settings Page: Common Controls
     * ==================================================== */

    function getAdminLocalizedStrings() {
        return window.PodcastmakerAdminData && window.PodcastmakerAdminData.strings ? window.PodcastmakerAdminData.strings : {};
    }

    function initPasswordVisibilityToggles() {
        var toggleButtons = document.querySelectorAll('[data-podcastmaker-password-toggle], [data-podcastmaker-secret-toggle]');

        if (!toggleButtons.length) {
            return;
        }

        toggleButtons.forEach(function (button) {
            button.addEventListener('click', function () {
                var targetSelector = this.getAttribute('data-podcastmaker-password-toggle') || this.getAttribute('data-podcastmaker-secret-toggle');
                var targetElement = targetSelector ? document.querySelector(targetSelector) : null;
                var icon = this.querySelector('.dashicons');

                if (!targetElement || !icon) {
                    return;
                }

                var isTextInput = targetElement.tagName === 'INPUT';
                var isCurrentlyHidden = isTextInput ? targetElement.type === 'password' : targetElement.style.filter !== '';

                if (isTextInput) {
                    targetElement.type = isCurrentlyHidden ? 'text' : 'password';
                } else {
                    targetElement.style.filter = isCurrentlyHidden ? '' : 'blur(4px)';
                    targetElement.style.userSelect = isCurrentlyHidden ? '' : 'none';
                }

                icon.classList.toggle('dashicons-visibility', !isCurrentlyHidden);
                icon.classList.toggle('dashicons-hidden', isCurrentlyHidden);
                this.setAttribute('aria-pressed', isCurrentlyHidden ? 'true' : 'false');
            });
        });
    }

    function initConfirmButtons() {
        var confirmButtons = document.querySelectorAll('[data-podcastmaker-confirm]');

        if (!confirmButtons.length) {
            return;
        }

        confirmButtons.forEach(function (button) {
            button.addEventListener('click', function (event) {
                var confirmMessage = this.getAttribute('data-podcastmaker-confirm') || '';
                if (confirmMessage && !window.confirm(confirmMessage)) {
                    event.preventDefault();
                }
            });
        });
    }

    function initVertexConnectionTest() {
        var testButton = document.getElementById('podcastmaker_test_vertex');
        var statusElement = document.getElementById('podcastmaker_vertex_status');
        var jsonField = document.getElementById('podcastmaker_vertex_auth_json');

        if (!testButton || !statusElement || !jsonField) {
            return;
        }

        testButton.addEventListener('click', function () {
            var localizedStrings = getAdminLocalizedStrings();
            var ajaxUrl = window.PodcastmakerAdminData && window.PodcastmakerAdminData.ajaxUrl ? window.PodcastmakerAdminData.ajaxUrl : window.ajaxurl;
            var nonce = window.PodcastmakerAdminData && window.PodcastmakerAdminData.adminNonce ? window.PodcastmakerAdminData.adminNonce : '';

            function formatErrorMessage(payload) {
                var message = payload && payload.data && payload.data.message ? payload.data.message : (localizedStrings.connectionFailed || 'Authentication failed.');
                var code = payload && payload.data && payload.data.code ? payload.data.code : '';
                var details = payload && payload.data && payload.data.details ? payload.data.details : '';
                var parts = [message];
                if (code) {
                    parts.push('[' + code + ']');
                }
                if (details) {
                    parts.push(details);
                }
                return parts.join(' ');
            }

            statusElement.classList.add('pm-admin-status--busy');
            statusElement.textContent = localizedStrings.testingConnection || 'Testing authentication...';
            testButton.disabled = true;

            var formData = new FormData();
            formData.append('action', 'podcastmaker_test_vertex_connection');
            formData.append('auth_json', jsonField.value);
            formData.append('nonce', nonce);

            fetch(ajaxUrl, {
                method: 'POST',
                credentials: 'same-origin',
                body: formData
            })
                .then(function (response) {
                    return response.text().then(function (text) {
                        try {
                            var parsed = JSON.parse(text);
                            if (typeof parsed !== 'object' || parsed === null) {
                                return {
                                    success: false,
                                    data: {
                                        message: text || (localizedStrings.connectionFailed || 'Authentication failed.'),
                                        details: '',
                                        code: 'unexpected_scalar_response'
                                    }
                                };
                            }
                            return parsed;
                        } catch (error) {
                            return {
                                success: false,
                                data: {
                                    message: text || (localizedStrings.connectionFailed || 'Authentication failed.'),
                                    details: '',
                                    code: 'invalid_response'
                                }
                            };
                        }
                    });
                })
                .then(function (payload) {
                    if (payload && payload.success) {
                        statusElement.classList.remove('pm-admin-status--busy');
                        statusElement.classList.add('pm-admin-status--success');
                        statusElement.classList.remove('pm-admin-status--error');
                        statusElement.textContent = payload.data && payload.data.message ? payload.data.message : (localizedStrings.connectionSuccess || 'Authentication successful.');
                    } else {
                        statusElement.classList.remove('pm-admin-status--busy');
                        statusElement.classList.add('pm-admin-status--error');
                        statusElement.classList.remove('pm-admin-status--success');
                        statusElement.textContent = formatErrorMessage(payload);
                    }
                })
                .catch(function (error) {
                    statusElement.classList.remove('pm-admin-status--busy');
                    statusElement.classList.add('pm-admin-status--error');
                    statusElement.classList.remove('pm-admin-status--success');
                    statusElement.textContent = (localizedStrings.connectionFailed || 'Authentication failed.') + (error && error.message ? ' ' + error.message : '');
                })
                .finally(function () {
                    testButton.disabled = false;
                });
        });
    }

    function initVertexAvailabilityCheck() {
        var buttons = document.querySelectorAll('.Podcastmaker-vertex-availability-check');
        var jsonField = document.getElementById('podcastmaker_vertex_auth_json');

        if (!buttons.length || !jsonField) {
            return;
        }

        function getEnabledModelsAndLocations(kind) {
            var isTts = kind === 'tts';
            var checkboxSelector = isTts
                ? 'input[name="podcastmaker_vertex_available_tts_models[]"]:checked'
                : 'input[name="podcastmaker_vertex_available_models[]"]:checked';
            var enabledCheckboxes = document.querySelectorAll(checkboxSelector);
            var targets = [];

            enabledCheckboxes.forEach(function (checkbox) {
                var model = checkbox.value || '';
                var regionSelector = isTts
                    ? 'input[name="podcastmaker_vertex_tts_model_regions[' + model + ']"]:checked'
                    : 'input[name="podcastmaker_vertex_model_regions[' + model + ']"]:checked';
                var locationRadio = document.querySelector(regionSelector);

                if (model && locationRadio && locationRadio.value) {
                    targets.push({
                        model: model,
                        location: locationRadio.value
                    });
                } else if (model) {
                    targets.push({
                        model: model,
                        location: '',
                        missingLocation: true
                    });
                }
            });

            return targets;
        }

        function formatErrorMessage(payload) {
            var localizedStrings = getAdminLocalizedStrings();
            var message = payload && payload.data && payload.data.message ? payload.data.message : (localizedStrings.availabilityFailed || 'Availability check failed.');
            var code = payload && payload.data && payload.data.code ? payload.data.code : '';
            var details = payload && payload.data && payload.data.details ? payload.data.details : '';
            var parts = [message];
            if (code) {
                parts.push('[' + code + ']');
            }
            if (details) {
                parts.push(details);
            }
            return parts.join('\n');
        }

        function formatSuccessMessage(payload) {
            var localizedStrings = getAdminLocalizedStrings();
            var message = payload && payload.data && payload.data.message ? payload.data.message : (localizedStrings.availabilitySuccess || 'Availability confirmed.');
            var details = payload && payload.data && payload.data.details ? payload.data.details : '';
            return details ? (message + '\n' + details) : message;
        }

        buttons.forEach(function (button) {
            button.addEventListener('click', function () {
                var localizedStrings = getAdminLocalizedStrings();
                var ajaxUrl = window.PodcastmakerAdminData && window.PodcastmakerAdminData.ajaxUrl ? window.PodcastmakerAdminData.ajaxUrl : window.ajaxurl;
                var kind = button.getAttribute('data-vertex-kind') || 'text';
                var statusId = button.getAttribute('data-availability-target') || (kind === 'tts' ? 'podcastmaker_vertex_availability_status_tts' : 'podcastmaker_vertex_availability_status_text');
                var statusElement = document.getElementById(statusId);
                var targets = getEnabledModelsAndLocations(kind);
                var formData;

                if (!statusElement) {
                    return;
                }

                if (!targets.length) {
                    statusElement.classList.remove('pm-admin-status--success');
                    statusElement.classList.add('pm-admin-status--error');
                    statusElement.classList.remove('pm-admin-status--busy');
                    statusElement.textContent = localizedStrings.availabilityFailed || 'Availability check failed.';
                    return;
                }

                if (targets.some(function (target) {
                    return !target.location || target.missingLocation;
                })) {
                    statusElement.classList.remove('pm-admin-status--success');
                    statusElement.classList.add('pm-admin-status--error');
                    statusElement.classList.remove('pm-admin-status--busy');
                    statusElement.textContent = localizedStrings.availabilityFailed || 'Availability check failed.';
                    return;
                }

                statusElement.classList.add('pm-admin-status--busy');
                statusElement.classList.remove('pm-admin-status--error');
                statusElement.classList.remove('pm-admin-status--success');
                statusElement.textContent = localizedStrings.checkingAvailability || 'Checking availability...';
                button.disabled = true;

                formData = new FormData();
                formData.append('action', 'podcastmaker_check_vertex_availability');
                formData.append('nonce', window.PodcastmakerAdminData && window.PodcastmakerAdminData.adminNonce ? window.PodcastmakerAdminData.adminNonce : '');
                formData.append('kind', kind);
                formData.append('targets', JSON.stringify(targets));
                formData.append('auth_json', jsonField.value);

                fetch(ajaxUrl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: formData
                })
                    .then(function (response) {
                        return response.text().then(function (text) {
                            try {
                                return JSON.parse(text);
                            } catch (error) {
                                return {
                                    success: false,
                                    data: {
                                        message: text || (localizedStrings.availabilityFailed || 'Availability check failed.'),
                                        details: '',
                                        code: 'invalid_response'
                                    }
                                };
                            }
                        });
                    })
                    .then(function (payload) {
                        statusElement.classList.remove('pm-admin-status--busy');
                        if (payload && payload.success) {
                            statusElement.classList.add('pm-admin-status--success');
                            statusElement.classList.remove('pm-admin-status--error');
                            statusElement.textContent = formatSuccessMessage(payload);
                        } else {
                            statusElement.classList.add('pm-admin-status--error');
                            statusElement.classList.remove('pm-admin-status--success');
                            statusElement.textContent = formatErrorMessage(payload);
                        }
                    })
                    .catch(function (error) {
                        statusElement.classList.remove('pm-admin-status--busy');
                        statusElement.classList.add('pm-admin-status--error');
                        statusElement.classList.remove('pm-admin-status--success');
                        statusElement.textContent = (localizedStrings.availabilityFailed || 'Availability check failed.') + (error && error.message ? ' ' + error.message : '');
                    })
                    .finally(function () {
                        button.disabled = false;
                    });
            });
        });
    }

    function initGeminiModelRefresh() {
        var refreshButton = document.getElementById('podcastmaker_refresh_gemini_models');
        var statusElement = document.getElementById('podcastmaker_gemini_models_status');
        var apiKeyField = document.getElementById('Podcastmaker_gemini_api_key');

        if (!refreshButton || !statusElement || !apiKeyField) {
            return;
        }

        refreshButton.addEventListener('click', function () {
            var localizedStrings = getAdminLocalizedStrings();
            var ajaxUrl = window.PodcastmakerAdminData && window.PodcastmakerAdminData.ajaxUrl ? window.PodcastmakerAdminData.ajaxUrl : window.ajaxurl;
            var nonce = window.PodcastmakerAdminData && window.PodcastmakerAdminData.adminNonce ? window.PodcastmakerAdminData.adminNonce : '';

            statusElement.classList.add('pm-admin-status--busy');
            statusElement.classList.remove('pm-admin-status--error');
            statusElement.classList.remove('pm-admin-status--success');
            statusElement.textContent = localizedStrings.refreshingModels || 'Updating models...';
            refreshButton.disabled = true;

            var formData = new FormData();
            formData.append('action', 'podcastmaker_refresh_gemini_models');
            formData.append('nonce', nonce);
            formData.append('api_key', apiKeyField.value || '');

            fetch(ajaxUrl, {
                method: 'POST',
                credentials: 'same-origin',
                body: formData
            })
                .then(function (response) {
                    return response.text().then(function (responseText) {
                        var parsedPayload = null;

                        try {
                            parsedPayload = responseText ? JSON.parse(responseText) : null;
                        } catch (error) {
                            parsedPayload = null;
                        }

                        return {
                            ok: response.ok,
                            status: response.status,
                            payload: parsedPayload,
                            rawText: responseText
                        };
                    });
                })
                .then(function (result) {
                    if (result && result.payload && result.payload.success) {
                        statusElement.classList.remove('pm-admin-status--busy');
                        statusElement.classList.add('pm-admin-status--success');
                        statusElement.classList.remove('pm-admin-status--error');
                        statusElement.textContent = result.payload.data && result.payload.data.message ? result.payload.data.message : (localizedStrings.modelsRefreshSuccess || 'Model list updated.');
                        window.setTimeout(function () {
                            window.location.reload();
                        }, 600);
                    } else {
                        statusElement.classList.remove('pm-admin-status--busy');
                        statusElement.classList.add('pm-admin-status--error');
                        statusElement.classList.remove('pm-admin-status--success');
                        if (result && result.payload && result.payload.data && result.payload.data.message) {
                            statusElement.textContent = result.payload.data.message;
                        } else if (result && result.rawText && result.rawText.trim() !== '') {
                            statusElement.textContent = (localizedStrings.modelsRefreshFailedPrefix || 'Model update failed:') + ' ' + result.rawText.trim();
                        } else {
                            statusElement.textContent = localizedStrings.modelsRefreshFailed || 'Model update failed.';
                        }
                    }
                })
                .catch(function (error) {
                    statusElement.classList.remove('pm-admin-status--busy');
                    statusElement.classList.add('pm-admin-status--error');
                    statusElement.classList.remove('pm-admin-status--success');
                    statusElement.textContent = localizedStrings.modelsRefreshFailed || 'Model update failed.';
                })
                .finally(function () {
                    refreshButton.disabled = false;
                });
        });
    }

    /* ====================================================
     * 7. Initialization
     * ==================================================== */

    function init() {
        // List screen
        forceLeftAlign();
        replaceTitleColumn();
        setTimeout(forceLeftAlign, 100);
        setTimeout(forceLeftAlign, 500);

        // Settings screen
        initModelSelector();
        initVertexRegionMatrix();
        initSpeakerSelect();
        initBasePromptEditor();
        initPromptSetEditor();
        initVoicePreviews();
        initPasswordVisibilityToggles();
        initConfirmButtons();
        initVertexConnectionTest();
        initVertexAvailabilityCheck();
        initGeminiModelRefresh();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();
