<x-admin-layout title="Agenda — OPCON">

@php
    $mesNome = \Carbon\Carbon::createFromDate($ano, $mes, 1)->translatedFormat('F Y');
    $primeiroDia = \Carbon\Carbon::createFromDate($ano, $mes, 1);
    $ultimoDia   = $primeiroDia->copy()->endOfMonth();
    $inicioGrid  = $primeiroDia->copy()->startOfWeek(\Carbon\Carbon::SUNDAY);
    $fimGrid     = $ultimoDia->copy()->endOfWeek(\Carbon\Carbon::SATURDAY);

    $tarefasPorDia = $tarefas->groupBy(fn($t) => $t->data->format('Y-m-d'));

    $tipoColors = [
        'tarefa'        => '#2563eb',
        'reuniao'       => '#7c3aed',
        'prazo_fiscal'  => '#dc2626',
        'lembrete'      => '#d97706',
    ];
    $tipoLabels = [
        'tarefa'        => 'Tarefa',
        'reuniao'       => 'Reunião',
        'prazo_fiscal'  => 'Prazo Fiscal',
        'lembrete'      => 'Lembrete',
    ];
    $prioColors = ['baixa' => '#64748b', 'media' => '#d97706', 'alta' => '#dc2626'];

    $mesPrev = $mes == 1  ? 12 : $mes - 1;
    $anoPrev = $mes == 1  ? $ano - 1 : $ano;
    $mesNext = $mes == 12 ? 1  : $mes + 1;
    $anoNext = $mes == 12 ? $ano + 1 : $ano;
@endphp

<div x-data="agendaPage()" x-init="init()">

    {{-- Header --}}
    <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:1.5rem; flex-wrap:wrap; gap:0.75rem;">
        <div>
            <h1 style="font-size:1.375rem; font-weight:700; color:#1e3a5f; margin:0;">Agenda</h1>
            <p style="font-size:0.8125rem; color:#64748b; margin:0.25rem 0 0;">Calendário de tarefas, reuniões e prazos fiscais</p>
        </div>
        <button @click="openCreate(null)"
                style="display:inline-flex; align-items:center; gap:0.5rem; padding:0.625rem 1.125rem; background:#1e3a5f; color:#fff; border:none; border-radius:10px; font-size:0.875rem; font-weight:600; cursor:pointer; font-family:inherit; transition:background 0.15s;"
                onmouseover="this.style.background='#162d4a'" onmouseout="this.style.background='#1e3a5f'">
            <svg style="width:16px;height:16px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
            </svg>
            Nova tarefa
        </button>
    </div>

    <style>
        .agenda-grid { display:grid; grid-template-columns:1fr 280px; gap:1.5rem; align-items:start; }
        @media (max-width:900px) { .agenda-grid { grid-template-columns:1fr; } }
    </style>

    <div class="agenda-grid">

        {{-- Calendar panel --}}
        <div style="background:#fff; border-radius:16px; border:1px solid #e2e8f0; overflow:hidden;">

            {{-- Month nav --}}
            <div style="display:flex; align-items:center; justify-content:space-between; padding:1rem 1.25rem; border-bottom:1px solid #f1f5f9;">
                <a href="{{ route('admin.agenda', ['mes' => $mesPrev, 'ano' => $anoPrev]) }}"
                   style="display:flex; align-items:center; justify-content:center; width:34px; height:34px; border-radius:8px; border:1px solid #e2e8f0; color:#64748b; text-decoration:none; transition:all 0.15s;"
                   onmouseover="this.style.background='#f8fafc'" onmouseout="this.style.background='transparent'">
                    <svg style="width:16px;height:16px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                    </svg>
                </a>
                <h2 style="font-size:1rem; font-weight:700; color:#1e3a5f; margin:0; text-transform:capitalize;">{{ $mesNome }}</h2>
                <a href="{{ route('admin.agenda', ['mes' => $mesNext, 'ano' => $anoNext]) }}"
                   style="display:flex; align-items:center; justify-content:center; width:34px; height:34px; border-radius:8px; border:1px solid #e2e8f0; color:#64748b; text-decoration:none; transition:all 0.15s;"
                   onmouseover="this.style.background='#f8fafc'" onmouseout="this.style.background='transparent'">
                    <svg style="width:16px;height:16px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                    </svg>
                </a>
            </div>

            {{-- Day headers --}}
            <div style="display:grid; grid-template-columns:repeat(7,1fr); border-bottom:1px solid #f1f5f9;">
                @foreach(['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'] as $dow)
                    <div style="padding:0.5rem; text-align:center; font-size:0.6875rem; font-weight:700; text-transform:uppercase; letter-spacing:0.05em; color:#94a3b8;">{{ $dow }}</div>
                @endforeach
            </div>

            {{-- Grid cells --}}
            <div style="display:grid; grid-template-columns:repeat(7,1fr);">
                @php $cursor = $inicioGrid->copy(); @endphp
                @while ($cursor <= $fimGrid)
                    @php
                        $key = $cursor->format('Y-m-d');
                        $isCurrentMonth = $cursor->month == $mes;
                        $isToday = $cursor->isToday();
                        $dayTasks = $tarefasPorDia->get($key, collect());
                        $dateStr = $key;
                        $dayNum = $cursor->day;
                    @endphp
                    <div style="min-height:90px; border-right:1px solid #f1f5f9; border-bottom:1px solid #f1f5f9; padding:0.375rem; position:relative; cursor:pointer; {{ !$isCurrentMonth ? 'background:#fafafa;' : '' }}"
                         @click="openCreate('{{ $dateStr }}')"
                         onmouseover="this.style.background='{{ $isCurrentMonth ? '#f8fffe' : '#f5f5f5' }}'"
                         onmouseout="this.style.background='{{ !$isCurrentMonth ? '#fafafa' : 'transparent' }}'">

                        <span style="display:inline-flex; align-items:center; justify-content:center; width:26px; height:26px; border-radius:50%; font-size:0.75rem; font-weight:{{ $isToday ? '700' : '500' }}; {{ $isToday ? 'background:#1e3a5f; color:#fff;' : ($isCurrentMonth ? 'color:#1e3a5f;' : 'color:#cbd5e1;') }}">
                            {{ $dayNum }}
                        </span>

                        @if($dayTasks->isNotEmpty())
                            <div style="margin-top:0.25rem; display:flex; flex-direction:column; gap:2px;">
                                @foreach($dayTasks->take(3) as $t)
                                    <div @click.stop="viewTask({{ $t->id }})"
                                         style="font-size:0.6875rem; font-weight:600; padding:2px 5px; border-radius:4px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; background:{{ $tipoColors[$t->tipo] ?? '#64748b' }}1a; color:{{ $tipoColors[$t->tipo] ?? '#64748b' }}; border-left:2px solid {{ $tipoColors[$t->tipo] ?? '#64748b' }}; cursor:pointer; {{ $t->status === 'concluida' ? 'opacity:0.5; text-decoration:line-through;' : '' }}"
                                         title="{{ $t->titulo }}">
                                        {{ Str::limit($t->titulo, 20) }}
                                    </div>
                                @endforeach
                                @if($dayTasks->count() > 3)
                                    <span style="font-size:0.625rem; color:#94a3b8; padding:0 5px;">+{{ $dayTasks->count() - 3 }} mais</span>
                                @endif
                            </div>
                        @endif
                    </div>
                    @php $cursor->addDay(); @endphp
                @endwhile
            </div>
        </div>

        {{-- Sidebar: upcoming + legend --}}
        <div style="display:flex; flex-direction:column; gap:1rem;">

            {{-- Upcoming tasks --}}
            <div style="background:#fff; border-radius:16px; border:1px solid #e2e8f0; overflow:hidden;">
                <div style="padding:0.875rem 1rem; border-bottom:1px solid #f1f5f9;">
                    <h3 style="font-size:0.875rem; font-weight:700; color:#1e3a5f; margin:0;">Próximas tarefas</h3>
                </div>
                <div style="max-height:400px; overflow-y:auto;">
                    @forelse($proximas as $t)
                        <div style="padding:0.625rem 1rem; border-bottom:1px solid #f8fafc; display:flex; align-items:flex-start; gap:0.625rem; cursor:pointer;"
                             @click="viewTask({{ $t->id }})"
                             onmouseover="this.style.background='#f8fafc'" onmouseout="this.style.background='transparent'">
                            <button @click.stop="toggleTask({{ $t->id }}, $event)"
                                    style="width:18px; height:18px; border-radius:50%; border:2px solid {{ $tipoColors[$t->tipo] ?? '#64748b' }}; background:transparent; cursor:pointer; flex-shrink:0; margin-top:1px; transition:all 0.15s;"
                                    title="Marcar como concluída"></button>
                            <div style="flex:1; min-width:0;">
                                <p style="font-size:0.8125rem; font-weight:600; color:#1e3a5f; margin:0; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">{{ $t->titulo }}</p>
                                <p style="font-size:0.6875rem; color:#94a3b8; margin:0.1rem 0 0;">
                                    {{ $t->data->format('d/m') }}{{ $t->hora ? ' às ' . substr($t->hora, 0, 5) : '' }}
                                    · <span style="color:{{ $tipoColors[$t->tipo] ?? '#64748b' }};">{{ $tipoLabels[$t->tipo] ?? $t->tipo }}</span>
                                </p>
                            </div>
                            <span style="font-size:0.625rem; font-weight:700; padding:2px 6px; border-radius:100px; background:{{ $prioColors[$t->prioridade] ?? '#64748b' }}1a; color:{{ $prioColors[$t->prioridade] ?? '#64748b' }};">
                                {{ ucfirst($t->prioridade) }}
                            </span>
                        </div>
                    @empty
                        <p style="padding:1.5rem; text-align:center; font-size:0.8125rem; color:#94a3b8;">Nenhuma tarefa pendente</p>
                    @endforelse
                </div>
            </div>

            {{-- Legend --}}
            <div style="background:#fff; border-radius:16px; border:1px solid #e2e8f0; padding:1rem;">
                <p style="font-size:0.75rem; font-weight:700; color:#94a3b8; text-transform:uppercase; letter-spacing:0.05em; margin:0 0 0.75rem;">Legenda</p>
                @foreach($tipoLabels as $key => $label)
                    <div style="display:flex; align-items:center; gap:0.5rem; margin-bottom:0.4rem;">
                        <span style="width:10px; height:10px; border-radius:2px; background:{{ $tipoColors[$key] }}; flex-shrink:0;"></span>
                        <span style="font-size:0.8125rem; color:#374151;">{{ $label }}</span>
                    </div>
                @endforeach
            </div>
        </div>
    </div>

    {{-- Modal: create/edit task --}}
    <div x-show="modal"
         x-transition:enter="transition ease-out duration-200"
         x-transition:enter-start="opacity-0"
         x-transition:enter-end="opacity-100"
         x-transition:leave="transition ease-in duration-150"
         x-transition:leave-start="opacity-100"
         x-transition:leave-end="opacity-0"
         @keydown.escape.window="modal=false"
         style="position:fixed; inset:0; background:rgba(15,23,42,0.5); backdrop-filter:blur(3px); z-index:200;">
    <div style="display:flex; align-items:center; justify-content:center; min-height:100%; width:100%; padding:1rem;">
        <div @click.stop
             x-transition:enter="transition ease-out duration-200"
             x-transition:enter-start="opacity-0 scale-95"
             x-transition:enter-end="opacity-100 scale-100"
             style="background:#fff; border-radius:16px; width:100%; max-width:480px; overflow:hidden; box-shadow:0 20px 60px rgba(0,0,0,0.2);">

            {{-- Modal header --}}
            <div style="display:flex; align-items:center; justify-content:space-between; padding:1.125rem 1.25rem; background:#1e3a5f;">
                <h3 x-text="editId ? 'Editar tarefa' : 'Nova tarefa'" style="font-size:1rem; font-weight:700; color:#fff; margin:0;"></h3>
                <button @click="modal=false" style="background:none; border:none; color:rgba(255,255,255,0.6); cursor:pointer; display:flex; padding:0.25rem; border-radius:6px;">
                    <svg style="width:18px;height:18px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>

            {{-- Modal body --}}
            <form @submit.prevent="saveTask()" style="padding:1.25rem; display:flex; flex-direction:column; gap:1rem;">

                <div>
                    <label style="display:block; font-size:0.75rem; font-weight:600; color:#374151; margin-bottom:0.375rem;">Título *</label>
                    <input x-model="form.titulo" type="text" placeholder="Ex: Enviar DCTF, Reunião com cliente..." required
                           style="width:100%; padding:0.625rem 0.75rem; border:1px solid #e2e8f0; border-radius:8px; font-size:0.875rem; font-family:inherit; color:#1e3a5f; outline:none; box-sizing:border-box;"
                           onfocus="this.style.borderColor='#1e3a5f'" onblur="this.style.borderColor='#e2e8f0'">
                </div>

                <div style="display:grid; grid-template-columns:1fr 1fr; gap:0.75rem;">
                    <div>
                        <label style="display:block; font-size:0.75rem; font-weight:600; color:#374151; margin-bottom:0.375rem;">Data *</label>
                        <input x-model="form.data" type="date" required
                               style="width:100%; padding:0.625rem 0.75rem; border:1px solid #e2e8f0; border-radius:8px; font-size:0.875rem; font-family:inherit; color:#1e3a5f; outline:none; box-sizing:border-box;"
                               onfocus="this.style.borderColor='#1e3a5f'" onblur="this.style.borderColor='#e2e8f0'">
                    </div>
                    <div>
                        <label style="display:block; font-size:0.75rem; font-weight:600; color:#374151; margin-bottom:0.375rem;">Hora</label>
                        <input x-model="form.hora" type="time"
                               style="width:100%; padding:0.625rem 0.75rem; border:1px solid #e2e8f0; border-radius:8px; font-size:0.875rem; font-family:inherit; color:#1e3a5f; outline:none; box-sizing:border-box;"
                               onfocus="this.style.borderColor='#1e3a5f'" onblur="this.style.borderColor='#e2e8f0'">
                    </div>
                </div>

                <div style="display:grid; grid-template-columns:1fr 1fr; gap:0.75rem;">
                    <div>
                        <label style="display:block; font-size:0.75rem; font-weight:600; color:#374151; margin-bottom:0.375rem;">Tipo *</label>
                        <select x-model="form.tipo" required
                                style="width:100%; padding:0.625rem 0.75rem; border:1px solid #e2e8f0; border-radius:8px; font-size:0.875rem; font-family:inherit; color:#1e3a5f; outline:none; background:#fff; box-sizing:border-box;">
                            <option value="tarefa">Tarefa</option>
                            <option value="reuniao">Reunião</option>
                            <option value="prazo_fiscal">Prazo Fiscal</option>
                            <option value="lembrete">Lembrete</option>
                        </select>
                    </div>
                    <div>
                        <label style="display:block; font-size:0.75rem; font-weight:600; color:#374151; margin-bottom:0.375rem;">Prioridade *</label>
                        <select x-model="form.prioridade" required
                                style="width:100%; padding:0.625rem 0.75rem; border:1px solid #e2e8f0; border-radius:8px; font-size:0.875rem; font-family:inherit; color:#1e3a5f; outline:none; background:#fff; box-sizing:border-box;">
                            <option value="baixa">Baixa</option>
                            <option value="media">Média</option>
                            <option value="alta">Alta</option>
                        </select>
                    </div>
                </div>

                <div>
                    <label style="display:block; font-size:0.75rem; font-weight:600; color:#374151; margin-bottom:0.375rem;">Descrição</label>
                    <textarea x-model="form.descricao" rows="3" placeholder="Detalhes adicionais..."
                              style="width:100%; padding:0.625rem 0.75rem; border:1px solid #e2e8f0; border-radius:8px; font-size:0.875rem; font-family:inherit; color:#1e3a5f; outline:none; resize:vertical; box-sizing:border-box;"
                              onfocus="this.style.borderColor='#1e3a5f'" onblur="this.style.borderColor='#e2e8f0'"></textarea>
                </div>

                <div x-show="errMsg" x-text="errMsg" style="font-size:0.8125rem; color:#dc2626; padding:0.5rem 0.75rem; background:#fef2f2; border-radius:8px;"></div>

                <div style="display:flex; justify-content:space-between; align-items:center; gap:0.75rem; padding-top:0.25rem;">
                    <button x-show="editId" type="button" @click="deleteTask()"
                            style="font-size:0.8125rem; color:#dc2626; background:none; border:1px solid #fecaca; border-radius:8px; padding:0.5rem 0.875rem; cursor:pointer; font-family:inherit; transition:all 0.15s;"
                            onmouseover="this.style.background='#fef2f2'" onmouseout="this.style.background='none'">
                        Excluir
                    </button>
                    <div style="display:flex; gap:0.625rem; margin-left:auto;">
                        <button type="button" @click="modal=false"
                                style="padding:0.5625rem 1rem; border:1px solid #e2e8f0; border-radius:8px; font-size:0.875rem; font-weight:500; color:#64748b; background:#fff; cursor:pointer; font-family:inherit;">
                            Cancelar
                        </button>
                        <button type="submit" :disabled="saving"
                                style="padding:0.5625rem 1.25rem; background:#1e3a5f; color:#fff; border:none; border-radius:8px; font-size:0.875rem; font-weight:600; cursor:pointer; font-family:inherit; transition:background 0.15s;"
                                onmouseover="if(!this.disabled)this.style.background='#162d4a'" onmouseout="if(!this.disabled)this.style.background='#1e3a5f'">
                            <span x-text="saving ? 'Salvando...' : (editId ? 'Salvar' : 'Criar tarefa')"></span>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>{{-- /centering --}}
</div>{{-- /overlay --}}

<script>
function agendaPage() {
    return {
        modal: false,
        saving: false,
        errMsg: '',
        editId: null,
        form: { titulo:'', data:'', hora:'', tipo:'tarefa', prioridade:'media', descricao:'' },

        init() {},

        openCreate(dateStr) {
            this.editId = null;
            this.errMsg = '';
            this.form = { titulo:'', data: dateStr || '', hora:'', tipo:'tarefa', prioridade:'media', descricao:'' };
            this.modal = true;
        },

        viewTask(id) {
            // fetch task data and open edit modal
            fetch(`/admin/agenda/${id}`, { headers: { 'Accept': 'application/json' } })
                .then(r => r.json())
                .then(data => {
                    if (!data.tarefa) return;
                    const t = data.tarefa;
                    this.editId = t.id;
                    this.errMsg = '';
                    this.form = {
                        titulo: t.titulo,
                        data: t.data,
                        hora: t.hora ? t.hora.slice(0,5) : '',
                        tipo: t.tipo,
                        prioridade: t.prioridade,
                        descricao: t.descricao || '',
                    };
                    this.modal = true;
                })
                .catch(() => {});
        },

        async toggleTask(id, event) {
            const btn = event.currentTarget;
            const res = await fetch(`/admin/agenda/${id}/toggle`, {
                method: 'PATCH',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content,
                    'Accept': 'application/json'
                }
            });
            const data = await res.json();
            if (data.ok && data.status === 'concluida') {
                btn.style.background = '#25b87e';
                btn.style.borderColor = '#25b87e';
                btn.closest('[style*="cursor"]').style.opacity = '0.5';
            }
        },

        async saveTask() {
            this.saving = true;
            this.errMsg = '';
            try {
                const url    = this.editId ? `/admin/agenda/${this.editId}` : '/admin/agenda';
                const method = this.editId ? 'PUT' : 'POST';
                const res = await fetch(url, {
                    method,
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content,
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify(this.form)
                });
                const data = await res.json();
                if (data.ok) {
                    this.modal = false;
                    window.location.reload();
                } else {
                    const errs = data.errors ? Object.values(data.errors).flat().join(' ') : 'Erro ao salvar.';
                    this.errMsg = errs;
                }
            } catch(e) {
                this.errMsg = 'Erro de conexão. Tente novamente.';
            } finally {
                this.saving = false;
            }
        },

        async deleteTask() {
            if (!confirm('Excluir esta tarefa?')) return;
            const res = await fetch(`/admin/agenda/${this.editId}`, {
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content,
                    'Accept': 'application/json'
                }
            });
            const data = await res.json();
            if (data.ok) {
                this.modal = false;
                window.location.reload();
            }
        }
    };
}
</script>

</x-admin-layout>
