(function () {
  const state = {
    overview: null,
    searchAbortController: null,
    uploadDialog: null,
  };

  const selectors = {
    body: document.body,
    feedback: document.querySelector("[data-dashboard-feedback]"),
    feedbackTitle: document.querySelector("[data-dashboard-feedback-title]"),
    feedbackBody: document.querySelector("[data-dashboard-feedback-body]"),
    summaryPatients: document.querySelector("[data-summary-patients]"),
    summaryCases: document.querySelector("[data-summary-cases]"),
    summaryEpicrisis: document.querySelector("[data-summary-epicrisis]"),
    summaryDocuments: document.querySelector("[data-summary-documents]"),
    activityList: document.querySelector("[data-dashboard-activity-list]"),
    activityEmpty: document.querySelector("[data-dashboard-activity-empty]"),
    caseGrid: document.querySelector("[data-dashboard-case-grid]"),
    casesEmpty: document.querySelector("[data-dashboard-cases-empty]"),
    batchList: document.querySelector("[data-dashboard-batch-list]"),
    batchesEmpty: document.querySelector("[data-dashboard-batches-empty]"),
    searchInput: document.querySelector("[data-dashboard-search-input]"),
    searchResults: document.querySelector("[data-dashboard-search-results]"),
    searchRoot: document.querySelector("[data-dashboard-search-root]"),
    navToggle: document.querySelector("[data-dashboard-nav-toggle]"),
    userMenuRoot: document.querySelector("[data-user-menu-root]"),
    userMenuButton: document.querySelector("[data-user-menu-button]"),
    userMenuPanel: document.querySelector("[data-user-menu-panel]"),
    collapseButtons: Array.from(document.querySelectorAll("[data-dashboard-collapse-button]")),
    jumpLinks: Array.from(document.querySelectorAll("[data-dashboard-jump]")),
  };

  function escapeHtml(value) {
    return String(value ?? "")
      .replaceAll("&", "&amp;")
      .replaceAll("<", "&lt;")
      .replaceAll(">", "&gt;")
      .replaceAll('"', "&quot;")
      .replaceAll("'", "&#39;");
  }

  function formatDate(value) {
    if (!value) return "Sin fecha";
    const parsed = new Date(value);
    if (Number.isNaN(parsed.getTime())) return "Sin fecha";
    return new Intl.DateTimeFormat("es-CO", {
      day: "2-digit",
      month: "short",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    }).format(parsed);
  }

  function isAuthExpiredError(error) {
    return error?.code === "auth_expired" || error?.message === "AUTH_EXPIRED";
  }

  function showFeedback({ title, body, tone = "info" }) {
    if (!selectors.feedback) return;
    selectors.feedback.className = `dashboard-feedback ui-alert ui-alert--${tone}`;
    selectors.feedback.classList.remove("ui-hidden");
    selectors.feedbackTitle.textContent = title;
    selectors.feedbackBody.textContent = body;
  }

  function clearFeedback() {
    if (!selectors.feedback) return;
    selectors.feedback.classList.add("ui-hidden");
    selectors.feedbackTitle.textContent = "";
    selectors.feedbackBody.textContent = "";
    selectors.feedback.className = "dashboard-feedback ui-alert ui-hidden";
  }

  function buildPill(status, variant) {
    if (!status) return "";
    return `<span class="dashboard-pill dashboard-pill--${escapeHtml(variant || "info")}">${escapeHtml(status)}</span>`;
  }

  function buildActionLinks(actions) {
    if (!Array.isArray(actions) || actions.length === 0) return "";
    return actions
      .map((action) => {
        const variant = action.variant || "secondary";
        return `<a class="dashboard-link-button dashboard-link-button--${escapeHtml(variant)}" href="${escapeHtml(
          action.href || "#"
        )}">${escapeHtml(action.label || "Abrir")}</a>`;
      })
      .join("");
  }

  function renderOverview(overview) {
    state.overview = overview;
    const summary = overview.summary || {};
    selectors.summaryPatients.textContent = String(summary.patients || 0);
    selectors.summaryCases.textContent = String(summary.cases || 0);
    selectors.summaryEpicrisis.textContent = String(summary.completed_epicrisis || 0);
    selectors.summaryDocuments.textContent = String(summary.documents || 0);

    const activity = Array.isArray(overview.recent_activity) ? overview.recent_activity : [];
    selectors.activityEmpty.classList.toggle("ui-hidden", activity.length > 0);
    selectors.activityList.innerHTML = activity
      .map(
        (item) => `
          <article class="dashboard-activity-item">
            <div class="dashboard-activity-item__header">
              <div class="dashboard-activity-item__meta">
                <strong>${escapeHtml(item.title)}</strong>
                <span>${escapeHtml(item.subtitle)}</span>
              </div>
              ${buildPill(item.status, item.status_variant)}
            </div>
            <span class="ui-text-muted">${escapeHtml(formatDate(item.updated_at))}</span>
            <div class="dashboard-activity-item__actions">
              ${buildActionLinks(item.actions)}
            </div>
          </article>
        `
      )
      .join("");

    const cases = Array.isArray(overview.recent_cases) ? overview.recent_cases : [];
    selectors.casesEmpty.classList.toggle("ui-hidden", cases.length > 0);
    selectors.caseGrid.innerHTML = cases
      .map(
        (item) => `
          <article class="dashboard-case-item">
            <div class="dashboard-case-item__header">
              <div class="dashboard-case-item__meta">
                <strong>${escapeHtml(item.case_number)}</strong>
                <span>${escapeHtml(item.patient_name)}</span>
              </div>
              ${buildPill(item.epicrisis_status, item.status_variant)}
            </div>
            <div class="dashboard-case-item__tags">
              <span class="dashboard-tag">${escapeHtml(item.document_count)} documento(s)</span>
              ${Array.isArray(item.document_types)
                ? item.document_types
                    .slice(0, 3)
                    .map((tag) => `<span class="dashboard-tag">${escapeHtml(String(tag).replaceAll("_", " "))}</span>`)
                    .join("")
                : ""}
            </div>
            <span class="ui-text-muted">${escapeHtml(formatDate(item.updated_at))}</span>
            <div class="dashboard-case-item__actions">
              ${buildActionLinks(item.actions)}
            </div>
          </article>
        `
      )
      .join("");

    const batches = Array.isArray(overview.recent_batches) ? overview.recent_batches : [];
    selectors.batchesEmpty?.classList.toggle("ui-hidden", batches.length > 0);
    if (selectors.batchList) {
      selectors.batchList.innerHTML = batches
        .map(
          (item) => `
            <article class="dashboard-batch-item">
              <div class="dashboard-batch-item__header">
                <div class="dashboard-batch-item__meta">
                  <strong>${escapeHtml(item.title)}</strong>
                  <span>${escapeHtml(item.batch_id || "Sin lote")}</span>
                </div>
                ${buildPill(item.status, item.status_variant)}
              </div>
              <div class="dashboard-batch-item__stats">
                <span class="dashboard-tag">${escapeHtml(item.total_files)} archivos</span>
                <span class="dashboard-tag">${escapeHtml(item.associated_files)} asociados</span>
                <span class="dashboard-tag">${escapeHtml(item.pending_validation_files)} pendientes</span>
                <span class="dashboard-tag">${escapeHtml(item.failed_files)} fallidos</span>
              </div>
              <span class="ui-text-muted">${escapeHtml(formatDate(item.updated_at || item.created_at))}</span>
              <div class="dashboard-batch-item__actions">
                ${buildActionLinks(item.actions)}
              </div>
            </article>
          `
        )
        .join("");
    }
  }

  async function fetchOverview() {
    try {
      const response = await fetch("/api/dashboard/overview", {
        headers: { Accept: "application/json" },
      });
      const payload = await response.json();
      if (!response.ok) {
        throw new Error(payload.detail || "No fue posible cargar el tablero");
      }
      renderOverview(payload);
    } catch (error) {
      if (isAuthExpiredError(error)) return;
      showFeedback({
        title: "No fue posible cargar el dashboard",
        body: error.message,
        tone: "error",
      });
    }
  }

  function renderSearchResults(results) {
    if (!selectors.searchResults) return;
    if (!Array.isArray(results) || results.length === 0) {
      selectors.searchResults.innerHTML = '<div class="dashboard-search__hint">Sin resultados para esa búsqueda.</div>';
      selectors.searchResults.classList.remove("ui-hidden");
      return;
    }
    selectors.searchResults.innerHTML = results
      .map(
        (result) => `
          <article class="dashboard-search__result">
            <div class="dashboard-search__result-head">
              <div>
                <a class="dashboard-search__result-title" href="${escapeHtml(result.href || "#")}">${escapeHtml(
                  result.title || "Resultado"
                )}</a>
                <div class="dashboard-search__result-subtitle">${escapeHtml(result.subtitle || "")}</div>
              </div>
              ${result.status ? buildPill(result.status, result.status === "completado" ? "success" : "info") : ""}
            </div>
            <div class="dashboard-search__result-actions">
              ${buildActionLinks(result.actions)}
            </div>
          </article>
        `
      )
      .join("");
    selectors.searchResults.classList.remove("ui-hidden");
  }

  async function searchDashboard(query) {
    const trimmed = String(query || "").trim();
    if (!trimmed) {
      selectors.searchResults.classList.add("ui-hidden");
      selectors.searchResults.innerHTML = "";
      return;
    }

    if (state.searchAbortController) {
      state.searchAbortController.abort();
    }
    state.searchAbortController = new AbortController();
    selectors.searchResults.innerHTML = '<div class="dashboard-search__hint">Buscando…</div>';
    selectors.searchResults.classList.remove("ui-hidden");

    try {
      const response = await fetch(`/api/dashboard/search?q=${encodeURIComponent(trimmed)}`, {
        headers: { Accept: "application/json" },
        signal: state.searchAbortController.signal,
      });
      const payload = await response.json();
      if (!response.ok) {
        throw new Error(payload.detail || "No fue posible completar la búsqueda");
      }
      renderSearchResults(payload.results || []);
    } catch (error) {
      if (error.name === "AbortError") {
        return;
      }
      if (isAuthExpiredError(error)) return;
      selectors.searchResults.innerHTML = `<div class="dashboard-search__hint">${escapeHtml(error.message)}</div>`;
    }
  }

  let searchTimer = null;
  function onSearchInput(event) {
    const value = event.target.value;
    globalThis.clearTimeout(searchTimer);
    searchTimer = globalThis.setTimeout(() => {
      searchDashboard(value);
    }, 180);
  }

  function initializeUploadDialog() {
    if (!globalThis.CaseUploadDialog?.mount) return;
    state.uploadDialog = globalThis.CaseUploadDialog.mount({
      mode: "all",
      requireCaseSelection: false,
      onStorySuccess() {
        fetchOverview();
      },
      onSupportSuccess() {
        fetchOverview();
      },
    });
  }

  function closeUserMenu() {
    selectors.userMenuPanel?.classList.add("ui-hidden");
    selectors.userMenuButton?.setAttribute("aria-expanded", "false");
  }

  function toggleUserMenu() {
    const hidden = selectors.userMenuPanel?.classList.toggle("ui-hidden");
    selectors.userMenuButton?.setAttribute("aria-expanded", hidden ? "false" : "true");
  }

  function toggleSidebar() {
    const nextState = !selectors.body.classList.contains("is-nav-open");
    selectors.body.classList.toggle("is-nav-open", nextState);
    selectors.navToggle?.setAttribute("aria-expanded", nextState ? "true" : "false");
  }

  function setCollapseState(button, panel, expanded) {
    button.setAttribute("aria-expanded", expanded ? "true" : "false");
    panel.hidden = !expanded;
    const label = button.querySelector("[data-dashboard-collapse-label]");
    if (label) {
      label.textContent = expanded ? button.dataset.expandedLabel || "Ocultar" : button.dataset.collapsedLabel || "Mostrar";
    }
  }

  function initializeCollapseControls() {
    selectors.collapseButtons.forEach((button) => {
      const panelId = button.getAttribute("aria-controls");
      if (!panelId) return;
      const panel = document.getElementById(panelId);
      if (!panel) return;

      const initiallyExpanded = button.getAttribute("aria-expanded") !== "false";
      setCollapseState(button, panel, initiallyExpanded);
      button.addEventListener("click", () => {
        const expanded = button.getAttribute("aria-expanded") === "true";
        setCollapseState(button, panel, !expanded);
      });
    });
  }

  function initializeEvents() {
    selectors.searchInput?.addEventListener("input", onSearchInput);

    selectors.jumpLinks.forEach((link) => {
      link.addEventListener("click", (event) => {
        event.preventDefault();
        state.uploadDialog?.open("story", link);
      });
    });

    selectors.userMenuButton?.addEventListener("click", toggleUserMenu);
    selectors.navToggle?.addEventListener("click", toggleSidebar);

    document.addEventListener("click", (event) => {
      if (
        selectors.userMenuRoot &&
        !selectors.userMenuRoot.contains(event.target) &&
        !selectors.userMenuPanel?.classList.contains("ui-hidden")
      ) {
        closeUserMenu();
      }

      if (selectors.searchRoot && !selectors.searchRoot.contains(event.target)) {
        selectors.searchResults?.classList.add("ui-hidden");
      }
    });
  }

  initializeUploadDialog();
  initializeCollapseControls();
  initializeEvents();
  fetchOverview();
})();
