const Repro = {
    async init() {
        this.setupTabs();
        document.getElementById('rDate').value = new Date().toISOString().split('T')[0];
        await this.loadData();
    },

    setupTabs() {
        document.querySelectorAll('.tab').forEach(tab => {
            tab.addEventListener('click', () => {
                document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
                tab.classList.add('active');
                document.getElementById('tab-' + tab.dataset.tab).classList.add('active');
            });
        });
    },

    async loadData() {
        await Promise.all([
            this.loadEvents(),
            this.loadPregnancies(),
            this.loadUpcomingBirths(),
            this.loadBreeders(),
            this.loadAnimalSelects()
        ]);
    },

    async loadEvents() {
        try {
            const res = await API.get('/reproduction?per_page=30');
            const items = res.data || [];

            // KPI - total events
            const el = document.getElementById('kpiEvents');
            if (el) el.textContent = items.length;

            document.getElementById('eventsBody').innerHTML = items.length
                ? items.map(e => {
                    const typeLabels = {
                        'natural_mating': 'Monta natural',
                        'artificial_insemination': 'Inseminación',
                        'pregnancy_check': 'Chequeo gestación',
                        'heat_detection': 'Detección celo',
                        'abortion': 'Aborto',
                    };
                    const label = typeLabels[e.event_type] || e.event_type.replace(/_/g, ' ');
                    return `<tr>
                        <td><a href="/animales/${e.animal_id}" class="link-primary">${e.animal_name || e.tag_id}</a></td>
                        <td>${e.male_name || '—'}</td>
                        <td><span class="chip">${label}</span></td>
                        <td>${App.formatDate(e.event_date)}</td>
                        <td>${e.result || '—'}</td>
                        <td>
                            <button class="btn btn-sm btn-ghost text-danger" onclick="Repro.deleteEvent(${e.id})" title="Eliminar">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
                            </button>
                        </td>
                    </tr>`;
                }).join('')
                : '<tr><td colspan="6" class="text-center"><div class="empty-state"><p>Sin eventos registrados</p></div></td></tr>';
        } catch(e) {}
    },

    async deleteEvent(id) {
        if (!confirm('¿Eliminar este evento reproductivo?')) return;
        try {
            await API.delete(`/reproduction/${id}`);
            Toast.success('Evento eliminado');
            this.loadData();
        } catch(e) { Toast.danger('Error al eliminar'); }
    },

    async loadPregnancies() {
        try {
            const res = await API.get('/reproduction/pregnancies');
            const items = res.data || [];
            document.getElementById('kpiPregnant').textContent = items.length;

            document.getElementById('pregnanciesList').innerHTML = items.length
                ? items.map(p => {
                    const days = p.estimated_due_date ? Math.ceil((new Date(p.estimated_due_date) - new Date()) / 86400000) : '?';
                    // Gestation progress
                    let progress = 0;
                    if (p.service_date && p.estimated_due_date) {
                        const total = (new Date(p.estimated_due_date) - new Date(p.service_date)) / 86400000;
                        const elapsed = (new Date() - new Date(p.service_date)) / 86400000;
                        progress = Math.min(100, Math.max(0, (elapsed / total) * 100));
                    }
                    const progressColor = progress > 90 ? '#DC2626' : progress > 70 ? '#D97706' : '#047857';

                    return `<div class="upcoming-card" style="background:var(--card-bg);border:1px solid var(--border-color);border-radius:12px;padding:1rem;margin-bottom:0.75rem">
                        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:0.5rem">
                            <div>
                                <a href="/animales/${p.animal_id}" class="link-primary"><strong>${p.animal_name || p.tag_id}</strong></a>
                                <span style="margin-left:0.5rem;color:var(--text-muted)">${p.species_name || ''}</span>
                                ${p.male_name ? `<div style="font-size:0.8rem;color:var(--text-muted)">Padre: ${p.male_name}</div>` : ''}
                                <div style="font-size:0.8rem;color:var(--text-muted)">Servicio: ${App.formatDate(p.service_date)} · Parto est.: ${p.estimated_due_date ? App.formatDate(p.estimated_due_date) : '?'}</div>
                            </div>
                            <div style="text-align:center;min-width:48px">
                                <div style="font-size:1.5rem;font-weight:800;color:${progressColor}">${typeof days === 'number' && days <= 0 ? 'HOY' : days}</div>
                                <div style="font-size:0.7rem;color:var(--text-muted)">${typeof days === 'number' && days > 0 ? 'días' : ''}</div>
                            </div>
                        </div>
                        <div style="background:var(--bg-main);border-radius:4px;height:6px;overflow:hidden">
                            <div style="height:100%;width:${progress.toFixed(0)}%;background:${progressColor};border-radius:4px;transition:width 0.6s ease"></div>
                        </div>
                        <div style="font-size:0.72rem;color:var(--text-muted);margin-top:3px;text-align:right">${progress.toFixed(0)}% gestación</div>
                    </div>`;
                }).join('')
                : '<div class="empty-state"><p>Sin gestaciones activas</p></div>';
        } catch(e) {}
    },

    async loadUpcomingBirths() {
        try {
            const res = await API.get('/reproduction/upcoming-births?days=30');
            const items = res.data || [];
            document.getElementById('kpiDue').textContent = items.length;

            document.getElementById('upcomingBirthsList').innerHTML = items.length
                ? items.map(p => {
                    const days = Math.ceil((new Date(p.estimated_due_date) - new Date()) / 86400000);
                    return `<div style="background:var(--card-bg);border:1px solid var(--border-color);border-radius:12px;padding:1rem;margin-bottom:0.75rem;display:flex;justify-content:space-between;align-items:center">
                        <div>
                            <strong>${p.animal_name || p.tag_id}</strong>
                            <div style="font-size:0.8rem;color:var(--text-muted)">Parto estimado: ${App.formatDate(p.estimated_due_date)}</div>
                        </div>
                        <span style="padding:0.25rem 0.75rem;border-radius:8px;font-weight:700;font-size:0.8rem;background:${days <= 7 ? 'rgba(220,53,69,0.2);color:#ff6b7a' : 'rgba(255,193,7,0.2);color:#ffc107'}">${days <= 0 ? 'HOY' : `${days}d`}</span>
                    </div>`;
                }).join('')
                : '<div class="empty-state"><p>Sin partos próximos</p></div>';
        } catch(e) {}
    },

    async loadBreeders() {
        try {
            const [females, males] = await Promise.all([
                API.get('/reproduction/breeding-females'),
                API.get('/reproduction/breeding-males')
            ]);

            document.getElementById('kpiBreeders').textContent = (females.data || []).length;

            document.getElementById('femalesList').innerHTML = (females.data || []).map(f =>
                `<div class="breeder-item">
                    <div><a href="/animales/${f.id}" class="link-primary">${f.name || f.tag_id}</a><div style="font-size:0.75rem;color:var(--text-muted)">${f.species_name} · ${f.breed_name || ''}</div></div>
                    <div style="text-align:right"><span class="chip">${f.reproductive_status || '—'}</span><div style="font-size:0.75rem;color:var(--text-muted)">${f.total_births} partos</div></div>
                </div>`
            ).join('') || '<p class="text-center" style="padding:1rem;color:var(--text-muted)">Sin hembras reproductoras</p>';

            document.getElementById('malesList').innerHTML = (males.data || []).map(m =>
                `<div class="breeder-item">
                    <div><a href="/animales/${m.id}" class="link-primary">${m.name || m.tag_id}</a><div style="font-size:0.75rem;color:var(--text-muted)">${m.species_name} · ${m.breed_name || ''}</div></div>
                    <div style="text-align:right"><div style="font-size:0.75rem;color:var(--text-muted)">${m.services_count} servicios</div></div>
                </div>`
            ).join('') || '<p class="text-center" style="padding:1rem;color:var(--text-muted)">Sin machos reproductores</p>';
        } catch(e) {}
    },

    async loadAnimalSelects() {
        try {
            const res = await API.get('/animals?per_page=500&status=active');
            const animals = res.data || [];
            const females = animals.filter(a => a.sex === 'female');
            const males = animals.filter(a => a.sex === 'male');

            document.getElementById('rAnimalId').innerHTML = '<option value="">Seleccionar hembra...</option>' +
                females.map(a => `<option value="${a.id}">${a.name || a.tag_id}</option>`).join('');
            document.getElementById('rMaleId').innerHTML = '<option value="">Sin registrar</option>' +
                males.map(a => `<option value="${a.id}">${a.name || a.tag_id}</option>`).join('');

            document.getElementById('kpiHeat').textContent = females.filter(f => f.reproductive_status === 'in_heat').length;
        } catch(e) {}
    },

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

    async save() {
        const data = {
            female_id: document.getElementById('rAnimalId').value,
            male_id: document.getElementById('rMaleId').value || null,
            event_type: document.getElementById('rEventType').value,
            event_date: document.getElementById('rDate').value,
            result: document.getElementById('rResult').value || null,
            notes: document.getElementById('rNotes').value || null,
        };

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

        try {
            await API.post('/reproduction', data);
            Toast.success('Evento reproductivo registrado');
            Modal.close('reproModal');
            this.loadData();
        } catch(e) {
            Toast.danger('Error al guardar');
        }
    }
};

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