{% extends "base.html" %}

{% block title %}Mein Kalender{% 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; }
    .post-chip.approved { background: #3b82f6; color: white; }
    .post-chip.ready { background: #22c55e; color: white; }
    .view-toggle .active { background: #ffc700; color: #2d3838; }

    .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-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;
    }
    .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.ready { background: #22c55e; color: white; }
</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">Mein Kalender</h1>
            <p class="text-gray-400 mt-1">Deine geplanten und freigegebenen Posts</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="/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="/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="/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="/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="/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="/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="/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="/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>

    <!-- Status Legend -->
    <div class="card-bg border rounded-xl p-4 mb-6">
        <p class="text-sm text-gray-400 mb-3">Status</p>
        <div class="flex flex-wrap gap-4">
            <div class="flex items-center gap-2"><div class="w-3 h-3 rounded" style="background:#3b82f6;"></div><span class="text-sm text-white">Bearbeitet</span></div>
            <div class="flex items-center gap-2"><div class="w-3 h-3 rounded" style="background:#22c55e;"></div><span class="text-sm text-white">Freigegeben</span></div>
            <div class="flex items-center gap-2"><div class="w-3 h-3 rounded" style="background:#ffc700;"></div><span class="text-sm text-white">Geplant</span></div>
            <div class="flex items-center gap-2"><div class="w-3 h-3 rounded" style="background:#6b7280;"></div><span class="text-sm text-white">Veröffentlicht</span></div>
        </div>
    </div>

    <!-- Calendar -->
    {% if view == 'week' %}
    <div class="card-bg border rounded-xl overflow-hidden">
        <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>
        <div class="timeline-grid" id="timelineGrid">
            {% for hour in range(0, 24) %}
            <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 }}">
                {% for post in day.posts %}
                    {% set post_hour = post.time[:2]|int %}
                    {% if post_hour == hour %}
                    <div class="timeline-post {{ post.status }}"
                         onclick="window.location.href='/posts/{{ post.id }}'"
                         title="{{ post.topic_title }}"
                         style="top: {{ post.time[3:]|int }}px;">
                        <div style="font-weight:600;font-size:10px;">{{ post.time }}</div>
                        <div style="font-size:10px;">{{ post.topic_title[:20] }}{% if post.topic_title|length > 20 %}...{% endif %}</div>
                    </div>
                    {% endif %}
                {% endfor %}
            </div>
            {% endfor %}
            {% endfor %}
        </div>
    </div>
    {% else %}
    <div class="card-bg border rounded-xl overflow-hidden">
        <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>
        <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>
                    {% for post in day.posts %}
                    <div class="post-chip {{ post.status }}"
                         onclick="window.location.href='/posts/{{ post.id }}'"
                         title="{{ post.topic_title }}">
                        <span style="font-size:10px;color:inherit;opacity:0.8;">{{ post.time }}</span>
                        {{ post.topic_title[:20] }}{% if post.topic_title|length > 20 %}...{% endif %}
                    </div>
                    {% endfor %}
                </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 eingeplante Posts</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 border border-transparent hover:border-brand-highlight transition-colors">
                <div class="flex items-start justify-between gap-2 mb-2">
                    <span class="text-xs px-2 py-1 rounded {% if post.status == 'ready' %}bg-green-500/20 text-green-400{% else %}bg-blue-500/20 text-blue-400{% endif %} inline-block">{{ post.status }}</span>
                    {% if post.status == 'ready' %}
                    <button onclick="openScheduleModalForPost('{{ post.id }}', '{{ post.topic_title | replace("'", "\\'") }}')"
                            class="text-xs px-2 py-1 bg-brand-highlight text-brand-bg-dark rounded font-medium hover:bg-brand-highlight-dark transition-colors flex-shrink-0">
                        Planen
                    </button>
                    {% endif %}
                </div>
                <a href="/posts/{{ post.id }}" class="block">
                    <p class="text-white text-sm font-medium mt-1">{{ post.topic_title }}</p>
                    <p class="text-gray-400 text-xs line-clamp-2 mt-1">{{ post.post_content[:100] }}...</p>
                </a>
            </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>
        <p id="schedulePostTitle" class="text-gray-300 text-sm mb-4"></p>
        <form id="scheduleForm" onsubmit="submitSchedule(event)">
            <input type="hidden" id="schedulePostId" name="post_id">
            <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>
            <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 font-medium">
                    Einplanen
                </button>
            </div>
        </form>
    </div>
</div>

{% endblock %}

{% block scripts %}
<script>
    function openScheduleModalForPost(postId, title) {
        document.getElementById('schedulePostId').value = postId;
        document.getElementById('schedulePostTitle').textContent = title ? `"${title}"` : '';
        const today = new Date().toISOString().split('T')[0];
        document.getElementById('scheduleDate').value = today;
        document.getElementById('scheduleTime').value = '09:00';
        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;
        const date = document.getElementById('scheduleDate').value;
        const time = document.getElementById('scheduleTime').value;

        if (!postId) return;

        const localDateTime = new Date(`${date}T${time}:00`);
        if (localDateTime < new Date()) {
            alert('Der gewählte Zeitpunkt liegt in der Vergangenheit.');
            return;
        }

        try {
            const formData = new FormData();
            formData.append('scheduled_at', localDateTime.toISOString());
            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);
        }
    }

    document.getElementById('scheduleModal').addEventListener('click', function(e) {
        if (e.target === this) closeScheduleModal();
    });
</script>
{% endblock %}
