document.addEventListener('DOMContentLoaded', function() {
    if (typeof window.packshotphotoConfig === 'undefined') return;
    
    const radios = document.querySelectorAll('input[name="packshotphoto_connection_type"]');
    const sectionOur    = document.getElementById('packshotphoto-section-our-service');
    const sectionCustom = document.getElementById('packshotphoto-section-custom-api');

    function toggleSections() {
        const val = document.querySelector('input[name="packshotphoto_connection_type"]:checked')?.value;
        if (sectionOur) sectionOur.style.display    = val === 'our_service' ? '' : 'none';
        if (sectionCustom) sectionCustom.style.display = val === 'custom_api'  ? '' : 'none';
    }

    radios.forEach(r => r.addEventListener('change', toggleSections));

    // Test custom API button
    const testBtn    = document.getElementById('packshotphoto-test-custom-api');
    const testResult = document.querySelector('.packshotphoto-custom-test-result');

    if (testBtn) {
        testBtn.addEventListener('click', function() {
            testResult.textContent = '⏳ ' + packshotphotoConfig.i18n.testing;
            testResult.style.color = '#888';

            const data = new FormData();
            data.append('action',   'packshotphoto_test_custom_api');
            data.append('nonce',    packshotphotoConfig.nonce);
            data.append('endpoint', document.getElementById('packshotphoto_dev_api_endpoint').value);
            data.append('model',    document.getElementById('packshotphoto_dev_model').value);
            data.append('api_key',  document.getElementById('packshotphoto_dev_api_key').value);

            fetch(packshotphotoConfig.ajaxUrl, { method: 'POST', body: data })
                .then(r => r.json())
                .then(json => {
                    if (json.success) {
                        testResult.textContent = '✅ ' + json.data;
                        testResult.style.color = '#00a32a';
                    } else {
                        testResult.textContent = '❌ ' + (json.data?.message || json.data || packshotphotoConfig.i18n.errors);
                        testResult.style.color = '#d63638';
                    }
                })
                .catch(err => {
                     testResult.textContent = '❌ ' + packshotphotoConfig.i18n.networkError;
                     testResult.style.color = '#d63638';
                });
        });
    }
});
