const Health = {
    page: 1,
    evidenceFile: null,
    
    async init() {
        document.getElementById('hDate').value = new Date().toISOString().split('T')[0];
        await this.loadAnimals();
        await this.loadEvents();
        
        document.getElementById('filterSeverity')?.addEventListener('change', () => { this.page = 1; this.loadEvents(); });
        document.getElementById('filterEventType')?.addEventListener('change', () => { this.page = 1; this.loadEvents(); });
        document.getElementById('searchHealth')?.addEventListener('input', App.debounce(() => { this.page = 1; this.loadEvents(); }, 400));

        // Photo evidence
        const photoArea = document.getElementById('healthPhotoArea');
        const photoInput = document.getElementById('healthPhoto');
        if (photoArea && photoInput) {
            photoArea.addEventListener('click', () => photoInput.click());
            photoInput.addEventListener('change', (e) => {
                if (e.target.files[0]) {
                    this.evidenceFile = e.target.files[0];
                    const reader = new FileReader();
                    reader.onload = (ev) => {
                        document.getElementById('healthPhotoPreview').innerHTML = `<img src="${ev.target.result}" style="max-height:80px; border-radius:8px">`;
                    };
                    reader.readAsDataURL(this.evidenceFile);
                }
            });
        }
    },

    async loadAnimals() {
        try {
            const res = await API.get('/animals?per_page=500&status=active');
            const opts = (res.data || []).map(a => `<option value="${a.id}">${a.name || a.tag_id} — ${a.species_name || ''}</option>`).join('');
            document.getElementById('hAnimalId').innerHTML = '<option value="">Seleccionar...</option>' + opts;
        } catch(e) {}
    },

    async loadEvents() {
        const tbody = document.getElementById('healthTableBody');
        const severity = document.getElementById('filterSeverity')?.value;
        const search = document.getElementById('searchHealth')?.value;

        let url = `/health?page=${this.page}&per_page=20`;
        if (severity) url += `&filter[severity]=${severity}`;
        if (search) url += `&search=${encodeURIComponent(search)}`;

        try {
            const res = await API.get(url);
            const items = res.data || [];

            if (!items.length) {
                tbody.innerHTML = '<tr><td colspan="7" class="text-center"><div class="empty-state"><p>Sin eventos registrados</p></div></td></tr>';
                return;
            }

            tbody.innerHTML = items.map(e => `<tr>
                <td>
                    <a href="/animales/${e.animal_id}" class="link-primary"><strong>${e.animal_name || '—'}</strong></a>
                    <div style="font-size:0.75rem;color:var(--text-muted)">${e.tag_id || ''}</div>
                </td>
                <td><span class="chip">${e.event_type}</span></td>
                <td>${e.diagnosis || '—'}</td>
                <td><span class="severity-badge ${e.severity}">${e.severity}</span></td>
                <td>${App.formatDate(e.event_date)}</td>
                <td><span class="chip chip-${e.status === 'active' ? 'warning' : 'success'}">${e.status}</span></td>
                <td><a href="/animales/${e.animal_id}" class="btn btn-sm btn-ghost">Ver perfil</a></td>
            </tr>`).join('');

            // Paginación
            if (res.meta) {
                const pg = document.getElementById('healthPagination');
                const total = Math.ceil(res.meta.total / res.meta.per_page);
                pg.innerHTML = Array.from({length: Math.min(total, 5)}, (_, i) =>
                    `<button class="btn btn-sm ${i+1 === this.page ? 'btn-primary' : 'btn-ghost'}" onclick="Health.goPage(${i+1})">${i+1}</button>`
                ).join('');
            }
        } catch(e) {
            tbody.innerHTML = '<tr><td colspan="7">Error al cargar</td></tr>';
        }
    },

    goPage(p) { this.page = p; this.loadEvents(); },

    openCreate() { Modal.open('healthModal'); },

    async save() {
        const animalId = document.getElementById('hAnimalId').value;
        const data = {
            animal_id: animalId,
            event_type: document.getElementById('hEventType').value,
            diagnosis: document.getElementById('hDiagnosis').value || null,
            severity: document.getElementById('hSeverity').value,
            event_date: document.getElementById('hDate').value,
            symptoms: document.getElementById('hSymptoms').value || null,
            treatment: document.getElementById('hTreatment').value || null,
            notes: document.getElementById('hNotes').value || null,
            update_health_status: document.getElementById('hHealthStatus').value || null,
        };

        if (!data.animal_id || !data.event_date) { Toast.warning('Complete los campos obligatorios'); return; }

        try {
            await API.post('/health', data);
            // Upload evidence photo if selected
            if (this.evidenceFile && animalId) {
                try { await API.upload(`/animals/${animalId}/photos`, this.evidenceFile, 'photo'); } catch(pe) {}
            }
            Toast.success('Evento registrado');
            Modal.close('healthModal');
            document.getElementById('healthForm').reset();
            document.getElementById('hDate').value = new Date().toISOString().split('T')[0];
            this.evidenceFile = null;
            const preview = document.getElementById('healthPhotoPreview');
            if (preview) preview.innerHTML = '\ud83d\udcf7 Tomar foto de evidencia';
            this.loadEvents();
        } catch(e) {
            Toast.danger('Error al guardar');
        }
    }
};

document.addEventListener('DOMContentLoaded', () => Health.init());
