{% extends "base.html" %}
{% load static %}

{% block title %}Subscribarr – Overview{% endblock %}

{% block extra_style %}
<link rel="stylesheet" href="{% static 'css/index.css' %}">
{% endblock %}

{% block content %}
<div class="debug-info">
    kind={{ kind }} · days={{ days }} · series={{ series_grouped|length }} · movies={{ movies|length }}
</div>


{% csrf_token %}
<div class="wrap">
    <h1>Subscribarr</h1>

    <div class="controls">
        <form method="get" class="controls-form">
            <input type="hidden" name="kind" value="{{ kind|default:'all' }}">
            <input type="text" name="q" placeholder="Search series/movies…" value="{{ query|default:'' }}">
            <input type="number" name="days" min="1" max="365" value="{{ days|default:30 }}" title="Time range (days)">
            <button type="submit">Search</button>
        </form>

        <nav class="seg" aria-label="Filter type">
            {% with qs=query|urlencode %}
            <a href="?kind=all&days={{ days }}{% if qs %}&q={{ qs }}{% endif %}"
                class="{% if kind == 'all' %}active{% endif %}">All</a>
            <a href="?kind=series&days={{ days }}{% if qs %}&q={{ qs }}{% endif %}"
                class="{% if kind == 'series' %}active{% endif %}">Series</a>
            <a href="?kind=movies&days={{ days }}{% if qs %}&q={{ qs }}{% endif %}"
                class="{% if kind == 'movies' %}active{% endif %}">Movies</a>
            {% endwith %}
        </nav>

        <div class="controls-actions">
            <a href="/calendar/" class="btn btn-accent" title="Open calendar">📅 Calendar</a>
        </div>
    </div>

    {% if show_series %}
    <div class="section">
    <h2>Ongoing series</h2>
        <div class="grid">
            {% for s in series_grouped %}
            <div class="card" data-series-id="{{ s.seriesId }}" data-title="{{ s.seriesTitle|escape }}"
                data-poster="{{ s.seriesPoster|default:'' }}" data-overview="{{ s.seriesOverview|default:''|escape }}">
                <div class="poster">
                    {% if s.seriesPoster %}
                    <img src="{{ s.seriesPoster }}" alt="{{ s.seriesTitle }}">
                    {% else %}
                    <img src="https://via.placeholder.com/110x165?text=No+Poster" alt="">
                    {% endif %}
                </div>
                <div class="meta">
                    <div class="title" title="{{ s.seriesTitle }}">{{ s.seriesTitle }}</div>
                    <div class="episodes">
                        {% for e in s.episodes %}
                        <div class="ep">
                            S{{ e.seasonNumber }}E{{ e.episodeNumber }} — {{ e.title|default:"(tba)" }}<br>
                            <span class="muted" data-dt="{{ e.airDateUtc|default:'' }}"></span>
                        </div>
                        {% empty %}
                        <div class="muted">No upcoming episodes.</div>
                        {% endfor %}
                    </div>
                </div>
                {# sichere Episoden-JSON für Modal #}
                {% with sid=s.seriesId|stringformat:"s" %}
                {% with eid="eps-"|add:sid %}
                {{ s.episodes|json_script:eid }}
                {% endwith %}
                {% endwith %}
            </div>
            {% empty %}
            <p class="muted">No series found.</p>
            {% endfor %}
        </div>
    </div>
    {% endif %}

    {% if show_movies %}
    <div class="section">
    <h2>Upcoming movies</h2>
        <div class="grid">
            {% for m in movies %}
            <div class="movie-card" data-kind="movie" data-title="{{ m.title|escape }}"
                data-poster="{{ m.posterUrl|default:'' }}" data-overview="{{ m.overview|default:''|escape }}">
                {% if m.posterUrl %}
                <img src="{{ m.posterUrl }}" alt="{{ m.title }}">
                {% else %}
                <img src="https://via.placeholder.com/300x450?text=No+Poster" alt="">
                {% endif %}
                <div class="title">{{ m.title }}{% if m.year %} ({{ m.year }}){% endif %}</div>
                <div class="muted">
                    {% if m.inCinemas %}In theaters: <span data-dt="{{ m.inCinemas }}"></span>{% endif %}
                    {% if m.digitalRelease %}<br>Digital: <span data-dt="{{ m.digitalRelease }}"></span>{% endif %}
                    {% if m.physicalRelease %}<br>Physical: <span data-dt="{{ m.physicalRelease }}"></span>{% endif %}
                </div>
            </div>
            {% empty %}
            <p class="muted">No movies found.</p>
            {% endfor %}
        </div>
    </div>
    {% endif %}
</div>

<!-- Modal -->
<div id="modalBackdrop" class="modal-backdrop" role="dialog" aria-modal="true" aria-hidden="true">
    <div class="modal">
        <div class="modal-header">
            <div class="m-poster-wrap">
                <div class="m-poster"><img id="mPoster" alt=""></div>
                <button id="subscribeBtn" class="btn-subscribe" type="button">Subscribe</button>
            </div>
            <div>
                <div id="mTitle" class="m-title"></div>
                <div id="mSub" class="m-sub"></div>
                <div id="mBadges" class="badges"></div>
            </div>
            <button class="modal-close" title="Close" aria-label="Close">&times;</button>
        </div>

        <div class="modal-body">
            <div class="section-block">
                <div class="section-title">Overview</div>
                <div id="mOverview" class="desc muted"></div>
            </div>

            <div class="section-block">
                <div class="section-title">Upcoming episodes</div>
                <div class="section-divider"></div>
                <div id="mEpisodes"></div>
            </div>
        </div>
    </div>
</div>

<script>
    (function () {
        // ===== Helpers =====
        const $ = (sel, root = document) => root.querySelector(sel);
        const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));

        // ===== Modal-Elemente =====
        const backdrop = $("#modalBackdrop");
        const closeBtn = backdrop.querySelector(".modal-close");
        const mPoster = $("#mPoster");
        const mTitle = $("#mTitle");
        const mOverview = $("#mOverview");
        const mEpisodes = $("#mEpisodes");
        const mBadges = $("#mBadges");
        const mSub = $("#mSub");
        const epSection = mEpisodes.closest(".section-block");
        const subscribeBtn = $("#subscribeBtn");
    const bc = ('BroadcastChannel' in window) ? new BroadcastChannel('subscribarr-sub') : null;

        let lastClickedCard = null;

        // ===== Modal open/close =====
        function openModal() {
            backdrop.style.display = "flex";
            backdrop.setAttribute("aria-hidden", "false");
            document.body.style.overflow = "hidden";
        }
        function closeModal() {
            backdrop.style.display = "none";
            backdrop.setAttribute("aria-hidden", "true");
            document.body.style.overflow = "";
        }
        closeBtn.addEventListener("click", closeModal);
        backdrop.addEventListener("click", e => { if (e.target === backdrop) closeModal(); });
        window.addEventListener("keydown", e => { if (e.key === "Escape") closeModal(); });

        // ===== Subscribe-UI mit Backend-Sync =====
        function subKey(card) {
            if (!card) return null;
            if (card.classList.contains("card") && card.dataset.seriesId) return "series:" + card.dataset.seriesId;
            return "movie:" + (card.dataset.title || "");
        }

    // Cache for subscription state
        const subCache = new Map();

        async function loadAllSubs() {
            try {
                const [seriesResp, moviesResp] = await Promise.all([
                    fetch('/api/series/subscriptions/'),
                    fetch('/api/movies/subscriptions/')
                ]);

                if (seriesResp.ok) {
                    const seriesSubs = await seriesResp.json();
                    seriesSubs.forEach(id => subCache.set(`series:${id}`, true));
                }

                if (moviesResp.ok) {
                    const movieSubs = await moviesResp.json();
                    movieSubs.forEach(title => subCache.set(`movie:${title}`, true));
                }
            } catch (err) {
                console.error("Failed to load subscriptions:", err);
            }
        }

        function loadSub(card) {
            const k = subKey(card);
            return k ? subCache.get(k) || false : false;
        }

    async function saveSub(card, on) {
            const k = subKey(card);
            if (!k) return;
            const [type, id] = k.split(":");

            try {
                const resp = await fetch(`/api/${type}/${on ? 'subscribe' : 'unsubscribe'}/${encodeURIComponent(id)}/`, {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                    }
                });

                if (resp.status === 403) {
                    // Not logged in
                    window.location.href = '/accounts/login/?next=' + encodeURIComponent(window.location.pathname);
                    return;
                }

                if (!resp.ok) throw new Error(`HTTP ${resp.status}`);

                // Update cache
                if (on) {
                    subCache.set(k, true);
                } else {
                    subCache.delete(k);
                }

                // Cross-tab/page notify
                if (bc) bc.postMessage({ type: 'sub_change', kind: type, key: id, on });
            } catch (err) {
                console.error("Failed to update subscription:", err);
                // Revert optimistic cache on error
                if (on) {
                    subCache.delete(k);
                } else {
                    subCache.set(k, true);
                }

                // Show error
                const errorMsg = document.createElement('div');
                errorMsg.className = 'error-message';
                errorMsg.textContent = 'Failed to update subscription. Please try again later.';
                document.body.appendChild(errorMsg);
                setTimeout(() => errorMsg.remove(), 3000);
            }
        }
        function applySubUI(card, on) {
            if (card) card.classList.toggle("subscribed", !!on); // green outline via .subscribed (CSS)
            if (subscribeBtn) {
                subscribeBtn.textContent = on ? "Unsubscribe" : "Subscribe";
                subscribeBtn.setAttribute("aria-pressed", on ? "true" : "false");
            }
        }

    // On load: fetch all subscriptions in a single API call
        (async () => {
            await loadAllSubs();
            const cards = $$(".card, .movie-card");
            cards.forEach(card => {
                applySubUI(card, loadSub(card));
            });
        })();

        // Listen to subscription changes from other pages (e.g., calendar)
        if (bc) {
            bc.onmessage = (evt) => {
                const msg = evt.data || {};
                if (msg.type !== 'sub_change') return;
                const { kind, key, on } = msg;
                // Keep cache in sync
                const cacheKey = `${kind}:${key}`;
                if (on) subCache.set(cacheKey, true); else subCache.delete(cacheKey);

                // Update matching cards
                const cards = $$(".card, .movie-card");
                cards.forEach(card => {
                    const isSeries = card.classList.contains('card') && card.dataset.seriesId;
                    const isMovie = card.classList.contains('movie-card') && card.dataset.title;
                    let match = false;
                    if (kind === 'series' && isSeries && String(card.dataset.seriesId) === String(key)) match = true;
                    if (kind === 'movie' && isMovie && (card.dataset.title || '') === key) match = true;
                    if (match) applySubUI(card, on);
                });
            };
        }

    // ===== Open series cards =====
        $$(".card").forEach(card => {
            card.addEventListener("click", () => {
                lastClickedCard = card;

                const id = card.dataset.seriesId;
                const title = card.dataset.title || "";
                const poster = card.dataset.poster || "";
                const overview = card.dataset.overview || "";

                // Episodes from embedded JSON <script id="eps-<id>">
                let episodes = [];
                const script = document.getElementById("eps-" + id);
                if (script) { try { episodes = JSON.parse(script.textContent); } catch { } }

                // Fill modal
                mTitle.textContent = title;
                mPoster.src = poster || "https://via.placeholder.com/130x195?text=No+Poster";
                mPoster.alt = title;
                mOverview.textContent = overview || "No overview available.";

                mSub.textContent = episodes.length
                    ? `${episodes.length} upcoming episode(s)`
                    : "No upcoming episodes";

                // Genre badges if data-genres is present
                mBadges.innerHTML = "";
                if (card.dataset.genres) {
                    card.dataset.genres.split(",").map(s => s.trim()).filter(Boolean).forEach(g => {
                        const b = document.createElement("span");
                        b.className = "badge";
                        b.textContent = g;
                        mBadges.appendChild(b);
                    });
                }

                // Episodes section
                epSection.style.display = "";
                mEpisodes.innerHTML = "";
                if (!episodes.length) {
                    const p = document.createElement("p");
                    p.className = "muted";
                    p.textContent = "—";
                    mEpisodes.appendChild(p);
                } else {
                    episodes.forEach(e => {
                        const row = document.createElement("div");
                        row.className = "ep-row";
                        const dt = e.airDateUtc ? new Date(e.airDateUtc) : null;
                        const when = dt && !isNaN(dt) ? dt.toLocaleString() : "-";
                        row.innerHTML = `<strong>S${e.seasonNumber}E${e.episodeNumber}</strong> — ${e.title ?? "(tba)"}<br><span class="muted">${when}</span>`;
                        mEpisodes.appendChild(row);
                    });
                }

                // Set subscribe UI for this card
                applySubUI(lastClickedCard, loadSub(lastClickedCard));

                // Refresh status again for safety
                loadAllSubs().then(() => {
                    applySubUI(lastClickedCard, loadSub(lastClickedCard));
                });

                openModal();
            });
        });

    // ===== Open movie cards =====
        $$(".movie-card").forEach(card => {
            card.addEventListener("click", () => {
                lastClickedCard = card;

                const title = card.dataset.title || "";
                const poster = card.dataset.poster || "";
                const overview = card.dataset.overview || "";

                mTitle.textContent = title;
                mPoster.src = poster || "https://via.placeholder.com/130x195?text=No+Poster";
                mPoster.alt = title;
                mOverview.textContent = overview || "No overview available.";

                mSub.textContent = "";
                mBadges.innerHTML = "";

                // Hide episodes section
                epSection.style.display = "none";
                mEpisodes.innerHTML = "";

                // Set subscribe UI for this card
                applySubUI(lastClickedCard, loadSub(lastClickedCard));

                // Refresh status again for safety
                loadAllSubs().then(() => {
                    applySubUI(lastClickedCard, loadSub(lastClickedCard));
                });

                openModal();
            });
        });

    // ===== Subscribe button in modal with backend sync =====
        if (subscribeBtn) {
            subscribeBtn.addEventListener("click", async () => {
                if (!lastClickedCard) return;
                const current = await loadSub(lastClickedCard);
                const newState = !current;

                // Optimistic UI update
                applySubUI(lastClickedCard, newState);

                // Backend sync
                await saveSub(lastClickedCard, newState);

                // Refresh status again for safety
                const finalState = await loadSub(lastClickedCard);
                applySubUI(lastClickedCard, finalState);
            });
        }

    // ===== Format date/time labels in the overview =====
        document.querySelectorAll("[data-dt]").forEach(el => {
            const v = el.getAttribute("data-dt");
            if (!v) return;
            const d = new Date(v);
            el.textContent = isNaN(d) ? v : d.toLocaleString();
        });
    })();
</script>
{% endblock %}
</body>

</html>