<?php
$blockBookings = $bookings ?? [];
$blockLeadId = (int)($lead_id ?? $leadId ?? 0);
$blockLead = $lead ?? null;

$statusBadgeMap = [
    'booked'      => 'bg-emerald-100 text-emerald-700 border-emerald-200',
    'completed'   => 'bg-blue-100 text-blue-700 border-blue-200',
    'cancelled'   => 'bg-rose-100 text-rose-700 border-rose-200',
    'rescheduled' => 'bg-amber-100 text-amber-700 border-amber-200',
    'no_show'     => 'bg-slate-100 text-slate-700 border-slate-200',
];

/**
 * Resolve the best available booking datetime value from a booking row.
 * Accepts legacy split columns (booking_date / start_time / ends_at) or unified columns (starts_at / ends_at)
 * or stored duration_minutes field, whichever are present, and produces:
 *   dateKey, dateReadable, dayOfWeek, startTime, endTime, durationMinutes, hasRange
 * all in an array so templates never see undefined keys.
 */
$bookingMeta = function(array $b): array {
    $startsAt    = $b['starts_at']    ?? null;
    $endsAt      = $b['ends_at']      ?? null;
    $bookingDate = $b['booking_date'] ?? null;
    $startTime   = $b['start_time']  ?? null;

    $rangeSt = null;
    if ($startsAt) {
        $rangeSt = $startsAt;
    } elseif ($bookingDate && $startTime) {
        $rangeSt = $bookingDate . ' ' . $startTime;
    } elseif ($bookingDate) {
        $rangeSt = $bookingDate;
    } elseif ($startTime) {
        $rangeSt = $startTime;
    }
    $rangeEn = $endsAt ?: null;

    $stTs = $rangeSt ? @strtotime($rangeSt) : false;
    $enTs = $rangeEn ? @strtotime($rangeEn) : false;

    $dateReadable = '—';
    $dayOfWeek    = '';
    $dateShort    = '—';
    $startTimeFmt = '—';
    $endTimeFmt   = '—';
    $durMin       = 0;

    if ($stTs) {
        $dateReadable = date('M j, Y', $stTs);
        $dayOfWeek    = date('l',    $stTs);
        $dateShort    = date('M j',  $stTs);
        $startTimeFmt = date('g:i A', $stTs);
    }
    if ($enTs) {
        $endTimeFmt = date('g:i A', $enTs);
    }
    if ($stTs && $enTs) {
        $durMin = (int)round(($enTs - $stTs) / 60);
    }
    if ($durMin <= 0 && !empty($b['duration_minutes'])) {
        $durMin = (int)$b['duration_minutes'];
    }

    return [
        'dateReadable' => $dateReadable,
        'dayOfWeek'    => $dayOfWeek,
        'dateShort'    => $dateShort,
        'startTime'    => $startTimeFmt,
        'endTime'      => $endTimeFmt,
        'durationMin'  => $durMin,
    ];
};

$latestBooking = null;
foreach ($blockBookings as $bb) {
    $st = $bb['status'] ?? '';
    if ($st === 'booked' || $st === 'rescheduled') {
        $latestBooking = $bb;
        break;
    }
}
if ($latestBooking === null && !empty($blockBookings)) {
    $latestBooking = $blockBookings[0];
}
?>

<div class="glass rounded-2xl border border-white/60 shadow-sm overflow-hidden">
    <div class="px-6 py-4 bg-gradient-to-r from-indigo-50/60 via-white to-violet-50/60 border-b border-slate-200/60">
        <div class="flex items-start justify-between gap-3 flex-wrap">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-indigo-500 to-violet-600 flex items-center justify-center flex-shrink-0 shadow-md shadow-indigo-500/20">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                    </svg>
                </div>
                <div>
                    <h3 class="font-bold text-slate-800 text-base">Bookings &amp; Assessments</h3>
                    <p class="text-xs text-slate-500"><?= count($blockBookings) ?> total assessment booking<?= count($blockBookings) !== 1 ? 's' : '' ?></p>
                </div>
            </div>
            <?php if ($blockLeadId > 0): ?>
                <a href="<?= esc(site_url('/agent/leads/book/' . $blockLeadId)) ?>"
                   class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold text-white bg-gradient-to-r from-indigo-600 to-violet-600 shadow-lg shadow-indigo-500/25 hover:shadow-xl hover:shadow-indigo-500/30 hover:-translate-y-0.5 active:translate-y-0 transition-all">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4" />
                    </svg>
                    Book Assessment
                </a>
            <?php endif; ?>
        </div>
    </div>

    <div class="p-6">
        <?php if (empty($blockBookings)): ?>
            <div class="py-10 text-center">
                <div class="mx-auto w-20 h-20 rounded-3xl bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center mb-5 border border-slate-200">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-10 h-10 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                    </svg>
                </div>
                <h4 class="text-base font-bold text-slate-800 mb-1.5">No assessments booked yet</h4>
                <p class="text-sm text-slate-500 mb-5 max-w-md mx-auto">Schedule an assessment to lock in a meeting time with this lead. Pick a schedule, date, and an available time slot.</p>
                <?php if ($blockLeadId > 0): ?>
                    <a href="<?= esc(site_url('/agent/leads/book/' . $blockLeadId)) ?>"
                       class="inline-flex items-center gap-2 px-6 py-3.5 rounded-xl text-sm font-bold text-white bg-gradient-to-r from-indigo-600 to-blue-600 shadow-xl shadow-indigo-500/25 hover:shadow-2xl hover:shadow-indigo-500/30 hover:-translate-y-0.5 active:translate-y-0 transition-all">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                        </svg>
                        Book an Assessment
                    </a>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <?php if ($latestBooking !== null):
                $latestStatus = strtolower((string)($latestBooking['status'] ?? 'booked'));
                $latestBadge = $statusBadgeMap[$latestStatus] ?? 'bg-slate-100 text-slate-700 border-slate-200';
                $latestMeta = $bookingMeta($latestBooking);
                $durMin = $latestMeta['durationMin'];
                $headerGrad = match ($latestStatus) {
                    'booked'      => 'from-emerald-500 to-teal-600',
                    'completed'   => 'from-blue-500 to-indigo-600',
                    'cancelled'   => 'from-rose-500 to-red-600',
                    'rescheduled' => 'from-amber-500 to-orange-600',
                    default       => 'from-slate-500 to-slate-700',
                };
            ?>
                <a href="<?= esc(site_url('/agent/bookings/view/' . (int)$latestBooking['id'])) ?>"
                   class="block rounded-2xl border-2 <?= $latestStatus === 'booked' ? 'border-emerald-200' : ($latestStatus === 'cancelled' ? 'border-rose-200' : 'border-slate-200') ?> overflow-hidden mb-5 hover:shadow-lg transition-all group">
                    <div class="bg-gradient-to-r <?= $headerGrad ?> px-5 py-3 flex items-center justify-between gap-3">
                        <div class="flex items-center gap-2 flex-wrap">
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z" />
                            </svg>
                            <span class="text-xs font-bold text-white uppercase tracking-wider">
                                <?= $latestStatus === 'booked' ? 'Next Scheduled' : ('Most Recent') ?>
                            </span>
                        </div>
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-white/25 text-white backdrop-blur-sm border border-white/20">
                            <?= esc(ucfirst($latestStatus)) ?>
                        </span>
                    </div>
                    <div class="p-5 bg-gradient-to-br from-white to-slate-50">
                        <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
                            <div>
                                <p class="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Date</p>
                                <p class="text-sm font-extrabold text-slate-800">
                                    <?= esc($latestMeta['dateReadable']) ?>
                                </p>
                                <p class="text-[11px] text-slate-400 font-medium">
                                    <?= esc($latestMeta['dayOfWeek']) ?>
                                </p>
                            </div>
                            <div>
                                <p class="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Time</p>
                                <p class="text-sm font-extrabold text-slate-800 font-mono">
                                    <?= esc($latestMeta['startTime']) ?>
                                </p>
                            </div>
                            <div>
                                <p class="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Duration</p>
                                <p class="text-sm font-extrabold text-slate-800"><?= $durMin > 0 ? $durMin . ' min' : '—' ?></p>
                            </div>
                            <div>
                                <p class="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Agent</p>
                                <p class="text-sm font-extrabold text-slate-800 truncate" title="<?= esc($latestBooking['assigned_name'] ?? $latestBooking['assigned_agent_name'] ?? $latestBooking['agent_name'] ?? '') ?>">
                                    <?= esc($latestBooking['assigned_name'] ?? $latestBooking['assigned_agent_name'] ?? $latestBooking['agent_name'] ?? '—') ?>
                                </p>
                            </div>
                        </div>
                    </div>
                </a>
            <?php endif; ?>

            <div>
                <p class="text-[11px] font-bold text-slate-400 uppercase tracking-wider mb-3">All Bookings</p>
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
                    <?php foreach ($blockBookings as $bb):
                        $bStatus = strtolower((string)($bb['status'] ?? 'booked'));
                        $bBadge = $statusBadgeMap[$bStatus] ?? 'bg-slate-100 text-slate-700 border-slate-200';
                        $bMeta = $bookingMeta($bb);
                    ?>
                        <a href="<?= esc(site_url('/agent/bookings/view/' . (int)($bb['id']))) ?>"
                           class="group relative rounded-xl border border-slate-200 hover:border-indigo-300 hover:shadow-md hover:bg-indigo-50/30 transition-all p-4 bg-white">
                            <div class="flex items-center justify-between gap-2 mb-2.5">
                                <p class="text-sm font-extrabold text-slate-800">
                                    <?= esc($bMeta['dateShort']) ?>
                                </p>
                                <span class="inline-flex px-2 py-0.5 rounded-lg text-[10px] font-bold border <?= $bBadge ?>">
                                    <?= esc(ucfirst($bStatus)) ?>
                                </span>
                            </div>
                            <p class="text-xs text-slate-600 font-mono mb-1.5">
                                <?= esc($bMeta['startTime']) ?>
                                <span class="text-slate-400 mx-0.5">–</span>
                                <?= esc($bMeta['endTime']) ?>
                            </p>
                            <?php if (!empty($bb['schedule_name'] ?? $bb['schedule_title'])): ?>
                                <p class="text-[11px] text-slate-400 font-medium truncate">
                                    <?= esc($bb['schedule_name'] ?? $bb['schedule_title']) ?>
                                </p>
                            <?php endif; ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>
