@extends('layouts.app')
@section('title', 'Calendar')
@section('breadcrumb')<span class="text-white">Calendar</span>@endsection

@section('content')
<div class="space-y-5" x-data="calendar()" x-init="init()">
    <!-- Header row -->
    <div class="flex items-center justify-between flex-wrap gap-3">
        <div><h1>Calendar</h1><p>Schedule appointments, deliveries, and installations</p></div>
        <div class="flex items-center gap-2 flex-wrap">
            <div class="flex rounded-lg overflow-hidden border border-slate-700">
                <button @click="viewMode='month'" :class="viewMode==='month' ? 'bg-blue-700 text-white' : 'bg-slate-800 text-slate-300 hover:bg-slate-700'" class="px-3 py-1.5 text-xs font-medium transition-colors">Month</button>
                <button @click="viewMode='week'"  :class="viewMode==='week'  ? 'bg-blue-700 text-white' : 'bg-slate-800 text-slate-300 hover:bg-slate-700'" class="px-3 py-1.5 text-xs font-medium transition-colors border-x border-slate-700">Week</button>
                <button @click="viewMode='day'"   :class="viewMode==='day'   ? 'bg-blue-700 text-white' : 'bg-slate-800 text-slate-300 hover:bg-slate-700'" class="px-3 py-1.5 text-xs font-medium transition-colors border-r border-slate-700">Day</button>
                <button @click="viewMode='team'"  :class="viewMode==='team'  ? 'bg-blue-700 text-white' : 'bg-slate-800 text-slate-300 hover:bg-slate-700'" class="px-3 py-1.5 text-xs font-medium transition-colors">Team</button>
            </div>
            <button @click="prev()" class="btn btn-secondary py-1.5 px-3"><i class="fas fa-chevron-left text-xs"></i></button>
            <button @click="goToday()" class="btn btn-secondary py-1.5 px-3 text-xs">Today</button>
            <button @click="next()" class="btn btn-secondary py-1.5 px-3"><i class="fas fa-chevron-right text-xs"></i></button>
        </div>
    </div>

    <!-- Period label -->
    <div class="text-white font-semibold text-lg" x-text="periodLabel"></div>

    <!-- Filters row -->
    <div class="flex flex-wrap gap-2 items-center">
        <button @click="activeType=''" :class="activeType==='' ? 'bg-blue-700 text-white' : 'bg-slate-800 text-slate-400 hover:bg-slate-700'" class="px-3 py-1 rounded-full text-xs font-medium transition-colors">All Types</button>
        @foreach([
            'check_measure'   => ['Check Measure','#60a5fa'],
            'delivery'        => ['Delivery','#fb923c'],
            'installation'    => ['Installation','#4ade80'],
            'consultation'    => ['Consultation','#f472b6'],
            'follow_up'       => ['Follow Up','#c084fc'],
            'appointment'     => ['Appointment','#fbbf24'],
            'processing'      => ['Processing','#2dd4bf'],
            'contracts_admin' => ['Contracts Admin','#818cf8'],
            'other'           => ['Other','#94a3b8'],
        ] as $type => [$label, $color])
        <button @click="activeType='{{ $type }}'" :class="activeType==='{{ $type }}' ? 'text-white ring-1 ring-white/30' : 'text-slate-400 hover:text-white'" class="px-3 py-1 rounded-full text-xs font-medium transition-colors flex items-center gap-1.5" style="background: {{ $color }}22;">
            <span class="w-2 h-2 rounded-full inline-block" style="background:{{ $color }};"></span>{{ $label }}
        </button>
        @endforeach
        <div class="ml-auto flex items-center gap-2" x-show="viewMode==='team' || viewMode==='week'">
            <span class="text-xs text-slate-500">Filter installer:</span>
            <select x-model="activeMember" class="input text-xs py-1 px-2" style="width:180px;">
                <option value="">All team members</option>
                @foreach($users as $user)
                <option value="{{ $user->id }}">{{ $user->name }}</option>
                @endforeach
            </select>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-4 gap-5">
        <!-- Calendar area -->
        <div class="lg:col-span-3">

            <!-- ═══ MONTH VIEW ═══ -->
            <div x-show="viewMode==='month'" class="card p-4">
                <div class="grid grid-cols-7 mb-1">
                    @foreach(['Mon','Tue','Wed','Thu','Fri','Sat','Sun'] as $d)
                    <div class="text-center text-xs text-slate-500 font-semibold py-1.5">{{ $d }}</div>
                    @endforeach
                </div>
                <div class="grid grid-cols-7 gap-px" style="background:#334155;">
                    <template x-for="day in monthDays" :key="day.key">
                        <div class="p-1 min-h-[90px] cursor-pointer transition-colors hover:bg-slate-700/40"
                             style="background:#1e293b;"
                             :class="{ 'opacity-40': !day.currentMonth, 'ring-inset ring-1 ring-blue-500': day.isToday }"
                             @click="selectDay(day)">
                            <div class="flex items-center justify-between mb-0.5">
                                <span class="text-xs font-medium w-6 h-6 flex items-center justify-center rounded-full"
                                      :class="day.isToday ? 'bg-blue-600 text-white' : (day.currentMonth ? 'text-slate-300' : 'text-slate-600')"
                                      x-text="day.date"></span>
                            </div>
                            <template x-for="event in filteredEvents(day.events).slice(0,3)" :key="event.id">
                                <div class="text-xs px-1.5 py-0.5 rounded mb-0.5 truncate"
                                     :style="`background:${event.color}33; color:${event.color}; border-left:2px solid ${event.color}`"
                                     x-text="event.title"></div>
                            </template>
                            <template x-if="filteredEvents(day.events).length > 3">
                                <div class="text-xs text-slate-500 px-1" x-text="`+${filteredEvents(day.events).length - 3} more`"></div>
                            </template>
                        </div>
                    </template>
                </div>
            </div>

            <!-- ═══ WEEK VIEW ═══ -->
            <div x-show="viewMode==='week'" class="card p-4 overflow-x-auto">
                <div class="grid gap-px min-w-[560px]" :style="`grid-template-columns: 56px repeat(7, 1fr);`" style="background:#334155;">
                    <div style="background:#1e293b;" class="p-2"></div>
                    <template x-for="day in weekDays" :key="day.key">
                        <div class="p-2 text-center" style="background:#1e293b;"
                             :class="day.isToday ? 'ring-inset ring-1 ring-blue-500' : ''">
                            <div class="text-xs text-slate-500 font-semibold" x-text="day.dayName"></div>
                            <div class="text-sm font-bold mt-0.5"
                                 :class="day.isToday ? 'text-blue-400' : 'text-slate-300'"
                                 x-text="day.date"></div>
                        </div>
                    </template>
                    <template x-for="hour in Array.from({length:12}, (_,i)=>i+8)" :key="hour">
                        <template x-if="true">
                            <div class="contents">
                                <div class="p-1 text-right" style="background:#1e293b;">
                                    <span class="text-xs text-slate-600" x-text="(hour%12||12)+(hour<12?'am':'pm')"></span>
                                </div>
                                <template x-for="day in weekDays" :key="day.key+'-'+hour">
                                    <div class="p-1 min-h-[50px]" style="background:#1e293b; border-top:1px solid #334155;">
                                        <template x-for="event in filteredEvents(day.events).filter(e=>parseInt(e.hour)===hour && (!activeMember || String(e.assigned_id)===String(activeMember)))">
                                            <div class="text-xs px-1.5 py-1 rounded mb-0.5 truncate"
                                                 :style="`background:${event.color}33; color:${event.color}; border-left:2px solid ${event.color}`"
                                                 x-text="event.title + (event.time ? ' '+event.time : '')"></div>
                                        </template>
                                    </div>
                                </template>
                            </div>
                        </template>
                    </template>
                </div>
            </div>

            <!-- ═══ DAY VIEW ═══ -->
            <div x-show="viewMode==='day'" class="card p-4">
                <template x-for="hour in Array.from({length:14}, (_,i)=>i+7)" :key="hour">
                    <div class="flex gap-3 border-b border-slate-800 py-2 min-h-[52px]">
                        <div class="w-14 text-right flex-shrink-0">
                            <span class="text-xs text-slate-600" x-text="(hour%12||12)+(hour<12?'am':'pm')"></span>
                        </div>
                        <div class="flex-1 space-y-1">
                            <template x-for="event in filteredEvents(dayEvents).filter(e=>parseInt(e.hour)===hour)" :key="event.id">
                                <div class="px-3 py-1.5 rounded text-sm"
                                     :style="`background:${event.color}22; color:${event.color}; border-left:3px solid ${event.color}`">
                                    <div class="font-medium" x-text="event.title"></div>
                                    <div class="text-xs opacity-70 mt-0.5" x-text="(event.location ? '📍 '+event.location+' · ' : '') + (event.assigned ? '👤 '+event.assigned : '')"></div>
                                </div>
                            </template>
                        </div>
                    </div>
                </template>
                <div x-show="filteredEvents(dayEvents).length===0" class="text-center py-12 text-slate-500">
                    <i class="fas fa-calendar-day text-3xl mb-2 block opacity-30"></i>
                    <p>No events on this day</p>
                </div>
            </div>

            <!-- ═══ TEAM / RESOURCE VIEW ═══ -->
            <div x-show="viewMode==='team'" class="card p-4 overflow-x-auto">
                <div class="mb-3 flex items-center gap-2">
                    <i class="fas fa-users text-blue-400 text-sm"></i>
                    <span class="text-sm font-semibold text-white">Team Schedule</span>
                    <span class="text-xs text-slate-500 ml-1" x-text="'Week of ' + weekDays[0]?.fullDate"></span>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full min-w-[700px]" style="border-collapse:collapse;">
                        <thead>
                            <tr style="background:#0f172a;">
                                <th class="text-left p-2 text-xs text-slate-500 font-semibold border-b border-slate-700" style="width:140px;">Team Member</th>
                                <template x-for="day in weekDays" :key="'th-'+day.key">
                                    <th class="p-2 text-center text-xs font-semibold border-b border-slate-700"
                                        :class="day.isToday ? 'text-blue-400' : 'text-slate-400'">
                                        <div x-text="day.dayName"></div>
                                        <div class="font-bold" x-text="day.date"></div>
                                    </th>
                                </template>
                            </tr>
                        </thead>
                        <tbody>
                            <template x-for="member in teamMembers" :key="'m-'+member.id">
                                <tr x-show="!activeMember || String(member.id) === String(activeMember)"
                                    style="border-bottom:1px solid #1e293b;">
                                    <td class="p-2 align-top" style="background:#1e293b;">
                                        <div class="flex items-center gap-2">
                                            <div class="w-7 h-7 rounded-full bg-blue-900 flex items-center justify-center text-xs font-bold text-blue-300 flex-shrink-0" x-text="member.initials"></div>
                                            <div>
                                                <div class="text-xs font-medium text-white" x-text="member.name"></div>
                                                <div class="text-xs text-slate-500" x-text="member.role"></div>
                                            </div>
                                        </div>
                                    </td>
                                    <template x-for="day in weekDays" :key="'cell-'+member.id+'-'+day.key">
                                        <td class="p-1 align-top min-w-[100px]" style="background:#1e293b; border-left:1px solid #0f172a;">
                                            <template x-for="event in filteredEvents(day.events).filter(e => String(e.assigned_id) === String(member.id))" :key="'ev-'+event.id">
                                                <div class="text-xs px-1.5 py-1 rounded mb-1"
                                                     :style="`background:${event.color}22; color:${event.color}; border-left:2px solid ${event.color}`">
                                                    <div class="font-medium truncate" x-text="event.title"></div>
                                                    <div class="opacity-60" x-text="event.time || 'All day'"></div>
                                                </div>
                                            </template>
                                            <template x-if="filteredEvents(day.events).filter(e => String(e.assigned_id) === String(member.id)).length === 0">
                                                <div class="text-center py-2 text-slate-700 text-xs">—</div>
                                            </template>
                                        </td>
                                    </template>
                                </tr>
                            </template>
                            <tr style="border-bottom:1px solid #1e293b;" x-show="!activeMember">
                                <td class="p-2 align-top" style="background:#1e293b;">
                                    <div class="flex items-center gap-2">
                                        <div class="w-7 h-7 rounded-full bg-slate-800 flex items-center justify-center text-xs text-slate-500 flex-shrink-0">?</div>
                                        <div class="text-xs font-medium text-slate-500">Unassigned</div>
                                    </div>
                                </td>
                                <template x-for="day in weekDays" :key="'un-'+day.key">
                                    <td class="p-1 align-top" style="background:#1e293b; border-left:1px solid #0f172a;">
                                        <template x-for="event in filteredEvents(day.events).filter(e => !e.assigned_id)" :key="'unev-'+event.id">
                                            <div class="text-xs px-1.5 py-1 rounded mb-1"
                                                 :style="`background:${event.color}22; color:${event.color}; border-left:2px solid ${event.color}`"
                                                 x-text="event.title"></div>
                                        </template>
                                    </td>
                                </template>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="mt-4 flex flex-wrap gap-3">
                    @foreach(['check_measure'=>['Check Measure','#60a5fa'],'delivery'=>['Delivery','#fb923c'],'installation'=>['Installation','#4ade80'],'consultation'=>['Consultation','#f472b6'],'appointment'=>['Appointment','#fbbf24'],'follow_up'=>['Follow Up','#c084fc'],'processing'=>['Processing','#2dd4bf'],'contracts_admin'=>['Contracts Admin','#818cf8'],'other'=>['Other','#94a3b8']] as $type=>[$label,$color])
                    <div class="flex items-center gap-1.5 text-xs text-slate-400">
                        <span class="w-2 h-2 rounded-full" style="background:{{ $color }};"></span>{{ $label }}
                    </div>
                    @endforeach
                </div>
            </div>
        </div>

        <!-- ═══ Sidebar ═══ -->
        <div class="space-y-4">
            <div class="card p-4">
                <h3 class="mb-3">Upcoming</h3>
                <div class="space-y-2">
                    @forelse($upcomingEvents->take(8) as $event)
                    @php $colors=['check_measure'=>'#60a5fa','delivery'=>'#fb923c','installation'=>'#4ade80','consultation'=>'#f472b6','follow_up'=>'#c084fc','processing'=>'#2dd4bf','contracts_admin'=>'#818cf8','other'=>'#94a3b8']; $c=$colors[$event->type]??'#94a3b8'; @endphp
                    <div class="flex gap-2 p-2 rounded" style="background:#0f172a;">
                        <div class="w-0.5 rounded-full flex-shrink-0 mt-1" style="background:{{ $c }};"></div>
                        <div class="min-w-0">
                            <div class="text-sm font-medium text-white truncate">{{ $event->title }}</div>
                            <div class="text-xs text-slate-500">{{ $event->start_at->format('D d M, g:ia') }}</div>
                            @if($event->assignedTo)<div class="text-xs text-slate-600">{{ $event->assignedTo->name }}</div>@endif
                        </div>
                    </div>
                    @empty
                    <p class="text-xs text-slate-500 py-2 text-center">No upcoming events</p>
                    @endforelse
                </div>
            </div>

            @auth
            <div class="card p-4">
                <h3 class="mb-3">Quick Add Event</h3>
                <form method="POST" action="{{ route('calendar.store') }}" class="space-y-3">
                    @csrf
                    <div>
                        <label>Title</label>
                        <input type="text" name="title" class="input w-full" required placeholder="e.g. Check measure — Smith">
                    </div>
                    <div>
                        <label>Type</label>
                        <select name="type" class="input w-full">
                            <option value="consultation">Consultation</option>
                            <option value="check_measure">Check Measure</option>
                            <option value="delivery">Delivery</option>
                            <option value="installation">Installation</option>
                            <option value="follow_up">Follow Up</option>
                            <option value="processing">Processing</option>
                            <option value="contracts_admin">Contracts Admin</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                    <div>
                        <label>Start</label>
                        <input type="datetime-local" name="start_at" class="input w-full" required>
                    </div>
                    <div>
                        <label>End (optional)</label>
                        <input type="datetime-local" name="end_at" class="input w-full">
                    </div>
                    <div>
                        <label>Location</label>
                        <input type="text" name="location" class="input w-full" placeholder="Address">
                    </div>
                    <div>
                        <label>Assign To</label>
                        <select name="assigned_to" class="input w-full">
                            <option value="">Anyone</option>
                            @foreach($users as $user)
                            <option value="{{ $user->id }}">{{ $user->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div>
                        <label>Job</label>
                        <select name="job_id" class="input w-full">
                            <option value="">— None —</option>
                            @foreach($jobs as $job)
                            <option value="{{ $job->id }}">{{ $job->job_number }} — {{ $job->contact?->full_name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary w-full justify-center">Add Event</button>
                </form>
            </div>
            @endauth
        </div>
    </div>
</div>

@push('scripts')
@php
$colorMap = [
    'check_measure'   => '#60a5fa',
    'delivery'        => '#fb923c',
    'installation'    => '#4ade80',
    'consultation'    => '#f472b6',
    'follow_up'       => '#c084fc',
    'appointment'     => '#fbbf24',
    'processing'      => '#2dd4bf',
    'contracts_admin' => '#818cf8',
    'other'           => '#94a3b8',
];

// ── Calendar events (from CalendarEvent model) ───────────────────────────
$calEvents = $events->map(fn($e) => [
    'id'          => 'evt-'.$e->id,
    'title'       => $e->title,
    'date'        => $e->start_at->format('Y-m-d'),
    'hour'        => (int) $e->start_at->format('G'),
    'time'        => $e->start_at->format('g:ia'),
    'type'        => $e->type,
    'color'       => $colorMap[$e->type] ?? '#94a3b8',
    'location'    => $e->location ?? '',
    'assigned'    => $e->assignedTo?->name ?? '',
    'assigned_id' => $e->assigned_to ?? null,
]);

// ── Appointments from leads ───────────────────────────────────────────────
$apptEvents = $appointments->map(fn($a) => [
    'id'          => 'appt-'.$a->id,
    'title'       => 'Appt: '.($a->lead?->contact?->full_name ?? 'Lead').($a->appointment_with ? ' ('.$a->appointment_with.')' : ''),
    'date'        => $a->appointment_date->format('Y-m-d'),
    'hour'        => $a->appointment_time ? (int)\Carbon\Carbon::createFromFormat('H:i:s', $a->appointment_time)->format('G') : 9,
    'time'        => $a->appointment_time ? \Carbon\Carbon::createFromFormat('H:i:s', $a->appointment_time)->format('g:ia') : '',
    'type'        => 'appointment',
    'color'       => '#fbbf24',
    'location'    => $a->appointment_location ?? '',
    'assigned'    => $a->lead?->contact?->full_name ?? '',
    'assigned_id' => null,
]);

// ── Follow-ups from leads ─────────────────────────────────────────────────
$fuEvents = $followUps->map(fn($f) => [
    'id'          => 'fu-'.$f->id,
    'title'       => 'Follow-up: '.($f->lead?->contact?->full_name ?? 'Lead').($f->follow_up_type ? ' ('.$f->follow_up_type.')' : ''),
    'date'        => $f->follow_up_date->format('Y-m-d'),
    'hour'        => $f->follow_up_time ? (int)\Carbon\Carbon::createFromFormat('H:i:s', $f->follow_up_time)->format('G') : 9,
    'time'        => $f->follow_up_time ? \Carbon\Carbon::createFromFormat('H:i:s', $f->follow_up_time)->format('g:ia') : '',
    'type'        => 'follow_up',
    'color'       => '#c084fc',
    'location'    => '',
    'assigned'    => $f->lead?->contact?->full_name ?? '',
    'assigned_id' => null,
]);

// ── Consult Booking ─────────────────────────────────────────────────
$consultEvents = $leads->map(fn($f) => [
    'id'          => 'Consult-'.$f->id,
    'title'       => 'Consult: '.($f?->contact?->full_name ?? 'Lead'),
    'date'        => $f->booking_date?->format('Y-m-d') ?? null,
    'type'        => 'consultation',
    'color'       => '#f472b6',
    'location'    => '',
    'assigned'    => $f?->contact?->full_name ?? '',
    'assigned_id' => null,
]);

$allCalEvents = $calEvents->concat($apptEvents)->concat($fuEvents)->concat($consultEvents)->values();

$teamMembers = $users->map(fn($u) => [
    'id'      => $u->id,
    'name'    => $u->name,
    'initials'=> strtoupper(substr($u->name, 0, 2)),
    'role'    => $u->role?->name ?? '',
]);
@endphp
<script>
function calendar() {
    const ALL_EVENTS   = @json($allCalEvents);
    const TEAM_MEMBERS = @json($teamMembers);
    return {
        current:       new Date(),
        viewMode:      'month',
        activeType:    '',
        activeMember:  '',
        newEventModal: false,
        teamMembers:   TEAM_MEMBERS,
        init() {},

        get periodLabel() {
            const opts = { month: 'long', year: 'numeric' };
            if (this.viewMode === 'month') return this.current.toLocaleDateString('en-AU', opts);
            if (this.viewMode === 'week' || this.viewMode === 'team') {
                const w = this.weekRange();
                return w[0].toLocaleDateString('en-AU', {day:'numeric',month:'short'}) + ' – ' +
                       w[6].toLocaleDateString('en-AU', {day:'numeric',month:'short',year:'numeric'});
            }
            return this.current.toLocaleDateString('en-AU', {weekday:'long',day:'numeric',month:'long',year:'numeric'});
        },

        filteredEvents(list) {
            if (!this.activeType) return list;
            return list.filter(e => e.type === this.activeType);
        },

        // ── Month ──────────────────────────────────────────────
        get monthDays() {
            const y = this.current.getFullYear(), m = this.current.getMonth();
            const first = new Date(y, m, 1), last = new Date(y, m+1, 0), today = new Date();
            let offset = first.getDay() - 1; if (offset < 0) offset = 6;
            const days = [];
            for (let i = offset-1; i >= 0; i--) {
                const d = new Date(y, m, -i);
                days.push({ key:'p'+i, date:d.getDate(), currentMonth:false, isToday:false, events:[] });
            }
            for (let i = 1; i <= last.getDate(); i++) {
                const d = new Date(y, m, i);
                const ds = d.toISOString().split('T')[0];
                days.push({ key:'c'+i, date:i, fullDate:ds, currentMonth:true, isToday:d.toDateString()===today.toDateString(), events: ALL_EVENTS.filter(e=>e.date===ds) });
            }
            const rem = 42 - days.length;
            for (let i = 1; i <= rem; i++) days.push({ key:'n'+i, date:i, currentMonth:false, isToday:false, events:[] });
            return days;
        },

        selectDay(day) {
            if (!day.currentMonth) return;
            this.current = new Date(day.fullDate);
            this.viewMode = 'day';
        },

        // ── Week (shared with Team) ────────────────────────────
        weekRange() {
            const d = new Date(this.current); const dow = (d.getDay() + 6) % 7;
            d.setDate(d.getDate() - dow);
            return Array.from({length:7}, (_, i) => { const x = new Date(d); x.setDate(d.getDate()+i); return x; });
        },
        get weekDays() {
            const today = new Date();
            return this.weekRange().map((d, i) => {
                const ds = d.toISOString().split('T')[0];
                return { key:'w'+i, dayName:['Mon','Tue','Wed','Thu','Fri','Sat','Sun'][i], date:d.getDate(), fullDate:ds, isToday:d.toDateString()===today.toDateString(), events: ALL_EVENTS.filter(e=>e.date===ds) };
            });
        },

        // ── Day ────────────────────────────────────────────────
        get dayEvents() {
            const ds = this.current.toISOString().split('T')[0];
            return ALL_EVENTS.filter(e => e.date === ds);
        },

        // ── Navigation ─────────────────────────────────────────
        prev() {
            const d = new Date(this.current);
            if (this.viewMode==='month') d.setMonth(d.getMonth()-1);
            else if (this.viewMode==='week' || this.viewMode==='team') d.setDate(d.getDate()-7);
            else d.setDate(d.getDate()-1);
            this.current = d;
        },
        next() {
            const d = new Date(this.current);
            if (this.viewMode==='month') d.setMonth(d.getMonth()+1);
            else if (this.viewMode==='week' || this.viewMode==='team') d.setDate(d.getDate()+7);
            else d.setDate(d.getDate()+1);
            this.current = d;
        },
        goToday() { this.current = new Date(); },
    };
}
</script>
@endpush
@endsection
