@extends('layouts.master')

@section('title', 'Diary Calendar')

@push('styles')
<!-- FullCalendar CSS v6.1.4 -->
<link href='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.4/index.global.min.css' rel='stylesheet' />
<link href="https://fonts.googleapis.com/css2?family=Lora:wght@400;600;700&family=Outfit:wght@300;400;500;600&display=swap" rel="stylesheet">
<style>
/* ══ SHARED TOKENS ══ */
:root {
    --ink:        #0f1923;
    --ink-soft:   #3a4a5c;
    --ink-muted:  #7a8fa6;
    --paper:      #f6fafd;
    --surface:    #ffffff;
    --rule:       #dce8f2;
    --rule-strong:#b8d0e8;
    --blue:       #1d6fce;
    --blue-light: #2d87f0;
    --blue-pale:  #e8f2fd;
    --blue-deep:  #124fa0;
    --blue-grad:  linear-gradient(135deg, #2d87f0, #124fa0);
    --amber:      #d97706;
    --amber-pale: #fef3cd;
    --rose:       #dc2626;
    --rose-pale:  #fee2e2;
    --emerald:    #059669;
    --emerald-pale:#d1fae5;
    --font-serif: 'Lora', Georgia, serif;
    --font-sans:  'Outfit', system-ui, sans-serif;
    --r-sm: 6px; --r-md: 10px; --r-lg: 16px; --r-xl: 22px;
    --sh-sm: 0 1px 4px rgba(15,25,35,.07);
    --sh-md: 0 4px 16px rgba(15,25,35,.09);
    --sh-blue: 0 6px 22px rgba(29,111,206,.22);
}

body, .content-wrapper { background: var(--paper) !important; font-family: var(--font-sans); }

@keyframes slideUp { from{opacity:0;transform:translateY(14px)} to{opacity:1;transform:translateY(0)} }

/* ─ Breadcrumb ─ */
.diary-topnav {
    display:flex; align-items:center; gap:7px;
    font-size:.77rem; font-weight:500; color:var(--ink-muted);
    margin-bottom:18px; letter-spacing:.02em;
}
.diary-topnav a { color:var(--blue); text-decoration:none; transition:color .15s; }
.diary-topnav a:hover { color:var(--blue-deep); }
.diary-topnav .sep { opacity:.4; }
.diary-topnav .current { color:var(--ink-soft); font-weight:600; }

/* ─ Page header ─ */
.diary-page { padding:24px 28px; max-width:1400px; margin:0 auto; }
.diary-page-header {
    display:flex; align-items:center; justify-content:space-between;
    margin-bottom:20px; padding-bottom:18px; border-bottom:1.5px solid var(--rule);
    animation:slideUp .45s ease both;
}
.diary-page-header-left { display:flex; align-items:center; gap:16px; }
.diary-page-icon {
    width:48px; height:48px; flex-shrink:0;
    background:var(--blue-grad); border-radius:var(--r-lg);
    display:flex; align-items:center; justify-content:center;
    font-size:1.2rem; color:#fff; box-shadow:var(--sh-blue);
}
.diary-page-title {
    font-family:var(--font-serif); font-size:1.6rem; font-weight:700;
    color:var(--ink); line-height:1.15; letter-spacing:-.015em; margin:0 0 3px;
}
.diary-page-sub { font-size:.78rem; color:var(--ink-muted); margin:0; }
.diary-page-header-right { display:flex; gap:8px; flex-wrap:wrap; }

/* ─ Buttons ─ */
.btn-diary {
    display:inline-flex; align-items:center; gap:7px;
    padding:8px 16px; border-radius:var(--r-md); font-family:var(--font-sans);
    font-size:.8rem; font-weight:600; text-decoration:none; border:none;
    cursor:pointer; transition:all .18s; white-space:nowrap;
    box-shadow:var(--sh-sm); line-height:1.3;
}
.btn-diary:hover { transform:translateY(-1px); box-shadow:var(--sh-md); text-decoration:none; }
.btn-diary-primary { background:var(--blue-grad); color:#fff; box-shadow:var(--sh-blue); }
.btn-diary-primary:hover { filter:brightness(1.07); color:#fff; }
.btn-diary-ghost   { background:var(--surface); color:var(--ink-soft); border:1.5px solid var(--rule-strong); }
.btn-diary-ghost:hover { background:var(--blue-pale); color:var(--blue-deep); border-color:var(--blue); }
.btn-diary-success { background:#f0fdf4; color:var(--emerald); border:1.5px solid #bbf7d0; }
.btn-diary-success:hover { background:var(--emerald-pale); color:#065f46; }

/* ─ Alerts ─ */
.diary-alert {
    display:flex; align-items:flex-start; gap:10px;
    padding:12px 16px; border-radius:var(--r-md); font-size:.84rem; margin-bottom:18px;
}
.diary-alert.success { background:var(--emerald-pale); color:#065f46; border:1px solid #a7f3d0; }
.diary-alert.error   { background:var(--rose-pale);    color:#991b1b; border:1px solid #fca5a5; }
.da-close { margin-left:auto; background:none; border:none; cursor:pointer; color:inherit; opacity:.55; font-size:.9rem; padding:0; }
.da-close:hover { opacity:1; }

/* ─ Calendar card ─ */
.cal-card {
    background:var(--surface); border:1.5px solid var(--rule);
    border-radius:var(--r-xl); overflow:hidden;
    box-shadow:var(--sh-sm); animation:slideUp .45s .07s ease both;
}

/* ─ FullCalendar theme overrides ─ */
#calendar {
    max-width:100%; min-height:600px !important; background:#fff;
    font-family:var(--font-sans) !important;
}

.fc-header-toolbar {
    margin:0 !important; padding:14px 20px;
    background:#fff; border-bottom:1.5px solid var(--rule);
    box-shadow:none;
}
.fc-toolbar-title {
    font-family:var(--font-serif) !important;
    font-size:1.1rem !important; font-weight:700 !important;
    color:var(--blue-deep) !important; margin:0;
}
.fc-button {
    border:1.5px solid var(--rule-strong) !important;
    border-radius:var(--r-sm) !important;
    padding:6px 11px !important; margin:0 2px !important;
    background:var(--surface) !important; color:var(--ink-soft) !important;
    font-family:var(--font-sans) !important; font-weight:600 !important;
    font-size:.78rem !important; height:auto !important;
    box-shadow:var(--sh-sm) !important; transition:all .15s !important;
}
.fc-button:hover {
    background:var(--blue-pale) !important; color:var(--blue) !important;
    border-color:var(--blue) !important;
}
.fc-button.fc-button-primary,
.fc-button.fc-button-active {
    background:var(--blue-grad) !important; color:#fff !important;
    border-color:var(--blue-deep) !important;
}
.fc-button.fc-button-primary:hover { filter:brightness(1.07) !important; }

.fc-daygrid-day {
    min-height:90px; border:1px solid var(--rule) !important;
    background:#fff; transition:background .13s;
}
.fc-daygrid-day:hover { background:var(--blue-pale) !important; }
.fc-daygrid-day-number {
    font-weight:600; color:var(--ink-soft);
    font-size:.8rem; padding:5px 8px 0;
    font-family:var(--font-sans);
}
.fc-day-today { background:#eef6ff !important; border-color:var(--blue) !important; }
.fc-day-today .fc-daygrid-day-number { color:var(--blue); font-weight:700; }
.fc-day-other { background:var(--paper) !important; }
.fc-day-other .fc-daygrid-day-number { color:var(--ink-muted); }

.fc-event {
    border:none !important; border-radius:6px !important;
    padding:3px 7px !important; margin:2px 4px !important;
    font-size:.74rem !important; cursor:pointer !important;
    box-shadow:0 1px 3px rgba(0,0,0,.08) !important;
    background:#fff !important; color:var(--ink-soft) !important;
    border-left:3px solid !important;
}
.fc-event.high   { border-left-color:#ef4444 !important; }
.fc-event.medium { border-left-color:#f59e0b !important; }
.fc-event.low    { border-left-color:#10b981 !important; }
.fc-event:not(.high):not(.medium):not(.low) { border-left-color:var(--blue) !important; }

.fc-event-title { font-weight:500; color:var(--ink); font-size:.74rem; }
.fc-event-time  { font-size:.69rem; color:var(--ink-muted); }

.fc-col-header-cell {
    background:var(--paper) !important;
    padding:8px 0 !important;
    font-size:.72rem; font-weight:700;
    text-transform:uppercase; letter-spacing:.07em;
    color:var(--ink-muted) !important;
    font-family:var(--font-sans) !important;
    border:1px solid var(--rule) !important;
}

/* Fallback */
#calendar-fallback { display:none; padding:2rem; text-align:center; min-height:600px; }

@media(max-width:640px){
    .diary-page { padding:16px; }
    .diary-page-header { flex-direction:column; align-items:flex-start; gap:14px; }
    .fc-header-toolbar { flex-direction:column !important; gap:8px; }
}
</style>
@endpush

@section('content')
<div class="diary-page">

    {{-- Breadcrumb --}}
    <nav class="diary-topnav" aria-label="Breadcrumb">
        <a href="{{ url('/') }}"><i class="fas fa-home"></i></a>
        <span class="sep">/</span>
        <a href="{{ route('modules.processing.diary.dashboard') }}">Diary</a>
        <span class="sep">/</span>
        <span class="current">Calendar</span>
    </nav>

    {{-- Page Header --}}
    <div class="diary-page-header">
        <div class="diary-page-header-left">
            <div class="diary-page-icon"><i class="fas fa-calendar-alt"></i></div>
            <div>
                <h1 class="diary-page-title">Calendar View</h1>
                <p class="diary-page-sub">Browse and schedule diary entries on a monthly view</p>
            </div>
        </div>
        <div class="diary-page-header-right">
            <a href="{{ route('modules.processing.diary.list') }}" class="btn-diary btn-diary-ghost">
                <i class="fas fa-list"></i> List View
            </a>
            <a href="{{ route('modules.processing.diary.dashboard') }}" class="btn-diary btn-diary-ghost">
                <i class="fas fa-chart-bar"></i> Dashboard
            </a>
            <a href="{{ route('modules.processing.diary.add') }}" class="btn-diary btn-diary-primary">
                <i class="fas fa-plus"></i> Add Entry
            </a>
        </div>
    </div>

    {{-- Alerts --}}
    @if(session('success'))
        <div class="diary-alert success" role="alert">
            <i class="fas fa-check-circle"></i>
            <span>{{ session('success') }}</span>
            <button class="da-close" onclick="this.closest('.diary-alert').remove()">&times;</button>
        </div>
    @endif
    @if(session('error'))
        <div class="diary-alert error" role="alert">
            <i class="fas fa-exclamation-circle"></i>
            <span>{{ session('error') }}</span>
            <button class="da-close" onclick="this.closest('.diary-alert').remove()">&times;</button>
        </div>
    @endif

    {{-- Calendar Card --}}
    <div class="cal-card">
        <div id="calendar"></div>
        <div id="calendar-fallback">
            <div style="background:var(--amber-pale);border:1px solid #fde68a;border-radius:12px;padding:24px;max-width:480px;margin:auto;text-align:left;">
                <h4 style="color:var(--amber);margin:0 0 12px;font-family:var(--font-sans);font-weight:700;">
                    <i class="fas fa-exclamation-triangle" style="margin-right:6px;"></i> Calendar could not load
                </h4>
                <p style="font-size:.84rem;color:var(--ink-soft);margin:0 0 12px;">This may be due to a network issue, ad-blocker, or a missing <code>$diaryEntries</code> variable from the controller.</p>
                <p style="font-size:.82rem;color:var(--ink-muted);margin:0 0 16px;">Try: refreshing (Ctrl+Shift+R), disabling ad-blockers, or checking the browser console (F12).</p>
                <button class="btn-diary btn-diary-primary" onclick="location.reload()">
                    <i class="fas fa-redo"></i> Refresh Page
                </button>
            </div>
        </div>
    </div>

</div>
@endsection

@push('scripts')
<script src='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.4/index.global.min.js'></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    var calendarEl = document.getElementById('calendar');
    var fallbackEl = document.getElementById('calendar-fallback');

    if (!calendarEl || typeof FullCalendar === 'undefined') {
        if (fallbackEl) fallbackEl.style.display = 'block';
        return;
    }

    var events = @json($diaryEntries ?? []);

    calendarEl.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;min-height:400px;gap:12px;color:var(--ink-muted);font-family:var(--font-sans);font-size:.88rem;"><div class="spinner-border text-primary" role="status" style="width:20px;height:20px;border-width:2px;"></div> Loading calendar…</div>';

    try {
        var calendar = new FullCalendar.Calendar(calendarEl, {
            initialView: 'dayGridMonth',
            headerToolbar: {
                left:   'prev,next today',
                center: 'title',
                right:  'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
            },
            events: events,
            height: 'auto',
            aspectRatio: 1.8,
            dayMaxEvents: true,
            moreLinkClick: 'popover',
            eventTimeFormat: { hour:'2-digit', minute:'2-digit', hour12:false },
            eventDisplay: 'block',
            eventDidMount: function (info) {
                if (info.view.type === 'dayGridMonth') {
                    var priority = info.event.extendedProps.priority || info.event.classNames[0];
                    var dot = document.createElement('div');
                    dot.style.cssText = 'position:absolute;bottom:4px;right:4px;width:7px;height:7px;border-radius:50%;background:' +
                        (priority === 'high' ? '#ef4444' : priority === 'medium' ? '#f59e0b' : priority === 'low' ? '#10b981' : '#1d6fce');
                    info.el.appendChild(dot);
                }
            },
            dateClick: function (info) {
                window.location.href = '{{ route('modules.processing.diary.add') }}?date=' + info.dateStr;
            },
            eventClick: function (info) {
                if (info.event.url) {
                    info.jsEvent.preventDefault();
                    window.location.href = info.event.url;
                }
            },
            loading: function (isLoading) {
                if (!isLoading) {
                    var spinner = calendarEl.querySelector('[role="status"]');
                    if (spinner) spinner.closest('div').remove();
                }
            },
            weekends: true,
            nowIndicator: true,
            editable: false
        });

        calendar.render();
        if (fallbackEl) fallbackEl.style.display = 'none';

    } catch (err) {
        console.error('Calendar error:', err);
        if (fallbackEl) fallbackEl.style.display = 'block';
        calendarEl.innerHTML = '';
    }
});
</script>
@endpush
