@props([
    'activity_data' => [],
    'weeks'         => 52,
    'color'         => 'emerald',
])

@php
    // Build a 52-week × 7-day grid starting from the Monday 52 weeks ago
    $endDate   = \Carbon\Carbon::today();
    $startDate = $endDate->copy()->subWeeks($weeks)->startOfWeek(\Carbon\Carbon::MONDAY);

    // Build columns: each column = one week (Mon–Sun)
    $grid = [];
    $current = $startDate->copy();
    while ($current->lte($endDate)) {
        $week = [];
        for ($d = 0; $d < 7; $d++) {
            $dateStr = $current->format('Y-m-d');
            $count   = $activity_data[$dateStr] ?? 0;
            $week[]  = ['date' => $dateStr, 'count' => $count, 'future' => $current->gt($endDate)];
            $current->addDay();
        }
        $grid[] = $week;
    }

    // Color intensity helper
    $colorClass = function(int $count) use ($color): string {
        if ($count === 0) return 'bg-gray-100';
        if ($count <= 2)  return "bg-{$color}-200";
        if ($count <= 5)  return "bg-{$color}-400";
        return "bg-{$color}-600";
    };

    $dayLabels = ['M', '', 'W', '', 'F', '', ''];
@endphp

<div class="overflow-x-auto">
    <div class="flex gap-1 min-w-max">
        {{-- Day-of-week labels column --}}
        <div class="flex flex-col gap-1 mr-1 justify-start pt-0">
            @foreach($dayLabels as $label)
                <div class="w-3 h-3 flex items-center justify-center">
                    <span class="text-gray-400 text-[9px] leading-none">{{ $label }}</span>
                </div>
            @endforeach
        </div>

        {{-- Week columns --}}
        @foreach($grid as $week)
            <div class="flex flex-col gap-1">
                @foreach($week as $cell)
                    @if($cell['future'])
                        <div class="w-3 h-3 rounded-sm bg-transparent"></div>
                    @else
                        <div class="w-3 h-3 rounded-sm {{ $colorClass($cell['count']) }} transition-all duration-100 hover:ring-2 hover:ring-{{ $color }}-400 cursor-pointer"
                             title="{{ $cell['count'] }} contribution{{ $cell['count'] !== 1 ? 's' : '' }} on {{ $cell['date'] }}">
                        </div>
                    @endif
                @endforeach
            </div>
        @endforeach
    </div>

    {{-- Legend --}}
    <div class="flex items-center gap-1 mt-2 text-xs text-gray-500">
        <span>Less</span>
        <div class="w-3 h-3 rounded-sm bg-gray-100"></div>
        <div class="w-3 h-3 rounded-sm bg-{{ $color }}-200"></div>
        <div class="w-3 h-3 rounded-sm bg-{{ $color }}-400"></div>
        <div class="w-3 h-3 rounded-sm bg-{{ $color }}-600"></div>
        <span>More</span>
    </div>
</div>
