@php
    $totalHours = $hourEnd - $hourStart; // 24
    $cellPx     = 48;   // px pro Stunde  (muss mit CELL_PX in calendar-week-canvas.js übereinstimmen)
    $totalPx    = $totalHours * $cellPx;
    $days       = [t('calendar.days.mo'), t('calendar.days.di'), t('calendar.days.mi'), t('calendar.days.do'), t('calendar.days.fr'), t('calendar.days.sa'), t('calendar.days.so')];
    $tz         = auth()->user()->timezone;
    $today      = now($tz)->toDateString();
    $nowLocal   = now($tz);

    // Named-Color-Palette (für Kompatibilität mit bestehenden Einträgen)
    $palette = [
        'indigo' => ['#EEF2FF', '#4F46E5', '#3730A3'],
        'green'  => ['#ECFDF5', '#10B981', '#065F46'],
        'amber'  => ['#FFFBEB', '#F59E0B', '#92400E'],
        'red'    => ['#FEF2F2', '#EF4444', '#991B1B'],
        'blue'   => ['#EFF6FF', '#3B82F6', '#1E40AF'],
        'purple' => ['#FAF5FF', '#9333EA', '#6B21A8'],
    ];

    /**
     * Liefert [$bg, $border, $text] für beliebige Farb-Werte:
     *   - Named key ('indigo', 'green', …) → Palette
     *   - Hex-String ('#4F46E5', '#abc')   → generierte RGBA-Töne
     *   - null / unbekannt                 → Primary-Fallback (#4F46E5)
     */
    $resolveColor = function (?string $color) use ($palette): array {
        if ($color && isset($palette[$color])) {
            return $palette[$color];
        }

        // Hex-Farbe (#rgb oder #rrggbb)
        if ($color && preg_match('/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/', $color)) {
            $hex = ltrim($color, '#');
            if (strlen($hex) === 3) {
                $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
            }
            $r = hexdec(substr($hex, 0, 2));
            $g = hexdec(substr($hex, 2, 2));
            $b = hexdec(substr($hex, 4, 2));

            // Solides Pastell: 18 % Farbe + 82 % Weiß → deckt dahinterliegende Events vollständig ab
            $bgR = (int) round(255 - (255 - $r) * 0.18);
            $bgG = (int) round(255 - (255 - $g) * 0.18);
            $bgB = (int) round(255 - (255 - $b) * 0.18);

            return [
                "rgb($bgR,$bgG,$bgB)", // solider Pastell-Hintergrund
                $color,                // Border: die Farbe selbst
                $color,                // Text: die Farbe selbst
            ];
        }

        // Default: Primary (passend zum Design-System)
        return ['rgb(236,237,253)', '#4F46E5', '#3730A3'];
    };
@endphp

<div x-data="weekCanvas"
     data-hour-start="{{ $hourStart }}"
     class="bg-white rounded-xl border border-gray-100 overflow-hidden select-none">

    {{-- ── Header ── --}}
    <div class="flex items-center justify-between px-4 py-3 border-b border-gray-100">
        <div class="flex items-center gap-2">
            <button wire:click="navigate('prev')"
                    class="w-7 h-7 flex items-center justify-center text-gray-400 hover:text-gray-600 border border-gray-200 rounded-md text-sm hover:bg-gray-50 transition-colors">‹</button>
            <span class="text-sm font-medium text-gray-800 min-w-[170px] text-center">
                {{ $this->titleString }}
            </span>
            <button wire:click="navigate('next')"
                    class="w-7 h-7 flex items-center justify-center text-gray-400 hover:text-gray-600 border border-gray-200 rounded-md text-sm hover:bg-gray-50 transition-colors">›</button>
        </div>
        <div class="flex items-center gap-2">
            <button wire:click="$set('currentDate', '{{ $today }}')"
                    class="px-3 py-1 text-xs text-gray-500 border border-gray-200 rounded-md hover:bg-gray-50 transition-colors">
                {{ t('calendar.today') }}
            </button>
            <div class="flex gap-0.5 bg-gray-100 rounded-lg p-1">
                @foreach(['month' => t('calendar.month'), 'week' => t('calendar.week'), 'day' => t('calendar.day')] as $v => $label)
                    <button wire:click="$set('view', '{{ $v }}')"
                            class="px-3 py-1 rounded-md text-xs font-medium transition-colors
                                {{ $view === $v ? 'bg-white text-indigo-600 shadow-sm' : 'text-gray-500 hover:text-gray-700' }}">
                        {{ $label }}
                    </button>
                @endforeach
            </div>
        </div>
    </div>

    {{-- ── Skeleton (sichtbar während Livewire-Request) ── --}}
    <div wire:loading wire:target="navigate, view, currentDate">
        @if($view === 'week')
            @include('livewire.calendar.skeletons.week')
        @elseif($view === 'day')
            @include('livewire.calendar.skeletons.day')
        @else
            @include('livewire.calendar.skeletons.month')
        @endif
    </div>

    {{-- ── Echter Inhalt (ausgeblendet während Livewire-Request) ── --}}
    <div wire:loading.remove wire:target="navigate, view, currentDate">

        {{-- ── Tagesspalten-Header (nur Wochenansicht) ── --}}
        @if($view === 'week')
        <div class="flex border-b border-gray-100">
            <div class="w-12 shrink-0"></div>
            @foreach($weekDays as $i => $day)
                <div class="flex-1 py-2 text-center {{ $i > 0 ? 'border-l border-gray-100' : '' }}">
                    <div class="text-[11px] text-gray-400 uppercase tracking-wide">{{ $days[$i] }}</div>
                    <div class="text-sm font-medium mx-auto w-7 h-7 flex items-center justify-center rounded-full mt-0.5
                        {{ $day->toDateString() === $today ? 'bg-indigo-600 text-white' : 'text-gray-700' }}">
                        {{ $day->day }}
                    </div>
                </div>
            @endforeach
        </div>
        @endif

        {{-- ── Ganztägige Events (nur Wochenansicht) ── --}}
        @if($view === 'week' && $hasAllDay)
            <div class="flex border-b border-gray-100 bg-gray-50/30">

                {{-- "ganzt." Label --}}
                <div class="w-12 shrink-0 flex items-start justify-end pt-2 pr-2">
                    <span class="text-[9px] text-gray-300 uppercase tracking-wider leading-none">{{ t('calendar.all_day') }}</span>
                </div>

                {{-- Einziger Container über alle 7 Spalten – Events absolute darin --}}
                <div class="flex-1 relative"
                     style="height: {{ $allDayHeight }}px"
                     x-ref="allDayStrip"
                     x-on:dragover.prevent="onAllDayDragOver($event)"
                     x-on:dragleave="onAllDayDragLeave($event)"
                     x-on:drop="onAllDayDrop($event)">

                    {{-- Spalten-Trennlinien als Hintergrund --}}
                    @foreach($weekDays as $colIndex => $day)
                        <div class="absolute top-0 bottom-0 {{ $colIndex > 0 ? 'border-l border-gray-100' : '' }}"
                             style="left: {{ ($colIndex / 7) * 100 }}%; width: {{ (1 / 7) * 100 }}%"
                             data-col="{{ $colIndex }}"
                             data-date="{{ $day->toDateString() }}"></div>
                    @endforeach

                    {{-- Drop-Preview Highlight --}}
                    <template x-if="allDayDropCol !== null">
                        <div class="absolute top-0 bottom-0 pointer-events-none z-50 rounded-sm"
                             x-bind:style="`left: calc(${allDayDropCol} / 7 * 100%); width: calc(1 / 7 * 100%); background: rgba(99,102,241,0.10); border: 1.5px dashed rgba(99,102,241,0.4);`">
                        </div>
                    </template>

                    {{-- All-Day Events – jeder als einzelner Block --}}
                    @foreach($allDayRows as $allDayEvent)
                        @php
                            [$bg, $border, $text] = $resolveColor($allDayEvent['color']);
                            $leftPct  = ($allDayEvent['startCol'] / 7) * 100;
                            $widthPct = (($allDayEvent['endCol'] - $allDayEvent['startCol'] + 1) / 7) * 100;
                            $topPx    = $allDayEvent['row'] * 26 + 4;

                            // Abgerundete Ecken: links wenn Start in dieser Woche, rechts wenn Ende in dieser Woche
                            $rLeft  = $allDayEvent['startsInWeek'] ? '4px' : '0';
                            $rRight = $allDayEvent['endsInWeek']   ? '4px' : '0';
                        @endphp

                        <div class="absolute flex items-center gap-1 overflow-hidden cursor-grab text-[10px] font-medium"
                             style="
                                left:         calc({{ $leftPct }}% + 2px);
                                width:        calc({{ $widthPct }}% - 4px);
                                top:          {{ $topPx }}px;
                                height:       22px;
                                padding:      0 6px;
                                background:   {{ $bg }};
                                color:        {{ $text }};
                                border-top:    1.5px solid {{ $border }};
                                border-bottom: 1.5px solid {{ $border }};
                                border-right:  1.5px solid {{ $allDayEvent['endsInWeek']   ? $border : 'transparent' }};
                                border-left:   1.5px solid {{ $allDayEvent['startsInWeek'] ? $border : 'transparent' }};
                                border-radius: {{ $rLeft }} {{ $rRight }} {{ $rRight }} {{ $rLeft }};
                             "
                             draggable="true"
                             wire:key="allday-{{ $allDayEvent['id'] }}"
                             x-on:dragstart="onAllDayDragStart($event, '{{ $allDayEvent['id'] }}', {{ $allDayEvent['startCol'] }}, '{{ $allDayEvent['startDate'] }}')"
                             x-on:dragend="onAllDayDragEnd($event)"
                             x-on:dblclick.stop="$wire.openSidebar('{{ $allDayEvent['id'] }}', '{{ $allDayEvent['startDate'] }}')">

                            @if(!$allDayEvent['startsInWeek'])
                                <span class="shrink-0 opacity-50" style="font-size:9px">‹</span>
                            @endif

                            <span class="truncate flex-1">
                                @if($allDayEvent['startTime'])
                                    <span class="opacity-60">{{ $allDayEvent['startTime'] }}–{{ $allDayEvent['endTime'] }}</span>
                                @endif
                                {{ $allDayEvent['title'] }}
                            </span>

                            @if(!$allDayEvent['endsInWeek'])
                                <span class="shrink-0 opacity-50 ml-auto" style="font-size:9px">›</span>
                            @endif
                        </div>
                    @endforeach

                </div>
            </div>
        @endif


        {{-- ── Scroll-Bereich (nur timed Events) ── --}}
        <div class="overflow-y-auto" style="max-height: 560px" x-ref="scrollarea">

            {{-- VIEW --}}
            @if($view === 'month')
                @include('livewire.calendar.views.month-canvas')
            @endif

            @if($view === 'week')
                @include('livewire.calendar.views.week-canvas')
            @endif

            @if($view === 'day')
                @include('livewire.calendar.views.day-canvas')
            @endif
        </div>

    </div>

    {{-- SIDEBAR --}}
    @livewire('calendar.sidebar')


</div>
