/* ===============================
   Process History – ARDEM VITU
   - Sync filters across tabs via localStorage.
   - Keep table empty until all 3 filters are set.
   - State-aware: passes state to backend so only actual data shows.
=============================== */

/* ---------- Date formatting helper ---------- */
/**
 * Converts a timestamp that starts with YYYY-MM-DD into MMDDYYYY while
 * preserving the rest of the string (time, 'T', timezone, etc).
 * Examples:
 *  "2025-08-29T21:03:00+05:30" -> "08292025T21:03:00+05:30"
 *  "2025-08-29"                -> "08292025"
 *  Non-matching strings are returned as-is.
 */
function formatToMMDDYYYYTS(value) {
  if (!value) return "";
  const m = String(value).match(/^(\d{4})-(\d{2})-(\d{2})(.*)$/);
  if (!m) return value; // leave as-is if it doesn't start with ISO date
  const yyyy = m[1], mm = m[2], dd = m[3], rest = m[4] || "";
  return `${mm}${dd}${yyyy}${rest}`;
}

/* ---------- Filters helpers ---------- */
function getSavedFilters() {
  try { return JSON.parse(localStorage.getItem("filters") || "{}"); }
  catch { return {}; }
}
function saveFilters(f) {
  localStorage.setItem("filters", JSON.stringify(f || {}));
}
function getUIFilters() {
  return {
    fromDate: document.getElementById("fromDate")?.value || "",
    toDate: document.getElementById("toDate")?.value || "",
    state: document.getElementById("stateSelect")?.value || ""
  };
}
function applyFiltersToUI() {
  const f = getSavedFilters();
  if (f.fromDate) document.getElementById("fromDate").value = f.fromDate;
  if (f.toDate) document.getElementById("toDate").value = f.toDate;
  if (f.state) document.getElementById("stateSelect").value = f.state;
}
function allFiltersSet(f) {
  return !!(f.fromDate && f.toDate && f.state);
}

/* ---------- Table helpers ---------- */
function getTbody() {
  return document.getElementById("filesTbody") ||
         document.querySelector(".table tbody") ||
         document.querySelector("tbody");
}
function clearTableWithMessage(msg) {
  const tb = getTbody();
  if (!tb) return;
  tb.innerHTML = `
    <tr>
      <td colspan="6" class="text-center text-muted">${msg}</td>
    </tr>`;
}
function renderRows(items) {
  const tb = getTbody();
  if (!tb) return;

  if (!items || !items.length) {
    clearTableWithMessage("No records to display for the selected filters.");
    return;
  }

  const rows = items.map(r => {
    const filename = r.filename || "-";
    const pages = (r.pages ?? "") === "" ? "" : String(r.pages);

    // Format start/end date as MMDDYYYYT... (preserve time/offset)
    const started = formatToMMDDYYYYTS(r.started || "");
    const ended = formatToMMDDYYYYTS(r.ended || "");

    const duration = (typeof r.durationSec === "number")
      ? r.durationSec.toFixed(1)
      : (r.durationSec || "");

    const date = r.date || "";
    const viewHref = date && filename
      ? `view.html?date=${encodeURIComponent(date)}&filename=${encodeURIComponent(filename)}`
      : `#`;

    return `
      <tr>
        <td>${filename}</td>
        <td>${pages}</td>
        <td>${started}</td>
        <td>${ended}</td>
        <td>${duration}</td>
        <td><a href="${viewHref}" class="btn btn-sm btn-primary"${viewHref==="#"?' tabindex="-1" aria-disabled="true"':''}>View</a></td>
      </tr>`;
  });

  tb.innerHTML = rows.join("");
}

/* ---------- Fetch + render ---------- */
async function fetchAndRender() {
  const f = getUIFilters();

  // Persist current UI selection
  saveFilters(f);

  if (!allFiltersSet(f)) {
    clearTableWithMessage("Select a date range and state to load files.");
    return;
  }

  const params = new URLSearchParams({
    from: f.fromDate,
    to: f.toDate,
    state: f.state     // 🔹 ensure state is always passed
  });

  try {
    const res = await fetch(`/api/files?${params.toString()}`, { credentials: "include" });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const data = await res.json();
    renderRows(data);
  } catch (e) {
    console.error("Process History fetch error:", e);
    clearTableWithMessage("Error loading data. Please adjust filters or try again.");
  }
}

/* ---------- Init ---------- */
document.addEventListener("DOMContentLoaded", () => {
  // Preload saved filters (shared with Dashboard)
  applyFiltersToUI();

  // Initial render
  fetchAndRender();

  // Refresh on any filter change
  ["fromDate", "toDate", "stateSelect"].forEach(id => {
    const el = document.getElementById(id);
    if (el) el.addEventListener("change", fetchAndRender);
  });

  // Keep in sync across tabs
  window.addEventListener("storage", (event) => {
    if (event.key === "filters") {
      applyFiltersToUI();
      fetchAndRender();
    }
  });
});
