// Функции для модальных окон
window.showSuccessModal = function() {
    const modal = document.getElementById("successModal");
    if (modal) modal.style.display = "flex";
};
window.showOpenAIErrorModal = function() {
    const modal = document.getElementById("openAIErrorModal");
    if (modal) modal.style.display = "flex";
};
window.showAnthropicErrorModal = function() {
    const modal = document.getElementById("anthropicErrorModal");
    if (modal) modal.style.display = "flex";
};
window.showGenericErrorModal = function() {
    const modal = document.getElementById("genericErrorModal");
    if (modal) modal.style.display = "flex";
};
window.showOpenAIModelsSuccess = function() {
    const modal = document.getElementById("openaiModelsSuccessModal");
    if (modal) modal.style.display = "flex";
};
window.showOpenAIModelsError = function() {
    const modal = document.getElementById("openaiModelsErrorModal");
    if (modal) modal.style.display = "flex";
};

// Общие функции
window.toggleVisibility = function(id) {
    const fld = document.getElementById(id);
    if (!fld) return;
    fld.type = (fld.type === "password") ? "text" : "password";
};

window.resetField = function(field_id, hidden_id) {
    const field = document.getElementById(field_id);
    const hidden = document.getElementById(hidden_id);
    if (field && hidden) {
        field.value = "";
        hidden.value = "1";
    }
};

window.openModal = function(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) modal.style.display = "flex";
};

// Переключение провайдеров текстовых моделей
function toggleTextProviders(provider) {
    const openaiBlock = document.getElementById('openai_key_block');
    const anthropicBlock = document.getElementById('anthropic_key_block');
    const deepseekBlock = document.getElementById('deepseek_key_block');
    const openaiBtn = document.getElementById('openai_models_button_block');
    const openaiContainer = document.getElementById('openai_models_container');
    const anthroContainer = document.getElementById('anthropic_models_container');
    const deepseekContainer = document.getElementById('deepseek_models_container');
    const fineTuned = document.getElementById('fine_tuned_container');

    // Если элементы не найдены, выходим
    if (!openaiBlock || !anthropicBlock || !deepseekBlock || !openaiBtn || !openaiContainer || !anthroContainer || !deepseekContainer || !fineTuned) return;

    if (provider === "openai") {
        openaiBlock.style.display = 'block';
        anthropicBlock.style.display = 'none';
        deepseekBlock.style.display = 'none';
        openaiBtn.style.display = 'block';
        openaiContainer.style.display = 'block';
        anthroContainer.style.display = 'none';
        deepseekContainer.style.display = 'none';
        fineTuned.style.display = 'block';
    } else if (provider === "anthropic") {
        openaiBlock.style.display = 'none';
        anthropicBlock.style.display = 'block';
        deepseekBlock.style.display = 'none';
        openaiBtn.style.display = 'none';
        openaiContainer.style.display = 'none';
        anthroContainer.style.display = 'block';
        deepseekContainer.style.display = 'none';
        fineTuned.style.display = 'none';
    } else if (provider === "deepseek") {
        openaiBlock.style.display = 'none';
        anthropicBlock.style.display = 'none';
        deepseekBlock.style.display = 'block';
        openaiBtn.style.display = 'none';
        openaiContainer.style.display = 'none';
        anthroContainer.style.display = 'none';
        deepseekContainer.style.display = 'block';
        fineTuned.style.display = 'none';
    }
}

// Переключение провайдеров изображений
function toggleImageProviders(provider) {
    const dalleKeyBlock = document.getElementById('dalle_key_block');
    const deepaiKeyBlock = document.getElementById('deepai_key_block');
    const stableDiffusionKeyBlock = document.getElementById('stablediffusion_key_block');
    const ideogramKeyBlock = document.getElementById('ideogram_key_block');
    const geminiImageKeyBlock = document.getElementById('gemini_image_key_block');
    const dalleModelsContainer = document.getElementById('dalle_models_container');
    const deepaiModelsContainer = document.getElementById('deepai_models_container');
    const stableDiffusionModelsContainer = document.getElementById('stablediffusion_models_container');
    const ideogramModelsContainer = document.getElementById('ideogram_models_container');
    const geminiImageModelsContainer = document.getElementById('gemini_image_models_container');

    // Если элементы не найдены, выходим
    if (!dalleKeyBlock || !deepaiKeyBlock || !stableDiffusionKeyBlock || !ideogramKeyBlock ||
        !geminiImageKeyBlock || !dalleModelsContainer || !deepaiModelsContainer || !stableDiffusionModelsContainer || !ideogramModelsContainer || !geminiImageModelsContainer) return;

    dalleKeyBlock.style.display = (provider === 'dalle') ? 'block' : 'none';
    deepaiKeyBlock.style.display = (provider === 'deepai') ? 'block' : 'none';
    stableDiffusionKeyBlock.style.display = (provider === 'stablediffusion') ? 'block' : 'none';
    ideogramKeyBlock.style.display = (provider === 'ideogram') ? 'block' : 'none';
    geminiImageKeyBlock.style.display = (provider === 'gemini') ? 'block' : 'none';
    dalleModelsContainer.style.display = (provider === 'dalle') ? 'block' : 'none';
    deepaiModelsContainer.style.display = (provider === 'deepai') ? 'block' : 'none';
    stableDiffusionModelsContainer.style.display = (provider === 'stablediffusion') ? 'block' : 'none';
    ideogramModelsContainer.style.display = (provider === 'ideogram') ? 'block' : 'none';
    geminiImageModelsContainer.style.display = (provider === 'gemini') ? 'block' : 'none';
}

// Проверка состояния "unsaved" для плавающего окна
function checkFloatingStatusUnsaved() {
    const textUnsaved = document.getElementById('aiw-text-unsaved');
    const imageUnsaved = document.getElementById('aiw-image-unsaved');
    const header = document.getElementById('aiw-floating-status-header');

    // Если элементы не найдены, выходим
    if (!textUnsaved || !imageUnsaved || !header) return;

    if ((textUnsaved.style.display !== 'none') || (imageUnsaved.style.display !== 'none')) {
        header.classList.add('pulsate');
    } else {
        header.classList.remove('pulsate');
    }
}

// Основная логика страницы
document.addEventListener('DOMContentLoaded', function() {
        const getRadioLabel = (radio) => {
            if (!radio) return '';
            if (radio.dataset && radio.dataset.label) {
                return radio.dataset.label;
            }
            const labelEl = document.querySelector("label[for='" + radio.id + "']");
            return labelEl ? labelEl.textContent.trim() : radio.value;
        };

        const updateActiveTextSummary = () => {
            const activeModelEl = document.getElementById('aiw-active-text-model-name');
            if (activeModelEl) {
                const selectedModel = document.querySelector('input[name="text_model_selector"]:checked');
                const currentValue = getRadioLabel(selectedModel);
                if (currentValue) {
                    activeModelEl.textContent = currentValue;
                }
            }
            const activeProviderEl = document.getElementById('aiw-active-text-provider');
            if (activeProviderEl) {
                const selectedProvider = document.querySelector('input[name="text_provider"]:checked');
                const providerValue = getRadioLabel(selectedProvider);
                if (providerValue) {
                    activeProviderEl.textContent = providerValue;
                }
            }
        };

        const updateActiveImageSummary = () => {
            const activeImageModelEl = document.getElementById('aiw-active-image-model-name');
            if (activeImageModelEl) {
                const selectedImageModel = document.querySelector('input[name="image_model_selector"]:checked');
                const modelValue = getRadioLabel(selectedImageModel);
                if (modelValue) {
                    activeImageModelEl.textContent = modelValue;
                }
            }
            const activeImageProviderEl = document.getElementById('aiw-active-image-provider');
            if (activeImageProviderEl) {
                const selectedImageProvider = document.querySelector('input[name="image_provider"]:checked');
                const providerValue = getRadioLabel(selectedImageProvider);
                if (providerValue) {
                    activeImageProviderEl.textContent = providerValue;
                }
            }
        };

    // Проверяем, существует ли контейнер настроек API
    const settingsContainer = document.querySelector('.ai-content-wizard-settings');
    if (!settingsContainer) return; // Если нет контейнера, выходим (скрипт не выполняется на других страницах)

    // Табы
    const tabButtons = document.querySelectorAll('.aiw-tab-button');
    const tabContents = document.querySelectorAll('.aiw-tab-content');
    tabButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            tabButtons.forEach(b => b.classList.remove('active'));
            tabContents.forEach(tc => tc.classList.remove('active'));
            this.classList.add('active');
            document.getElementById(this.getAttribute('data-tab')).classList.add('active');
        });
    });

    // Переключение текстовых провайдеров
    const textProvRadios = document.getElementsByName('text_provider');
    Array.from(textProvRadios).forEach(r => {
        r.addEventListener('change', () => {
            toggleTextProviders(r.value);
            updateActiveTextSummary();
        });
    });
    const checkedTP = document.querySelector('input[name="text_provider"]:checked');
    if (checkedTP) toggleTextProviders(checkedTP.value);

    // Переключение провайдеров изображений
    const imgProvRadios = document.getElementsByName('image_provider');
    Array.from(imgProvRadios).forEach(r => {
        r.addEventListener('change', () => {
            toggleImageProviders(r.value);
            updateActiveImageSummary();
        });
    });
    const checkedIP = document.querySelector('input[name="image_provider"]:checked');
    if (checkedIP) toggleImageProviders(checkedIP.value);

    // Выбор текстовых моделей
    const textModelsRadioGroup = document.getElementById('text-models-radio-group');
    const textHiddenField = document.getElementById('ai_content_wizard_text_model');
    const textUnsavedEl = document.getElementById('aiw-text-unsaved');
    if (textModelsRadioGroup && textHiddenField && textUnsavedEl) {
        const textSavedVal = textHiddenField.value;
        textModelsRadioGroup.addEventListener('change', function(e) {
            if (e.target && e.target.name === 'text_model_selector') {
                textHiddenField.value = e.target.value;
                const selectedTextModelEl = document.getElementById('aiw-selected-text-model');
                if (selectedTextModelEl) {
                    selectedTextModelEl.innerText = e.target.value;
                }
                if (e.target.value !== textSavedVal) {
                    textUnsavedEl.style.display = 'inline';
                } else {
                    textUnsavedEl.style.display = 'none';
                }
                if (e.target.value.match(/^ftjob-/)) {
                    alert('This model cannot be selected as it is not a finalized model.');
                    e.target.checked = false;
                    const oldRadio = textModelsRadioGroup.querySelector('input[value="' + textSavedVal + '"]');
                    if (oldRadio) oldRadio.checked = true;
                    if (selectedTextModelEl) {
                        selectedTextModelEl.innerText = textSavedVal;
                    }
                    textUnsavedEl.style.display = 'none';
                }
                updateActiveTextSummary();
                checkFloatingStatusUnsaved();
            }
        });
    }

    // Выбор моделей изображений
    const imgModelsRadioGroup = document.getElementById('image-models-radio-group');
    const imgHiddenField = document.getElementById('ai_content_wizard_image_model');
    const imgUnsavedEl = document.getElementById('aiw-image-unsaved');
    if (imgModelsRadioGroup && imgHiddenField && imgUnsavedEl) {
        const imgSavedVal = imgHiddenField.value;
        const currentImgRadio = imgModelsRadioGroup.querySelector('input[value="' + imgSavedVal + '"]');
        if (currentImgRadio) currentImgRadio.checked = true;
        imgModelsRadioGroup.addEventListener('change', function(e) {
            if (e.target && e.target.name === 'image_model_selector') {
                imgHiddenField.value = e.target.value;
                const selectedImageModelEl = document.getElementById('aiw-selected-image-model');
                if (selectedImageModelEl) {
                    selectedImageModelEl.innerText = e.target.value;
                }
                if (e.target.value !== imgSavedVal) {
                    imgUnsavedEl.style.display = 'inline';
                } else {
                    imgUnsavedEl.style.display = 'none';
                }
                updateActiveImageSummary();
                checkFloatingStatusUnsaved();
            }
        });
    }

    updateActiveTextSummary();
    updateActiveImageSummary();

    // Переименование fine-tuned моделей
    const renameBtn = document.getElementById('rename_model');
    if (renameBtn) {
        renameBtn.addEventListener('click', function(ev) {
            ev.preventDefault();
            const selModel = document.getElementById('ai_content_wizard_fine_tuned_model')?.value;
            const newName = document.getElementById('new_model_name')?.value;
            const jobidPattern = /^ftjob-\w+$/;
            const modelNamePattern = /^ft:gpt-3\.5-turbo.*/;
            if (!jobidPattern.test(selModel)) {
                alert('Selected model ID does not match the required pattern (ftjob-*****).');
                return;
            }
            if (!modelNamePattern.test(newName)) {
                alert('New model name must start with "ft:gpt-3.5-turbo".');
                return;
            }
            if (selModel && newName) {
                const radios = document.querySelectorAll('#text-models-radio-group input[type="radio"]');
                radios.forEach(r => {
                    if (r.value === selModel) {
                        r.value = newName;
                        const lbl = document.querySelector("label[for='" + r.id + "']");
                        if (lbl) lbl.innerText = newName;
                    }
                });
                const data = {
                    action: 'rename_model',
                    old_name: selModel,
                    new_name: newName
                };
                jQuery.post(ajaxurl, data, function(response) {
                    if (response.success) {
                        alert('Model renamed successfully');
                    } else {
                        alert('Error renaming model: ' + (response.data || ""));
                    }
                });
            } else {
                alert('Please select a model and enter a new name.');
            }
        });
    }

    // Управление плавающим окном
    const toggleBtn = document.getElementById('toggle-floating-status');
    const floatingContent = document.querySelector('.aiw-floating-status-content');
    const header = document.getElementById('aiw-floating-status-header');
    if (toggleBtn && floatingContent && header) {
        toggleBtn.addEventListener('click', function() {
            if (window.getComputedStyle(floatingContent).display === "none") {
                floatingContent.style.display = "block";
                toggleBtn.innerHTML = "−";
                header.classList.remove('pulsate');
            } else {
                floatingContent.style.display = "none";
                toggleBtn.innerHTML = "+";
            }
        });
    }

    // Закрытие модальных окон
    const closeButtons = document.getElementsByClassName("ai-content-wizard-close");
    for (let i = 0; i < closeButtons.length; i++) {
        closeButtons[i].onclick = function() {
            this.parentElement.parentElement.style.display = "none";
        };
    }
    window.onclick = function(e) {
        const modals = document.querySelectorAll(".ai-content-wizard-modal");
        modals.forEach(m => {
            if (e.target === m) {
                m.style.display = "none";
            }
        });
    };
});