{% extends "base.html" %}

{% block title %}Blog verwalten{% endblock %}

{% block head %}
{{ super() }}
<style>
    .blog-admin-grid {
        display: grid;
        grid-template-columns: 0.7fr 1.3fr;
        gap: 1.2rem;
    }

    .new-post-form {
        background: #ffffff;
        border: 1px solid #d4e0e9;
        border-radius: 16px;
        padding: 1.4rem;
        box-shadow: 0 14px 32px rgba(20, 39, 55, 0.06);
        height: fit-content;
        position: sticky;
        top: 100px;
    }

    .new-post-form h2 {
        font-size: 1.2rem;
        color: #0f354d;
        margin: 0 0 0.9rem;
    }

    .section-separator {
        margin: 1.2rem 0;
        border: 0;
        border-top: 1px solid #dbe5ec;
    }

    .field-hint {
        margin-top: 0.35rem;
        color: #47657b;
        font-size: 0.82rem;
        line-height: 1.45;
    }

    .preview-status {
        margin-top: 0.55rem;
        padding: 0.5rem 0.62rem;
        border-radius: 8px;
        font-size: 0.82rem;
        border: 1px solid #c8d7e3;
        background: #f3f8fc;
        color: #2a4f68;
    }

    .preview-status.success {
        border-color: #b8d9c6;
        background: #eef8f2;
        color: #255b3f;
    }

    .preview-status.error {
        border-color: #e3c2c2;
        background: #fcf2f2;
        color: #7b2e2e;
    }

    .preview-panel {
        margin-top: 0.75rem;
        border: 1px solid #d1dde7;
        border-radius: 12px;
        overflow: hidden;
        background: #0e1c27;
    }

    .preview-frame-wrap {
        position: relative;
        width: 100%;
        padding-bottom: 56.25%;
        height: 0;
    }

    .preview-frame-wrap iframe {
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        border: 0;
    }

    .preview-empty {
        display: grid;
        place-items: center;
        padding: 1rem;
        min-height: 96px;
        background: #f5f8fb;
        color: #47657b;
        font-size: 0.85rem;
        border-top: 1px solid #d1dde7;
    }

    .hint-list {
        margin: 0.35rem 0 0;
        padding-left: 1.1rem;
    }

    .hint-list li {
        margin: 0.2rem 0;
    }

    .field {
        margin-bottom: 0.9rem;
    }

    .field label {
        display: block;
        margin-bottom: 0.3rem;
        font-weight: 700;
        color: #1f4b65;
        font-size: 0.9rem;
    }

    .field input,
    .field textarea {
        width: 100%;
        border: 1px solid #c4d4e0;
        border-radius: 10px;
        padding: 0.65rem 0.72rem;
        font: inherit;
        color: #143f5d;
        background: #ffffff;
    }

    .field textarea {
        min-height: 120px;
        resize: vertical;
    }

    .field input:focus,
    .field textarea:focus {
        outline: none;
        border-color: #2f79a7;
        box-shadow: 0 0 0 3px rgba(58, 133, 180, 0.2);
    }

    .submit-btn {
        width: 100%;
        border: none;
        border-radius: 999px;
        padding: 0.72rem;
        font-size: 0.95rem;
        font-weight: 700;
        color: #ffffff;
        background: linear-gradient(120deg, #0a5f8f 0%, #0b4567 100%);
        cursor: pointer;
    }

    .posts-list {
        display: grid;
        gap: 0.8rem;
    }

    .post-card {
        background: #ffffff;
        border: 1px solid #d4e0e9;
        border-radius: 14px;
        padding: 1.1rem;
        box-shadow: 0 10px 28px rgba(20, 40, 55, 0.05);
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        gap: 1rem;
    }

    .post-info h3 {
        font-size: 1.05rem;
        color: #113d59;
        margin: 0 0 0.25rem;
    }

    .post-info p {
        margin: 0.2rem 0;
        font-size: 0.9rem;
        color: #5a7a8f;
    }

    .post-meta {
        font-size: 0.8rem;
        color: #7a8fa2;
        margin-top: 0.3rem;
    }

    .delete-form {
        display: flex;
    }

    .delete-btn {
        border: none;
        border-radius: 6px;
        padding: 0.4rem 0.7rem;
        font-size: 0.8rem;
        font-weight: 700;
        color: #ffffff;
        background: linear-gradient(120deg, #a74444 0%, #8a3535 100%);
        cursor: pointer;
    }

    @media (max-width: 980px) {
        .blog-admin-grid {
            grid-template-columns: 1fr;
        }

        .new-post-form {
            position: static;
        }
    }
</style>
{% endblock %}

{% block content %}
<div style="display:flex; gap:0.8rem; align-items:center; justify-content:space-between; flex-wrap:wrap; margin-bottom: 1.2rem;">
    <h1 style="font-size: 2rem; color: #0f354d; margin: 0;">Blog verwalten</h1>
    <a href="{{ url_for('admin_tutorial_upload') }}" style="display:inline-flex; align-items:center; gap:0.45rem; padding:0.68rem 1rem; border-radius:999px; border:1px solid #0a4c74; color:#0a4c74; font-weight:700; background:#fff; text-decoration:none;">Tutorial-Upload öffnen</a>
</div>

<section class="blog-admin-grid">
    <aside class="new-post-form">
        <h2>Neuer Beitrag</h2>
        <form method="POST" action="{{ url_for('admin_blog') }}">
            <div class="field">
                <label for="title">Titel</label>
                <input
                    id="title"
                    name="title"
                    type="text"
                    placeholder="Beitragstitel"
                    required
                />
            </div>
            <div class="field">
                <label for="excerpt">Zusammenfassung</label>
                <textarea
                    id="excerpt"
                    name="excerpt"
                    placeholder="Optionale Kurzbeschreibung"
                ></textarea>
            </div>
            <div class="field">
                <label for="content">Inhalt</label>
                <textarea
                    id="content"
                    name="content"
                    placeholder="Beitrag schreiben..."
                    required
                ></textarea>
            </div>
            <input type="hidden" name="action" value="create" />
            <button type="submit" class="submit-btn">Veröffentlichen</button>
        </form>

        <hr class="section-separator" />

        <h2>Tutorial-Video hinzufügen</h2>
        <form method="POST" action="{{ url_for('append_video') }}">
            <div class="field">
                <label for="tutorial_title">Titel</label>
                <input
                    id="tutorial_title"
                    name="title"
                    type="text"
                    placeholder="z. B. Erste Schritte"
                    required
                />
            </div>
            <div class="field">
                <label for="tutorial_video_url">Video-URL</label>
                <input
                    id="tutorial_video_url"
                    name="video_url"
                    type="url"
                    placeholder="https://www.youtube.com/watch?v=..."
                    required
                />
                <div class="field-hint">
                    Erlaubte Formate:
                    <ul class="hint-list">
                        <li>https://www.youtube.com/watch?v=VIDEO_ID</li>
                        <li>https://youtu.be/VIDEO_ID</li>
                        <li>https://www.youtube.com/shorts/VIDEO_ID</li>
                        <li>https://www.youtube.com/embed/VIDEO_ID</li>
                    </ul>
                </div>
                <div id="preview-status" class="preview-status" aria-live="polite">
                    Vorschau wird angezeigt, sobald eine gueltige YouTube-URL erkannt wird.
                </div>
                <div class="preview-panel">
                    <div class="preview-frame-wrap" id="preview-frame-wrap" hidden>
                        <iframe
                            id="tutorial-video-preview"
                            src=""
                            title="Live Vorschau Tutorial-Video"
                            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                            referrerpolicy="strict-origin-when-cross-origin"
                            allowfullscreen
                        ></iframe>
                    </div>
                    <div id="preview-empty" class="preview-empty">
                        Noch keine Vorschau verfuegbar.
                    </div>
                </div>
            </div>
            <div class="field">
                <label for="tutorial_description">Beschreibung</label>
                <textarea
                    id="tutorial_description"
                    name="description"
                    placeholder="Kurze Beschreibung des Videos"
                ></textarea>
            </div>
            <div class="field">
                <label for="tutorial_thumbnail">Thumbnail-URL (optional)</label>
                <input
                    id="tutorial_thumbnail"
                    name="thumbnail_url"
                    type="url"
                    placeholder="https://..."
                />
            </div>
            <div class="field">
                <label for="tutorial_duration">Dauer (optional)</label>
                <input
                    id="tutorial_duration"
                    name="duration"
                    type="text"
                    placeholder="z. B. 12:34"
                />
            </div>
            <div class="field">
                <label for="tutorial_category">Kategorie (optional)</label>
                <input
                    id="tutorial_category"
                    name="category"
                    type="text"
                    placeholder="z. B. Anfänger"
                />
            </div>
            <button type="submit" class="submit-btn">Video hinzufügen</button>
        </form>
    </aside>

    <article>
        <h2 style="font-size: 1.2rem; color: #0f354d; margin: 0 0 0.8rem;">Veröffentlichte Beiträge</h2>
        <section class="posts-list">
            {% if posts %}
                {% for post in posts %}
                    <article class="post-card">
                        <div class="post-info">
                            <h3>{{ post.title }}</h3>
                            <p>{{ post.excerpt }}</p>
                            <div class="post-meta">
                                <strong>Autor:</strong> {{ post.author }}<br />
                                <strong>Veröffentlicht:</strong> {{ post.created_at[:10] }}
                            </div>
                        </div>
                        <form method="POST" action="{{ url_for('admin_blog') }}" class="delete-form">
                            <input type="hidden" name="action" value="delete" />
                            <input type="hidden" name="post_id" value="{{ post.id }}" />
                            <button type="submit" class="delete-btn" onclick="return confirm('Sicher?')">Löschen</button>
                        </form>
                    </article>
                {% endfor %}
            {% else %}
                <p>Noch keine Beiträge veröffentlicht.</p>
            {% endif %}
        </section>
    </article>
</section>

<script>
    (function () {
        const input = document.getElementById("tutorial_video_url");
        const status = document.getElementById("preview-status");
        const frameWrap = document.getElementById("preview-frame-wrap");
        const frame = document.getElementById("tutorial-video-preview");
        const empty = document.getElementById("preview-empty");

        function extractYoutubeId(rawUrl) {
            let parsed;
            try {
                parsed = new URL((rawUrl || "").trim());
            } catch {
                return "";
            }

            const host = parsed.hostname.toLowerCase();
            const path = parsed.pathname;

            if (host === "youtu.be" || host === "www.youtu.be") {
                return path.replace(/^\//, "").split("/")[0] || "";
            }

            if (host.includes("youtube.com")) {
                if (path === "/watch") {
                    return parsed.searchParams.get("v") || "";
                }
                if (path.startsWith("/shorts/")) {
                    return path.split("/shorts/")[1].split("/")[0] || "";
                }
                if (path.startsWith("/embed/")) {
                    return path.split("/embed/")[1].split("/")[0] || "";
                }
            }

            if (host.includes("youtube-nocookie.com") && path.startsWith("/embed/")) {
                return path.split("/embed/")[1].split("/")[0] || "";
            }

            return "";
        }

        function toEmbedUrl(videoId) {
            const origin = encodeURIComponent(window.location.origin);
            return `https://www.youtube-nocookie.com/embed/${videoId}?rel=0&modestbranding=1&playsinline=1&origin=${origin}`;
        }

        function updatePreview() {
            const videoId = extractYoutubeId(input.value);
            const validId = /^[A-Za-z0-9_-]{6,20}$/.test(videoId);

            if (!input.value.trim()) {
                frame.src = "";
                frameWrap.hidden = true;
                empty.hidden = false;
                status.className = "preview-status";
                status.textContent = "Vorschau wird angezeigt, sobald eine gueltige YouTube-URL erkannt wird.";
                return;
            }

            if (!validId) {
                frame.src = "";
                frameWrap.hidden = true;
                empty.hidden = false;
                status.className = "preview-status error";
                status.textContent = "Keine gueltige YouTube-URL erkannt.";
                return;
            }

            frame.src = toEmbedUrl(videoId);
            frameWrap.hidden = false;
            empty.hidden = true;
            status.className = "preview-status success";
            status.textContent = "Gueltige URL erkannt. Live-Vorschau aktiv.";
        }

        input.addEventListener("input", updatePreview);
        input.addEventListener("change", updatePreview);
    })();
</script>
{% endblock %}
