/**
 * Real-time HPL Calculator
 * Dipanggil saat field HPHT berubah
 */
document.addEventListener('DOMContentLoaded', function () {
    const hphtInput = document.getElementById('hpht');
    if (!hphtInput) return;
    hphtInput.addEventListener('change', hitungDariHPHT);
});

function hitungDariHPHT() {
    const hpht = document.getElementById('hpht').value;
    if (!hpht) return;

    // Hitung HPL: HPHT + 280 hari
    const tglHPHT = new Date(hpht);
    const tglHPL  = new Date(tglHPHT);
    tglHPL.setDate(tglHPL.getDate() + 280);

    // Format: DD-MM-YYYY untuk tampilan, YYYY-MM-DD untuk value
    const hplFormatted = tglHPL.toLocaleDateString('id-ID', {
        day:'2-digit', month:'long', year:'numeric'
    });
    
    const hplDisplay = document.getElementById('hpl_display');
    if(hplDisplay) hplDisplay.value  = hplFormatted;
    
    const hplHidden = document.getElementById('hpl_hidden');
    if(hplHidden) hplHidden.value   = tglHPL.toISOString().split('T')[0];

    // Usia kehamilan
    const today    = new Date();
    const diffTime = today - tglHPHT;
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
    const minggu   = Math.floor(diffDays / 7);
    const sisa     = diffDays % 7;
    
    const usiaKehamilan = document.getElementById('usia_kehamilan');
    if(usiaKehamilan) {
        if(diffDays < 0) {
            usiaKehamilan.value = "HPHT di masa depan";
        } else {
            usiaKehamilan.value = minggu + ' minggu ' + sisa + ' hari';
        }
    }

    // Trimester
    let trimester = '3';
    if (minggu <= 13) trimester = '1';
    else if (minggu <= 26) trimester = '2';
    
    const trimesterInput = document.getElementById('trimester');
    if(trimesterInput) trimesterInput.value = 'Trimester ' + trimester;
}
