{% extends "base.html" %}

{% block title %}Schichtplan - Mercedes-Benz MYP Platform{% endblock %}

{% block head %}
{{ super() }}
<meta name="csrf-token" content="{{ csrf_token() }}">
<!-- FullCalendar CSS -->
<link href="{{ url_for('static', filename='js/fullcalendar/main.min.css') }}" rel="stylesheet">
{% endblock %}

{% block extra_css %}
<style>
    /* Mercedes-Benz Corporate Design */
    .text-mercedes-black { color: #000000; }
    .text-mercedes-gray { color: #6b7280; }
    .text-mercedes-silver { color: #9ca3af; }
    .text-mercedes-blue { color: #0073ce; }
    .text-mercedes-green { color: #008c32; }
    .text-mercedes-red { color: #dc2626; }
    
    .bg-mercedes-black { background-color: #000000; }
    .bg-mercedes-silver { background-color: #e5e7eb; }
    .bg-mercedes-blue { background-color: #0073ce; }
    .bg-mercedes-green { background-color: #008c32; }
    
    .border-mercedes-silver { border-color: #d1d5db; }
    .border-mercedes-blue { border-color: #0073ce; }
    
    /* Premium Calendar Container */
    .fc {
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        --fc-border-color: #d1d5db;
        --fc-today-bg-color: rgba(0, 115, 206, 0.12);
        background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 
            0 20px 25px -5px rgba(0, 0, 0, 0.1),
            0 10px 10px -5px rgba(0, 0, 0, 0.04);
        border: 1px solid #e5e7eb;
    }
    
    .dark .fc {
        background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
        --fc-border-color: #334155;
        --fc-today-bg-color: rgba(0, 115, 206, 0.15);
        border-color: #374151;
    }
    
    /* Enhanced Header Toolbar */
    .fc-header-toolbar {
        margin-bottom: 0 !important;
        padding: 1.5rem 2rem !important;
        background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
        border: none !important;
        border-bottom: 2px solid #e5e7eb !important;
        border-radius: 0 !important;
        backdrop-filter: blur(10px);
    }
    
    .dark .fc-header-toolbar {
        background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
        border-bottom-color: #334155 !important;
    }
    
    /* Premium Navigation Buttons */
    .fc-button {
        background: linear-gradient(135deg, #0073ce 0%, #005ba3 100%) !important;
        border: none !important;
        border-radius: 10px !important;
        padding: 0.75rem 1.25rem !important;
        font-weight: 600 !important;
        font-size: 0.875rem !important;
        text-transform: uppercase !important;
        letter-spacing: 0.05em !important;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
        position: relative !important;
        overflow: hidden !important;
    }
    
    .fc-button::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
        transition: left 0.5s;
    }
    
    .fc-button:hover::before {
        left: 100%;
    }
    
    .fc-button:hover {
        background: linear-gradient(135deg, #005ba3 0%, #003d82 100%) !important;
        transform: translateY(-2px) scale(1.02) !important;
        box-shadow: 
            0 12px 20px -5px rgba(0, 115, 206, 0.4),
            0 4px 6px -1px rgba(0, 0, 0, 0.1) !important;
    }
    
    .fc-button:focus {
        box-shadow: 
            0 0 0 3px rgba(0, 115, 206, 0.3),
            0 12px 20px -5px rgba(0, 115, 206, 0.4) !important;
        outline: none !important;
    }
    
    .fc-button-active {
        background: linear-gradient(135deg, #003d82 0%, #002952 100%) !important;
        transform: translateY(1px) !important;
        box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.2) !important;
    }
    
    .fc-today-button {
        background: linear-gradient(135deg, #16a34a 0%, #15803d 100%) !important;
    }
    
    .fc-today-button:hover {
        background: linear-gradient(135deg, #15803d 0%, #166534 100%) !important;
    }
    
    /* Calendar Title Typography */
    .fc-toolbar-title {
        color: #000000 !important;
        font-size: 1.875rem !important;
        font-weight: 800 !important;
        letter-spacing: -0.025em !important;
        background: linear-gradient(135deg, #000000 0%, #374151 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
    
    .dark .fc-toolbar-title {
        background: linear-gradient(135deg, #ffffff 0%, #e2e8f0 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    
    /* Enhanced Column Headers */
    .fc-col-header {
        background: linear-gradient(135deg, #ffffff 0%, #f1f5f9 100%) !important;
        border: none !important;
        border-bottom: 3px solid #0073ce !important;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    }
    
    .dark .fc-col-header {
        background: linear-gradient(135deg, #1e293b 0%, #334155 100%) !important;
        border-bottom-color: #0ea5e9 !important;
    }
    
    .fc-col-header-cell {
        padding: 1.25rem 1rem !important;
        font-weight: 700 !important;
        font-size: 0.875rem !important;
        text-transform: uppercase !important;
        letter-spacing: 0.1em !important;
        color: #1f2937 !important;
        position: relative !important;
    }
    
    .dark .fc-col-header-cell {
        color: #e2e8f0 !important;
    }
    
    /* Optimized Time Grid for Light Mode */
    .fc-timegrid-axis {
        font-weight: 700 !important;
        color: #374151 !important;
        font-size: 0.8rem !important;
        background: linear-gradient(135deg, #f9fafb 0%, #f3f4f6 100%) !important;
        border-right: 2px solid #e5e7eb !important;
        text-align: center !important;
        min-width: 65px !important;
    }
    
    .dark .fc-timegrid-axis {
        color: #9ca3af !important;
        background: linear-gradient(135deg, #1e293b 0%, #334155 100%) !important;
        border-right-color: #374151 !important;
    }
    
    .fc-timegrid-axis-cushion {
        padding: 0.75rem 0.5rem !important;
        font-weight: 700 !important;
        color: #1f2937 !important;
        background: linear-gradient(135deg, #f9fafb 0%, #f3f4f6 100%) !important;
        border-radius: 0 8px 8px 0 !important;
        margin-right: 1px !important;
        text-align: center !important;
        min-width: 60px !important;
    }
    
    .dark .fc-timegrid-axis-cushion {
        color: #e5e7eb !important;
        background: linear-gradient(135deg, #1e293b 0%, #334155 100%) !important;
    }
    
    .fc-timegrid-slot-label {
        font-variant-numeric: tabular-nums !important;
        font-weight: 600 !important;
        color: #1f2937 !important;
    }
    
    .dark .fc-timegrid-slot-label {
        color: #d1d5db !important;
    }
    
    /* Enhanced Grid Styling */
    .fc-daygrid-day, .fc-timegrid-slot {
        border-color: #e5e7eb !important;
        transition: background-color 0.2s ease !important;
        background: #ffffff;
    }
    
    .dark .fc-daygrid-day, .dark .fc-timegrid-slot {
        border-color: #1e293b !important;
        background: #0f172a;
    }
    
    .fc-timegrid-col {
        background: #ffffff !important;
        border-left: 1px solid #d1d5db !important;
        border-right: 1px solid #d1d5db !important;
    }
    
    .dark .fc-timegrid-col {
        background: #0f172a !important;
        border-left-color: #374151 !important;
        border-right-color: #374151 !important;
    }
    
    .fc-timegrid-slot:hover {
        background: rgba(0, 115, 206, 0.06) !important;
    }
    
    .dark .fc-timegrid-slot:hover {
        background: rgba(0, 115, 206, 0.08) !important;
    }
    
    /* Improved Time Slot Lines */
    .fc-timegrid-slot-minor {
        border-top: 1px solid #f3f4f6 !important;
    }
    
    .fc-timegrid-slot-major {
        border-top: 2px solid #e5e7eb !important;
    }
    
    .dark .fc-timegrid-slot-minor {
        border-top-color: #1e293b !important;
    }
    
    .dark .fc-timegrid-slot-major {
        border-top-color: #374151 !important;
    }
    
    .fc-timegrid-body {
        border-left: 2px solid #d1d5db !important;
    }
    
    .dark .fc-timegrid-body {
        border-left-color: #374151 !important;
    }
    
    /* Enhanced Today Highlighting */
    .fc-day-today {
        background: linear-gradient(135deg, rgba(0, 115, 206, 0.15) 0%, rgba(0, 115, 206, 0.08) 100%) !important;
        position: relative !important;
        border: 2px solid rgba(0, 115, 206, 0.3) !important;
    }
    
    .fc-day-today::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: linear-gradient(90deg, #0073ce, #00a8ff, #0073ce);
        border-radius: 0 0 4px 4px;
        z-index: 10;
    }
    
    .dark .fc-day-today {
        background: linear-gradient(135deg, rgba(0, 115, 206, 0.20) 0%, rgba(0, 115, 206, 0.12) 100%) !important;
        border-color: rgba(0, 115, 206, 0.4) !important;
    }
    
    /* Enhanced All-Day Events */
    .fc-daygrid-body {
        background: #ffffff !important;
        border: 1px solid #e5e7eb !important;
        border-top: none !important;
    }
    
    .dark .fc-daygrid-body {
        background: #0f172a !important;
        border-color: #374151 !important;
    }
    
    .fc-daygrid-event-harness {
        margin: 2px 4px !important;
    }
    
    .fc-daygrid-event {
        background: linear-gradient(135deg, #0073ce 0%, #005ba3 100%) !important;
        border: none !important;
        border-radius: 8px !important;
        color: white !important;
        font-weight: 600 !important;
        font-size: 0.875rem !important;
        padding: 0.5rem 0.75rem !important;
        box-shadow: 
            0 4px 6px rgba(0, 115, 206, 0.25),
            0 1px 3px rgba(0, 0, 0, 0.1) !important;
        min-height: 28px !important;
    }
    
    .fc-daygrid-event:hover {
        transform: translateY(-1px) !important;
        box-shadow: 
            0 6px 12px rgba(0, 115, 206, 0.3),
            0 2px 6px rgba(0, 0, 0, 0.15) !important;
    }
    
    .fc-daygrid-more-link {
        background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%) !important;
        color: white !important;
        border-radius: 6px !important;
        font-weight: 600 !important;
        padding: 0.25rem 0.5rem !important;
        box-shadow: 0 2px 4px rgba(245, 158, 11, 0.3) !important;
    }
    
    /* Weekend Highlighting */
    .fc-day-sat, .fc-day-sun {
        background: linear-gradient(135deg, #fafafa 0%, #f5f5f5 100%) !important;
    }
    
    .dark .fc-day-sat, .dark .fc-day-sun {
        background: linear-gradient(135deg, #0c1220 0%, #0f172a 100%) !important;
    }
    
    /* Premium Event Styling */
    .fc-event {
        border-radius: 12px !important;
        border: none !important;
        padding: 0.5rem 0.75rem !important;
        margin: 3px !important;
        box-shadow: 
            0 4px 6px -1px rgba(0, 0, 0, 0.1),
            0 2px 4px -1px rgba(0, 0, 0, 0.06) !important;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
        position: relative !important;
        overflow: hidden !important;
        backdrop-filter: blur(10px) !important;
    }
    
    .fc-event::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 3px;
        background: linear-gradient(90deg, rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 0.4), rgba(255, 255, 255, 0.8));
        opacity: 0;
        transition: opacity 0.3s ease;
    }
    
    .fc-event:hover {
        transform: translateY(-3px) scale(1.02) !important;
        box-shadow: 
            0 20px 25px -5px rgba(0, 0, 0, 0.1),
            0 10px 10px -5px rgba(0, 0, 0, 0.04) !important;
    }
    
    .fc-event:hover::before {
        opacity: 1;
    }
    
    .fc-event-title {
        font-weight: 700 !important;
        font-size: 0.875rem !important;
        line-height: 1.4 !important;
    }
    
    .fc-event-time {
        font-size: 0.75rem !important;
        font-weight: 500 !important;
        opacity: 0.9 !important;
        text-transform: uppercase !important;
        letter-spacing: 0.05em !important;
    }
    
    /* Status-specific Event Colors */
    .fc-event.event-running {
        background: linear-gradient(135deg, #10b981 0%, #059669 80%, #047857 100%) !important;
        color: white !important;
        box-shadow: 0 8px 32px rgba(16, 185, 129, 0.3) !important;
    }
    
    .fc-event.event-queued {
        background: linear-gradient(135deg, #3b82f6 0%, #2563eb 80%, #1d4ed8 100%) !important;
        color: white !important;
        box-shadow: 0 8px 32px rgba(59, 130, 246, 0.3) !important;
    }
    
    .fc-event.event-completed {
        background: linear-gradient(135deg, #16a34a 0%, #15803d 80%, #166534 100%) !important;
        color: white !important;
        box-shadow: 0 8px 32px rgba(22, 163, 74, 0.3) !important;
    }
    
    .fc-event.event-cancelled {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 80%, #b91c1c 100%) !important;
        color: white !important;
        box-shadow: 0 8px 32px rgba(239, 68, 68, 0.3) !important;
    }
    
    .fc-event.event-maintenance {
        background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 80%, #6d28d9 100%) !important;
        color: white !important;
        box-shadow: 0 8px 32px rgba(139, 92, 246, 0.3) !important;
    }
    
    .fc-event.event-high-priority {
        box-shadow: 
            0 0 0 3px rgba(245, 158, 11, 0.4),
            0 8px 32px rgba(245, 158, 11, 0.2) !important;
        animation: priority-pulse 3s infinite ease-in-out;
    }
    
    .fc-event.event-urgent {
        box-shadow: 
            0 0 0 3px rgba(239, 68, 68, 0.6),
            0 8px 32px rgba(239, 68, 68, 0.4) !important;
        animation: urgent-pulse 2s infinite ease-in-out;
    }
    
    @keyframes priority-pulse {
        0%, 100% { 
            box-shadow: 
                0 0 0 3px rgba(245, 158, 11, 0.4),
                0 8px 32px rgba(245, 158, 11, 0.2);
        }
        50% { 
            box-shadow: 
                0 0 0 6px rgba(245, 158, 11, 0.6),
                0 12px 40px rgba(245, 158, 11, 0.3);
        }
    }
    
    @keyframes urgent-pulse {
        0%, 100% { 
            box-shadow: 
                0 0 0 3px rgba(239, 68, 68, 0.6),
                0 8px 32px rgba(239, 68, 68, 0.4);
        }
        50% { 
            box-shadow: 
                0 0 0 8px rgba(239, 68, 68, 0.8),
                0 16px 48px rgba(239, 68, 68, 0.5);
        }
    }
    
    /* Premium Form Elements */
    .mercedes-form-input {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        border: 2px solid #e5e7eb;
        background: linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(248, 250, 252, 0.95) 100%);
        backdrop-filter: blur(10px);
        border-radius: 12px;
        font-weight: 500;
    }
    
    .mercedes-form-input:focus {
        border-color: #0073ce;
        box-shadow: 
            0 0 0 4px rgba(0, 115, 206, 0.1),
            0 10px 15px -3px rgba(0, 0, 0, 0.1),
            0 4px 6px -2px rgba(0, 0, 0, 0.05);
        transform: translateY(-2px);
        background: linear-gradient(135deg, rgba(255, 255, 255, 1) 0%, rgba(248, 250, 252, 1) 100%);
    }
    
    .dark .mercedes-form-input {
        background: linear-gradient(135deg, rgba(30, 41, 59, 0.8) 0%, rgba(15, 23, 42, 0.8) 100%);
        border-color: #475569;
        color: #f8fafc;
    }
    
    .dark .mercedes-form-input:focus {
        border-color: #0ea5e9;
        box-shadow: 
            0 0 0 4px rgba(14, 165, 233, 0.1),
            0 10px 15px -3px rgba(0, 0, 0, 0.3),
            0 4px 6px -2px rgba(0, 0, 0, 0.2);
        background: linear-gradient(135deg, rgba(30, 41, 59, 1) 0%, rgba(15, 23, 42, 1) 100%);
    }
    
    /* Enhanced Statistics Cards */
    .stat-card {
        background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
        border: 2px solid #f1f5f9;
        border-radius: 16px;
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        position: relative;
        overflow: hidden;
        backdrop-filter: blur(10px);
    }
    
    .stat-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: linear-gradient(90deg, transparent, rgba(0, 115, 206, 0.3), transparent);
        transform: translateX(-100%);
        transition: transform 0.6s ease;
    }
    
    .stat-card:hover::before {
        transform: translateX(100%);
    }
    
    .dark .stat-card {
        background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
        border-color: #334155;
    }
    
    .stat-card:hover {
        transform: translateY(-4px) scale(1.02);
        box-shadow: 
            0 25px 50px -12px rgba(0, 0, 0, 0.15),
            0 10px 15px -3px rgba(0, 0, 0, 0.1);
        border-color: #0073ce;
    }
    
    .stat-card.active {
        border-left: 5px solid #10b981;
        background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%);
    }
    
    .dark .stat-card.active {
        background: linear-gradient(135deg, #064e3b 0%, #065f46 100%);
    }
    
    .stat-card.queued {
        border-left: 5px solid #3b82f6;
        background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
    }
    
    .dark .stat-card.queued {
        background: linear-gradient(135deg, #1e3a8a 0%, #1e40af 100%);
    }
    
    .stat-card.time {
        border-left: 5px solid #f59e0b;
        background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%);
    }
    
    .dark .stat-card.time {
        background: linear-gradient(135deg, #92400e 0%, #b45309 100%);
    }
    
    /* Premium Modal Styling */
    .mercedes-modal {
        background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
        border: 1px solid #e2e8f0;
        box-shadow: 
            0 25px 50px -12px rgba(0, 0, 0, 0.25),
            0 4px 6px -1px rgba(0, 0, 0, 0.1);
        border-radius: 16px;
        backdrop-filter: blur(10px);
        max-height: 90vh;
        overflow-y: auto;
        scrollbar-width: thin;
        scrollbar-color: rgba(0, 115, 206, 0.2) transparent;
    }
    
    .dark .mercedes-modal {
        background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
        border-color: #334155;
        box-shadow: 
            0 25px 50px -12px rgba(0, 0, 0, 0.5),
            0 4px 6px -1px rgba(0, 0, 0, 0.3);
        scrollbar-color: rgba(59, 130, 246, 0.3) transparent;
    }

    /* Dashboard card als Modal */
    .dashboard-card {
        max-height: 90vh;
        overflow-y: auto;
        scrollbar-width: thin;
        scrollbar-color: rgba(0, 115, 206, 0.2) transparent;
    }

    .dark .dashboard-card {
        scrollbar-color: rgba(59, 130, 246, 0.3) transparent;
    }

    /* Modal Scrollbar Styling */
    .mercedes-modal::-webkit-scrollbar,
    .dashboard-card::-webkit-scrollbar {
        width: 8px;
    }
    
    .mercedes-modal::-webkit-scrollbar-track,
    .dashboard-card::-webkit-scrollbar-track {
        background: transparent;
        border-radius: 4px;
    }
    
    .mercedes-modal::-webkit-scrollbar-thumb,
    .dashboard-card::-webkit-scrollbar-thumb {
        background: rgba(0, 115, 206, 0.2);
        border-radius: 4px;
        transition: all 0.3s ease;
    }
    
    .mercedes-modal::-webkit-scrollbar-thumb:hover,
    .dashboard-card::-webkit-scrollbar-thumb:hover {
        background: rgba(0, 115, 206, 0.4);
    }
    
    .dark .mercedes-modal::-webkit-scrollbar-thumb,
    .dark .dashboard-card::-webkit-scrollbar-thumb {
        background: rgba(59, 130, 246, 0.3);
    }
    
    .dark .mercedes-modal::-webkit-scrollbar-thumb:hover,
    .dark .dashboard-card::-webkit-scrollbar-thumb:hover {
        background: rgba(59, 130, 246, 0.5);
    }
    
    /* Smooth Scrolling for Calendar */
    .fc-scroller {
        scrollbar-width: thin;
        scrollbar-color: #cbd5e1 #f1f5f9;
    }
    
    .fc-scroller::-webkit-scrollbar {
        width: 8px;
    }
    
    .fc-scroller::-webkit-scrollbar-track {
        background: #f1f5f9;
        border-radius: 4px;
    }
    
    .fc-scroller::-webkit-scrollbar-thumb {
        background: linear-gradient(135deg, #cbd5e1, #94a3b8);
        border-radius: 4px;
    }
    
    .fc-scroller::-webkit-scrollbar-thumb:hover {
        background: linear-gradient(135deg, #94a3b8, #64748b);
    }
    
    /* Loading Animation */
    @keyframes calendar-load {
        0% { opacity: 0; transform: translateY(20px); }
        100% { opacity: 1; transform: translateY(0); }
    }
    
    .fc {
        animation: calendar-load 0.6s ease-out;
    }
    
    /* Responsive Optimizations */
    @media (max-width: 768px) {
        .fc-toolbar-title {
            font-size: 1.25rem !important;
        }
        
        .fc-button {
            padding: 0.5rem 0.75rem !important;
            font-size: 0.75rem !important;
        }
        
        .fc-header-toolbar {
            padding: 1rem !important;
        }
        
        .fc-col-header-cell {
            padding: 0.75rem 0.5rem !important;
            font-size: 0.75rem !important;
        }
        
        .fc-timegrid-axis-cushion {
            min-width: 45px !important;
            font-size: 0.75rem !important;
            padding: 0.5rem 0.25rem !important;
        }
        
        .fc-timegrid-axis {
            border-right-width: 1px !important;
        }
        
        .fc-daygrid-event {
            font-size: 0.75rem !important;
            padding: 0.375rem 0.5rem !important;
            min-height: 24px !important;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="space-y-8">
    <!-- Enhanced Page Header -->
    <div class="dashboard-card p-6">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-6">
            <div class="flex items-center gap-6">
                <div class="w-16 h-16 flex-shrink-0 bg-mercedes-blue text-white rounded-xl flex items-center justify-center">
                    <svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/>
                    </svg>
                </div>
                <div>
                    <h1 class="text-4xl font-bold text-mercedes-black dark:text-white tracking-tight">Produktionsplanung</h1>
                    <p class="text-mercedes-gray dark:text-slate-400 mt-1 text-lg">Intelligente Planung und Überwachung Ihrer 3D-Druckprozesse</p>
                    <div class="flex items-center mt-2 text-sm text-mercedes-blue">
                        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
                        </svg>
                        <span id="calendar-status">Live-Synchronisation aktiv</span>
                    </div>
                </div>
            </div>
            <div class="flex flex-wrap gap-3">
                {% if can_edit %}
                <button onclick="openCreateEventModal()" 
                        class="btn-primary flex items-center gap-2">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"/>
                    </svg>
                    <span>Neuen Job planen</span>
                </button>
                <button onclick="openBatchPlanningModal()" 
                        class="btn-secondary flex items-center gap-2">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16"/>
                    </svg>
                    <span>Batch-Planung</span>
                </button>
                {% endif %}
                <button onclick="refreshCalendar()" id="refresh-button"
                        class="btn-secondary flex items-center gap-2">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
                    </svg>
                    <span>Aktualisieren</span>
                </button>
                <button onclick="exportCalendar()" 
                        class="btn-secondary flex items-center gap-2">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                    </svg>
                    <span>Exportieren</span>
                </button>
                <button onclick="toggleAutoOptimization()" id="auto-opt-toggle"
                        class="btn-secondary flex items-center gap-2 relative group">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
                    </svg>
                    <span>Auto-Optimierung</span>
                    
                    <!-- Info-Tooltip für Auto-Optimierung -->
                    <div class="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 w-80 bg-slate-900 dark:bg-slate-700 text-white text-xs rounded-lg p-3 opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none z-50 shadow-lg">
                        <div class="font-semibold mb-2">🚀 Intelligente Auto-Optimierung</div>
                        <ul class="space-y-1 text-left">
                            <li>• <strong>Round Robin:</strong> Gleichmäßige Druckerverteilung</li>
                            <li>• <strong>Load Balancing:</strong> Auslastungsoptimierung</li>
                            <li>• <strong>Prioritätsbasiert:</strong> Wichtige Jobs zuerst</li>
                            <li>• <strong>Rüstzeiten:</strong> Minimierung der Umrüstzeiten</li>
                            <li>• <strong>Entfernungen:</strong> Berücksichtigung der Druckerstandorte</li>
                        </ul>
                        <div class="mt-2 text-xs text-slate-300">
                            Tastenkürzel: <kbd class="bg-slate-800 px-1 rounded">Ctrl+Alt+O</kbd>
                        </div>
                        <div class="absolute top-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent border-t-slate-900 dark:border-t-slate-700"></div>
                    </div>
                </button>
            </div>
        </div>
    </div>

    <!-- Enhanced Filter and Analytics Section -->
    <div class="filter-section p-6">
        <div class="flex items-center justify-between mb-6">
            <div>
                <h3 class="text-lg font-semibold text-mercedes-black dark:text-white mb-2">Intelligente Filter & Analyse</h3>
                <p class="text-sm text-mercedes-gray dark:text-slate-400">Optimieren Sie Ihre Produktionsplanung mit erweiterten Filteroptionen</p>
            </div>
            <button onclick="clearAllFilters()" class="text-sm text-mercedes-blue hover:text-blue-700 transition-colors">
                <svg class="w-4 h-4 inline mr-1" 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>
                Alle Filter zurücksetzen
            </button>
        </div>
        
        <div class="grid grid-cols-1 lg:grid-cols-4 gap-6 mb-6">
            <!-- Enhanced Drucker Filter -->
            <div>
                <label for="printerFilter" class="block text-sm font-medium text-mercedes-black dark:text-slate-300 mb-2">
                    <svg class="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01"/>
                    </svg>
                    Produktionseinheit
                </label>
                <select id="printerFilter" class="mercedes-form-input block w-full px-4 py-3 rounded-lg">
                    <option value="">Alle Produktionseinheiten</option>
                    {% for printer in printers %}
                    <option value="{{ printer.id }}">{{ printer.name }} {% if printer.location %}({{ printer.location }}){% endif %}</option>
                    {% endfor %}
                </select>
            </div>
            
            <!-- Enhanced Status Filter -->
            <div>
                <label for="statusFilter" class="block text-sm font-medium text-mercedes-black dark:text-slate-300 mb-2">
                    <svg class="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.414A1 1 0 013 6.707V4z"/>
                    </svg>
                    Produktionsstatus
                </label>
                <select id="statusFilter" class="mercedes-form-input block w-full px-4 py-3 rounded-lg">
                    <option value="">Alle Status</option>
                    <option value="running">Aktiv</option>
                    <option value="queued">Warteschlange</option>
                    <option value="completed">Abgeschlossen</option>
                    <option value="cancelled">Abgebrochen</option>
                    <option value="maintenance">Wartung</option>
                </select>
            </div>
            
            <!-- Priority Filter -->
            <div>
                <label for="priorityFilter" class="block text-sm font-medium text-mercedes-black dark:text-slate-300 mb-2">
                    <svg class="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
                    </svg>
                    Prioritätsstufe
                </label>
                <select id="priorityFilter" class="mercedes-form-input block w-full px-4 py-3 rounded-lg">
                    <option value="">Alle Prioritäten</option>
                    <option value="urgent">Dringend</option>
                    <option value="high">Hoch</option>
                    <option value="normal">Standard</option>
                    <option value="low">Niedrig</option>
                </select>
            </div>
            
            <!-- Time Range Filter -->
            <div>
                <label for="timeRangeFilter" class="block text-sm font-medium text-mercedes-black dark:text-slate-300 mb-2">
                    <svg class="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                    Zeitbereich
                </label>
                <select id="timeRangeFilter" class="mercedes-form-input block w-full px-4 py-3 rounded-lg">
                    <option value="">Alle Zeiten</option>
                    <option value="today">Heute</option>
                    <option value="tomorrow">Morgen</option>
                    <option value="week">Diese Woche</option>
                    <option value="month">Dieser Monat</option>
                </select>
            </div>
        </div>
        
        <!-- Quick Analytics -->
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div class="stat-card active p-4">
                <div class="flex justify-between items-center">
                    <div>
                        <h3 class="text-sm font-medium text-mercedes-gray dark:text-slate-400 mb-1">Aktive Jobs</h3>
                        <div class="text-2xl font-bold text-green-600 dark:text-green-400" id="active-jobs">-</div>
                        <div class="text-xs text-mercedes-gray dark:text-slate-400">Läuft derzeit</div>
                    </div>
                    <div class="w-10 h-10 bg-green-100 dark:bg-green-900/30 rounded-lg flex items-center justify-center">
                        <div class="w-3 h-3 bg-green-500 rounded-full animate-pulse"></div>
                    </div>
                </div>
            </div>
            
            <div class="stat-card queued p-4">
                <div class="flex justify-between items-center">
                    <div>
                        <h3 class="text-sm font-medium text-mercedes-gray dark:text-slate-400 mb-1">Warteschlange</h3>
                        <div class="text-2xl font-bold text-blue-600 dark:text-blue-400" id="queued-jobs">-</div>
                        <div class="text-xs text-mercedes-gray dark:text-slate-400">Geplant</div>
                    </div>
                    <div class="w-10 h-10 bg-blue-100 dark:bg-blue-900/30 rounded-lg flex items-center justify-center">
                        <div class="w-3 h-3 bg-blue-500 rounded-full"></div>
                    </div>
                </div>
            </div>
            
            <div class="stat-card time p-4">
                <div class="flex justify-between items-center">
                    <div>
                        <h3 class="text-sm font-medium text-mercedes-gray dark:text-slate-400 mb-1">Heute geplant</h3>
                        <div class="text-2xl font-bold text-orange-600 dark:text-orange-400" id="total-time">-h</div>
                        <div class="text-xs text-mercedes-gray dark:text-slate-400">Produktionszeit</div>
                    </div>
                    <div class="w-10 h-10 bg-orange-100 dark:bg-orange-900/30 rounded-lg flex items-center justify-center">
                        <svg class="w-5 h-5 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
                        </svg>
                    </div>
                </div>
            </div>
            
            <div class="stat-card p-4">
                <div class="flex justify-between items-center">
                    <div>
                        <h3 class="text-sm font-medium text-mercedes-gray dark:text-slate-400 mb-1">Auslastung</h3>
                        <div class="text-2xl font-bold text-mercedes-blue dark:text-blue-400" id="utilization">-%</div>
                        <div class="text-xs text-mercedes-gray dark:text-slate-400">Durchschnitt</div>
                    </div>
                    <div class="w-10 h-10 bg-mercedes-silver rounded-lg flex items-center justify-center">
                        <svg class="w-5 h-5 text-mercedes-black dark:text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/>
                        </svg>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Calendar Container -->
    <div class="dashboard-card p-6">
        <div id="calendar"></div>
    </div>

    <!-- Legend Section -->
    <div class="dashboard-card p-6">
        <h3 class="section-title mb-6">Status-Legende</h3>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-6">
            <div class="flex items-center gap-3 p-3 rounded-lg bg-gray-50 dark:bg-slate-700/30">
                <div class="w-6 h-6 bg-gradient-to-br from-green-400 to-green-600 rounded-lg"></div>
                <div>
                    <div class="text-sm font-medium text-slate-900 dark:text-white">Produktiv</div>
                    <div class="text-xs text-slate-500 dark:text-slate-400">Druckvorgang läuft</div>
                </div>
            </div>
            <div class="flex items-center gap-3 p-3 rounded-lg bg-gray-50 dark:bg-slate-700/30">
                <div class="w-6 h-6 bg-gradient-to-br from-blue-400 to-blue-600 rounded-lg"></div>
                <div>
                    <div class="text-sm font-medium text-slate-900 dark:text-white">Warteschlange</div>
                    <div class="text-xs text-slate-500 dark:text-slate-400">Wartet auf Start</div>
                </div>
            </div>
            <div class="flex items-center gap-3 p-3 rounded-lg bg-gray-50 dark:bg-slate-700/30">
                <div class="w-6 h-6 bg-gradient-to-br from-emerald-400 to-emerald-600 rounded-lg"></div>
                <div>
                    <div class="text-sm font-medium text-slate-900 dark:text-white">Abgeschlossen</div>
                    <div class="text-xs text-slate-500 dark:text-slate-400">Erfolgreich gedruckt</div>
                </div>
            </div>
            <div class="flex items-center gap-3 p-3 rounded-lg bg-gray-50 dark:bg-slate-700/30">
                <div class="w-6 h-6 bg-gradient-to-br from-red-400 to-red-600 rounded-lg"></div>
                <div>
                    <div class="text-sm font-medium text-slate-900 dark:text-white">Abgebrochen</div>
                    <div class="text-xs text-slate-500 dark:text-slate-400">Fehler aufgetreten</div>
                </div>
            </div>
        </div>
    </div>
</div>

{% if can_edit %}
<!-- Event Modal -->
<div id="eventModal" class="fixed inset-0 bg-black/60 backdrop-blur-sm hidden z-50">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="dashboard-card max-w-2xl w-full p-8 transform transition-all duration-300 scale-95 opacity-0" id="modalContent">
            <div class="flex justify-between items-center mb-6">
                <div>
                    <h3 id="modalTitle" class="text-xl font-bold text-slate-900 dark:text-white mb-2">
                        Neuen Produktionsauftrag erstellen
                    </h3>
                    <p class="text-slate-500 dark:text-slate-400">Planen Sie Ihren nächsten 3D-Druckauftrag</p>
                </div>
                <button onclick="closeEventModal()" class="p-2 hover:bg-gray-100 dark:hover:bg-slate-700 rounded-lg transition-colors">
                    <svg class="w-6 h-6 text-slate-500 dark:text-slate-400" 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"></path>
                    </svg>
                </button>
            </div>
            
            <form id="eventForm" class="space-y-6">
                <input type="hidden" id="eventId" name="eventId">
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Titel -->
                    <div class="md:col-span-2">
                        <label for="eventTitle" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                            Auftrags-Bezeichnung <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="eventTitle" name="title" required
                               class="block w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-800 text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                               placeholder="z.B. Prototyp Mercedes C-Klasse Bauteil">
                    </div>
                    
                    <!-- Beschreibung -->
                    <div class="md:col-span-2">
                        <label for="eventDescription" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                            Detaillierte Beschreibung
                        </label>
                        <textarea id="eventDescription" name="description" rows="3"
                                  class="block w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-800 text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none"
                                  placeholder="Beschreiben Sie den Druckauftrag und besondere Anforderungen..."></textarea>
                    </div>
                    
                    <!-- Drucker -->
                    <div>
                        <label for="eventPrinter" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                            Produktionseinheit
                            <span class="text-xs text-slate-500 dark:text-slate-400 ml-1">(Optional - Automatische Zuweisung verfügbar)</span>
                        </label>
                        <select id="eventPrinter" name="printerId"
                                class="block w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-800 text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                            <option value="">🤖 Intelligente Automatische Zuweisung</option>
                            <optgroup label="─── Verfügbare Produktionseinheiten ───">
                                {% for printer in printers %}
                                <option value="{{ printer.id }}">
                                    🖨️ {{ printer.name }} 
                                    {% if printer.location %}(📍 {{ printer.location }}){% endif %}
                                    {% if printer.status == 'offline' %} - ⚠️ Offline{% endif %}
                                </option>
                                {% endfor %}
                            </optgroup>
                        </select>
                        <div class="mt-2 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
                            <div class="flex items-start gap-2">
                                <svg class="w-4 h-4 text-blue-600 dark:text-blue-400 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                                </svg>
                                <div class="text-xs text-blue-700 dark:text-blue-300">
                                    <strong>Intelligente Zuweisung berücksichtigt:</strong><br>
                                    • Verfügbarkeit und Auslastung der Drucker<br>
                                    • Materialkompatibilität und Druckqualität<br>
                                    • Standort und Rüstzeiten<br>
                                    • Wartungszyklen und Prioritätsstufen
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Priorität -->
                    <div>
                        <label for="eventPriority" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                            Prioritätsstufe
                        </label>
                        <select id="eventPriority" name="priority"
                                class="block w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-800 text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                            <option value="normal">Standard</option>
                            <option value="high">Hoch</option>
                            <option value="urgent">Dringend</option>
                        </select>
                    </div>
                    
                    <!-- Start-Zeit -->
                    <div>
                        <label for="eventStart" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                            Produktionsstart <span class="text-red-500">*</span>
                        </label>
                        <input type="datetime-local" id="eventStart" name="start" required
                               class="block w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-800 text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    
                    <!-- End-Zeit -->
                    <div>
                        <label for="eventEnd" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                            Produktionsende <span class="text-red-500">*</span>
                        </label>
                        <input type="datetime-local" id="eventEnd" name="end" required
                               class="block w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-800 text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                </div>
                
                <!-- Buttons -->
                <div class="flex items-center justify-end gap-3 pt-6 border-t border-gray-200 dark:border-slate-600">
                    <button type="button" onclick="closeEventModal()" 
                            class="btn-secondary">
                        Abbrechen
                    </button>
                    <button type="submit" 
                            class="btn-primary">
                        Auftrag speichern
                    </button>
                    <button type="button" id="deleteEventBtn" onclick="deleteEvent()" style="display: none;"
                            class="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors">
                        Löschen
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endif %}

<!-- FullCalendar JS -->
<script src="{{ url_for('static', filename='js/fullcalendar/core.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/fullcalendar/daygrid.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/fullcalendar/timegrid.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/fullcalendar/interaction.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/fullcalendar/list.min.js') }}"></script>
<input type="hidden" id="canEditFlag" value="{% if can_edit %}true{% else %}false{% endif %}">
<script>
document.addEventListener('DOMContentLoaded', function() {
    const calendarEl = document.getElementById('calendar');
    const printerFilter = document.getElementById('printerFilter');
    const statusFilter = document.getElementById('statusFilter');
    const canEdit = document.getElementById('canEditFlag').value === 'true';
    
    // Modal Animation
    const modal = document.getElementById('eventModal');
    const modalContent = document.getElementById('modalContent');
    
    window.openCreateEventModal = function() {
        modal.classList.remove('hidden');
        setTimeout(() => {
            modalContent.classList.remove('scale-95', 'opacity-0');
            modalContent.classList.add('scale-100', 'opacity-100');
        }, 10);
    };
    
    window.closeEventModal = function() {
        modalContent.classList.remove('scale-100', 'opacity-100');
        modalContent.classList.add('scale-95', 'opacity-0');
        setTimeout(() => {
            modal.classList.add('hidden');
        }, 200);
    };
    
    let calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: 'timeGridWeek',
        locale: 'de',
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay'
        },
        height: 'auto',
        slotMinTime: '06:00:00',
        slotMaxTime: '22:00:00',
        businessHours: {
            daysOfWeek: [1, 2, 3, 4, 5],
            startTime: '08:00',
            endTime: '18:00'
        },
        events: '/api/calendar/events',
        editable: canEdit,
        selectable: canEdit,
        selectMirror: true,
        eventDidMount: function(info) {
            const event = info.event;
            const element = info.el;
            
            element.style.borderRadius = '8px';
            element.style.border = 'none';
            element.style.boxShadow = '0 2px 8px rgba(0,0,0,0.1)';
        },
        select: function(info) {
            if (canEdit) {
                openCreateEventModal();
                document.getElementById('eventStart').value = info.startStr.slice(0, 16);
                document.getElementById('eventEnd').value = info.endStr.slice(0, 16);
            }
        },
        eventClick: function(info) {
            if (canEdit) {
                openCreateEventModal();
                document.getElementById('modalTitle').textContent = 'Produktionsauftrag bearbeiten';
                document.getElementById('eventId').value = info.event.id;
                document.getElementById('eventTitle').value = info.event.title;
                document.getElementById('eventDescription').value = info.event.extendedProps.description || '';
                document.getElementById('eventPrinter').value = info.event.extendedProps.printerId || '';
                document.getElementById('eventStart').value = info.event.startStr.slice(0, 16);
                document.getElementById('eventEnd').value = info.event.endStr.slice(0, 16);
                document.getElementById('deleteEventBtn').style.display = 'block';
            }
        }
    });
    
    calendar.render();
    
    // Filter Event Handlers
    printerFilter.addEventListener('change', function() {
        calendar.refetchEvents();
    });
    
    statusFilter.addEventListener('change', function() {
        calendar.refetchEvents();
    });
    
    // Form Submit Handler
    document.getElementById('eventForm').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const formData = new FormData(e.target);
        const data = Object.fromEntries(formData);
        
        // Lade-Indikator anzeigen
        const submitButton = this.querySelector('button[type="submit"]');
        const originalText = submitButton.textContent;
        submitButton.disabled = true;
        submitButton.innerHTML = `
            <svg class="animate-spin -ml-1 mr-3 h-4 w-4 text-white inline" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            Wird erstellt...
        `;
        
        try {
            const response = await fetch('/api/calendar/event', {
                method: data.eventId ? 'PUT' : 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                body: JSON.stringify(data)
            });
            
            const result = await response.json();
            
            if (response.ok) {
                calendar.refetchEvents();
                closeEventModal();
                document.getElementById('eventForm').reset();
                hideSmartRecommendation();
                
                // Erfolgreiche Erstellung anzeigen
                if (result.message) {
                    showSuccessNotification(result.message);
                } else {
                    showSuccessNotification('Auftrag erfolgreich erstellt!');
                }
            } else {
                throw new Error(result.error || 'Fehler beim Speichern des Events');
            }
        } catch (error) {
            console.error('Error:', error);
            showErrorNotification(error.message || 'Fehler beim Speichern des Events');
        } finally {
            submitButton.disabled = false;
            submitButton.innerHTML = originalText;
        }
    });
    
    function showSuccessNotification(message) {
        // Einfache Toast-Benachrichtigung
        const toast = document.createElement('div');
        toast.className = 'fixed top-4 right-4 bg-gradient-to-r from-green-500 to-green-600 text-white px-6 py-4 rounded-lg shadow-xl z-50 transform transition-all duration-300 translate-x-full';
        toast.innerHTML = `
            <div class="flex items-center gap-3">
                <div class="w-6 h-6 bg-white/20 rounded-full flex items-center justify-center">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                    </svg>
                </div>
                <span class="font-medium">${message}</span>
            </div>
        `;
        
        document.body.appendChild(toast);
        setTimeout(() => toast.classList.remove('translate-x-full'), 100);
        setTimeout(() => {
            toast.classList.add('translate-x-full');
            setTimeout(() => toast.remove(), 300);
        }, 4000);
    }
    
    function showErrorNotification(message) {
        const toast = document.createElement('div');
        toast.className = 'fixed top-4 right-4 bg-gradient-to-r from-red-500 to-red-600 text-white px-6 py-4 rounded-lg shadow-xl z-50 transform transition-all duration-300 translate-x-full';
        toast.innerHTML = `
            <div class="flex items-center gap-3">
                <div class="w-6 h-6 bg-white/20 rounded-full flex items-center justify-center">
                    <svg class="w-4 h-4" 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>
                </div>
                <span class="font-medium">${message}</span>
            </div>
        `;
        
        document.body.appendChild(toast);
        setTimeout(() => toast.classList.remove('translate-x-full'), 100);
        setTimeout(() => {
            toast.classList.add('translate-x-full');
            setTimeout(() => toast.remove(), 300);
        }, 4000);
    }
    
    // Global Functions
    window.refreshCalendar = function() {
        calendar.refetchEvents();
    };
    
    window.exportCalendar = function() {
        showExportModal();
    };
    
    window.deleteEvent = function() {
        const eventId = document.getElementById('eventId').value;
        if (eventId && confirm('Möchten Sie diesen Produktionsauftrag wirklich löschen?')) {
            closeEventModal();
        }
    };
    
    // Export-Modal Funktionen
    function showExportModal() {
        // Modal HTML erstellen falls nicht vorhanden
        let exportModal = document.getElementById('exportModal');
        if (!exportModal) {
            createExportModal();
            exportModal = document.getElementById('exportModal');
        }
        
        // Modal anzeigen
        exportModal.classList.remove('hidden');
        setTimeout(() => {
            const modalContent = exportModal.querySelector('.modal-content');
            modalContent.classList.remove('scale-95', 'opacity-0');
            modalContent.classList.add('scale-100', 'opacity-100');
        }, 10);
    }
    
    function hideExportModal() {
        const exportModal = document.getElementById('exportModal');
        if (exportModal) {
            const modalContent = exportModal.querySelector('.modal-content');
            modalContent.classList.remove('scale-100', 'opacity-100');
            modalContent.classList.add('scale-95', 'opacity-0');
            setTimeout(() => {
                exportModal.classList.add('hidden');
            }, 200);
        }
    }
    
    function createExportModal() {
        const modalHTML = `
            <div id="exportModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
                <div class="modal-content bg-white dark:bg-slate-800 rounded-xl shadow-2xl w-full max-w-md mx-4 transform transition-all duration-200 scale-95 opacity-0">
                    <div class="flex items-center justify-between p-6 border-b border-slate-200 dark:border-slate-600">
                        <div>
                            <h3 class="text-xl font-bold text-slate-900 dark:text-white mb-2">
                                📊 Schichtplan Export
                            </h3>
                            <p class="text-slate-500 dark:text-slate-400">Exportieren Sie Ihre Produktionsplanung</p>
                        </div>
                        <button onclick="hideExportModal()" class="p-2 hover:bg-gray-100 dark:hover:bg-slate-700 rounded-lg transition-colors">
                            <svg class="w-6 h-6 text-slate-500 dark:text-slate-400" 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"></path>
                            </svg>
                        </button>
                    </div>
                    
                    <div class="p-6 space-y-6">
                        <!-- Export-Format -->
                        <div>
                            <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-3">
                                📋 Export-Format
                            </label>
                            <div class="grid grid-cols-3 gap-3">
                                <label class="flex items-center p-3 border-2 border-slate-200 dark:border-slate-600 rounded-lg cursor-pointer hover:border-blue-300 dark:hover:border-blue-500 transition-colors export-format-option">
                                    <input type="radio" name="exportFormat" value="csv" checked class="text-blue-600 focus:ring-blue-500">
                                    <div class="ml-2">
                                        <div class="text-sm font-medium text-slate-900 dark:text-white">CSV</div>
                                        <div class="text-xs text-slate-500 dark:text-slate-400">Excel-kompatibel</div>
                                    </div>
                                </label>
                                <label class="flex items-center p-3 border-2 border-slate-200 dark:border-slate-600 rounded-lg cursor-pointer hover:border-blue-300 dark:hover:border-blue-500 transition-colors export-format-option">
                                    <input type="radio" name="exportFormat" value="json" class="text-blue-600 focus:ring-blue-500">
                                    <div class="ml-2">
                                        <div class="text-sm font-medium text-slate-900 dark:text-white">JSON</div>
                                        <div class="text-xs text-slate-500 dark:text-slate-400">Strukturiert</div>
                                    </div>
                                </label>
                                <label class="flex items-center p-3 border-2 border-slate-200 dark:border-slate-600 rounded-lg cursor-pointer hover:border-blue-300 dark:hover:border-blue-500 transition-colors export-format-option">
                                    <input type="radio" name="exportFormat" value="excel" class="text-blue-600 focus:ring-blue-500">
                                    <div class="ml-2">
                                        <div class="text-sm font-medium text-slate-900 dark:text-white">Excel</div>
                                        <div class="text-xs text-slate-500 dark:text-slate-400">Mit Statistiken</div>
                                    </div>
                                </label>
                            </div>
                        </div>
                        
                        <!-- Zeitraum -->
                        <div>
                            <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-3">
                                📅 Zeitraum
                            </label>
                            <div class="grid grid-cols-2 gap-3">
                                <div>
                                    <label class="block text-xs text-slate-500 dark:text-slate-400 mb-1">Von</label>
                                    <input type="date" id="exportStartDate" class="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-white text-sm">
                                </div>
                                <div>
                                    <label class="block text-xs text-slate-500 dark:text-slate-400 mb-1">Bis</label>
                                    <input type="date" id="exportEndDate" class="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-white text-sm">
                                </div>
                            </div>
                            <div class="mt-2">
                                <button onclick="setExportDateRange('week')" class="text-xs px-2 py-1 bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 rounded mr-2 hover:bg-blue-200 dark:hover:bg-blue-800">Diese Woche</button>
                                <button onclick="setExportDateRange('month')" class="text-xs px-2 py-1 bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 rounded mr-2 hover:bg-blue-200 dark:hover:bg-blue-800">Dieser Monat</button>
                                <button onclick="setExportDateRange('quarter')" class="text-xs px-2 py-1 bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 rounded hover:bg-blue-200 dark:hover:bg-blue-800">Dieses Quartal</button>
                            </div>
                        </div>
                        
                        <!-- Filter -->
                        <div>
                            <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-3">
                                🔍 Filter (Optional)
                            </label>
                            <div class="space-y-3">
                                <div>
                                    <label class="block text-xs text-slate-500 dark:text-slate-400 mb-1">Drucker</label>
                                    <select id="exportPrinterFilter" class="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-white text-sm">
                                        <option value="">Alle Drucker</option>
                                        {% for printer in printers %}
                                        <option value="{{ printer.id }}">{{ printer.name }}{% if printer.location %} ({{ printer.location }}){% endif %}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div>
                                    <label class="block text-xs text-slate-500 dark:text-slate-400 mb-1">Status</label>
                                    <select id="exportStatusFilter" class="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-white text-sm">
                                        <option value="">Alle Status</option>
                                        <option value="scheduled">Geplant</option>
                                        <option value="running">Läuft</option>
                                        <option value="finished">Abgeschlossen</option>
                                        <option value="cancelled">Abgebrochen</option>
                                        <option value="failed">Fehlgeschlagen</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="flex items-center justify-end gap-3 p-6 border-t border-slate-200 dark:border-slate-600">
                        <button onclick="hideExportModal()" class="px-4 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-800 dark:hover:text-slate-200 transition-colors">
                            Abbrechen
                        </button>
                        <button onclick="performExport()" class="px-6 py-2 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white rounded-lg transition-colors flex items-center gap-2">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                            </svg>
                            Export starten
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', modalHTML);
        
        // Format-Radio-Button-Styling
        document.querySelectorAll('.export-format-option input[type="radio"]').forEach(radio => {
            radio.addEventListener('change', function() {
                document.querySelectorAll('.export-format-option').forEach(option => {
                    option.classList.remove('border-blue-500', 'bg-blue-50', 'dark:bg-blue-900/20');
                });
                if (this.checked) {
                    this.closest('.export-format-option').classList.add('border-blue-500', 'bg-blue-50', 'dark:bg-blue-900/20');
                }
            });
        });
        
        // Standard-Zeitraum setzen (nächste 4 Wochen)
        setExportDateRange('month');
    }
    
    window.setExportDateRange = function(range) {
        const startDate = new Date();
        let endDate = new Date();
        
        if (range === 'week') {
            // Diese Woche (Montag bis Sonntag)
            const dayOfWeek = startDate.getDay() || 7; // Sonntag = 7
            startDate.setDate(startDate.getDate() - dayOfWeek + 1);
            endDate.setDate(startDate.getDate() + 6);
        } else if (range === 'month') {
            // Dieser Monat
            startDate.setDate(1);
            endDate = new Date(startDate.getFullYear(), startDate.getMonth() + 1, 0);
        } else if (range === 'quarter') {
            // Dieses Quartal
            const quarter = Math.floor(startDate.getMonth() / 3);
            startDate.setMonth(quarter * 3, 1);
            endDate = new Date(startDate.getFullYear(), quarter * 3 + 3, 0);
        }
        
        document.getElementById('exportStartDate').value = startDate.toISOString().split('T')[0];
        document.getElementById('exportEndDate').value = endDate.toISOString().split('T')[0];
    };
    
    window.performExport = async function(retryCount = 0) {
        try {
            // Export-Parameter sammeln
            const format = document.querySelector('input[name="exportFormat"]:checked').value;
            const startDate = document.getElementById('exportStartDate').value;
            const endDate = document.getElementById('exportEndDate').value;
            const printerId = document.getElementById('exportPrinterFilter').value;
            const status = document.getElementById('exportStatusFilter').value;
            
            // Validierung
            if (!startDate || !endDate) {
                showErrorNotification('Bitte wählen Sie einen gültigen Zeitraum aus.');
                return;
            }
            
            if (new Date(startDate) > new Date(endDate)) {
                showErrorNotification('Das Startdatum darf nicht nach dem Enddatum liegen.');
                return;
            }
            
            // URL-Parameter zusammenstellen
            const params = new URLSearchParams({
                format: format,
                start_date: startDate + 'T00:00:00',
                end_date: endDate + 'T23:59:59'
            });
            
            if (printerId) params.append('printer_id', printerId);
            if (status) params.append('status', status);
            
            // Loading-State anzeigen
            const exportButton = document.querySelector('button[onclick="performExport()"]');
            const originalHTML = exportButton.innerHTML;
            exportButton.disabled = true;
            
            // Retry-spezifische Loading-Anzeige
            let loadingText = 'Exportiere...';
            if (retryCount > 0) {
                loadingText = `Wiederhole Export (${retryCount}/3)...`;
            }
            
            exportButton.innerHTML = `
                <svg class="animate-spin w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                ${loadingText}
            `;
            
            // Export-Request
            const response = await fetch(`/api/calendar/export?${params.toString()}`);
            
            if (response.ok) {
                // Datei-Download initiieren
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                
                // Dateiname aus Content-Disposition-Header extrahieren
                const contentDisposition = response.headers.get('Content-Disposition');
                let filename = `schichtplan_export_${new Date().toISOString().split('T')[0]}.${format}`;
                
                if (contentDisposition) {
                    const filenameMatch = contentDisposition.match(/filename="(.+)"/);
                    if (filenameMatch) {
                        filename = filenameMatch[1];
                    }
                }
                
                link.href = url;
                link.download = filename;
                link.style.display = 'none';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                window.URL.revokeObjectURL(url);
                
                // Erfolg anzeigen
                let successMessage = `📊 ${format.toUpperCase()}-Export erfolgreich heruntergeladen`;
                if (retryCount > 0) {
                    successMessage += ` (nach ${retryCount} Wiederholung${retryCount > 1 ? 'en' : ''})`;
                }
                showSuccessNotification(successMessage);
                hideExportModal();
                
            } else if (response.status === 404 && retryCount < 3) {
                // Temporärer 404-Fehler: Automatische Wiederholung
                console.warn(`Temporärer 404-Fehler beim Export (Versuch ${retryCount + 1}/3). Wiederhole in 2 Sekunden...`);
                
                // Button-Text für Retry aktualisieren
                exportButton.innerHTML = `
                    <svg class="animate-pulse w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                    Wiederhole in 2s...
                `;
                
                // Nach 2 Sekunden automatisch wiederholen
                setTimeout(() => {
                    window.performExport(retryCount + 1);
                }, 2000);
                
                return; // Nicht den finally-Block ausführen
                
            } else if (response.status === 401 || response.status === 302) {
                // Authentifizierung erforderlich
                showErrorNotification('⚠️ Sitzung abgelaufen. Bitte melden Sie sich erneut an.');
                
                // Optional: Automatische Weiterleitung zur Login-Seite
                setTimeout(() => {
                    window.location.href = '/auth/login?next=' + encodeURIComponent(window.location.pathname);
                }, 2000);
                
            } else {
                const errorData = await response.json().catch(() => null);
                const errorMessage = errorData?.error || `HTTP ${response.status}: ${response.statusText}`;
                throw new Error(errorMessage);
            }
            
        } catch (error) {
            console.error('Export-Fehler:', error);
            
            // Bei Netzwerkfehlern oder anderen temporären Problemen: Retry
            if ((error.name === 'NetworkError' || error.message.includes('fetch')) && retryCount < 3) {
                console.warn(`Netzwerkfehler beim Export (Versuch ${retryCount + 1}/3). Wiederhole in 3 Sekunden...`);
                
                const exportButton = document.querySelector('button[onclick="performExport()"]');
                exportButton.innerHTML = `
                    <svg class="animate-pulse w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                    Netzwerkfehler - Wiederhole in 3s...
                `;
                
                setTimeout(() => {
                    window.performExport(retryCount + 1);
                }, 3000);
                
                return; // Nicht den finally-Block ausführen
            }
            
            // Finaler Fehler nach allen Retry-Versuchen
            let errorMessage = `Export fehlgeschlagen: ${error.message}`;
            if (retryCount > 0) {
                errorMessage = `Export nach ${retryCount} Wiederholung${retryCount > 1 ? 'en' : ''} fehlgeschlagen: ${error.message}`;
            }
            showErrorNotification(errorMessage);
            
        } finally {
            // Loading-State zurücksetzen (nur wenn kein Retry läuft)
            const exportButton = document.querySelector('button[onclick="performExport()"]');
            if (exportButton && !exportButton.innerHTML.includes('Wiederhole')) {
                exportButton.disabled = false;
                exportButton.innerHTML = `
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                    </svg>
                    Export starten
                `;
            }
        }
    };
    
    // Modal schließen bei Klick außerhalb
    document.addEventListener('click', function(event) {
        const exportModal = document.getElementById('exportModal');
        if (exportModal && event.target === exportModal) {
            hideExportModal();
        }
    });
});
</script>
{% endblock %} 