document.addEventListener('DOMContentLoaded', function () {
    const button = document.getElementById('ezhp_load_agents');
    const dropdown = document.getElementById('ezhp_agent_dropdown');
    const savedAgentId = ezhpVoiceAgent.savedAgentId || "";

    async function loadAgents() {
        dropdown.innerHTML = '<option>Loading...</option>';

        try {
            const response = await fetch(ajaxurl + '?action=ezhp_load_agents');
            const data = await response.json();

            if (!data.success) {
                // Always include the demo agent
                dropdown.innerHTML = '';
                const demoOpt = document.createElement('option');
                demoOpt.value = '03A262CA-8DAA-4620-A9B2-90A133EDA393';
                demoOpt.textContent = 'Astrology Demonstration Agent';
                demoOpt.selected = true;
                dropdown.appendChild(demoOpt);

                // Show the error as a disabled option below the demo
                const errOpt = document.createElement('option');
                let msg = data.data || 'Failed';
                if (msg.includes('401') || msg.toLowerCase().includes('unauthorized')) {
                    msg = 'Please enter a valid API key & Save settings';
                }
                errOpt.textContent = msg;
                errOpt.disabled = true;
                dropdown.appendChild(errOpt);

                dropdown.disabled = false; // keep enabled so demo agent can be selected
                return;
            }

            dropdown.innerHTML = '';
            data.data.forEach(agent => {
                const opt = document.createElement('option');
                opt.value = agent.agentId;
                opt.textContent = agent.name;
                if (savedAgentId && agent.agentId.toLowerCase() === savedAgentId.toLowerCase()) {
                    opt.selected = true;
                }
                dropdown.appendChild(opt);
            });
            dropdown.disabled = false;
        } catch (err) {
            console.error(err);
            dropdown.innerHTML = '<option>Error loading agents</option>';
        }
    }

    // ✅ Run automatically on page load
    loadAgents();

    // ✅ Also run when button is clicked
    if (button) {
        button.addEventListener('click', loadAgents);
    }

    // -------------------------------
    // Generate Shortcode Handler
    // -------------------------------
    const genBtn = document.getElementById('ezhp_generate_shortcode');
    const resultDiv = document.getElementById('ezhp_shortcode_result');

    if (genBtn) {
        genBtn.addEventListener('click', async function () {
            const agentId = dropdown.value;
            if (!agentId) {
                resultDiv.innerHTML = '<span style="color:red;">No agent selected.</span>';
                return;
            }

            resultDiv.innerHTML = 'Generating shortcode...';

            try {
                const formData = new FormData();
                formData.append('action', 'ezhp_generate_voice_shortcode');
                formData.append('agent_id', agentId);
                formData.append('security', ezhpAjax.security);

                const response = await fetch(ajaxurl, {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    const shortcode = data.data.shortcode;
                    resultDiv.innerHTML =
                        '<code id="ezhp_generated_shortcode">' + shortcode + '</code>' +
                        '<button type="button" class="button" id="ezhp_copy_shortcode" style="margin-left:8px;">Copy</button>';

                    // ✅ Attach event listener for copy button
                    const copyBtn = document.getElementById('ezhp_copy_shortcode');
                    copyBtn.addEventListener('click', function () {
                        const text = document.getElementById('ezhp_generated_shortcode').innerText;
                        navigator.clipboard.writeText(text).then(() => {
                            copyBtn.textContent = 'Copied!';
                            setTimeout(() => copyBtn.textContent = 'Copy', 1500);
                        }).catch(err => {
                            console.error('Clipboard error', err);
                            copyBtn.textContent = 'Failed';
                        });
                    });
                } else {
                    resultDiv.innerHTML = '<span style="color:red;">❌ ' + (data.data || 'Error') + '</span>';
                }
            } catch (err) {
                console.error(err);
                resultDiv.innerHTML = '<span style="color:red;">❌ Request failed</span>';
            }
        });
    }
});
