{% extends "company_base.html" %}

{% block title %}Posting-Kalender - {{ session.company_name }}{% endblock %}

{% block head %}
<style>
    .calendar-grid {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        gap: 1px;
        background: #5a6868;
    }
    .calendar-cell {
        background: #4a5858;
        min-height: 120px;
        padding: 8px;
    }
    .calendar-cell.other-month {
        background: #3d4848;
        opacity: 0.5;
    }
    .calendar-cell.today {
        border: 2px solid #ffc700;
    }
    .post-chip {
        font-size: 11px;
        padding: 4px 8px;
        border-radius: 4px;
        margin-bottom: 4px;
        cursor: pointer;
        transition: transform 0.1s;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .post-chip:hover {
        transform: scale(1.02);
    }
    .post-chip.scheduled {
        background: #ffc700;
        color: #2d3838;
    }
    .post-chip.published {
        background: #6b7280;
        color: #9ca3af;
        opacity: 0.6;
        cursor: pointer;
    }
    .post-chip.approved {
        background: #3b82f6;
        color: white;
    }
    .employee-color-1 { border-left: 3px solid #f472b6; }
    .employee-color-2 { border-left: 3px solid #60a5fa; }
    .employee-color-3 { border-left: 3px solid #34d399; }
    .employee-color-4 { border-left: 3px solid #fbbf24; }
    .employee-color-5 { border-left: 3px solid #a78bfa; }
    .time-slot {
        font-size: 10px;
        color: #9ca3af;
        margin-bottom: 2px;
    }
    .view-toggle .active {
        background: #ffc700;
        color: #2d3838;
    }

    /* Timeline Week View */
    .timeline-header {
        display: grid;
        grid-template-columns: 50px repeat(7, 1fr);
        background: #3d4848;
    }
    .timeline-header-cell {
        padding: 8px 4px;
        text-align: center;
        font-size: 13px;
        color: #9ca3af;
        border-left: 1px solid #5a6868;
    }
    .timeline-header-cell.today {
        color: #ffc700;
        font-weight: bold;
    }
    .timeline-grid {
        display: grid;
        grid-template-columns: 50px repeat(7, 1fr);
        position: relative;
    }
    .timeline-hour-label {
        font-size: 11px;
        color: #6b7280;
        text-align: right;
        padding-right: 8px;
        height: 60px;
        line-height: 1;
        padding-top: 0;
        transform: translateY(-6px);
    }
    .timeline-day-col {
        position: relative;
        height: 60px;
        border-top: 1px solid #5a6868;
        border-left: 1px solid #5a6868;
    }
    .timeline-day-col:hover {
        background: rgba(255, 199, 0, 0.03);
    }
    .timeline-day-col.past-slot {
        cursor: default !important;
        opacity: 0.4;
    }
    .timeline-day-col.past-slot:hover {
        background: none;
    }
    .calendar-cell .schedule-btn.past-slot {
        display: none !important;
    }
    .timeline-post {
        position: absolute;
        left: 2px;
        right: 2px;
        height: 36px;
        border-radius: 4px;
        padding: 2px 6px;
        font-size: 10px;
        cursor: pointer;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        z-index: 5;
        transition: transform 0.1s, z-index 0s;
        line-height: 1.4;
    }
    .timeline-post:hover {
        transform: scale(1.03);
        z-index: 20;
    }
    .timeline-post.scheduled {
        background: #ffc700;
        color: #2d3838;
    }
    .timeline-post.approved {
        background: #3b82f6;
        color: white;
    }
    .timeline-post.published {
        background: #374151;
        color: #9ca3af;
        border: 1px solid #6b7280;
    }
    .timeline-post .timeline-post-time {
        font-weight: 600;
        font-size: 10px;
    }
    .timeline-post .timeline-post-title {
        font-size: 10px;
        opacity: 0.9;
    }
</style>
{% endblock %}

{% block content %}
<div class="max-w-7xl mx-auto">
    <!-- Header -->
    <div class="flex items-center justify-between mb-6">
        <div>
            <h1 class="text-2xl font-bold text-white">Posting-Kalender</h1>
            <p class="text-gray-400 mt-1">Plane und verwalte Posts aller Mitarbeiter</p>
        </div>
        <div class="flex items-center gap-4">
            <!-- View Toggle -->
            <div class="view-toggle flex rounded-lg overflow-hidden border border-gray-600">
                <a href="/company/calendar?month={{ month }}&year={{ year }}&view=month"
                   class="px-3 py-1.5 text-sm transition-colors {% if view == 'month' %}active{% else %}text-gray-300 hover:bg-brand-bg-dark{% endif %}">
                    Monat
                </a>
                <a href="/company/calendar?view=week&month={{ month }}&year={{ year }}"
                   class="px-3 py-1.5 text-sm transition-colors {% if view == 'week' %}active{% else %}text-gray-300 hover:bg-brand-bg-dark{% endif %}">
                    Woche
                </a>
            </div>

            <!-- Navigation -->
            <div class="flex items-center gap-2">
                {% if view == 'week' %}
                <a href="/company/calendar?view=week&week_start={{ prev_week_start }}&month={{ month }}&year={{ year }}" class="p-2 rounded-lg bg-brand-bg-dark hover:bg-brand-bg-light transition-colors">
                    <svg class="w-5 h-5 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                    </svg>
                </a>
                <span class="text-white font-medium min-w-[200px] text-center">{{ week_label }}</span>
                <a href="/company/calendar?view=week&week_start={{ next_week_start }}&month={{ month }}&year={{ year }}" class="p-2 rounded-lg bg-brand-bg-dark hover:bg-brand-bg-light transition-colors">
                    <svg class="w-5 h-5 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                    </svg>
                </a>
                {% else %}
                <a href="/company/calendar?month={{ prev_month }}&year={{ prev_year }}&view=month" class="p-2 rounded-lg bg-brand-bg-dark hover:bg-brand-bg-light transition-colors">
                    <svg class="w-5 h-5 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                    </svg>
                </a>
                <span class="text-white font-medium min-w-[150px] text-center">{{ month_name }} {{ year }}</span>
                <a href="/company/calendar?month={{ next_month }}&year={{ next_year }}&view=month" class="p-2 rounded-lg bg-brand-bg-dark hover:bg-brand-bg-light transition-colors">
                    <svg class="w-5 h-5 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                    </svg>
                </a>
                {% endif %}
            </div>
            {% if view == 'week' %}
            <a href="/company/calendar?view=week" class="px-4 py-2 text-sm bg-brand-bg-dark hover:bg-brand-bg-light rounded-lg text-gray-300 transition-colors">
                Heute
            </a>
            {% else %}
            <a href="/company/calendar?month={{ current_month }}&year={{ current_year }}" class="px-4 py-2 text-sm bg-brand-bg-dark hover:bg-brand-bg-light rounded-lg text-gray-300 transition-colors">
                Heute
            </a>
            {% endif %}
        </div>
    </div>

    <!-- Employee Legend -->
    {% if employees %}
    <div class="card-bg border rounded-xl p-4 mb-6">
        <p class="text-sm text-gray-400 mb-3">Mitarbeiter</p>
        <div class="flex flex-wrap gap-3">
            {% for emp in employees %}
            <div class="flex items-center gap-2">
                <div class="w-3 h-3 rounded employee-color-{{ loop.index % 5 + 1 }}" style="background: currentColor;"></div>
                <span class="text-sm text-white">{{ emp.name }}</span>
            </div>
            {% endfor %}
        </div>
    </div>
    {% endif %}

    <!-- Calendar -->
    {% if view == 'week' %}
    <!-- Week Timeline View -->
    <div class="card-bg border rounded-xl overflow-hidden">
        <!-- Day Headers -->
        <div class="timeline-header">
            <div class="timeline-header-cell" style="border-left: none;"></div>
            {% for day in calendar_weeks[0] %}
            <div class="timeline-header-cell {% if day.is_today %}today{% endif %}">
                {{ day.full_date }}
            </div>
            {% endfor %}
        </div>

        <!-- Timeline Grid -->
        <div class="timeline-grid" id="timelineGrid">
            {% for hour in range(0, 24) %}
            <!-- Hour row -->
            <div class="timeline-hour-label">{{ '%02d'|format(hour) }}:00</div>
            {% for day in calendar_weeks[0] %}
            <div class="timeline-day-col"
                 data-date="{{ day.date }}" data-hour="{{ hour }}"
                 onclick="openScheduleModal('{{ day.date }}', '{{ '%02d'|format(hour) }}:00')"
                 style="cursor: pointer;">
                {% for post in day.posts %}
                    {% set post_hour = post.time[:2]|int %}
                    {% if post_hour == hour %}
                    <div class="timeline-post {{ post.status }} employee-color-{{ post.employee_index % 5 + 1 }}"
                         onclick="event.stopPropagation(); openPostModal('{{ post.id }}')"
                         title="{{ post.employee_name }}: {{ post.topic_title }}"
                         data-day="{{ day.date }}"
                         data-abs-min="{{ post.time[:2]|int * 60 + post.time[3:]|int }}"
                         style="top: {% if post.status == 'published' %}{{ post.time[3:]|int - 36 }}{% else %}{{ post.time[3:]|int }}{% endif %}px;">
                        <div class="timeline-post-time">{{ post.time }}</div>
                        <div class="timeline-post-title">{{ post.topic_title[:15] }}{% if post.topic_title|length > 15 %}...{% endif %}</div>
                    </div>
                    {% endif %}
                {% endfor %}
            </div>
            {% endfor %}
            {% endfor %}
        </div>
    </div>
    {% else %}
    <!-- Month Grid View -->
    <div class="card-bg border rounded-xl overflow-hidden">
        <!-- Weekday Headers -->
        <div class="grid grid-cols-7 bg-brand-bg-dark">
            <div class="p-3 text-center text-gray-400 text-sm font-medium">Mo</div>
            <div class="p-3 text-center text-gray-400 text-sm font-medium">Di</div>
            <div class="p-3 text-center text-gray-400 text-sm font-medium">Mi</div>
            <div class="p-3 text-center text-gray-400 text-sm font-medium">Do</div>
            <div class="p-3 text-center text-gray-400 text-sm font-medium">Fr</div>
            <div class="p-3 text-center text-gray-400 text-sm font-medium">Sa</div>
            <div class="p-3 text-center text-gray-400 text-sm font-medium">So</div>
        </div>

        <!-- Calendar Grid -->
        <div class="calendar-grid">
            {% for week in calendar_weeks %}
                {% for day in week %}
                <div class="calendar-cell {% if day.other_month %}other-month{% endif %} {% if day.is_today %}today{% endif %}">
                    <div class="text-sm {% if day.is_today %}text-brand-highlight font-bold{% else %}text-gray-400{% endif %} mb-2">
                        {{ day.day }}
                    </div>
                    <!-- Posts for this day -->
                    {% for post in day.posts %}
                    <div class="post-chip {{ post.status }} employee-color-{{ post.employee_index % 5 + 1 }}"
                         onclick="openPostModal('{{ post.id }}')"
                         title="{{ post.employee_name }}: {{ post.topic_title }}">
                        <span class="time-slot">{{ post.time }}</span>
                        {{ post.topic_title[:20] }}{% if post.topic_title|length > 20 %}...{% endif %}
                    </div>
                    {% endfor %}
                    <!-- Add post button for empty slots -->
                    {% if not day.other_month %}
                    <button onclick="openScheduleModal('{{ day.date }}')"
                            data-date="{{ day.date }}"
                            class="schedule-btn w-full mt-1 p-1 text-xs text-gray-500 hover:text-brand-highlight hover:bg-brand-bg-dark rounded transition-colors opacity-0 hover:opacity-100">
                        + Post planen
                    </button>
                    {% endif %}
                </div>
                {% endfor %}
            {% endfor %}
        </div>
    </div>
    {% endif %}

    <!-- Unscheduled Posts -->
    {% if unscheduled_posts %}
    <div class="card-bg border rounded-xl p-6 mt-6">
        <h2 class="text-lg font-semibold text-white mb-4">Nicht geplante Posts (bereit zum Einplanen)</h2>
        <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
            {% for post in unscheduled_posts %}
            <div class="bg-brand-bg-dark rounded-lg p-4" draggable="true" data-post-id="{{ post.id }}">
                <div class="flex items-start justify-between mb-2">
                    <span class="text-xs px-2 py-1 rounded bg-blue-500/20 text-blue-400">{{ post.employee_name }}</span>
                    <span class="text-xs text-gray-500">{{ post.created_at.strftime('%d.%m.') }}</span>
                </div>
                <p class="text-white text-sm font-medium mb-1">{{ post.topic_title }}</p>
                <p class="text-gray-400 text-xs line-clamp-2">{{ post.post_content[:100] }}...</p>
                {% if post.can_schedule %}
                <button onclick="openScheduleModalForPost('{{ post.id }}', '{{ post.topic_title|e }}')"
                        class="mt-3 w-full py-2 text-xs bg-brand-highlight text-brand-bg-dark rounded hover:bg-brand-highlight-dark transition-colors">
                    Einplanen
                </button>
                {% else %}
                <div class="mt-3 w-full py-2 text-xs text-center text-gray-500 bg-gray-700/30 rounded">
                    Keine Berechtigung zum Einplanen
                </div>
                {% endif %}
            </div>
            {% endfor %}
        </div>
    </div>
    {% endif %}
</div>

<!-- Schedule Modal -->
<div id="scheduleModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
    <div class="bg-brand-bg-light rounded-xl p-6 w-full max-w-md mx-4">
        <h3 class="text-lg font-semibold text-white mb-4">Post einplanen</h3>
        <form id="scheduleForm" onsubmit="submitSchedule(event)">
            <input type="hidden" id="schedulePostId" name="post_id">

            <!-- Select Post (if no post pre-selected) -->
            <div id="postSelectContainer" class="mb-4">
                <label class="block text-sm text-gray-300 mb-2">Post auswahlen</label>
                <select id="schedulePostSelect" name="post_id_select" class="w-full input-bg border rounded-lg px-4 py-2 text-white">
                    <option value="">-- Post auswahlen --</option>
                    {% for post in unscheduled_posts %}
                    {% if post.can_schedule %}
                    <option value="{{ post.id }}">{{ post.employee_name }}: {{ post.topic_title[:40] }}...</option>
                    {% endif %}
                    {% endfor %}
                </select>
            </div>

            <!-- Date -->
            <div class="mb-4">
                <label class="block text-sm text-gray-300 mb-2">Datum</label>
                <input type="date" id="scheduleDate" name="date" required
                       class="w-full input-bg border rounded-lg px-4 py-2 text-white">
            </div>

            <!-- Time -->
            <div class="mb-6">
                <label class="block text-sm text-gray-300 mb-2">Uhrzeit</label>
                <input type="time" id="scheduleTime" name="time" value="09:00" required
                       class="w-full input-bg border rounded-lg px-4 py-2 text-white">
            </div>

            <div class="flex gap-3">
                <button type="button" onclick="closeScheduleModal()" class="flex-1 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-500 transition-colors">
                    Abbrechen
                </button>
                <button type="submit" class="flex-1 py-2 bg-brand-highlight text-brand-bg-dark rounded-lg hover:bg-brand-highlight-dark transition-colors">
                    Einplanen
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Post Detail Modal -->
<div id="postModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
    <div class="bg-brand-bg-light rounded-xl p-6 w-full max-w-lg mx-4">
        <div class="flex items-start justify-between mb-4">
            <h3 id="postModalTitle" class="text-lg font-semibold text-white">Post Details</h3>
            <button onclick="closePostModal()" class="text-gray-400 hover:text-white">
                <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="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        </div>
        <div id="postModalContent" class="text-gray-300">
            <!-- Filled via JS -->
        </div>
        <div id="postModalActions" class="mt-6 flex gap-3">
            <!-- Filled via JS -->
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    function isInPast(date, time) {
        const now = new Date();
        const check = time ? new Date(date + 'T' + time) : new Date(date + 'T23:59:59');
        return check < now;
    }

    function openScheduleModal(date, time) {
        if (isInPast(date, time)) return;
        document.getElementById('schedulePostId').value = '';
        document.getElementById('postSelectContainer').style.display = 'block';
        document.getElementById('scheduleDate').value = date;
        if (time) {
            document.getElementById('scheduleTime').value = time;
        }
        document.getElementById('scheduleModal').classList.remove('hidden');
        document.getElementById('scheduleModal').classList.add('flex');
    }

    function openScheduleModalForPost(postId, title) {
        document.getElementById('schedulePostId').value = postId;
        document.getElementById('postSelectContainer').style.display = 'none';
        // Set default date to today
        const today = new Date().toISOString().split('T')[0];
        document.getElementById('scheduleDate').value = today;
        document.getElementById('scheduleModal').classList.remove('hidden');
        document.getElementById('scheduleModal').classList.add('flex');
    }

    function closeScheduleModal() {
        document.getElementById('scheduleModal').classList.add('hidden');
        document.getElementById('scheduleModal').classList.remove('flex');
    }

    async function submitSchedule(event) {
        event.preventDefault();
        const postId = document.getElementById('schedulePostId').value || document.getElementById('schedulePostSelect').value;
        const date = document.getElementById('scheduleDate').value;
        const time = document.getElementById('scheduleTime').value;

        if (!postId) {
            alert('Bitte wahlen Sie einen Post aus');
            return;
        }

        if (isInPast(date, time)) {
            alert('Der gewählte Zeitpunkt liegt in der Vergangenheit.');
            return;
        }

        try {
            // Convert local time to UTC for backend
            const localDateTime = new Date(`${date}T${time}:00`);
            const utcDateTime = localDateTime.toISOString();

            const formData = new FormData();
            formData.append('scheduled_at', utcDateTime);

            const response = await fetch(`/api/posts/${postId}/schedule`, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.detail || 'Fehler beim Einplanen');
            }

            window.location.reload();
        } catch (error) {
            alert('Fehler: ' + error.message);
        }
    }

    async function openPostModal(postId) {
        document.getElementById('postModal').classList.remove('hidden');
        document.getElementById('postModal').classList.add('flex');
        document.getElementById('postModalContent').innerHTML = '<p class="text-gray-400">Laden...</p>';
        document.getElementById('postModalActions').innerHTML = '';

        // Fetch post details
        try {
            const response = await fetch(`/api/posts/${postId}`, {
                credentials: 'same-origin'
            });

            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                throw new Error(errorData.detail || `HTTP ${response.status}`);
            }

            const post = await response.json();

            document.getElementById('postModalTitle').textContent = post.topic_title || 'Post Details';

            const scheduledAt = post.scheduled_at ? new Date(post.scheduled_at).toLocaleString('de-DE') : 'Nicht geplant';
            const statusLabel = {
                'scheduled': 'Geplant',
                'published': 'Veroffentlicht',
                'approved': 'Bereit',
                'draft': 'Entwurf'
            }[post.status] || post.status;

            document.getElementById('postModalContent').innerHTML = `
                <div class="mb-4">
                    <span class="text-xs px-2 py-1 rounded ${post.status === 'scheduled' ? 'bg-yellow-500/20 text-yellow-400' : post.status === 'published' ? 'bg-green-500/20 text-green-400' : 'bg-blue-500/20 text-blue-400'}">
                        ${statusLabel}
                    </span>
                    ${post.status === 'scheduled' ? `<span class="text-xs text-gray-400 ml-2">${scheduledAt}</span>` : ''}
                </div>
                <div class="bg-brand-bg-dark rounded-lg p-4 max-h-64 overflow-y-auto">
                    <p class="text-sm whitespace-pre-wrap">${post.post_content}</p>
                </div>
            `;

            let actionsHtml = `
                <a href="/company/manage/post/${postId}" class="flex-1 py-2 text-center bg-brand-bg-dark text-white rounded-lg hover:bg-gray-600 transition-colors">
                    Details ansehen
                </a>
            `;

            if (post.status === 'scheduled') {
                actionsHtml += `
                    <button onclick="unschedulePost('${postId}')" class="flex-1 py-2 bg-red-500/20 text-red-400 rounded-lg hover:bg-red-500/30 transition-colors">
                        Planung aufheben
                    </button>
                `;
            } else if (post.status === 'approved') {
                actionsHtml += `
                    <button onclick="closePostModal(); openScheduleModalForPost('${postId}', '')" class="flex-1 py-2 bg-brand-highlight text-brand-bg-dark rounded-lg hover:bg-brand-highlight-dark transition-colors">
                        Einplanen
                    </button>
                `;
            }

            document.getElementById('postModalActions').innerHTML = actionsHtml;
        } catch (error) {
            console.error('Error loading post:', error);
            document.getElementById('postModalContent').innerHTML = `<p class="text-red-400">Fehler beim Laden: ${error.message}</p>`;
        }
    }

    function closePostModal() {
        document.getElementById('postModal').classList.add('hidden');
        document.getElementById('postModal').classList.remove('flex');
    }

    async function unschedulePost(postId) {
        if (!confirm('Mochten Sie die Planung dieses Posts wirklich aufheben?')) return;

        try {
            const response = await fetch(`/api/posts/${postId}/unschedule`, {
                method: 'POST',
                credentials: 'same-origin'
            });

            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.detail || 'Fehler beim Aufheben der Planung');
            }

            window.location.reload();
        } catch (error) {
            alert('Fehler: ' + error.message);
        }
    }

    // Close modals on outside click
    document.getElementById('scheduleModal').addEventListener('click', function(e) {
        if (e.target === this) closeScheduleModal();
    });
    document.getElementById('postModal').addEventListener('click', function(e) {
        if (e.target === this) closePostModal();
    });

    // Layout overlapping timeline posts side by side
    (function() {
        const grid = document.getElementById('timelineGrid');
        if (!grid) return;

        const POST_HEIGHT = 36;
        const dayPosts = {};

        grid.querySelectorAll('.timeline-post').forEach(el => {
            const day = el.dataset.day;
            const absMin = parseInt(el.dataset.absMin);
            const isPublished = el.classList.contains('published');
            const top = isPublished ? absMin - POST_HEIGHT : absMin;
            if (!dayPosts[day]) dayPosts[day] = [];
            dayPosts[day].push({ el, top, bottom: top + POST_HEIGHT });
        });

        Object.values(dayPosts).forEach(posts => {
            if (posts.length <= 1) return;
            posts.sort((a, b) => a.top - b.top);

            // Group overlapping posts
            const groups = [];
            let group = [posts[0]];

            for (let i = 1; i < posts.length; i++) {
                const overlaps = group.some(p => posts[i].top < p.bottom && posts[i].bottom > p.top);
                if (overlaps) {
                    group.push(posts[i]);
                } else {
                    groups.push(group);
                    group = [posts[i]];
                }
            }
            groups.push(group);

            groups.forEach(g => {
                if (g.length <= 1) return;
                const w = 100 / g.length;
                g.forEach((p, idx) => {
                    p.el.style.left = (idx * w) + '%';
                    p.el.style.width = w + '%';
                    p.el.style.right = 'auto';
                });
            });
        });
    })();

    // Dim past slots and hide past schedule buttons
    (function() {
        const now = new Date();
        const todayStr = now.toISOString().split('T')[0];
        const currentHour = now.getHours();

        // Week view: dim past hour cells
        document.querySelectorAll('.timeline-day-col').forEach(cell => {
            const date = cell.dataset.date;
            const hour = parseInt(cell.dataset.hour);
            if (date < todayStr || (date === todayStr && hour <= currentHour)) {
                cell.classList.add('past-slot');
                cell.removeAttribute('onclick');
            }
        });

        // Month view: hide "+ Post planen" for past dates
        document.querySelectorAll('.schedule-btn').forEach(btn => {
            const date = btn.dataset.date;
            if (date < todayStr) {
                btn.classList.add('past-slot');
            }
        });
    })();

</script>
{% endblock %}
