@props(['loan', 'compact' => false])
@php
    $steps = $loan->timelineSteps();
    $progress = $loan->durationProgressPercent();
    $daysLeft = $loan->daysRemaining();
    $interest = $loan->interestSummary();

    $startAt = $loan->disbursement_date ?? $loan->approval_date ?? $loan->application_date;
    $maturityAt = $loan->maturity_date
        ? $loan->maturity_date->copy()->endOfDay()
        : null;

    $startIso = $startAt?->toIso8601String();
    $maturityIso = $maturityAt?->toIso8601String();
    $countdownTone = $daysLeft === null
        ? 'navy'
        : ($daysLeft < 0 ? 'danger' : ($daysLeft <= 30 ? 'warn' : 'ok'));
@endphp
<div
    class="vfh-timeline {{ $compact ? 'vfh-timeline--compact' : '' }}"
    data-vfh-countdown
    @if($startIso) data-start="{{ $startIso }}" @endif
    @if($maturityIso) data-maturity="{{ $maturityIso }}" @endif
>
    <div class="vfh-timeline__meta">
        <div>
            <span class="vfh-timeline__meta-label">Loan duration</span>
            <strong>{{ $loan->tenor_months }} months</strong>
            @if($loan->disbursement_date && $loan->maturity_date)
                <span class="text-muted">
                    · {{ $loan->disbursement_date->format('d M Y') }}
                    → {{ $loan->maturity_date->format('d M Y') }} 23:59
                </span>
            @elseif($loan->maturity_date)
                <span class="text-muted">· matures {{ $loan->maturity_date->format('d M Y') }} 23:59</span>
            @endif
        </div>
        <div class="vfh-timeline__meta-right">
            @if($maturityIso)
                <div class="vfh-countdown vfh-countdown--{{ $countdownTone }}" data-countdown-display aria-live="polite">
                    <span class="vfh-countdown__label" data-countdown-label>
                        @if($daysLeft !== null && $daysLeft < 0)
                            Overdue
                        @else
                            Time remaining
                        @endif
                    </span>
                    <div class="vfh-countdown__units" data-countdown-units>
                        <span class="vfh-countdown__unit"><strong data-d>—</strong><small>days</small></span>
                        <span class="vfh-countdown__sep">:</span>
                        <span class="vfh-countdown__unit"><strong data-h>—</strong><small>hrs</small></span>
                        <span class="vfh-countdown__sep">:</span>
                        <span class="vfh-countdown__unit"><strong data-m>—</strong><small>min</small></span>
                        <span class="vfh-countdown__sep">:</span>
                        <span class="vfh-countdown__unit"><strong data-s>—</strong><small>sec</small></span>
                    </div>
                </div>
            @endif
            <span class="vfh-pill vfh-pill--navy" data-elapsed-pill>{{ number_format($progress, 0) }}% elapsed</span>
        </div>
    </div>

    <div class="vfh-progress" aria-hidden="true">
        <div class="vfh-progress__bar" data-progress-bar style="width: {{ min(100, $progress) }}%"></div>
    </div>

    <ol class="vfh-steps">
        @foreach($steps as $step)
            @php
                $stepDate = !empty($step['date']) ? \Illuminate\Support\Carbon::parse($step['date']) : null;
                $isMaturity = ($step['key'] ?? '') === 'maturity';
                if ($stepDate && $isMaturity) {
                    $stepDate = $stepDate->copy()->endOfDay();
                }
            @endphp
            <li class="vfh-steps__item {{ !empty($step['done']) ? 'is-done' : '' }} {{ !empty($step['danger']) ? 'is-danger' : '' }}">
                <span class="vfh-steps__dot"></span>
                <span class="vfh-steps__label">{{ $step['label'] }}</span>
                <span class="vfh-steps__date">
                    @if($stepDate)
                        {{ $stepDate->format('d M Y') }}
                        <span class="vfh-steps__time">{{ $stepDate->format('H:i') }}</span>
                    @else
                        —
                    @endif
                </span>
            </li>
        @endforeach
    </ol>

    <div class="vfh-interest">
        <div class="vfh-interest__item">
            <span>Rate</span>
            <strong>{{ rtrim(rtrim(number_format($interest['rate'], 2), '0'), '.') }}% {{ $interest['method'] ? '· '.ucfirst($interest['method']) : '' }}</strong>
        </div>
        <div class="vfh-interest__item">
            <span>Interest accrued</span>
            <strong>{{ money($interest['accrued_estimate']) }}</strong>
        </div>
        <div class="vfh-interest__item">
            <span>Interest paid</span>
            <strong>{{ money($interest['paid']) }}</strong>
        </div>
        <div class="vfh-interest__item">
            <span>Interest outstanding</span>
            <strong>{{ money($interest['outstanding']) }}</strong>
        </div>
    </div>
</div>

@once
<script>
(function () {
    function pad(n) { return String(Math.max(0, n)).padStart(2, '0'); }

    function partsFromMs(ms) {
        var abs = Math.abs(ms);
        var totalSec = Math.floor(abs / 1000);
        return {
            overdue: ms < 0,
            days: Math.floor(totalSec / 86400),
            hours: Math.floor((totalSec % 86400) / 3600),
            minutes: Math.floor((totalSec % 3600) / 60),
            seconds: totalSec % 60,
        };
    }

    function tick(root) {
        var maturity = root.getAttribute('data-maturity');
        if (!maturity) return;
        var end = new Date(maturity).getTime();
        if (Number.isNaN(end)) return;

        var now = Date.now();
        var diff = end - now;
        var p = partsFromMs(diff);
        var label = root.querySelector('[data-countdown-label]');
        var display = root.querySelector('[data-countdown-display]');
        var d = root.querySelector('[data-d]');
        var h = root.querySelector('[data-h]');
        var m = root.querySelector('[data-m]');
        var s = root.querySelector('[data-s]');

        if (d) d.textContent = String(p.days);
        if (h) h.textContent = pad(p.hours);
        if (m) m.textContent = pad(p.minutes);
        if (s) s.textContent = pad(p.seconds);
        if (label) label.textContent = p.overdue ? 'Overdue by' : 'Time remaining';

        if (display) {
            display.classList.remove('vfh-countdown--ok', 'vfh-countdown--warn', 'vfh-countdown--danger', 'vfh-countdown--navy');
            var tone = 'ok';
            if (p.overdue) tone = 'danger';
            else if (p.days <= 30) tone = 'warn';
            display.classList.add('vfh-countdown--' + tone);
        }

        var startAttr = root.getAttribute('data-start');
        if (startAttr) {
            var start = new Date(startAttr).getTime();
            if (!Number.isNaN(start) && end > start) {
                var pct = Math.min(100, Math.max(0, ((now - start) / (end - start)) * 100));
                var bar = root.querySelector('[data-progress-bar]');
                var pill = root.querySelector('[data-elapsed-pill]');
                if (bar) bar.style.width = pct.toFixed(1) + '%';
                if (pill) pill.textContent = Math.round(pct) + '% elapsed';
            }
        }
    }

    function boot() {
        var roots = document.querySelectorAll('[data-vfh-countdown][data-maturity]');
        if (!roots.length) return;
        function refresh() { roots.forEach(tick); }
        refresh();
        if (window.__vfhCountdownTimer) clearInterval(window.__vfhCountdownTimer);
        window.__vfhCountdownTimer = setInterval(refresh, 1000);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', boot);
    } else {
        boot();
    }
})();
</script>
@endonce
