@extends('layouts.master')

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

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card shadow-lg border-0">
                <div class="card-header bg-gradient-primary text-white d-flex justify-content-between align-items-center">
                    <h3 class="card-title mb-0">
                        <i class="fas fa-calendar-alt me-2"></i> Diary Calendar
                    </h3>
                    <div class="card-tools">
                        <a href="{{ route('modules.processing.diary.list') }}" class="btn btn-light btn-sm me-2">
                            <i class="fas fa-list me-1"></i> List View
                        </a>
                        <a href="{{ route('modules.processing.diary.add') }}" class="btn btn-light btn-sm me-2">
                            <i class="fas fa-plus me-1"></i> Add New Entry
                        </a>
                        <a href="{{ route('modules.processing.diary.dashboard') }}" class="btn btn-light btn-sm">
                            <i class="fas fa-chart-bar me-1"></i> Dashboard
                        </a>
                    </div>
                </div>
                <div class="card-body p-3">
                    <div id="calendar" style="min-height: 600px; background: #fff;"></div>
                    <div id="calendar-fallback" style="display: none; padding: 2rem; text-align: center; min-height: 600px;">
                        <div class="alert alert-warning">
                            <h4><i class="fas fa-exclamation-triangle"></i> Calendar Loading Issue</h4>
                            <p>The calendar could not be loaded. Check browser console (F12) for errors.</p>
                            <p>This might be due to:</p>
                            <ul class="text-start">
                                <li>Network connectivity issues</li>
                                <li>FullCalendar script not loading</li>
                                <li>JavaScript errors (e.g., missing data from server)</li>
                            </ul>
                            <p><strong>Solutions:</strong></p>
                            <ul class="text-start">
                                <li>Refresh the page (Ctrl+Shift+R)</li>
                                <li>Check internet connection and disable ad-blockers</li>
                                <li>Ensure your controller passes <code>$diaryEntries</code></li>
                                <li>Try a different browser</li>
                            </ul>
                            <button class="btn btn-primary" onclick="location.reload()">
                                <i class="fas fa-refresh"></i> Refresh Page
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
<!-- FullCalendar CSS v6.1.4 -->
<link href='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.4/index.global.min.css' rel='stylesheet' />

<!-- Google Fonts for Roboto -->
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">

<style>
    body {
        font-family: 'Roboto', sans-serif;
    }
    #calendar {
        max-width: 100%;
        min-height: 600px !important;
        background-color: #fff;
    }

    /* Additional styling to mimic Google Calendar */
    .fc-header-toolbar {
        margin: 0;
        padding: 12px 16px;
        background: #fff;
        border-bottom: 1px solid #dadce0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        box-shadow: 0 1px 2px rgba(0,0,0,0.05);
    }

    .fc-toolbar-title {
        font-size: 1.25rem;
        font-weight: 500;
        color: #1a73e8;
        margin: 0;
    }

    .fc-button {
        border: none;
        border-radius: 18px;
        padding: 8px 12px;
        margin: 0 2px;
        background: #fff;
        color: #5f6368;
        font-weight: 500;
        font-size: 0.875rem;
        min-width: 32px;
        height: 32px;
        box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        transition: all 0.2s ease;
    }

    .fc-button:hover {
        background-color: #f1f3f4;
        color: #1a73e8;
        box-shadow: 0 2px 4px rgba(0,0,0,0.15);
    }

    .fc-button.fc-button-primary,
    .fc-button.fc-button-active {
        background-color: #1a73e8;
        color: #fff;
    }

    .fc-button.fc-button-primary:hover {
        background-color: #1557b0;
        box-shadow: 0 2px 4px rgba(26, 115, 232, 0.3);
    }

    .fc-daygrid-day {
        min-height: 100px;
        border: 1px solid #dadce0;
        background: #fff;
        transition: background-color 0.2s ease;
        position: relative;
    }

    .fc-daygrid-day:hover {
        background-color: #f8f9fa;
        border-color: #1a73e8;
    }

    .fc-daygrid-day-number {
        font-weight: 500;
        color: #3c4043;
        font-size: 0.875rem;
        padding: 4px 8px 0;
    }

    .fc-day-today {
        background-color: #e8f0fe !important;
        border-color: #1a73e8 !important;
    }

    .fc-day-today .fc-daygrid-day-number {
        color: #1a73e8;
        font-weight: 600;
    }

    .fc-day-other {
        background-color: #f8f9fa;
        color: #9aa0a6;
    }

    .fc-day-other .fc-daygrid-day-number {
        color: #9aa0a6;
    }

    .fc-event {
        border: none;
        border-radius: 8px;
        padding: 4px 8px;
        margin: 2px 4px;
        font-size: 0.8125rem;
        cursor: pointer;
        box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        background: #fff !important;
        color: #3c4043;
        border-left: 4px solid;
        position: relative;
        overflow: hidden;
    }

    .fc-event.high {
        border-left-color: #ea4335 !important; /* Red */
    }

    .fc-event.medium {
        border-left-color: #fbbc05 !important; /* Yellow */
    }

    .fc-event.low {
        border-left-color: #34a853 !important; /* Green */
    }

    .fc-event:not(.high):not(.medium):not(.low) {
        border-left-color: #4285f4 !important; /* Blue */
    }

    .fc-event-time {
        font-weight: 500;
        color: #5f6368;
        display: block;
        font-size: 0.75rem;
        margin-bottom: 2px;
    }

    .fc-event-title {
        font-weight: 400;
        color: #3c4043;
        margin: 0;
        line-height: 1.3;
        white-space: normal;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    /* Responsive */
    @media (max-width: 768px) {
        .fc-header-toolbar {
            flex-direction: column;
            gap: 8px;
        }

        .fc-toolbar-title {
            font-size: 1.125rem;
        }

        .fc-button {
            min-width: 40px;
            height: 36px;
        }

        .fc-daygrid-day {
            min-height: 80px;
        }
    }
</style>
@endpush

@push('scripts')
<!-- FullCalendar JS v6.1.4 -->
<script src='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.4/index.global.min.js'></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const calendarEl = document.getElementById('calendar');
    const fallbackEl = document.getElementById('calendar-fallback');

    if (!calendarEl) {
        console.error('Calendar element not found!');
        if (fallbackEl) fallbackEl.style.display = 'block';
        return;
    }

    if (typeof FullCalendar === 'undefined') {
        console.error('FullCalendar library not loaded!');
        if (fallbackEl) fallbackEl.style.display = 'block';
        return;
    }

    // Dummy events for testing
    const events = [
        {
            id: '1',
            title: 'Meeting with Team',
            start: new Date().toISOString().split('T')[0], // today
            className: 'high',
            allDay: true
        },
        {
            id: '2',
            title: 'Project Deadline',
            start: new Date(new Date().setDate(new Date().getDate() + 3)).toISOString().split('T')[0], // 3 days later
            className: 'medium',
            allDay: true
        },
        {
            id: '3',
            title: 'Lunch with Client',
            start: new Date(new Date().setHours(13, 0, 0)).toISOString(),
            className: 'low',
            allDay: false
        }
    ];

    // Show loading spinner while initializing
    calendarEl.innerHTML = `
        <div class="calendar-loading d-flex justify-content-center align-items-center" style="min-height: 400px; font-size: 1rem; color: #5f6368; background: #f1f3f4;">
            <div class="spinner-border text-primary me-2" role="status"><span class="visually-hidden">Loading...</span></div>
            Loading calendar...
        </div>
    `;

    try {
        const 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') {
                    const dot = document.createElement('div');
                    dot.style.position = 'absolute';
                    dot.style.bottom = '4px';
                    dot.style.right = '4px';
                    dot.style.width = '8px';
                    dot.style.height = '8px';
                    dot.style.borderRadius = '50%';
                    dot.style.backgroundColor = info.event.extendedProps.className === 'high' ? '#ea4335' :
                                               info.event.extendedProps.className === 'medium' ? '#fbbc05' :
                                               info.event.extendedProps.className === 'low' ? '#34a853' : '#4285f4';
                    info.el.appendChild(dot);
                }
            },
            dateClick: function(info) {
                alert('Date clicked: ' + info.dateStr);
            },
            eventClick: function(info) {
                alert('Event clicked: ' + info.event.title);
            },
            loading: function(isLoading) {
                if (!isLoading) {
                    const loadingEl = calendarEl.querySelector('.calendar-loading');
                    if (loadingEl) loadingEl.remove();
                }
            },
            weekends: true,
            nowIndicator: true,
            editable: false
        });

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

    } catch (error) {
        console.error('Calendar initialization error:', error);
        if (fallbackEl) fallbackEl.style.display = 'block';
        calendarEl.innerHTML = `<p class="text-danger text-center p-3">Failed to load calendar. Please try refreshing the page.</p>`;
    }
});
</script>
@endpush
