document.addEventListener("DOMContentLoaded", () => {

  /* ============================================================
     🔵 1. OBTENER DATOS DEL USUARIO DESDE EL BACKEND
     ============================================================ */
  async function obtenerSolicitud() {
    try {
      const response = await fetch("http://localhost:3000/api/solicitudes/completa", {
        method: "GET",
        headers: { "Content-Type": "application/json" }
      });

      if (!response.ok) return null;

      const data = await response.json();
      return data.solicitud || null;

    } catch (error) {
      console.error("Error al obtener solicitud:", error);
      return null;
    }
  }

  /* ============================================================
     🔵 2. ACTUALIZAR EL DASHBOARD DEL ASPIRANTE
     ============================================================ */
  async function actualizarDashboard() {
    const datos = await obtenerSolicitud();

    // Si no hay solicitud, mostrar mensajes vacíos
    if (!datos) {
      const name = document.querySelector(".user-name");
      if (name) name.textContent = "Aspirante";

      const currentApp = document.querySelector(".current-application");
      if (currentApp) {
        currentApp.innerHTML = `<p style="text-align:center; padding:20px; color:var(--text-secondary)">
          No tienes solicitudes registradas.
        </p>`;
      }
      return;
    }

    /* ----- Datos básicos ----- */
    const nombreCompleto = `${datos.nombre} ${datos.primer_apellido}`.trim();

    const nombreUsuario = document.querySelector(".user-name");
    if (nombreUsuario) nombreUsuario.textContent = nombreCompleto;

    const welcomeHeading = document.querySelector(".view-header h2");
    if (welcomeHeading) welcomeHeading.textContent = `Bienvenido(a), ${datos.nombre}`;

    /* ----- Cards estadísticas ----- */
    const statCards = document.querySelectorAll(".stat-card");

    // Solicitudes activas
    if (statCards[0]) {
      statCards[0].querySelector(".stat-value").textContent = "1";
      statCards[0].querySelector(".stat-change").textContent = "En evaluación";
    }

    // Documentos
    if (statCards[1]) {
      statCards[1].querySelector(".stat-value").textContent = "7/10";
      statCards[1].querySelector(".stat-change").textContent = "3 pendientes";
    }

    // Estado de solicitud
    if (statCards[2]) {
      statCards[2].querySelector(".stat-value").textContent = "Evaluación";
      statCards[2].querySelector(".stat-change").textContent = "Análisis socioeconómico";
    }

    // Completitud
    if (statCards[3]) {
      statCards[3].querySelector(".stat-value").textContent = "80%";
    }
  }

  actualizarDashboard();

  /* ============================================================
     🔵 3. NAVEGACIÓN ENTRE VISTAS
     ============================================================ */
  const navItems = document.querySelectorAll(".nav-item");
  const views = document.querySelectorAll(".view");
  const mobileMenuToggle = document.getElementById("mobileMenuToggleAspirant");
  const sidebar = document.getElementById("sidebarAspirant");

  if (mobileMenuToggle) {
    mobileMenuToggle.addEventListener("click", () => {
      sidebar.classList.toggle("open");
    });
  }

  navItems.forEach((item) => {
    item.addEventListener("click", async function (e) {
      e.preventDefault();

      const viewId = this.getAttribute("data-view") + "-view";

      navItems.forEach((n) => n.classList.remove("active"));
      views.forEach((v) => v.classList.remove("active"));

      this.classList.add("active");
      document.getElementById(viewId).classList.add("active");

      if (sidebar.classList.contains("open")) sidebar.classList.remove("open");

      // Si abre formulario de solicitud → cargar HTML
      if (this.getAttribute("data-view") === "aspirant-solicitar") {
        const cont = document.querySelector("#aspirant-solicitar-view #form-container");
        if (cont && !cont.dataset.loaded) {
          await cargarFormularioSolicitud(cont);
          cont.dataset.loaded = "true";
        }
      }
    });
  });

  /* ============================================================
     🔵 4. CARGAR FORMULARIO Y ENVIARLO AL BACKEND
     ============================================================ */
  async function cargarFormularioSolicitud(container) {
    try {
      const response = await fetch("solicitud.html");
      const html = await response.text();

      const parser = new DOMParser();
      const doc = parser.parseFromString(html, "text/html");
      const main = doc.querySelector(".main-content");

      container.innerHTML = main.innerHTML;

      // Reemplazar formulario.js por versión adaptada a API
      const script = document.createElement("script");
      script.src = "formulario-api.js"; 
      container.appendChild(script);

    } catch (error) {
      console.error("Error al cargar el formulario", error);
      container.innerHTML = `<p style="color:red; padding:30px;">Error al cargar formulario</p>`;
    }
  }

  const faqQuestions = document.querySelectorAll(".faq-question");
  faqQuestions.forEach((q) => {
    q.addEventListener("click", function () {
      const answer = this.nextElementSibling;
      const toggle = this.querySelector(".faq-toggle");

      const isOpen = answer.style.display === "block";
      answer.style.display = isOpen ? "none" : "block";
      toggle.textContent = isOpen ? "+" : "-";
    });
  });

});
