const loginView = document.querySelector("#loginView");
const adminView = document.querySelector("#adminView");
const loginForm = document.querySelector("#loginForm");
const passwordInput = document.querySelector("#password");
const loginError = document.querySelector("#loginError");
const sourcesEl = document.querySelector("#sources");
const refreshBtn = document.querySelector("#refreshBtn");
const indexAllBtn = document.querySelector("#indexAllBtn");
const repairBtn = document.querySelector("#repairBtn");
const maxMessages = document.querySelector("#maxMessages");
const actionStatus = document.querySelector("#actionStatus");
const logoutBtn = document.querySelector("#logoutBtn");

async function api(url, options = {}) {
  const response = await fetch(url, {
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/json",
      ...(options.headers || {})
    },
    ...options
  });

  const data = await response.json().catch(() => ({
    ok: false,
    error: `HTTP ${response.status}`
  }));

  if (!response.ok || data.ok === false) {
    throw new Error(data.error || `HTTP ${response.status}`);
  }

  return data;
}

function showLogin() {
  loginView.classList.remove("hidden");
  adminView.classList.add("hidden");
  passwordInput.focus();
}

function showAdmin() {
  loginView.classList.add("hidden");
  adminView.classList.remove("hidden");
}

async function checkSession() {
  try {
    await api("/api/admin/status");
    showAdmin();
    await loadSources();
  } catch {
    showLogin();
  }
}

loginForm.addEventListener("submit", async event => {
  event.preventDefault();
  loginError.textContent = "";

  try {
    await api("/api/admin/login", {
      method: "POST",
      body: JSON.stringify({
        password: passwordInput.value
      })
    });

    passwordInput.value = "";
    showAdmin();
    await loadSources();
  } catch (error) {
    loginError.textContent = error.message;
  }
});

async function loadSources() {
  sourcesEl.innerHTML = '<div class="empty">Descubriendo fuentes...</div>';

  try {
    const data = await api("/api/admin/sources");

    if (!data.sources.length) {
      sourcesEl.innerHTML =
        '<div class="empty">No se encontraron canales o grupos.</div>';
      return;
    }

    sourcesEl.innerHTML = data.sources.map(source => `
      <article class="source">
        <div>
          <div class="source-title">${escapeHtml(source.title)}</div>
          <div class="source-meta">
            ${escapeHtml(source.type)}
            ${source.username ? ` · @${escapeHtml(source.username)}` : ""}
            ${source.last_sync_at ? ` · ${escapeHtml(source.last_sync_at)}` : ""}
          </div>
        </div>

        <label class="switch">
          <input
            type="checkbox"
            data-source="${escapeHtml(source.chat_id)}"
            ${Number(source.enabled) ? "checked" : ""}
          >
          Activa
        </label>
      </article>
    `).join("");

    document.querySelectorAll("[data-source]").forEach(input => {
      input.addEventListener("change", async () => {
        try {
          await api(
            `/api/admin/sources/${encodeURIComponent(input.dataset.source)}/enabled`,
            {
              method: "POST",
              body: JSON.stringify({
                enabled: input.checked
              })
            }
          );

          actionStatus.textContent =
            input.checked
              ? "Fuente activada."
              : "Fuente desactivada.";
        } catch (error) {
          input.checked = !input.checked;
          actionStatus.textContent = error.message;
        }
      });
    });
  } catch (error) {
    sourcesEl.innerHTML =
      `<div class="empty">No se pudieron cargar las fuentes: ${escapeHtml(error.message)}</div>`;
  }
}

repairBtn.addEventListener("click", async () => {
  repairBtn.disabled = true;
  indexAllBtn.disabled = true;
  actionStatus.textContent =
    "Revisando mensajes para recuperar las imágenes...";

  try {
    const data = await api("/api/admin/repair-thumbnails", {
      method: "POST",
      body: JSON.stringify({
        maxMessages: Number(maxMessages.value || 500)
      })
    });

    actionStatus.textContent = data.message;
  } catch (error) {
    actionStatus.textContent = error.message;
  } finally {
    setTimeout(() => {
      repairBtn.disabled = false;
      indexAllBtn.disabled = false;
    }, 1500);
  }
});

refreshBtn.addEventListener("click", async () => {
  refreshBtn.disabled = true;
  actionStatus.textContent = "Descubriendo nuevas fuentes...";

  try {
    await api("/api/admin/sources/refresh", {
      method: "POST"
    });

    await loadSources();
    actionStatus.textContent =
      "Fuentes actualizadas.";
  } catch (error) {
    actionStatus.textContent = error.message;
  } finally {
    refreshBtn.disabled = false;
  }
});

indexAllBtn.addEventListener("click", async () => {
  indexAllBtn.disabled = true;
  actionStatus.textContent =
    "Indexando todas las fuentes. Puedes dejar esta ventana abierta o seguir usando la biblioteca.";

  try {
    const data = await api("/api/admin/index-all", {
      method: "POST",
      body: JSON.stringify({
        maxMessages: Number(maxMessages.value || 1000)
      })
    });

    actionStatus.textContent = data.message;
  } catch (error) {
    actionStatus.textContent = error.message;
  } finally {
    setTimeout(() => {
      indexAllBtn.disabled = false;
    }, 1500);
  }
});

logoutBtn.addEventListener("click", async () => {
  try {
    await api("/api/admin/logout", {
      method: "POST"
    });
  } finally {
    showLogin();
  }
});

function escapeHtml(value) {
  return String(value).replace(/[&<>"']/g, char => ({
    "&":"&amp;",
    "<":"&lt;",
    ">":"&gt;",
    '"':"&quot;",
    "'":"&#039;"
  }[char]));
}

checkSession();
