/**
 * Repertorization Engine
 * Real-time repertorization for case creation
 */

// ============================================
// Repertorization Class
// ============================================

class RepertorizationEngine {
    constructor(options = {}) {
        this.selectedRubrics = [];
        this.results = [];
        this.options = {
            autoUpdate: true,
            resultLimit: 20,
            ...options
        };
        this.init();
    }
    
    init() {
        this.bindEvents();
        this.loadInitialRubrics();
    }
    
    bindEvents() {
        // Listen for rubric selection events
        document.addEventListener('rubricSelected', (e) => {
            this.addRubric(e.detail.id);
        });
        
        document.addEventListener('rubricRemoved', (e) => {
            this.removeRubric(e.detail.id);
        });
        
        const updateBtn = document.getElementById('repertorizeBtn');
        if (updateBtn) {
            updateBtn.addEventListener('click', () => this.update());
        }
    }
    
    loadInitialRubrics() {
        const selectedInput = document.getElementById('selectedRubricsJson');
        if (selectedInput && selectedInput.value) {
            try {
                this.selectedRubrics = JSON.parse(selectedInput.value);
                this.updateDisplay();
                this.update();
            } catch(e) {}
        }
    }
    
    addRubric(id) {
        if (!this.selectedRubrics.includes(id)) {
            this.selectedRubrics.push(id);
            this.updateDisplay();
            if (this.options.autoUpdate) this.update();
        }
    }
    
    removeRubric(id) {
        const index = this.selectedRubrics.indexOf(id);
        if (index !== -1) {
            this.selectedRubrics.splice(index, 1);
            this.updateDisplay();
            if (this.options.autoUpdate) this.update();
        }
    }
    
    updateDisplay() {
        const container = document.getElementById('selectedList');
        const hiddenField = document.getElementById('selectedRubricsJson');
        
        if (container) {
            container.innerHTML = '';
            this.selectedRubrics.forEach(async (id) => {
                const rubric = await this.getRubricDetails(id);
                if (rubric) {
                    const item = document.createElement('div');
                    item.className = 'selected-rubric-item';
                    item.dataset.id = id;
                    item.innerHTML = `
                        <span>${rubric.full_path}</span>
                        <button type="button" class="btn-remove" onclick="repertorization.removeRubric(${id})">×</button>
                    `;
                    container.appendChild(item);
                }
            });
        }
        
        if (hiddenField) {
            hiddenField.value = JSON.stringify(this.selectedRubrics);
        }
    }
    
    async getRubricDetails(id) {
        try {
            const response = await fetch(`api/get-rubric.php?id=${id}`);
            const data = await response.json();
            return data.success ? data.rubric : null;
        } catch (error) {
            console.error('Error fetching rubric:', error);
            return null;
        }
    }
    
    async update() {
        if (this.selectedRubrics.length === 0) {
            this.displayResults([]);
            return;
        }
        
        this.showLoading();
        
        try {
            const response = await fetch('api/repertorize.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `rubric_ids=${JSON.stringify(this.selectedRubrics)}`
            });
            const data = await response.json();
            
            if (data.success) {
                this.results = data.results;
                this.displayResults(this.results.slice(0, this.options.resultLimit));
            } else {
                this.displayError(data.error);
            }
        } catch (error) {
            console.error('Repertorization error:', error);
            this.displayError('Network error. Please try again.');
        } finally {
            this.hideLoading();
        }
    }
    
    displayResults(results) {
        const container = document.getElementById('repertorizationResults');
        if (!container) return;
        
        if (results.length === 0) {
            container.innerHTML = '<div class="alert alert-info">No results. Select more rubrics.</div>';
            return;
        }
        
        let html = '<div class="list-group repertory-results">';
        results.forEach((result, index) => {
            const gradeBadges = this.getGradeBadges(result.grades);
            html += `
                <div class="list-group-item repertory-result-item" data-remedy-id="${result.id}">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <strong class="remedy-name">${result.name}</strong>
                            <div class="grade-badges mt-1">${gradeBadges}</div>
                        </div>
                        <div class="text-end">
                            <span class="badge bg-primary score-badge">Score: ${result.score}</span>
                            <button class="btn btn-sm btn-outline-info view-mm-btn" data-remedy="${result.name}">
                                <i class="fas fa-book"></i> MM
                            </button>
                        </div>
                    </div>
                    <div class="remedy-details mt-2" style="display: none;">
                        <div class="remedy-info-loading">Loading...</div>
                    </div>
                </div>
            `;
        });
        html += '</div>';
        container.innerHTML = html;
        
        // Add event listeners for MM buttons
        container.querySelectorAll('.view-mm-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                const remedyName = btn.dataset.remedy;
                this.showMateriaMedica(remedyName, btn.closest('.repertory-result-item'));
            });
        });
    }
    
    getGradeBadges(grades) {
        const gradeCount = {1:0, 2:0, 3:0, 4:0};
        grades.forEach(g => gradeCount[g]++);
        
        let html = '';
        for (let g = 4; g >= 1; g--) {
            if (gradeCount[g] > 0) {
                html += `<span class="grade-badge grade-${g}">G${g}: ${gradeCount[g]}</span>`;
            }
        }
        return html;
    }
    
    async showMateriaMedica(remedyName, container) {
        const detailsDiv = container.querySelector('.remedy-details');
        if (detailsDiv.style.display === 'block') {
            detailsDiv.style.display = 'none';
            return;
        }
        
        detailsDiv.style.display = 'block';
        
        try {
            const response = await fetch(`api/get-remedy-details.php?name=${encodeURIComponent(remedyName)}`);
            const data = await response.json();
            
            if (data.success && data.data) {
                const remedy = data.data;
                let modalitiesHtml = '';
                if (remedy.modalities) {
                    if (remedy.modalities.better?.length) {
                        modalitiesHtml += `<div><strong>Better:</strong> ${remedy.modalities.better.join(', ')}</div>`;
                    }
                    if (remedy.modalities.worse?.length) {
                        modalitiesHtml += `<div><strong>Worse:</strong> ${remedy.modalities.worse.join(', ')}</div>`;
                    }
                }
                
                detailsDiv.innerHTML = `
                    <div class="card bg-light">
                        <div class="card-body">
                            <h6>${remedy.name} ${remedy.abbreviation ? `(${remedy.abbreviation})` : ''}</h6>
                            ${modalitiesHtml}
                            <hr>
                            <div class="small">${remedy.materia_medica ? remedy.materia_medica.substring(0, 300) + '...' : 'No Materia Medica available'}</div>
                            <div class="mt-2">
                                <a href="materia-medica/view.php?name=${encodeURIComponent(remedy.name)}" target="_blank" class="btn btn-sm btn-primary">View Full Monograph</a>
                            </div>
                        </div>
                    </div>
                `;
            } else {
                detailsDiv.innerHTML = '<div class="alert alert-warning">No details available</div>';
            }
        } catch (error) {
            detailsDiv.innerHTML = '<div class="alert alert-danger">Error loading details</div>';
        }
    }
    
    displayError(error) {
        const container = document.getElementById('repertorizationResults');
        if (container) {
            container.innerHTML = `<div class="alert alert-danger">${error}</div>`;
        }
    }
    
    showLoading() {
        const container = document.getElementById('repertorizationResults');
        if (container) {
            container.innerHTML = '<div class="text-center p-4"><div class="spinner-border text-primary"></div><p class="mt-2">Analyzing...</p></div>';
        }
    }
    
    hideLoading() {
        // Loading removed when results displayed
    }
    
    getSelectedRubrics() {
        return this.selectedRubrics;
    }
    
    clear() {
        this.selectedRubrics = [];
        this.updateDisplay();
        this.displayResults([]);
    }
}

// Initialize repertorization engine
let repertorization = null;

document.addEventListener('DOMContentLoaded', () => {
    if (document.getElementById('repertorizationResults')) {
        repertorization = new RepertorizationEngine({
            autoUpdate: true,
            resultLimit: 20
        });
    }
});