async function generateAISuggestion(button) {
    const target = button.dataset.target || 'treatment_plan';
    const modal = button.closest(".modal");
    
    // Get editor instances or DOM elements
    const symptomsEditor = $(modal.querySelector('textarea[name="symptoms"]'));
    const diagnosisEditor = $(modal.querySelector('textarea[name="diagnosis"]'));
    const treatmentPlanEditor = $(modal.querySelector('textarea[name="treatment_plan"]'));

    // Helper to get value from Summernote or textarea
    const getValue = (editor, selector) => {
        if (editor.length && editor.summernote) return editor.summernote('code');
        const el = modal.querySelector(selector);
        return el ? el.value : '';
    };

    const symptomsText = getValue(symptomsEditor, 'textarea[name="symptoms"]');
    const diagnosisText = getValue(diagnosisEditor, 'textarea[name="diagnosis"]');
    
    // Helper to set value
    const setValue = (editor, selector, val) => {
        if (editor.length && editor.summernote) {
            editor.summernote('code', val);
        } else {
            const el = modal.querySelector(selector);
            if (el) el.value = val;
        }
    };

    // Validation
    const cleanSymptoms = symptomsText.replace(/<[^>]*>/g, "").trim();
    const cleanDiagnosis = diagnosisText.replace(/<[^>]*>/g, "").trim();

    if (target === 'diagnosis' && !cleanSymptoms) {
        alert("Please enter symptoms first.");
        return;
    }
    if (target === 'treatment_plan' && (!cleanSymptoms && !cleanDiagnosis)) {
        alert("Please enter symptoms or diagnosis first.");
        return;
    }
    
    const originalHTML = button.innerHTML;
    button.disabled = true;
    button.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> AI...';

    try {
        const payload = { 
            target: target,
            symptoms: symptomsText, 
            diagnosis: diagnosisText,
            current_value: (target === 'symptoms' ? symptomsText : (target === 'diagnosis' ? diagnosisText : ''))
        };

        const response = await fetch("api/ai_report.php", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(payload)
        });
        const data = await response.json();

        if (data.success) {
            if (target === 'symptoms') {
                setValue(symptomsEditor, 'textarea[name="symptoms"]', data.report);
            } else if (target === 'diagnosis') {
                setValue(diagnosisEditor, 'textarea[name="diagnosis"]', data.report);
            } else {
                setValue(treatmentPlanEditor, 'textarea[name="treatment_plan"]', data.report);
            }
        } else {
            alert("AI Error: " + (data.error || "Unknown error"));
        }
    } catch (error) {
        console.error("AI Suggestion failed:", error);
        alert("Failed to generate AI suggestion.");
    } finally {
        button.disabled = false;
        button.innerHTML = originalHTML;
    }
}

// Alias for backward compatibility
window.generateAIReport = generateAISuggestion;