document.addEventListener("DOMContentLoaded", () => {
  const cards = Array.from(document.querySelectorAll(".download-card"));
  const currentVersionLabel = document.querySelector("[data-current-version]");
  const archiveToggle = document.querySelector("[data-action-toggle-archive]");
  const versionsArchive = document.querySelector("[data-versions-archive]");
  const versionsListNode = document.querySelector("[data-versions-list]");
  const actionAdd = document.querySelector("[data-action-add]");
  const actionEdit = document.querySelector("[data-action-edit]");

  const VERSIONS_KEY = "fws:versions";

  const defaultVersions = [
    { label: "1.0.2", url: "https://download.example.org/fws-1.0.2.iso", date: "2026-05-10" },
    { label: "1.0.1", url: "https://download.example.org/fws-1.0.1.iso", date: "2026-03-22" },
    { label: "0.9.8", url: "https://download.example.org/fws-0.9.8.iso", date: "2025-12-05" },
  ];

  function loadVersions() {
    try {
      const raw = localStorage.getItem(VERSIONS_KEY);
      if (!raw) return defaultVersions.slice();
      const parsed = JSON.parse(raw);
      if (!Array.isArray(parsed) || !parsed.length) return defaultVersions.slice();
      return parsed;
    } catch (e) {
      return defaultVersions.slice();
    }
  }

  function saveVersions(list) {
    localStorage.setItem(VERSIONS_KEY, JSON.stringify(list));
  }

  let versions = loadVersions();
  let currentVersion = versions[0];

  function renderVersionsBar() {
    if (currentVersionLabel) {
      currentVersionLabel.textContent = `${currentVersion.label} ${currentVersion.date ? '— ' + currentVersion.date : ''}`.trim();
    }
    // update prominent latest download button
    const latestBtn = document.querySelector('[data-latest-download]');
    if (latestBtn) {
      latestBtn.href = currentVersion.url || '#';
    }
  }

  function renderArchive() {
    if (!versionsListNode) return;
    versionsListNode.innerHTML = "";
    versions.forEach((v, idx) => {
      const li = document.createElement("li");
      li.className = "version-item";
      li.innerHTML = `
        <strong>${v.label}</strong> <span class="version-meta">${v.date || ''}</span>
        <div class="version-actions">
          <a class="button" href="${v.url}" target="_blank">Télécharger</a>
          <button class="button button-secondary copy-version" data-idx="${idx}">Copier</button>
          <button class="button button-secondary make-latest" data-idx="${idx}">Faire dernière</button>
          <button class="button button-secondary edit-version" data-idx="${idx}">Modifier</button>
        </div>
      `;
      versionsListNode.appendChild(li);
    });
  }

  function setCurrentToIndex(idx) {
    const v = versions[idx];
    if (!v) return;
    versions.splice(idx, 1);
    versions.unshift(v);
    currentVersion = versions[0];
    saveVersions(versions);
    renderVersionsBar();
    renderArchive();
    applyLinksToCards();
  }

  function applyLinksToCards() {
    cards.forEach((card) => {
      const key = `fws:download:${card.dataset.key}`;
      const btn = card.querySelector(".download-btn");
      const copyBtn = card.querySelector(".copy-btn");
      const stored = localStorage.getItem(key);
      const finalUrl = stored || (currentVersion && currentVersion.url) || "#";
      if (btn) btn.href = finalUrl;
      if (btn) btn.dataset.link = finalUrl;
      if (copyBtn) copyBtn.dataset.link = finalUrl;
    });
  }

  function toast(message) {
    const t = document.createElement("div");
    t.className = "dl-toast";
    t.textContent = message;
    Object.assign(t.style, {
      position: "fixed",
      right: "1rem",
      bottom: "1rem",
      background: "rgba(2,6,23,0.9)",
      color: "#fff",
      padding: "0.6rem 0.9rem",
      borderRadius: "6px",
      boxShadow: "0 6px 20px rgba(2,6,23,0.5)",
      zIndex: 9999,
    });
    document.body.appendChild(t);
    setTimeout(() => t.remove(), 2200);
  }

  cards.forEach((card) => {
    const key = `fws:download:${card.dataset.key}`;
    const btn = card.querySelector(".download-btn");
    const copyBtn = card.querySelector(".copy-btn");
    const editBtn = card.querySelector(".edit-btn");

    function setLink(url) {
      if (!url) url = "#";
      btn.href = url;
      btn.dataset.link = url;
      copyBtn.dataset.link = url;
      localStorage.setItem(key, url);
    }

    const stored = localStorage.getItem(key);
    if (stored) {
      setLink(stored);
    } else {
      // apply global current version by default
      if (currentVersion && currentVersion.url) {
        setLink(currentVersion.url);
      }
    }

    editBtn.addEventListener("click", () => {
      const current = localStorage.getItem(key) || (currentVersion && currentVersion.url) || "";
      const value = window.prompt("Collez l'URL de téléchargement pour ce fichier:", current);
      if (value === null) return;
      const trimmed = value.trim();
      setLink(trimmed);
      toast("Lien enregistré");
    });

    copyBtn.addEventListener("click", async () => {
      const link = copyBtn.dataset.link || btn.href || "";
      if (!link || link === "#") {
        toast("Aucun lien défini — utilisez 'Modifier le lien'");
        return;
      }
      try {
        await navigator.clipboard.writeText(link);
        toast("Lien copié dans le presse-papiers");
      } catch (e) {
        window.prompt("Copiez manuellement ce lien:", link);
      }
    });

    btn.addEventListener("click", (ev) => {
      const href = btn.getAttribute("href") || "";
      if (!href || href === "#") {
        ev.preventDefault();
        toast("Aucun lien configuré — cliquez sur 'Modifier le lien' pour en ajouter un");
      }
    });
  });

  // render versions UI
  function toggleArchive() {
    const expanded = archiveToggle.getAttribute("aria-expanded") === "true";
    archiveToggle.setAttribute("aria-expanded", String(!expanded));
    if (versionsArchive) versionsArchive.hidden = expanded;
  }

  if (archiveToggle) {
    archiveToggle.addEventListener("click", () => {
      toggleArchive();
    });
  }

  if (actionAdd) {
    actionAdd.addEventListener("click", () => {
      const label = window.prompt("Nom de la version (ex: 1.0.3):", "");
      if (!label) return;
      const url = window.prompt("URL de téléchargement pour cette version:", "");
      if (!url) return;
      const date = new Date().toISOString().slice(0, 10);
      versions.unshift({ label: label.trim(), url: url.trim(), date });
      saveVersions(versions);
      currentVersion = versions[0];
      renderVersionsBar();
      renderArchive();
      applyLinksToCards();
      toast("Version ajoutée");
    });
  }

  if (actionEdit) {
    actionEdit.addEventListener("click", () => {
      const url = window.prompt("Nouvelle URL pour la version actuelle:", currentVersion.url || "");
      if (url === null) return;
      currentVersion.url = url.trim();
      versions[0] = currentVersion;
      saveVersions(versions);
      renderVersionsBar();
      applyLinksToCards();
      toast("Version mise à jour");
    });
  }

  // delegated events for archive list
  if (versionsListNode) {
    versionsListNode.addEventListener("click", (ev) => {
      const copyBtn = ev.target.closest(".copy-version");
      const makeBtn = ev.target.closest(".make-latest");
      const editBtn = ev.target.closest(".edit-version");
      if (copyBtn) {
        const idx = Number(copyBtn.dataset.idx);
        const v = versions[idx];
        if (v && v.url) {
          navigator.clipboard.writeText(v.url).then(() => toast("Lien copié"), () => window.prompt("Copiez le lien:", v.url));
        }
        return;
      }
      if (makeBtn) {
        const idx = Number(makeBtn.dataset.idx);
        setCurrentToIndex(idx);
        toast("Version définie comme dernière");
        return;
      }
      if (editBtn) {
        const idx = Number(editBtn.dataset.idx);
        const v = versions[idx];
        if (!v) return;
        const newUrl = window.prompt(`Nouvelle URL pour ${v.label}:`, v.url || "");
        if (newUrl === null) return;
        v.url = newUrl.trim();
        versions[idx] = v;
        saveVersions(versions);
        renderArchive();
        applyLinksToCards();
        toast("Version modifiée");
      }
    });
  }

  renderVersionsBar();
  renderArchive();
  applyLinksToCards();
});
