@model TorrentListViewModel
<link rel="stylesheet" href="~/css/torrent.css" />

<!-- Periodval -->
<div class="torrent-period">
    <button class="@(Model.CurrentRange == "day" ? "active" : "")" onclick="location.href='?range=day'">Dag</button>
    <button class="@(Model.CurrentRange == "week" ? "active" : "")" onclick="location.href='?range=week'">Vecka</button>
    <button class="@(Model.CurrentRange == "month" ? "active" : "")" onclick="location.href='?range=month'">Månad</button>
    <button class="@(Model.CurrentRange == "all" ? "active" : "")" onclick="location.href='?range=all'">All time</button>
</div>

<!-- Torrentlista -->
<div class="torrent-list">
    <div class="torrent-header">
        <div onclick="sortBy('title')" class="@(Model.CurrentSort == "title" ? "active" : "")">Titel</div>
        <div onclick="sortBy('date')" class="@(Model.CurrentSort == "date" ? "active" : "")">Tid / Datum</div>
        <div onclick="sortBy('seeders')" class="@(Model.CurrentSort == "seeders" ? "active" : "")">Seeders</div>
        <div onclick="sortBy('leechers')" class="@(Model.CurrentSort == "leechers" ? "active" : "")">Leechers</div>
        <div>Åtgärd</div>
    </div>

    @foreach (var group in Model.Items
        .GroupBy(t => new { t.MovieName, t.Metadata?.Year })
        .Select(g => new
        {
            MovieName = g.Key.MovieName,
            Year = g.Key.Year,
            Versions = g.OrderByDescending(t => t.Title.Contains("Fix") || t.Title.Contains("Repack"))
        .ThenByDescending(t => t.Seeders)
        .ToList()
        }))
    {
        var main = group.Versions.First();
        var lastVersion = group.Versions.Last();

        <!-- Huvudrad -->
        <div class="torrent-row torrent-group-title @(group.Versions.Count == 1 ? "last-row" : "")">
            <div class="col-title">
                @if (!string.IsNullOrEmpty(main.Metadata?.Poster) && main.Metadata.Poster != "N/A")
                {
                    <a href="@main.Metadata.Poster" class="glightbox">
                        <img src="@main.Metadata.Poster"
                             alt="@main.MovieName"
                             class="poster"
                             onerror="this.onerror=null; this.src='/images/fallback.jpg';" />
                    </a>
                }
                else
                {
                    <img src="/images/fallback.jpg" alt="@main.MovieName" class="poster placeholder" />
                }

                <div class="title-info">

                        @if (!string.IsNullOrEmpty(main.Metadata?.Title))
                        {
                            <strong>@group.MovieName (@group.Year) </strong>
                        } else
                        {
                            <strong>@main.Title </strong>
                        }
                    
                    @if (main.IsNew)
                    {
                        <img src="/images/new.png" alt="New" class="badge" />
                    }
                    <div class="meta">
                        @if (!string.IsNullOrEmpty(main.Metadata?.Genre))
                        {
                            <span class="genre">@main.Metadata.Genre</span>
                        }
                        @if (!string.IsNullOrEmpty(main.Metadata?.ImdbID))
                        {
                            <a class="imdb" href="https://www.imdb.com/title/@main.Metadata.ImdbID" target="_blank">
                                ⭐ @main.Metadata.ImdbRating
                            </a>
                        }
                        @if (main.AvailableOn?.Any() == true)
                        {
                            <span class="available-on">
                                Tillgänglig på: @string.Join(", ", main.AvailableOn)
                            </span>
                        }
                    </div>
                </div>
            </div>

            <div class="col-date">
                <div class="time">@main.PublishDate.ToString("HH:mm")</div>
                <div class="date">@main.PublishDate.ToString("yyyy-MM-dd")</div>
            </div>
            <div class="col-center @(main.Seeders > 40 ? "highlight-green" : "")">@main.Seeders</div>
            <div class="col-center highlight-red">@main.Leechers</div>
            <div class="col-action">
                @if (main.IsDownloaded)
                {
                    <span class="downloaded">✔ Nedladdad</span>
                }
                else
                {
                    <form class="download-form"
                            data-url="@Url.Action("Add", "Rss")"
                            data-torrent="@main.TorrentUrl">
                        <button type="submit" class="btn-add btn-small">➕ Ladda ner</button>
                    </form>
                }
            </div>
        </div>

        <!-- Versioner -->
        @if (group.Versions.Count > 1)
        {
            foreach (var version in group.Versions.Skip(1))
            {
                var isLast = version == lastVersion;
                <div class="torrent-row torrent-version @(isLast ? "last-version" : "")" title="@version.Title">
                    <div class="col-title">
                        <strong>
                            @version.Title
                            @if (version.IsNew)
                            {
                                <img src="/images/new.png" alt="New" class="badge" />
                            }
                        </strong>
                    </div>
                    <div>@version.PublishDate.ToString("HH:mm yyyy-MM-dd")</div>
                    <div class="@(version.Seeders > 40 ? "highlight-green" : "")">@version.Seeders</div>
                    <div class="highlight-red">@version.Leechers</div>
                    <div class="col-action">
                        <form asp-controller="RSS" asp-action="Add" method="post" onsubmit="return confirmDownload('@version.Title')">
                            <input type="hidden" name="torrentUrl" value="@version.TorrentUrl" />
                            <button type="submit" class="btn-add btn-small">➕</button>
                        </form>
                    </div>
                </div>
            }
        }
    }
    
</div>

<!-- Pagination -->
<div class="pagination">
    @for (int i = 1; i <= Model.TotalPages; i++)
    {
        if (i == Model.CurrentPage)
        {
            <span class="current">@i</span>
        }
        else
        {
            <a asp-route-page="@i" asp-route-sort="@Model.CurrentSort" asp-route-range="@Model.CurrentRange">@i</a>
        }
    }
</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/glightbox/dist/css/glightbox.min.css" />
<script src="https://cdn.jsdelivr.net/npm/glightbox/dist/js/glightbox.min.js"></script>
<script>
    const lightbox = GLightbox({ selector: '.glightbox' });
    function sortBy(field){
        const url = new URL(window.location);
        url.searchParams.set('sort', field);
        window.location = url;
    }

</script>
<script>
    document.addEventListener("DOMContentLoaded", () => {
        document.querySelectorAll(".download-form").forEach(form => {
            form.addEventListener("submit", async (e) => {
                e.preventDefault(); // 🔥 STOPPAR ALL REFRESH – ALLTID

                console.log("form:", form);
                const button = form.querySelector("button");
                console.log("button:", button);

                const torrentUrl = form.dataset.torrent;
                const postUrl = form.dataset.url;

                if (!torrentUrl || !postUrl) {
                    console.error("Saknar data-attribut");
                    return;
                }

                if (!confirm("Vill du ladda ner denna torrent?"))
                    return;

                if (button) {
                    button.disabled = true;
                    button.innerText = "⏳ Laddar...";
                }

                try {
                    const response = await fetch(postUrl, {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded"
                        },
                        body: new URLSearchParams({ torrentUrl })
                    });

                    const text = await response.text();
                    console.log("Raw response:", text);

                    const result = JSON.parse(text);

                    if (result.success) {
                        form.innerHTML = `<span class="downloaded">✔ Tillagd</span>`;
                    } else {
                        throw new Error(result.message || "Misslyckades");
                    }
                }
                catch (err) {
                    console.error("JS error:", err);

                    if (button) {
                        button.disabled = false;
                        button.innerText = "➕ Ladda ner";
                    }

                    alert("Ett fel uppstod");
                }
            });
        });
    });
</script>


