<?php
$pageTitle = $pageTitle ?? 'Invoice Deposit';
if (!Auth::isLoggedIn()) { redirect(base_url('login')); }
if (!isset($deposit) || !$deposit) {
    set_flash_message('deposit_history_error', 'Data invoice tidak valid.', 'error');
    redirect(base_url('deposit/history'));
}

$userBalance = $userBalance ?? 0;
$details = $deposit['payment_details_array'] ?? [];
$paymentNumber = $deposit['payment_number'] ?? $details['payment_number'] ?? null;
$qrCodeUrl = $deposit['qr_code_url'] ?? $details['qr_code_url'] ?? null;
$checkoutUrl = $deposit['checkout_url'] ?? $details['checkout_url'] ?? null;
$paymentGuide = $details['payment_guide'] ?? null;
$amountToPay = $details['amount_paydisini'] ?? $deposit['amount'];
$fee = $details['fee'] ?? 0;
$totalAmount = $amountToPay + $fee;
$methodName = $deposit['method_name'] ?? 'Metode Tidak Diketahui';
$methodLogo = $deposit['method_logo'] ?? null;

$expiredAtStringFromDb = $deposit['expired_at'] ?? null;
$expiredAtForJs = null;
$defaultTimezone = defined('DEFAULT_TIMEZONE') ? DEFAULT_TIMEZONE : 'UTC';

if ($expiredAtStringFromDb) {
    try {
        $serverTimezoneObj = new DateTimeZone($defaultTimezone);
        $dateTimeObj = new DateTime($expiredAtStringFromDb, $serverTimezoneObj);
        $expiredAtForJs = $dateTimeObj->getTimestamp() * 1000;
    } catch (Exception $e) {
        error_log("Error creating DateTime for expiredAt in invoice.php: " . $e->getMessage() . " | Value: " . $expiredAtStringFromDb . " | Timezone: " . $defaultTimezone);
        $expiredAtForJs = null; 
    }
}

$depositStatus = $deposit['status'] ?? 'pending';
$statusClass = getStatusBadgeClass($depositStatus);
$statusText = ucfirst($depositStatus);

$isExpired = false;
if ($expiredAtForJs) {
    if ( (time() * 1000) > $expiredAtForJs) {
        $isExpired = true;
    }
} else {
}

if ($isExpired && $depositStatus === 'pending') {
    $statusText = 'Expired';
    $statusClass = getStatusBadgeClass('canceled'); 
}

$depositId = $deposit['deposit_id'] ?? 'N/A';
$paydisiniUniqueCodeForJs = $deposit['paydisini_unique_code'] ?? null;

?>
<main class="flex-1 overflow-x-hidden overflow-y-auto p-4 md:p-8 bg-gradient-to-br from-slate-900 to-gray-800 min-h-screen">
    <div class="max-w-4xl mx-auto">
        <div class="flex flex-col sm:flex-row justify-between items-center mb-8">
            <h2 class="text-2xl sm:text-3xl font-bold text-white flex items-center">
                <i class="fas fa-file-invoice-dollar mr-3 text-purple-400"></i>
                Invoice #<span id="invoice-id-display"><?php echo htmlspecialchars($depositId); ?></span>
            </h2>
            <a href="<?php echo base_url('deposit/history'); ?>" class="mt-2 sm:mt-0 text-sm text-purple-300 hover:text-purple-200 hover:underline transition-colors duration-150">&larr; Kembali ke Riwayat</a>
        </div>

        <div class="bg-gray-800 shadow-2xl rounded-xl overflow-hidden border border-gray-700">
            <header class="bg-gradient-to-r from-purple-600 to-indigo-600 p-6 sm:p-8">
                <div class="flex flex-col sm:flex-row justify-between items-start text-white">
                    <div>
                        <h3 class="text-xl sm:text-2xl font-semibold">Detail Deposit Anda</h3>
                        <p class="text-xs sm:text-sm text-purple-200 mt-1">Dibuat pada: <?php echo htmlspecialchars(format_local_date($deposit['created_at'] ?? '', 'dd MMM yy, HH:mm')); ?></p>
                    </div>
                    <div class="mt-3 sm:mt-0 text-sm sm:text-right">
                        <span id="invoice-status-badge" class="px-3 py-1.5 inline-flex text-xs font-semibold rounded-full <?php echo $statusClass; ?> border-opacity-50 shadow-md">
                            STATUS: <?php echo htmlspecialchars(strtoupper($statusText)); ?>
                        </span>
                    </div>
                </div>
            </header>

            <div class="p-6 sm:p-8 space-y-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 text-gray-300">
                    <div class="bg-gray-700 p-4 rounded-lg shadow">
                        <p class="text-xs font-medium text-gray-400 mb-1 uppercase tracking-wider">Metode Pembayaran</p>
                        <div class="flex items-center">
                            <?php if ($methodLogo): ?>
                                <img src="<?php echo htmlspecialchars($methodLogo); ?>" alt="<?php echo htmlspecialchars($methodName); ?>" class="h-7 mr-2.5 object-contain bg-white p-0.5 rounded-sm">
                            <?php else: ?>
                                <i class="fas fa-credit-card text-gray-500 mr-2.5 text-lg"></i>
                            <?php endif; ?>
                            <p class="text-base font-semibold text-gray-100"><?php echo htmlspecialchars($methodName); ?></p>
                        </div>
                    </div>
                    <div class="bg-gray-700 p-4 rounded-lg shadow md:text-right">
                        <p class="text-xs font-medium text-gray-400 mb-1 uppercase tracking-wider">Jumlah Deposit</p>
                        <p class="text-lg font-semibold text-gray-100">Rp <?php echo number_format($deposit['amount'] ?? 0, 0, ',', '.'); ?></p>
                        <?php if (isset($deposit['bonus']) && $deposit['bonus'] > 0): ?>
                             <p class="text-xs text-green-400">+ Bonus Rp <?php echo number_format($deposit['bonus'], 0, ',', '.'); ?></p>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="bg-gradient-to-r from-purple-700 to-indigo-700 p-5 rounded-lg shadow-lg text-white">
                    <div class="flex justify-between items-center">
                        <p class="text-sm font-medium">Total Pembayaran</p>
                        <p class="text-2xl font-bold">Rp <?php echo number_format($totalAmount, 0, ',', '.'); ?></p>
                    </div>
                    <?php if ($fee > 0): ?>
                        <p class="text-xs text-purple-200 text-right mt-1">(Termasuk biaya Rp <?php echo number_format($fee, 0, ',', '.'); ?>)</p>
                    <?php endif; ?>
                </div>

                <div id="payment-instructions-container">
                    <?php if ($depositStatus === 'pending' && !$isExpired): ?>
                        <div class="text-center my-8 space-y-2">
                            <p class="text-sm text-gray-400">Selesaikan pembayaran dalam:</p>
                            <div id="countdown-timer" class="text-3xl font-bold text-red-400 bg-gray-700 px-4 py-3 rounded-lg inline-block border border-gray-600 shadow-inner" data-expired-at="<?php echo htmlspecialchars($expiredAtForJs ?? ''); ?>">
                                --:--:--
                            </div>
                        </div>

                        <div class="bg-gray-700 p-6 rounded-lg shadow space-y-6">
                            <h4 class="text-lg font-semibold text-gray-100 text-center border-b border-gray-600 pb-3">Instruksi Pembayaran</h4>

                            <?php if ($paymentNumber): ?>
                                <div class="space-y-2 text-center">
                                    <p class="text-sm text-gray-300">Nomor Pembayaran / Virtual Account:</p>
                                    <div class="flex justify-center items-center space-x-2">
                                        <strong id="payment-number-text" class="text-xl md:text-2xl font-mono text-purple-300 bg-gray-800 px-5 py-3 rounded-md border border-gray-600 select-all tracking-wider"><?php echo htmlspecialchars($paymentNumber); ?></strong>
                                        <button id="copy-payment-number" title="Salin Nomor" class="p-3 text-purple-300 bg-gray-600 hover:bg-purple-500 hover:text-white rounded-md transition-colors duration-150 focus:outline-none focus:ring-2 focus:ring-purple-400">
                                            <i class="far fa-copy text-lg"></i>
                                        </button>
                                    </div>
                                    <span id="copy-status" class="text-xs text-green-400 block mt-1 opacity-0 transition-opacity duration-300">Nomor berhasil disalin!</span>
                                </div>
                            <?php endif; ?>

                            <?php if ($qrCodeUrl): ?>
                                <div class="space-y-2 text-center">
                                    <p class="text-sm text-gray-300 pt-2"><?php echo $paymentNumber ? 'Atau s' : 'S'; ?>can QR Code:</p>
                                    <div class="flex justify-center">
                                        <img src="<?php echo htmlspecialchars($qrCodeUrl); ?>" alt="QR Code Pembayaran" class="max-w-[220px] w-full mx-auto my-2 border-4 border-gray-600 p-1.5 bg-white shadow-lg rounded-md">
                                    </div>
                                </div>
                            <?php endif; ?>
                             <?php if (!$paymentNumber && !$qrCodeUrl && !$checkoutUrl): ?>
                                 <p class="text-gray-400 italic text-center py-4">Instruksi pembayaran spesifik tidak tersedia. Silakan cek email atau hubungi support.</p>
                             <?php endif; ?>
                        </div>

                        <?php if ($paymentGuide && is_array($paymentGuide)): ?>
                            <div class="mt-8 pt-6 border-t border-gray-700 space-y-4">
                                 <h4 class="text-lg font-semibold text-gray-100 text-center mb-4">Panduan Pembayaran Rinci</h4>
                                 <div id="payment-guide-accordion" class="space-y-3">
                                     <?php foreach ($paymentGuide as $index => $guide): ?>
                                         <div class="bg-gray-700 rounded-lg shadow border border-gray-600">
                                             <button class="accordion-header flex justify-between items-center w-full p-4 text-left text-gray-200 hover:bg-gray-600 transition-colors duration-150 focus:outline-none" data-target="guide-content-<?php echo $index; ?>">
                                                 <span class="font-medium text-sm"><?php echo htmlspecialchars($guide['title'] ?? 'Panduan'); ?></span>
                                                 <i class="fas fa-chevron-down text-xs text-gray-400 transform transition-transform duration-300"></i>
                                             </button>
                                             <div id="guide-content-<?php echo $index; ?>" class="accordion-content max-h-0 overflow-hidden transition-max-height duration-500 ease-in-out">
                                                 <div class="p-4 border-t border-gray-600">
                                                     <ul class="list-decimal list-inside text-xs text-gray-300 space-y-1.5 pl-4">
                                                         <?php if (isset($guide['content']) && is_array($guide['content'])): ?>
                                                             <?php foreach ($guide['content'] as $step): ?>
                                                                 <li><?php echo htmlspecialchars($step); ?></li>
                                                             <?php endforeach; ?>
                                                         <?php endif; ?>
                                                     </ul>
                                                 </div>
                                             </div>
                                         </div>
                                     <?php endforeach; ?>
                                 </div>
                             </div>
                         <?php endif; ?>
                    <?php endif; ?>
                </div>

                <div id="payment-final-status-container" class="<?php echo ($depositStatus === 'pending' && !$isExpired) ? 'hidden' : ''; ?>">
                     <?php if ($depositStatus === 'success'): ?>
                        <div class="text-center p-8 bg-green-600 bg-opacity-20 border border-green-500 rounded-lg">
                            <i class="fas fa-check-circle text-5xl text-green-400 mb-4"></i>
                            <p class="text-xl font-semibold text-gray-100">Deposit Berhasil</p>
                            <p class="text-sm text-gray-300 mt-2">Saldo sejumlah Rp <?php echo number_format($deposit['received_amount'] ?? 0, 0, ',', '.'); ?> telah ditambahkan ke akun Anda.</p>
                            <a href="<?php echo base_url('dashboard'); ?>" class="inline-block mt-6 px-6 py-2.5 bg-purple-500 text-white text-sm font-medium rounded-md hover:bg-purple-400 transition-colors duration-150">Kembali ke Dashboard</a>
                        </div>
                    <?php elseif ($isExpired || in_array($depositStatus, ['failed', 'canceled', 'expired'])): ?>
                        <div class="text-center p-8 bg-red-600 bg-opacity-20 border border-red-500 rounded-lg">
                            <i class="fas fa-times-circle text-5xl text-red-400 mb-4"></i>
                            <p class="text-xl font-semibold text-gray-100">Deposit <?php echo htmlspecialchars($statusText); ?></p>
                            <p class="text-sm text-gray-300 mt-2">Deposit ini tidak dapat dilanjutkan. Silakan coba lagi atau hubungi dukungan jika masalah berlanjut.</p>
                            <a href="<?php echo base_url('deposit/new'); ?>" class="inline-block mt-6 px-6 py-2.5 bg-purple-500 text-white text-sm font-medium rounded-md hover:bg-purple-400 transition-colors duration-150">Buat Deposit Baru</a>
                        </div>
                    <?php endif; ?>
                </div>

            </div>
        </div>
    </div>
</main>

<style>
    .accordion-content {
        max-height: 0;
        overflow: hidden;
        transition: max-height 0.5s cubic-bezier(0, 1, 0, 1);
    }
    .accordion-content.open {
        max-height: 1000px; 
        transition: max-height 1s ease-in-out;
    }
    .accordion-header .fa-chevron-down {
        transition: transform 0.3s ease-in-out;
    }
    .accordion-header.active .fa-chevron-down {
        transform: rotate(180deg);
    }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const countdownElement = document.getElementById('countdown-timer');
    const expiredAtMsString = countdownElement?.dataset.expiredAt;
    const paydisiniUniqueCode = "<?php echo htmlspecialchars($paydisiniUniqueCodeForJs ?? '', ENT_QUOTES, 'UTF-8'); ?>";
    const initialStatus = "<?php echo htmlspecialchars($depositStatus ?? 'pending', ENT_QUOTES, 'UTF-8'); ?>";
    const isInitiallyExpired = <?php echo json_encode($isExpired); ?>;
    const initialReceivedAmount = <?php echo json_encode(floatval($deposit['received_amount'] ?? 0)); ?>;


    let countdownInterval;
    let statusCheckInterval;
    const POLLING_INTERVAL = 7000; 

    function updateCountdownDisplay(distance) {
        if (!countdownElement) return;
        if (distance < 0) {
            countdownElement.textContent = "Waktu Habis";
            countdownElement.classList.remove('text-red-400', 'bg-gray-700', 'border-gray-600');
            countdownElement.classList.add('text-gray-400', 'bg-gray-600', 'border-gray-500');
            return true;
        }
        const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((distance % (1000 * 60)) / 1000);
        countdownElement.textContent = `${hours}jam ${minutes < 10 ? '0' : ''}${minutes}menit ${seconds < 10 ? '0' : ''}${seconds}detik`;
        return false; 
    }

    if (countdownElement && expiredAtMsString && initialStatus === 'pending' && !isInitiallyExpired) {
        const expiredTimestamp = parseInt(expiredAtMsString);
        if (!isNaN(expiredTimestamp)) {
            const update = () => {
                const now = new Date().getTime();
                const distance = expiredTimestamp - now;
                const expired = updateCountdownDisplay(distance);
                if (expired) {
                    clearInterval(countdownInterval);
                    updateInvoiceStatus('expired', initialReceivedAmount);
                }
            };
            countdownInterval = setInterval(update, 1000);
            update();
        } else {
            countdownElement.textContent = "Error Waktu";
        }
    } else if (countdownElement && (initialStatus !== 'pending' || isInitiallyExpired)) {
         countdownElement.textContent = initialStatus === 'pending' && isInitiallyExpired ? "Waktu Habis" : "Tidak Aktif";
         if(isInitiallyExpired && initialStatus === 'pending') { // Hanya ubah style jika benar-benar expired dari awal
            countdownElement.classList.remove('text-red-400', 'bg-gray-700', 'border-gray-600');
            countdownElement.classList.add('text-gray-400', 'bg-gray-600', 'border-gray-500');
         }
    }


    function updateInvoiceStatus(newStatus, receivedAmount = 0) {
        const statusBadge = document.getElementById('invoice-status-badge');
        const paymentInstructionsContainer = document.getElementById('payment-instructions-container');
        const finalStatusContainer = document.getElementById('payment-final-status-container');

        if (!statusBadge || !paymentInstructionsContainer || !finalStatusContainer) return;

        const newStatusText = newStatus.charAt(0).toUpperCase() + newStatus.slice(1);
        const newStatusClass = getStatusBadgeClass(newStatus);

        statusBadge.textContent = `STATUS: ${newStatusText.toUpperCase()}`;
        statusBadge.className = `px-3 py-1.5 inline-flex text-xs font-semibold rounded-full ${newStatusClass} border-opacity-50 shadow-md`;

        if (newStatus === 'success') {
            paymentInstructionsContainer.innerHTML = ''; 
            paymentInstructionsContainer.classList.add('hidden');
            finalStatusContainer.innerHTML = `
                <div class="text-center p-8 bg-green-600 bg-opacity-20 border border-green-500 rounded-lg">
                    <i class="fas fa-check-circle text-5xl text-green-400 mb-4"></i>
                    <p class="text-xl font-semibold text-gray-100">Deposit Berhasil</p>
                    <p class="text-sm text-gray-300 mt-2">Saldo sejumlah Rp ${parseFloat(receivedAmount).toLocaleString('id-ID')} telah ditambahkan ke akun Anda.</p>
                    <a href="${BASE_URL}/dashboard" class="inline-block mt-6 px-6 py-2.5 bg-purple-500 text-white text-sm font-medium rounded-md hover:bg-purple-400 transition-colors duration-150">Kembali ke Dashboard</a>
                </div>`;
            finalStatusContainer.classList.remove('hidden');
            if (countdownInterval) clearInterval(countdownInterval);
            if (statusCheckInterval) clearInterval(statusCheckInterval);
        } else if (['failed', 'expired', 'canceled'].includes(newStatus)) {
            paymentInstructionsContainer.innerHTML = ''; 
            paymentInstructionsContainer.classList.add('hidden');
            finalStatusContainer.innerHTML = `
                <div class="text-center p-8 bg-red-600 bg-opacity-20 border border-red-500 rounded-lg">
                    <i class="fas fa-times-circle text-5xl text-red-400 mb-4"></i>
                    <p class="text-xl font-semibold text-gray-100">Deposit ${newStatusText}</p>
                    <p class="text-sm text-gray-300 mt-2">Deposit ini tidak dapat dilanjutkan.</p>
                    <a href="${BASE_URL}/deposit/new" class="inline-block mt-6 px-6 py-2.5 bg-purple-500 text-white text-sm font-medium rounded-md hover:bg-purple-400 transition-colors duration-150">Buat Deposit Baru</a>
                </div>`;
            finalStatusContainer.classList.remove('hidden');
            if (countdownInterval) clearInterval(countdownInterval);
            if (statusCheckInterval) clearInterval(statusCheckInterval);
            if (countdownElement && newStatus === 'expired') { 
                 countdownElement.textContent = "Waktu Habis";
                 countdownElement.classList.remove('text-red-400', 'bg-gray-700', 'border-gray-600');
                 countdownElement.classList.add('text-gray-400', 'bg-gray-600', 'border-gray-500');
            }
        } else if (newStatus === 'pending') {
             paymentInstructionsContainer.classList.remove('hidden');
             finalStatusContainer.classList.add('hidden');
        }
    }


    function checkDepositStatus() {
        if (!paydisiniUniqueCode || typeof BASE_URL === 'undefined') {
            if(statusCheckInterval) clearInterval(statusCheckInterval);
            return;
        }

        fetch(`${BASE_URL}/ajax/get_deposit_status?unique_code=${paydisiniUniqueCode}`)
            .then(response => response.json())
            .then(data => {
                if (data.success && data.status) {
                    const currentStatusOnPageElement = document.getElementById('invoice-status-badge');
                    const currentStatusOnPage = currentStatusOnPageElement ? currentStatusOnPageElement.textContent.replace('STATUS: ','').toLowerCase() : initialStatus;

                    if (data.status !== currentStatusOnPage) {
                        let receivedAmt = 0;
                        if (data.status === 'success') {
                             receivedAmt = initialReceivedAmount;
                        }
                        updateInvoiceStatus(data.status, receivedAmt);
                    }

                    if (data.status !== 'pending') {
                        clearInterval(statusCheckInterval);
                    }

                    if (data.expired_at && countdownElement) {
                        const serverExpiredTimestamp = new Date(data.expired_at.replace(' ', 'T') + 'Z').getTime();
                        const currentExpiredTimestamp = parseInt(countdownElement.dataset.expiredAt);

                        if (!isNaN(serverExpiredTimestamp) && currentExpiredTimestamp !== serverExpiredTimestamp) {
                            countdownElement.dataset.expiredAt = serverExpiredTimestamp;
                            if (countdownInterval) clearInterval(countdownInterval);

                            if (data.status === 'pending') {
                                const newExpiredTs = serverExpiredTimestamp;
                                const update = () => {
                                    const now = new Date().getTime();
                                    const distance = newExpiredTs - now;
                                    const expired = updateCountdownDisplay(distance);
                                    if (expired) {
                                        clearInterval(countdownInterval);
                                        updateInvoiceStatus('expired', initialReceivedAmount);
                                    }
                                };
                                countdownInterval = setInterval(update, 1000);
                                update();
                            }
                        }
                    }

                }
            })
            .catch(error => {
                console.error('Error checking deposit status:', error);
            });
    }

    if (initialStatus === 'pending' && !isInitiallyExpired && paydisiniUniqueCode) {
        statusCheckInterval = setInterval(checkDepositStatus, POLLING_INTERVAL);
        checkDepositStatus();
    } else {
        const paymentInstructionsContainer = document.getElementById('payment-instructions-container');
        const finalStatusContainer = document.getElementById('payment-final-status-container');
        if (paymentInstructionsContainer && finalStatusContainer) {
            if (initialStatus !== 'pending' || isInitiallyExpired) {
                paymentInstructionsContainer.classList.add('hidden');
                finalStatusContainer.classList.remove('hidden');
            }
        }
    }


    const copyButton = document.getElementById('copy-payment-number');
    const paymentNumberText = document.getElementById('payment-number-text');
    const copyStatusSpan = document.getElementById('copy-status');

    if (copyButton && paymentNumberText && copyStatusSpan) {
        copyButton.addEventListener('click', () => {
            const textToCopy = paymentNumberText.textContent.trim();
            navigator.clipboard.writeText(textToCopy).then(() => {
                copyStatusSpan.style.opacity = '1';
                setTimeout(() => {
                    copyStatusSpan.style.opacity = '0';
                }, 1500);
            }).catch(err => {
                console.error('Gagal menyalin: ', err);
                copyStatusSpan.textContent = 'Gagal menyalin';
                copyStatusSpan.classList.remove('text-green-400');
                copyStatusSpan.classList.add('text-red-400');
                copyStatusSpan.style.opacity = '1';
                setTimeout(() => {
                    copyStatusSpan.style.opacity = '0';
                     setTimeout(() => {
                         copyStatusSpan.textContent = 'Nomor berhasil disalin!';
                         copyStatusSpan.classList.add('text-green-400');
                         copyStatusSpan.classList.remove('text-red-400');
                     }, 300);
                }, 2000);
            });
        });
    }

    if (typeof getStatusBadgeClass === 'undefined') {
        function getStatusBadgeClass(status) {
            status = status ? status.toLowerCase() : '';
            switch (status) {
                case 'success': return 'bg-green-500 text-white';
                case 'processing': return 'bg-blue-500 text-white';
                case 'pending': return 'bg-yellow-400 text-gray-800';
                case 'error': case 'canceled': case 'expired': return 'bg-red-500 text-white';
                default: return 'bg-gray-500 text-white';
            }
        }
    }

     if (typeof formatLocalDate === 'undefined') {
         function formatLocalDate(dateString, format = 'dd MMM yy, HH:mm') {
             if (!dateString) return 'N/A';
             try {
                 const date = new Date(dateString.replace(' ', 'T') + 'Z');
                 if (isNaN(date.getTime())) {
                     return dateString;
                 }
                 const options = { day: '2-digit', month: 'short', year: 'numeric' };
                 if (format.includes('HH:mm')) {
                     options.hour = '2-digit';
                     options.minute = '2-digit';
                     options.hour12 = false;
                 }
                 let formattedDate = date.toLocaleDateString('id-ID', options);
                 if (format.includes('HH:mm')) {
                    formattedDate = formattedDate.replace(/\./g, ':');
                 }
                 return formattedDate;
             } catch (e) {
                 console.error("formatLocalDate Error:", e, "Input:", dateString);
                 return dateString;
             }
         }
     }

    const accordionHeaders = document.querySelectorAll('.accordion-header');
    accordionHeaders.forEach(header => {
        header.addEventListener('click', function() {
            const contentId = this.dataset.target;
            const contentElement = document.getElementById(contentId);
            const iconElement = this.querySelector('i.fa-chevron-down');

            if (contentElement) {
                const isOpen = contentElement.classList.contains('open');
                document.querySelectorAll('.accordion-content.open').forEach(openContent => {
                    if (openContent !== contentElement) {
                        openContent.classList.remove('open');
                        openContent.style.maxHeight = null;
                        const otherHeader = openContent.previousElementSibling;
                        if(otherHeader) otherHeader.classList.remove('active');
                        const otherIcon = otherHeader?.querySelector('i.fa-chevron-down');
                        if(otherIcon) otherIcon.classList.remove('rotate-180');
                    }
                });
                this.classList.toggle('active', !isOpen);
                contentElement.classList.toggle('open', !isOpen);
                if (!isOpen) {
                    contentElement.style.maxHeight = contentElement.scrollHeight + "px";
                } else {
                    contentElement.style.maxHeight = null;
                }
                if(iconElement) iconElement.classList.toggle('rotate-180', !isOpen);
            }
        });
    });
});
</script>
