@php
    $tz       = auth()->user()->timezone;
    $day      = \Carbon\Carbon::parse($currentDate, $tz);
    $today    = now($tz)->toDateString();
    $isToday  = $day->toDateString() === $today;
    $nowLocal = now($tz);
    $dayStr   = $day->toDateString();

    // Events für diesen Tag aufteilen
    $allDayEventsForDay = $events->filter(fn($e) =>
        $e->is_all_day
        && $e->starts_local->toDateString() <= $dayStr
        && ($e->ends_local ? $e->ends_local->toDateString() : $e->starts_local->toDateString()) >= $dayStr
    );

    // Mehrtägige Termine: alle Events die diesen Tag überspannen
    $timedDayEvents = $events->filter(function ($e) use ($dayStr) {
        if ($e->is_all_day) return false;
        $eStart = $e->starts_local->toDateString();
        $eEnd   = $e->ends_local ? $e->ends_local->toDateString() : $eStart;
        return $eStart <= $dayStr && $eEnd >= $dayStr;
    })->values();

    // Greedy-Tiefenzuweisung – identischer Algorithmus wie WeekCanvas
    $sorted     = $timedDayEvents->sortBy(fn($e) => $e->starts_local->hour * 60 + $e->starts_local->minute)->values();
    $assigned   = []; // ['start', 'end', 'depth']
    $dayLayouts = [];

    foreach ($sorted as $event) {
        $endLocalEvt = $event->ends_local ?? $event->starts_local->copy()->addHour();
        $startDec    = $event->starts_local->hour + $event->starts_local->minute / 60;
        $endDec      = min($endLocalEvt->hour + $endLocalEvt->minute / 60, 24.0);

        $usedDepths = [];
        foreach ($assigned as $a) {
            if ($startDec < $a['end'] && $endDec > $a['start']) {
                $usedDepths[] = $a['depth'];
            }
        }

        $depth = 0;
        while (in_array($depth, $usedDepths)) { $depth++; }

        $assigned[]              = ['start' => $startDec, 'end' => $endDec, 'depth' => $depth];
        $dayLayouts[$event->id]  = ['depth' => $depth];
    }
@endphp

{{-- ── Ganztägige Events (Tag-Ansicht) ── --}}
@if($allDayEventsForDay->isNotEmpty())
    <div class="flex border-b border-gray-100 bg-gray-50/30"
         x-on:dragover.prevent
         x-on:drop.prevent>
        <div class="w-12 shrink-0 flex items-center justify-end pr-2">
            <span class="text-[9px] text-gray-300 uppercase tracking-wider leading-none">{{ t('calendar.all_day') }}</span>
        </div>
        <div class="flex-1 py-1.5 flex flex-wrap gap-1 px-1">
            @foreach($allDayEventsForDay as $event)
                @php [$bg, $border, $text] = $resolveColor($event->color); @endphp
                <div class="text-[10px] font-medium px-2 py-0.5 rounded cursor-pointer"
                     style="background: {{ $bg }}; color: {{ $text }}; border: 1.5px solid {{ $border }};"
                     wire:key="day-allday-{{ $event->id }}"
                     x-on:dblclick="$wire.openSidebar('{{ $event->id }}', '{{ $dayStr }}')">
                    {{ $event->title }}
                </div>
            @endforeach
        </div>
    </div>
@endif

{{-- ── Zeitachse ── --}}
<div class="flex" style="min-height: {{ $hourEnd * $cellPx }}px">

    {{-- Zeit-Labels --}}
    <div class="w-12 shrink-0 relative" style="height: {{ $hourEnd * $cellPx }}px">
        @for($h = $hourStart; $h <= $hourEnd; $h++)
            <div class="absolute right-2 text-[10px] text-gray-300 -translate-y-2"
                 style="top: {{ ($h - $hourStart) * $cellPx }}px">
                @if($h < $hourEnd)
                    {{ str_pad($h, 2, '0', STR_PAD_LEFT) }}:00
                @endif
            </div>
        @endfor
    </div>

    {{-- Tagesspalte --}}
    <div class="flex-1 border-l border-gray-100 relative"
         style="height: {{ $hourEnd * $cellPx }}px"
         x-on:dragover="onDragOver($event)"
         x-on:dragleave="onDragLeave($event)"
         x-on:drop="onDrop($event, '{{ $dayStr }}')"
         x-on:dblclick.self="onCreateAt($event, '{{ $dayStr }}')"
         x-on:click.self="focusedEventId = null">

        {{-- Stunden-Linien --}}
        @for($h = $hourStart; $h < $hourEnd; $h++)
            <div class="absolute left-0 right-0 border-b border-gray-50 pointer-events-none"
                 style="top: {{ ($h - $hourStart) * $cellPx }}px; height: {{ $cellPx }}px"></div>
        @endfor

        {{-- 15-Minuten-Linien --}}
        @for($h = $hourStart; $h < $hourEnd; $h++)
            @for($q = 1; $q <= 3; $q++)
                <div class="absolute left-0 right-0 pointer-events-none"
                     style="top: {{ ($h - $hourStart) * $cellPx + $q * ($cellPx / 4) }}px;
                        border-top: 1px {{ $q === 2 ? 'dashed #f3f4f6' : 'solid #fafafa' }};"></div>
            @endfor
        @endfor

        {{-- Jetzt-Linie --}}
        @if($isToday)
            @php $nowPx = ($nowLocal->hour + $nowLocal->minute / 60 - $hourStart) * $cellPx; @endphp
            <div class="absolute left-0 right-0 z-20 pointer-events-none flex items-center"
                 style="top: {{ $nowPx }}px">
                <div class="w-2 h-2 rounded-full bg-indigo-500 shrink-0 -ml-1"></div>
                <div class="flex-1 border-t-2 border-indigo-500"></div>
            </div>
        @endif

        {{-- Events --}}
        @foreach($timedDayEvents as $event)
            @php
                $startLocal = $event->starts_local;
                $endLocal   = $event->ends_local ?? $startLocal->copy()->addHour();

                // Jeder Tag zeigt denselben Zeitslot (Original-Uhrzeit)
                $startDec = $startLocal->hour + $startLocal->minute / 60;
                $endDec   = min($endLocal->hour + $endLocal->minute / 60, 24);

                $topPx    = ($startDec - $hourStart) * $cellPx;
                $heightPx = max(($endDec - $startDec) * $cellPx - 2, $cellPx / 4);

                [$bg, $border, $text] = $resolveColor($event->color);

                $layout  = $dayLayouts[$event->id] ?? ['depth' => 0];
                $depth   = $layout['depth'];
                $leftPx  = $depth * 12 + 2;
                $zBase   = 10 + $depth;

                $endsHere = $endLocal->toDateString() === $dayStr;
            @endphp

            <div class="absolute rounded-md px-2 py-0.5 text-xs cursor-grab overflow-hidden transition-all duration-150"
                 style="top: {{ $topPx }}px; height: {{ $heightPx }}px;
                    left: {{ $leftPx }}px; right: 4px;
                    background: {{ $bg }}; border-left: 2px solid {{ $border }}; color: {{ $text }};
                    z-index: {{ $zBase }};"
                 draggable="true"
                 data-grab-date="{{ $dayStr }}"
                 wire:key="day-ev-{{ $event->id }}"
                 x-bind:class="{
                     'pointer-events-none': draggingId && draggingId !== '{{ $event->id }}'
                 }"
                 x-bind:style="focusedEventId === '{{ $event->id }}' ? { zIndex: 50, boxShadow: '0 4px 16px rgba(0,0,0,0.18)' } : {}"
                 x-on:click.stop="focusedEventId = (focusedEventId === '{{ $event->id }}' ? null : '{{ $event->id }}')"
                 x-on:dblclick.stop="$wire.openSidebar('{{ $event->id }}', '{{ $dayStr }}')"
                 x-on:dragstart="onDragStart($event, '{{ $event->id }}')"
                 x-on:dragend="onDragEnd($event)">

                <div class="font-medium truncate leading-tight pointer-events-none" style="font-size: 11px">
                    {{ $event->title }}
                </div>

                @if($heightPx >= 28)
                    <div class="leading-tight opacity-60 pointer-events-none" style="font-size: 10px">
                        {{ $startLocal->format('H:i') }}
                        @if($event->ends_local) – {{ $endLocal->format('H:i') }} @endif
                    </div>
                @endif

                {{-- Resize-Handle nur am letzten Tag --}}
                @if($endsHere)
                    <div class="absolute bottom-0 left-0 right-0 flex items-center justify-center cursor-ns-resize"
                         style="height: 8px"
                         x-on:mousedown.stop="onResizeStart($event, '{{ $event->id }}')">
                        <div class="w-5 rounded-full opacity-40 pointer-events-none"
                             style="height: 2px; background: {{ $border }}"></div>
                    </div>
                @endif
            </div>
        @endforeach

    </div>
</div>
