<div class="grid grid-cols-7 text-sm text-text-muted mb-2">
    @foreach(['Mo','Di','Mi','Do','Fr','Sa','So'] as $day)
        <div class="text-center font-semibold py-2">
            {{ $day }}
        </div>
    @endforeach
</div>

<div class="grid grid-cols-7 gap-3 bg-[radial-gradient(circle_at_top,rgba(99,102,241,0.06),transparent)] p-4 rounded-2xl">

    @php
        $tz = auth()->user()->timezone;

        $currentMonth = $date->copy()->startOfMonth();
        $start = $date->copy()->startOfMonth()->startOfWeek();
        $end = $date->copy()->endOfMonth()->endOfWeek();

        $period = \Carbon\CarbonPeriod::create($start, $end);
    @endphp

    @foreach ($period as $day)

        @php
            $key = $day->format('Y-m-d');
            $dayEvents = $events[$key] ?? collect();

            $isToday = $day->isSameDay(now($tz));
            $isCurrentMonth = $day->month === $currentMonth->month;
            $isWeekend = $day->isWeekend();
        @endphp

        {{-- 🔥 DAY CARD (DROP ZONE) --}}
{{--        <div--}}
{{--            x-data="{--}}
{{--        clickTimer: null,--}}
{{--        hoverRange: [],--}}
{{--        hovering: false,--}}
{{--        ...dropZone('{{ $key }}')--}}
{{--    }"--}}
        <div x-data="monthDropZone('{{ $key }}')"

            data-date="{{ $key }}"

            @dragenter.prevent="onEnter"
            @dragleave="onLeave"
            @dragover.prevent="onOver"
            @drop.prevent="onDrop"
            @dragend="
    $store.drag.id = null;
    $store.drag.range = [];
"
            :class="isInRange() ? 'ring-2 ring-primary border-primary bg-primary/5' : ''"
            class="#calendar-day relative bg-surface border border-border/60 rounded-2xl p-3 min-h-[115px] flex flex-col gap-2 cursor-pointer transition
                hover:border-primary hover:shadow-lg hover:-translate-y-[2px]
                {{ $isToday ? 'bg-primary/10 border-primary shadow-md' : '' }}
                {{ $isWeekend ? 'bg-red-50/30' : '' }}
                {{ !$isCurrentMonth ? 'opacity-40' : '' }}"

            {{-- CLICK --}}
            @click="
                clearTimeout(clickTimer);
                clickTimer = setTimeout(() => {
                    $wire.set('view', 'day');
                    $wire.set('date', '{{ $key }}');
                    $wire.loadEvents();
                }, 250);
            "

            {{-- DOUBLE CLICK --}}
            @dblclick="
                clearTimeout(clickTimer);
                $dispatch('sidebar:createEvent', { date: '{{ $key }}' });
            "
        >

            {{-- HEADER --}}
            <div class="relative flex justify-between pb-1 border-b border-border/40">
                <span class="text-xs font-bold {{ isset($holidays[$key]) ? 'text-red-500' : '' }}">
                    {{ $day->format('d') }}
                </span>

                @if($isToday)
                    <span class="text-[10px] text-primary font-semibold bg-primary/20 px-2 py-0.5 rounded-full">
                        Heute
                    </span>
                @endif
            </div>

            {{-- EVENTS --}}
            @php
                $count = $dayEvents->count();

                if ($count <= 2) {
                    $visibleEvents = $dayEvents;
                    $remainingCount = 0;
                } else {
                    $visibleEvents = $dayEvents->take(1);
                    $remainingCount = $count - 1;
                }
            @endphp

            @foreach($visibleEvents as $event)

                @php
                    $time = $event->getDisplayTimeForDate($key, $tz);
                    $start = $event->starts_at->copy()->setTimezone($tz)->startOfDay();
                    $current = \Carbon\Carbon::parse($key, $tz)->startOfDay();

                    $index = $start->diffInDays($current);

                @endphp

                {{-- 🔥 DRAGGABLE EVENT --}}
                <div
                    draggable="true"
                    wire:key="event-{{ $event->id }}-{{ $key }}"

{{--                    @dragstart="--}}
{{--        $store.drag.id = '{{ $event->id }}';--}}
{{--        $store.drag.index = {{ $index }};--}}
{{--        $store.drag.start = '{{ $event->starts_at->copy()->setTimezone($tz)->format('Y-m-d') }}';--}}
{{--        console.log('drag start', $store.drag);--}}
{{--    "--}}

{{--                    @dragstart="--}}
{{--    $store.drag = {--}}
{{--        id: '{{ $event->id }}',--}}
{{--        index: {{ $index }},--}}
{{--        start: '{{ $event->starts_at->copy()->setTimezone($tz)->format('Y-m-d') }}',--}}
{{--        title: '{{ addslashes($event->title) }}',--}}
{{--        color: '{{ $this->colorToRgba($event->color) }}',--}}
{{--        time: '{{ $time['start'] ? $time['start']->format('H:i') : '' }}'--}}
{{--    };--}}
{{--"--}}
                    @dragstart="
    $store.drag = {
        id: '{{ $event->id }}',
        index: {{ $index }},
        start: '{{ $event->starts_at->copy()->setTimezone($tz)->format('Y-m-d') }}',
        end: '{{ $event->ends_at?->copy()->setTimezone($tz)->format('Y-m-d') ?? $event->starts_at->copy()->setTimezone($tz)->format('Y-m-d') }}',
        title: '{{ addslashes($event->title) }}',
        color: '{{ $this->colorToRgba($event->color) }}',
        time: '{{ $time['start'] ? $time['start']->format('H:i') : '' }}'
    };
"
                    @dragend="$store.drag.id = null"

                    class="calendar-event max-w-fit text-[11px] text-white px-2 py-1.5 rounded-lg truncate shadow-sm cursor-move"
                    style="background-color: {{ $this->colorToRgba($event->color) }}"
                                    wire:click.stop="$dispatch('sidebar:openEvent', { eventId: '{{ $event->id }}', date: '{{ $key }}' })"
                >

                    @if(!$event->is_all_day)
                        @if($time['end'])
                            {{ $time['start']->format('H:i') }} - {{ $time['end']->format('H:i') }}
                        @else
                            {{ $time['start']->format('H:i') }}
                        @endif
                    @endif

                    {{ $event->title }}
                </div>


            @endforeach

            @if($remainingCount > 0)
                <div class="text-[10px] w-fit text-primary font-semibold px-2 py-1 bg-primary/10 rounded-md">
                    +{{ $remainingCount }} mehr
                </div>
            @endif
            <template x-if="$store.drag && isInRange()">
                <div
                    class="absolute left-2 right-2 top-10 z-20
               text-[11px] text-white px-2 py-1.5 rounded-lg shadow-sm
               opacity-40 pointer-events-none truncate"
{{--                    :style="'background-color: ' + ($store.drag.color || '#6366f1')"--}}
                >
{{--                    <span x-show="$store.drag.index === 0" x-text="$store.drag.title"></span>--}}
                </div>
            </template>

        </div>
    @endforeach
</div>

<script>
    function updateNowLine() {
        const hourHeight = 64;
        const headerOffset = 48;

        const now = new Date();

        const top =
            (now.getHours() * hourHeight) +
            ((now.getMinutes() / 60) * hourHeight) +
            headerOffset;

        const line = document.getElementById('now-line');
        const label = document.getElementById('now-label');

        if (line) line.style.top = top + 'px';

        if (label) {
            label.style.top = (top - 10) + 'px';
            label.innerText = now.toLocaleTimeString([], {
                hour: '2-digit',
                minute: '2-digit'
            });
        }
    }

    updateNowLine();
    setInterval(updateNowLine, 60000);
</script>

{{-- 🔥 DRAG SCRIPT --}}

{{--<script>--}}
{{--    document.addEventListener('alpine:init', () => {--}}

{{--        Alpine.store('drag', {--}}
{{--            id: null,--}}
{{--            index: 0,--}}
{{--            start: null,--}}
{{--            end: null,--}}
{{--            range: []--}}
{{--        });--}}

{{--        Alpine.data('dropZone', (date) => ({--}}

{{--            isValid() {--}}
{{--                let drag = Alpine.store('drag');--}}
{{--                return drag && drag.id && drag.start !== date;--}}
{{--            },--}}

{{--            buildRange() {--}}
{{--                let drag = Alpine.store('drag');--}}
{{--                if (!drag) return [];--}}

{{--                let target = new Date(date);--}}
{{--                target.setDate(target.getDate() - drag.index);--}}

{{--                let newStart = new Date(target);--}}

{{--                let start = new Date(drag.start);--}}
{{--                let end = new Date(drag.end);--}}

{{--                let diffDays = Math.floor((end - start) / (1000 * 60 * 60 * 24));--}}

{{--                let range = [];--}}

{{--                for (let i = 0; i <= diffDays; i++) {--}}
{{--                    let d = new Date(newStart);--}}
{{--                    d.setDate(d.getDate() + i);--}}
{{--                    range.push(d.toISOString().slice(0,10));--}}
{{--                }--}}

{{--                return range;--}}
{{--            },--}}

{{--            onEnter() {--}}
{{--                if (!this.isValid()) return;--}}

{{--                Alpine.store('drag').range = this.buildRange();--}}
{{--            },--}}

{{--            onLeave() {--}}
{{--                Alpine.store('drag').range = [];--}}
{{--            },--}}

{{--            onOver() {--}}
{{--                if (!this.isValid()) return;--}}

{{--                Alpine.store('drag').range = this.buildRange();--}}
{{--            },--}}

{{--            isInRange() {--}}
{{--                let drag = Alpine.store('drag');--}}
{{--                if (!drag || !drag.range) return false;--}}
{{--                return drag.range.includes(date);--}}
{{--            },--}}

{{--            onDrop() {--}}
{{--                Alpine.store('drag').range = [];--}}

{{--                let drag = Alpine.store('drag');--}}
{{--                if (!this.isValid()) return;--}}

{{--                let target = new Date(date);--}}
{{--                target.setDate(target.getDate() - drag.index);--}}

{{--                let finalDate = target.toISOString().slice(0,10);--}}

{{--                let component = this.$el.closest('[wire\\:id]');--}}
{{--                if (!component) return;--}}

{{--                Livewire.find(component.getAttribute('wire:id'))--}}
{{--                    .call('moveEventToDate', drag.id, finalDate);--}}
{{--            }--}}
{{--        }));--}}

{{--    });--}}
{{--</script>--}}




{{--<script>--}}
{{--    let calendarInitialized = false;--}}

{{--    function initCalendarDrag() {--}}

{{--        if (calendarInitialized) return;--}}
{{--        calendarInitialized = true;--}}

{{--        let dragged = null;--}}
{{--        let draggedId = null;--}}
{{--        let draggedIndex = 0;--}}
{{--        let preview = null;--}}
{{--        let currentDay = null;--}}

{{--        function cleanup() {--}}
{{--            if (preview) {--}}
{{--                preview.remove();--}}
{{--                preview = null;--}}
{{--            }--}}

{{--            document.querySelectorAll('.calendar-event')--}}
{{--                .forEach(el => el.classList.remove('opacity-30'));--}}

{{--            dragged = null;--}}
{{--            draggedId = null;--}}
{{--            currentDay = null;--}}
{{--        }--}}

{{--        // 🔥 DRAG START--}}
{{--        document.addEventListener('dragstart', e => {--}}

{{--            let el = e.target.closest('.calendar-event');--}}
{{--            if (!el) return;--}}

{{--            dragged = el;--}}
{{--            draggedId = el.dataset.id;--}}
{{--            draggedIndex = parseInt(el.dataset.index || 0);--}}

{{--            e.dataTransfer.setDragImage(new Image(), 0, 0);--}}

{{--            el.classList.add('opacity-30');--}}
{{--        });--}}

{{--        document.addEventListener('dragend', cleanup);--}}

{{--        // 🔥 SMOOTH PREVIEW (KEY FIX)--}}
{{--        document.addEventListener('dragover', e => {--}}

{{--            let day = e.target.closest('.calendar-day');--}}
{{--            if (!day || !dragged) return;--}}

{{--            e.preventDefault();--}}

{{--            // 👉 Nur wenn Day gewechselt wurde--}}
{{--            if (currentDay !== day) {--}}

{{--                currentDay = day;--}}

{{--                if (preview) preview.remove();--}}

{{--                preview = dragged.cloneNode(true);--}}

{{--                preview.classList.add(--}}
{{--                    'opacity-60',--}}
{{--                    'pointer-events-none',--}}
{{--                    'ring-2',--}}
{{--                    'ring-primary',--}}
{{--                    'shadow-xl'--}}
{{--                );--}}

{{--                preview.style.transform = 'scale(0.95)';--}}
{{--                preview.style.transition = 'all 0.15s ease';--}}

{{--                day.appendChild(preview);--}}
{{--            }--}}
{{--        });--}}

{{--        // 🔥 DROP--}}
{{--        document.addEventListener('drop', e => {--}}

{{--            let day = e.target.closest('.calendar-day');--}}
{{--            if (!day) return;--}}

{{--            e.preventDefault();--}}

{{--            if (!draggedId) return;--}}

{{--            let newDate = day.dataset.date;--}}
{{--            let originalStart = dragged.dataset.start;--}}

{{--            let finalDate;--}}

{{--            // 🔥 FIX: gleicher Tag → KEIN INDEX SHIFT--}}
{{--            if (newDate === originalStart) {--}}
{{--                finalDate = newDate;--}}
{{--            } else {--}}
{{--                let adjusted = new Date(newDate);--}}
{{--                adjusted.setDate(adjusted.getDate() - draggedIndex);--}}
{{--                finalDate = adjusted.toISOString().slice(0, 10);--}}
{{--            }--}}

{{--            // 🔥 zusätzlicher Guard--}}
{{--            if (originalStart === finalDate) {--}}
{{--                cleanup();--}}
{{--                return;--}}
{{--            }--}}

{{--            let component = day.closest('[wire\\:id]');--}}
{{--            if (!component) return;--}}

{{--            Livewire.find(component.getAttribute('wire:id'))--}}
{{--                .call('moveEventToDate', draggedId, finalDate);--}}

{{--            cleanup();--}}
{{--        });--}}
{{--    }--}}

{{--    document.addEventListener('DOMContentLoaded', initCalendarDrag);--}}


{{--</script>--}}
{{--<script>--}}
{{--    document.addEventListener('livewire:init', () => {--}}

{{--        let draggedEventId = null;--}}
{{--        let draggedIndex = 0;--}}

{{--        // 👉 Start dragging--}}
{{--        document.querySelectorAll('.calendar-event').forEach(el => {--}}
{{--            el.addEventListener('dragstart', e => {--}}
{{--                draggedEventId = el.dataset.id;--}}
{{--                draggedIndex = parseInt(el.dataset.index || 0);--}}
{{--            });--}}
{{--        });--}}

{{--        // 👉 Drop zones--}}
{{--        document.querySelectorAll('.calendar-day').forEach(day => {--}}

{{--            day.addEventListener('dragover', e => {--}}
{{--                e.preventDefault();--}}
{{--            });--}}

{{--            day.addEventListener('drop', e => {--}}
{{--                e.preventDefault();--}}

{{--                if (!draggedEventId) return;--}}

{{--                let newDate = day.dataset.date;--}}

{{--                // 🔥 EINZIGER FIX: INDEX berücksichtigen--}}
{{--                let adjusted = new Date(newDate);--}}
{{--                adjusted.setDate(adjusted.getDate() - draggedIndex);--}}

{{--                let finalDate = adjusted.toISOString().slice(0, 10);--}}

{{--                let component = day.closest('[wire\\:id]');--}}
{{--                if (!component) return;--}}

{{--                let livewireId = component.getAttribute('wire:id');--}}

{{--                Livewire.find(livewireId)--}}
{{--                    .call('moveEventToDate', draggedEventId, finalDate);--}}
{{--            });--}}
{{--        });--}}

{{--    });--}}


{{--    // document.addEventListener('DOMContentLoaded', () => {--}}
{{--    //--}}
{{--    //     let draggedEventId = null;--}}
{{--    //--}}
{{--    //     // 👉 Start dragging--}}
{{--    //     document.querySelectorAll('.calendar-event').forEach(el => {--}}
{{--    //         el.addEventListener('dragstart', e => {--}}
{{--    //             draggedEventId = el.dataset.id;--}}
{{--    //         });--}}
{{--    //     });--}}
{{--    //--}}
{{--    //     // 👉 Drop zones--}}
{{--    //     document.querySelectorAll('.calendar-day').forEach(day => {--}}
{{--    //--}}
{{--    //         day.addEventListener('dragover', e => {--}}
{{--    //             e.preventDefault();--}}
{{--    //         });--}}
{{--    //--}}
{{--    //         day.addEventListener('drop', e => {--}}
{{--    //             e.preventDefault();--}}
{{--    //--}}
{{--    //             if (!draggedEventId) return;--}}
{{--    //--}}
{{--    //             let newDate = day.dataset.date;--}}
{{--    //--}}
{{--    //             let component = day.closest('[wire\\:id]');--}}
{{--    //             if (!component) return;--}}
{{--    //--}}
{{--    //             let livewireId = component.getAttribute('wire:id');--}}
{{--    //--}}
{{--    //             Livewire.find(livewireId)--}}
{{--    //                 .call('moveEventToDate', draggedEventId, newDate);--}}
{{--    //         });--}}
{{--    //     });--}}
{{--    //--}}
{{--    // });--}}
{{--</script>--}}

{{--<div class="grid grid-cols-7 text-sm text-text-muted mb-2">--}}
{{--    @foreach(['Mo','Di','Mi','Do','Fr','Sa','So'] as $day)--}}
{{--        <div class="text-center font-semibold py-2">--}}
{{--            {{ $day }}--}}
{{--        </div>--}}
{{--    @endforeach--}}
{{--</div>--}}

{{--<div class="grid grid-cols-7 gap-3 bg-[radial-gradient(circle_at_top,rgba(99,102,241,0.06),transparent)] p-4 rounded-2xl">--}}

{{--    @php--}}
{{--        $tz = auth()->user()->timezone;--}}

{{--        $currentMonth = $date->copy()->startOfMonth();--}}

{{--        $start = $date->copy()->startOfMonth()->startOfWeek();--}}
{{--        $end = $date->copy()->endOfMonth()->endOfWeek();--}}
{{--    @endphp--}}

{{--    @php--}}
{{--        $period = \Carbon\CarbonPeriod::create($start, $end);--}}
{{--    @endphp--}}

{{--    @foreach ($period as $day)--}}
{{--    @for ($day = $start->copy(); $day <= $end; $day->addDay())--}}

{{--        @php--}}
{{--            $key = $day->format('Y-m-d');--}}
{{--            $dayEvents = $events[$key] ?? collect();--}}

{{--            $isToday = $day->isSameDay(now($tz));--}}
{{--            $isCurrentMonth = $day->month === $currentMonth->month;--}}
{{--            $isWeekend = $day->isWeekend();--}}
{{--        @endphp--}}

{{--        <div--}}
{{--            x-data="{ clickTimer: null }"--}}

{{--            --}}{{-- SINGLE CLICK → DAY VIEW --}}
{{--            @click="--}}
{{--        clearTimeout(clickTimer);--}}
{{--        clickTimer = setTimeout(() => {--}}
{{--            $wire.set('view', 'day');--}}
{{--            $wire.set('date', '{{ $key }}');--}}
{{--            $wire.loadEvents();--}}
{{--        }, 250);--}}
{{--    "--}}

{{--            --}}{{-- DOUBLE CLICK → CREATE EVENT --}}
{{--            @dblclick="--}}
{{--        clearTimeout(clickTimer);--}}
{{--        $dispatch('sidebar:createEvent', { date: '{{ $key }}' });--}}
{{--    "--}}

{{--            class="relative bg-surface border border-border/60 rounded-2xl p-3 min-h-[115px] flex flex-col gap-2 cursor-pointer transition--}}
{{--    hover:border-primary hover:shadow-lg hover:-translate-y-[2px]--}}
{{--    {{ $isToday ? 'bg-primary/10 border-primary shadow-md' : '' }}--}}
{{--    {{ $isWeekend ? 'bg-red-50/30' : '' }}--}}
{{--    {{ !$isCurrentMonth ? 'opacity-40' : '' }}"--}}
{{--        >--}}
{{--            --}}{{-- HEADER --}}
{{--            <div class="flex justify-between pb-1 border-b border-border/40">--}}

{{--                <span class="text-xs font-bold {{ isset($holidays[$key]) ? 'text-red-500' : '' }}">--}}
{{--                    {{ $day->format('d') }}--}}
{{--                </span>--}}

{{--                @if($isToday)--}}
{{--                    <span class="text-[10px] text-primary font-semibold bg-primary/20 px-2 py-0.5 rounded-full">--}}
{{--                        Heute--}}
{{--                    </span>--}}
{{--                @endif--}}
{{--            </div>--}}

{{--            --}}{{-- EVENTS --}}
{{--            @php--}}
{{--                $count = $dayEvents->count();--}}

{{--                if ($count <= 2) {--}}
{{--                    $visibleEvents = $dayEvents;--}}
{{--                    $remainingCount = 0;--}}
{{--                } else {--}}
{{--                    $visibleEvents = $dayEvents->take(1);--}}
{{--                    $remainingCount = $count - 1;--}}
{{--                }--}}
{{--            @endphp--}}

{{--            @foreach($visibleEvents as $event)--}}

{{--                @php--}}
{{--                    $time = $event->getDisplayTimeForDate($key, $tz);--}}
{{--                @endphp--}}

{{--                <div--}}
{{----}}
{{--                    wire:click.stop="$dispatch('openModal', { component: 'calendar.modals.event-modal', arguments: { eventId: '{{ $event->id }}', date: '{{ $key }}' } })"--}}
{{----}}
{{--                    wire:click.stop="$dispatch('sidebar:openEvent', { eventId: '{{ $event['id'] }}',  date: '{{ $key }}' })"--}}
{{--                    class="max-w-fit text-[11px] bg-[{!! $event->color !!}]790 text-white px-2 py-1.5 rounded-lg truncate shadow-sm"--}}
{{--                    style="background-color: {{ $this->colorToRgba($event->color) }}"--}}
{{--                >--}}

{{--                    @if(!$event->is_all_day)--}}

{{--                        @if($time['end'])--}}
{{--                            {{ $time['start']->format('H:i') }} - {{ $time['end']->format('H:i') }}--}}
{{--                        @else--}}
{{--                            {{ $time['start']->format('H:i') }}--}}
{{--                        @endif--}}

{{--                    @endif--}}

{{--                    {{ $event->title }}--}}

{{--                </div>--}}

{{--            @endforeach--}}

{{--            @if($remainingCount > 0)--}}
{{--                <div class="text-[10px] w-fit text-primary font-semibold px-2 py-1 bg-primary/10 rounded-md">--}}
{{--                    +{{ $remainingCount }} mehr--}}
{{--                </div>--}}
{{--            @endif--}}

{{--        </div>--}}

{{--    @endfor--}}
{{--    @endforeach--}}
{{--</div>--}}
