// =============================== // UI FUNCTIONS // =============================== // Mostra output JSON nel
function out(data) {
  document.getElementById("out").textContent =
    JSON.stringify(data, null, 2);
}

// ===============================
//  CARICA LISTA UTENTI (solo Admin)
// ===============================
async function loadUserDropdown() {
  try {
    const users = await apiGet(`/users`);

    const sel = document.getElementById("userSelect");
    if (!sel) return;

    sel.innerHTML = "";

    users.forEach(u => {
      const opt = document.createElement("option");
      opt.value = u.name;
      opt.textContent = u.name;
      sel.appendChild(opt);
    });

  } catch (err) {
    console.error("Errore nel caricare gli utenti:", err);
    out({ error: "Errore nel caricare gli utenti", details: err.message });
  }
}

// ===============================
//  TOGGLE SOFT DELETE (via prompt)
// ===============================
async function toggleSoftDeletePrompt() {
  const id = prompt("Inserisci l'ID della foto da togglare (soft delete):");

  if (!id) {
    alert("Nessun ID inserito");
    return;
  }

  try {
    const data = await apiPost(`/photos/toggle_soft/${id}`);
    out(data);
  } catch (err) {
    console.error("Errore toggle soft delete:", err);
    out({ error: err.message });
  }
}

// ===============================
//  INIZIALIZZAZIONE UI
// ===============================
document.addEventListener("DOMContentLoaded", async () => {

  // 1️⃣ Aspetta che config.js carichi Admin.BASE_URL
  await loadConfig();

  // 2️⃣ Inizializza pulsanti (solo se esistono nella pagina)
  const bind = (id, fn) => {
    const el = document.getElementById(id);
    if (el) el.onclick = fn;
  };

  bind("btnScan", scan);
  bind("btnResetDB", resetDB);
  bind("btnReadDBUser", readDBUser);
  bind("btnDeletePhoto", deletePhoto);
  bind("btnFindIdIndex", findIdIndex);
  bind("btnResetDBuser", resetDBuser);
  bind("btnSearchPhotoById", searchPhotoById);

  // ⭐ NUOVO: i due pulsanti richiesti
  bind("btnShowDBChanges", async () => {
    const since = getSinceISO();
    if (!since) return out({ error: "Inserisci una data/ora" });

    const payload = parseJwt(Admin.token);
    const user = payload.name;
    const res = await getDBChanges(since, user);
    out(res);
  });

  bind("btnShowHardDeleted", async () => {
    const since = getSinceISO();
    if (!since) return out({ error: "Inserisci una data/ora" });

    const payload = parseJwt(Admin.token);
    const user = payload.name;
    const res = await getHardDeleted(since, user);
    out(res.deleted || res);
  });

  // ⭐ Toggle Soft Delete via prompt
  bind("btnToggleSoft", toggleSoftDeletePrompt);

  // ⭐ Torna alla galleria
  bind("btnBack", () => window.location.href = "index.html");

  // 3️⃣ Carica dropdown utenti SOLO se Admin
  const payload = parseJwt(Admin.token);
  if (payload.name === "Admin") {
    loadUserDropdown();
  }
});