(() => {
  const OWNER = "You-re-like-Windows-a-bitch";
  const REPO = "ISO";
  const API_URL = `https://api.github.com/repos/${OWNER}/${REPO}/releases?per_page=6`;
  const REPO_URL = `https://github.com/${OWNER}/${REPO}`;

  const currentVersionNode = document.querySelector("[data-current-version]");
  const currentVersionDateNode = document.querySelector("[data-current-version-date]");
  const currentReleaseNoteNode = document.querySelector("[data-current-release-note]");
  const latestDownloadNode = document.querySelector("[data-latest-download]");
  const versionsListNode = document.querySelector("[data-versions-list]");

  function formatDate(value) {
    if (!value) return "";
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) return "";
    return date.toLocaleDateString("fr-FR", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
  }

  function getDirectDownloadUrl(release) {
    if (release?.assets?.length) {
      return release.assets[0].browser_download_url || release.assets[0].url || release.html_url || "#";
    }
    return release?.html_url || "#";
  }

  function getReleaseLabel(release) {
    return release.name || release.tag_name || "Sans nom";
  }

  function renderReleaseList(releases) {
    if (!versionsListNode) return;
    versionsListNode.innerHTML = "";

    if (!releases.length) {
      versionsListNode.innerHTML = `
        <li class="version-item version-item-empty">
          <div class="version-main">
            <strong>Aucune release trouvée</strong>
            <span>Le dépôt n'a pas encore publié de version.</span>
          </div>
          <div class="version-side">
            <a class="button button-secondary" href="${REPO_URL}" target="_blank" rel="noreferrer">Voir le repo</a>
          </div>
        </li>
      `;
      return;
    }

    releases.slice(1, 6).forEach((release) => {
      const li = document.createElement("li");
      li.className = "version-item";

      const versionLabel = getReleaseLabel(release);
      const downloadUrl = getDirectDownloadUrl(release);
      const published = formatDate(release.published_at);

      li.innerHTML = `
        <div class="version-main">
          <strong>${versionLabel}</strong>
          <span>${published ? `Publié le ${published}` : "Date inconnue"}</span>
        </div>
        <div class="version-side">
          <a class="button button-secondary" href="${downloadUrl}" target="_blank" rel="noreferrer">Télécharger</a>
        </div>
      `;

      versionsListNode.appendChild(li);
    });

    if (releases.length === 1) {
      const li = document.createElement("li");
      li.className = "version-item version-item-empty";
      li.innerHTML = `
        <div class="version-main">
          <strong>Aucune release précédente trouvée</strong>
          <span>La liste s'affiche ici quand il y en a au moins 2.</span>
        </div>
      `;
      versionsListNode.appendChild(li);
    }
  }

  async function loadReleases() {
    if (currentVersionNode) currentVersionNode.textContent = "Chargement...";

    try {
      const response = await fetch(API_URL, {
        headers: {
          Accept: "application/vnd.github+json",
        },
      });

      if (!response.ok) {
        throw new Error(`GitHub API ${response.status}`);
      }

      const releases = await response.json();
      if (!Array.isArray(releases)) {
        throw new Error("Réponse GitHub invalide");
      }

      if (releases.length === 0) {
        if (currentVersionNode) currentVersionNode.textContent = "Aucune release trouvée";
        if (currentVersionDateNode) currentVersionDateNode.textContent = "";
        if (currentReleaseNoteNode) currentReleaseNoteNode.textContent = "Le dépôt n'a pas encore publié de release GitHub.";
        if (latestDownloadNode) latestDownloadNode.href = REPO_URL;
        renderReleaseList([]);
        return;
      }

      const latest = releases[0];
      const latestLabel = getReleaseLabel(latest);
      const latestDownloadUrl = getDirectDownloadUrl(latest);
      const latestDate = formatDate(latest.published_at);

      if (currentVersionNode) currentVersionNode.textContent = latestLabel;
      if (currentVersionDateNode) currentVersionDateNode.textContent = latestDate ? ` · ${latestDate}` : "";
      if (currentReleaseNoteNode) currentReleaseNoteNode.textContent = latest.body || "Release GitHub la plus récente.";
      if (latestDownloadNode) latestDownloadNode.href = latestDownloadUrl;

      renderReleaseList(releases);
    } catch (error) {
      if (currentVersionNode) currentVersionNode.textContent = "Impossible de charger les releases";
      if (currentReleaseNoteNode) {
        currentReleaseNoteNode.textContent = `Erreur: ${error.message}. Vérifie que le repo GitHub est public et qu'il expose des releases.`;
      }
      if (latestDownloadNode) {
        latestDownloadNode.href = REPO_URL;
      }
      if (versionsListNode) {
        versionsListNode.innerHTML = `
          <li class="version-item version-item-empty">
            <div class="version-main">
              <strong>Impossible de charger les anciennes versions</strong>
              <span>Ouvre le repo GitHub pour voir les releases.</span>
            </div>
            <div class="version-side">
              <a class="button button-secondary" href="${REPO_URL}" target="_blank" rel="noreferrer">Voir le repo</a>
            </div>
          </li>
        `;
      }
    }
  }

  loadReleases();
})();