// /static/js/final_qc_page.js
// QC Dashboard client logic (externalized)
// Pie/doughnut code removed as requested — re-added only the small pie helper and invocation.

(function () {
  // ---- Utility helpers ----
  function nameFromEmail(email) {
    if (!email) return "";
    const local = email.split("@")[0].split("+")[0];
    const parts = local.split(/[._-]+/).filter(Boolean);
    if (!parts.length) return email;
    return parts.map(p => p.charAt(0).toUpperCase() + p.slice(1).toLowerCase()).join(" ");
  }

  // --- QC-specific storage keys (isolate this page) ---
  const QC_FILTERS_KEY = "qcFilters";
  const QC_FILTERS_APPLIED_KEY = "qcFiltersApplied";
  const VITU_CLEAR_KEY = "vitu_clear_on_login";

  function getFilters() {
    return {
      state: (document.getElementById("stateSelect")?.value || "").trim(),
      from: (document.getElementById("fromDate")?.value || "").trim(),
      to: (document.getElementById("toDate")?.value || "").trim()
    };
  }

  function setNavActive() {
    const current = (location.pathname.split("/").pop() || "final_qc_page.html").toLowerCase();
    document.querySelectorAll('.nav-sidebar a.nav-link').forEach(a => {
      const href = (a.getAttribute('href') || '').toLowerCase();
      if (!href) return;
      if (href.endsWith(current)) a.classList.add('active');
      else a.classList.remove('active');
    });
  }

  function goToHistoryWith(category) {
    const f = getFilters();

    localStorage.setItem("historyFilters", JSON.stringify({
      category,
      state: f.state,
      fromDate: f.from,
      toDate: f.to
    }));

    const shouldApply = !!(f.state && f.from && f.to);
    if (shouldApply) {
      localStorage.setItem("historyFiltersApplied", JSON.stringify({ applied: true, ts: Date.now() }));
    } else {
      localStorage.removeItem("historyFiltersApplied");
    }

    const params = new URLSearchParams({
      state: f.state || "",
      from: f.from || "",
      to: f.to || "",
      category: category
    });
    window.location.href = `process-history.html?${params.toString()}`;
  }

  async function tryFetchJson(url, opts = {}) {
    try {
      const r = await fetch(url, Object.assign({ credentials: 'include' }, opts));
      if (!r.ok) return null;
      return await r.json();
    } catch (e) {
      return null;
    }
  }

  // Count whether a file row should be considered suspect (multiple fallbacks)
  function countSuspectInRow(r) {
    try {
      if (r == null) return false;
      if (r.hasOwnProperty('has_suspect')) {
        if (r.has_suspect === 1 || r.has_suspect === true) return true;
      }
      if (r.is_suspect_data === 1 || r.is_suspect_data === true) return true;
      if (r.is_suspect === 1 || r.is_suspect === true) return true;

      // suspect_extract_data or suspect_map presence
      if (r.suspect_extract_data && Object.keys(r.suspect_extract_data || {}).length) return true;
      if (r.suspect_map && Object.keys(r.suspect_map || {}).length) return true;

      // Various "ProcessData" style fields
      for (const k of Object.keys(r || {})) {
        if (k.toLowerCase().includes('suspect')) {
          const v = r[k];
          if (v && (typeof v === 'object' ? Object.keys(v).length > 0 : String(v).trim() !== "")) return true;
        }
      }
    } catch (e) {
      // ignore
    }
    return false;
  }

  function isQCCompletedInRow(r) {
    if (!r) return false;
    if (r.hasOwnProperty('is_qc_completed')) {
      const v = r.is_qc_completed;
      if (v === 'Yes' || v === 'YES' || v === 'yes' || v === 1 || v === true) return true;
    }
    if (r.IsQCCompleted) {
      const v = r.IsQCCompleted;
      if (typeof v === 'string') return v.toUpperCase() === 'YES';
      return Boolean(v);
    }
    return false;
  }

  // ---------- Small helpers for robust client-side counts and state matching ----------
  function isRejectedOrDuplicateRow(r) {
    if (!r) return false;
    const s = (r.status || "").toString().toUpperCase();
    if (s === "FAILED" || s === "DUPLICATE") return true;
    if (r.is_duplicate === 1 || r.is_duplicate === true) return true;
    if (typeof r.rejected_for === "string" && r.rejected_for.trim() !== "") return true;
    if (typeof r.rejection_reason === "string" && r.rejection_reason.trim() !== "") return true;
    return false;
  }

  function matchesStateRow(row, state) {
    if (!state) return true; // empty state = all states
    if (!row) return false;
    const s = String(state).trim().toLowerCase();
    const maybe = [
      row.state,
      row.state_code,
      row.stateName,
      row.location,
      row.region,
      row.stateShort
    ];
    for (const v of maybe) {
      if (!v) continue;
      const vs = String(v).trim().toLowerCase();
      if (vs === s) return true;
      if (vs.includes(s)) return true;
      if (s.includes(vs)) return true;
    }
    return false;
  }

  // ---- Chart helpers ----
  // Pie helper (keeps pie slices same colors as tiles)
  function createOrUpdatePie(el, labels, values, colors) {
    try {
      const ctx = el.getContext('2d');
      if (window.__qcPieChart) {
        window.__qcPieChart.data.labels = labels;
        window.__qcPieChart.data.datasets[0].data = values;
        window.__qcPieChart.data.datasets[0].backgroundColor = colors;
        window.__qcPieChart.update();
        return window.__qcPieChart;
      }
      window.__qcPieChart = new Chart(ctx, {
        type: 'pie',
        data: {
          labels: labels,
          datasets: [{
            data: values,
            backgroundColor: colors,
            borderColor: '#ffffff',
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: { position: 'right' },
            tooltip: { callbacks: {} }
          }
        }
      });
      return window.__qcPieChart;
    } catch (e) {
      console.warn('Pie chart failure', e);
      return null;
    }
  }

  function createOrUpdateBar(el, labels, values) {
    const ctx = el.getContext('2d');
    if (window.__qcBarChart) {
      window.__qcBarChart.data.labels = labels;
      window.__qcBarChart.data.datasets[0].data = values;
      window.__qcBarChart.update();
      return window.__qcBarChart;
    }
    window.__qcBarChart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels,
        datasets: [{
          label: 'Files',
          data: values
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: { legend: { display: false } },
        scales: {
          x: { title: { display: true, text: 'Duration bins (s)' } },
          y: { title: { display: true, text: 'Files' }, beginAtZero: true }
        }
      }
    });
    return window.__qcBarChart;
  }

  // ---- Main loader ----
  async function loadQcDataAndRender() {
    const filters = getFilters();

    // set loading placeholders
    const elReceived = document.getElementById("filesReceived");
    const elSuspect = document.getElementById("filesProcessed");
    const elCleared = document.getElementById("filesDelivered");
    const elPending = document.getElementById("filesFailed");

    if (elReceived) elReceived.textContent = '...';
    if (elSuspect) elSuspect.textContent = '...';
    if (elCleared) elCleared.textContent = '...';
    if (elPending) elPending.textContent = '...';

    // try QC endpoints first (future-proof), else fall back
    const qs = `?from=${encodeURIComponent(filters.from)}&to=${encodeURIComponent(filters.to)}&state=${encodeURIComponent(filters.state)}`;
    let qcSummary = await tryFetchJson(`/api/qc/summary${qs}`);
    let kpiResp = null;
    if (!qcSummary) {
      kpiResp = await tryFetchJson(`/api/kpis${qs}`);
    } else {
      // if qcSummary present, it may be sufficient for some tiles; still fetch files for details
      kpiResp = await tryFetchJson(`/api/kpis${qs}`) || null;
    }

    // fetch file rows to compute suspect/cleared/pending robustly
    const filesResp = await tryFetchJson(`/api/files${qs}`);

    // charts
    let chartsResp = await tryFetchJson(`/api/qc/charts${qs}`);
    if (!chartsResp) chartsResp = await tryFetchJson(`/api/charts${qs}`);

    // Received - prefer file-derived and filtered-by-state when possible
    let received = 0;
    if (Array.isArray(filesResp)) {
      // filter files by selected state defensively
      const filesForState = filesResp.filter(r => matchesStateRow(r, (filters.state || "").trim().toLowerCase()));
      received = filesForState.length;
    } else if (qcSummary && typeof qcSummary.received === 'number') {
      received = qcSummary.received;
    } else if (kpiResp && typeof kpiResp.received === 'number') {
      received = kpiResp.received;
    }

    // compute suspect/cleared/rejected using filesResp when available (and filtered by state)
    let suspectCount = 0;
    let clearedCount = 0;
    let rejectedCount = 0;

    if (Array.isArray(filesResp)) {
      const filesForState = filesResp.filter(r => matchesStateRow(r, (filters.state || "").trim().toLowerCase()));
      for (const r of filesForState) {
        const status = String((r.status || '')).toUpperCase();
        const isRejected = isRejectedOrDuplicateRow(r) || status === 'FAILED' || status === 'DUPLICATE' || !!(r.rejection_reason || r.rejected_for);
        if (isRejected) {
          rejectedCount++;
          continue;
        }
        const isSus = countSuspectInRow(r);
        if (isSus) suspectCount++;
        const isProcessed = status === 'SUCCESS';
        const qcDone = isQCCompletedInRow(r);
        if (isProcessed && (qcDone || !isSus)) {
          clearedCount++;
        }
      }
    } else {
      // fallback to qcSummary or KPIs
      if (qcSummary) {
        suspectCount = qcSummary.suspect || 0;
        clearedCount = qcSummary.cleared || (kpiResp && kpiResp.processed ? kpiResp.processed : 0);
        rejectedCount = qcSummary.rejected || (kpiResp && kpiResp.rejected ? kpiResp.rejected : 0);
      } else if (kpiResp) {
        clearedCount = kpiResp.processed || 0;
        rejectedCount = kpiResp.rejected || 0;
        suspectCount = 0;
      }
    }

    // Here we map "pending" to the red tile meaning (files awaiting action / rejected)
    const pendingCount = rejectedCount;

    // Fill tiles
    if (elReceived) elReceived.textContent = String(received);
    if (elSuspect) elSuspect.textContent = String(suspectCount);
    if (elCleared) elCleared.textContent = String(clearedCount);
    if (elPending) elPending.textContent = String(pendingCount);

    // Render pie chart reflecting tiles: Suspected, Cleared, Pending using same tile colors
    try {
      const pieEl = document.getElementById('qcPieChart');
      if (pieEl) {
        const labels = ['Suspected', 'Cleared', 'Pending'];
        // Use client-derived counts (so tiles and pie always match)
        const values = [Number(suspectCount)||0, Number(clearedCount)||0, Number(pendingCount)||0];
        const colors = ['#f1c40f', '#28a745', '#ab251c'];
        createOrUpdatePie(pieEl, labels, values, colors);
      }
    } catch (e) {
      console.warn('Pie chart render failed', e);
    }

    // Bar chart - use chartsResp.time_hist if present
    try {
      const barEl = document.getElementById('barChart');
      let labels = ['N/A'];
      let values = [0];
      if (chartsResp && chartsResp.time_hist && Array.isArray(chartsResp.time_hist.counts)) {
        const counts = chartsResp.time_hist.counts;
        const edges = chartsResp.time_hist.bin_edges || [];
        if (edges.length === counts.length + 1) {
          labels = [];
          values = [];
          for (let i = 0; i < counts.length; ++i) {
            const a = Number(edges[i]).toFixed(0);
            const b = Number(edges[i + 1]).toFixed(0);
            labels.push(`${a}-${b}s`);
            values.push(counts[i]);
          }
        } else {
          labels = counts.map((_, i) => `B${i + 1}`);
          values = counts.slice();
        }
      }
      if (barEl) createOrUpdateBar(barEl, labels, values);
    } catch (e) { console.warn('bar chart error', e); }
  }

  // ---- Storage helpers for QC page independence ----
  function saveQcFiltersToStorage(filters) {
    try { localStorage.setItem(QC_FILTERS_KEY, JSON.stringify(filters || {})); } catch (e) { /* ignore */ }
  }
  function loadQcFiltersFromStorage() {
    try { const v = localStorage.getItem(QC_FILTERS_KEY); return v ? JSON.parse(v) : {}; } catch (e) { return {}; }
  }
  function setQcAppliedFlag(val) {
    try {
      if (val) localStorage.setItem(QC_FILTERS_APPLIED_KEY, JSON.stringify({ applied: true, ts: Date.now() }));
      else localStorage.removeItem(QC_FILTERS_APPLIED_KEY);
    } catch (e) { /* ignore */ }
  }
  function isQcAppliedFlagSet() {
    try { return !!JSON.parse(localStorage.getItem(QC_FILTERS_APPLIED_KEY) || "{}").applied; }
    catch { return false; }
  }

  function restoreUiFromSavedFilters() {
    try {
      const saved = loadQcFiltersFromStorage() || {};
      if (saved && saved.state) {
        const el = document.getElementById("stateSelect");
        if (el) el.value = saved.state;
      }
      if (saved && saved.from) {
        const el = document.getElementById("fromDate");
        if (el) el.value = saved.from;
      }
      if (saved && saved.to) {
        const el = document.getElementById("toDate");
        if (el) el.value = saved.to;
      }
    } catch (e) { /* ignore */ }
  }

  function clearUiAndStorageForQc() {
    try {
      const elState = document.getElementById("stateSelect");
      if (elState) elState.value = "";
      const elFrom = document.getElementById("fromDate");
      if (elFrom) elFrom.value = "";
      const elTo = document.getElementById("toDate");
      if (elTo) elTo.value = "";
      localStorage.removeItem(QC_FILTERS_KEY);
      setQcAppliedFlag(false);
    } catch (e) { /* ignore */ }
  }

  // ---- DOM boot ----
  document.addEventListener('DOMContentLoaded', async function () {
    // Auth check & username
    try {
      const r = await fetch('/auth/me', { credentials: 'include' });
      if (!r.ok) { window.location.href = 'index.html'; return; }
      const { user } = await r.json();
      const wel = document.getElementById("navbarUser");
      if (wel) wel.textContent = nameFromEmail(user) || "User";
    } catch (e) {
      window.location.href = 'index.html';
      return;
    }

    // IMPORTANT: neutralize dashboard.js cross-page helpers INSIDE this tab only.
    // dashboard.js defines global functions and a storage listener that reacts to "dashboardFilters".
    // Overriding those functions here prevents dashboard's listener from updating QC DOM.
    try {
      const nop = () => {};
      if (typeof window.loadFiltersToUI === 'function') window.loadFiltersToUI = nop;
      if (typeof window.fetchAndRender === 'function') window.fetchAndRender = nop;
      if (typeof window.resetAll === 'function') window.resetAll = nop;
      if (typeof window.setAppliedFlag === 'function') window.setAppliedFlag = nop;
      // isApplied should return false on QC page so dashboard listener (if fired) won't trigger fetch
      if (typeof window.isApplied === 'function') window.isApplied = () => false;
      // if initCharts or saveFilters exist in dashboard.js, make them no-ops here to be safe
      if (typeof window.initCharts === 'function') window.initCharts = nop;
      if (typeof window.saveFilters === 'function') window.saveFilters = nop;
    } catch (e) {
      // ignore if any of these don't exist
    }

    // Logout
    document.getElementById("logoutBtn")?.addEventListener("click", async (e) => {
      e.preventDefault();
      try { await fetch("/auth/logout", { method: "POST", credentials: "include" }); } catch {}
      try { localStorage.removeItem("loggedIn"); localStorage.removeItem("username"); } catch {}
      window.location.href = "index.html";
    });

    // nav highlight
    setNavActive();

    // wire tile clicks
    document.getElementById("tileReceived")?.addEventListener("click", () => goToHistoryWith("received"));
    document.getElementById("tileProcessed")?.addEventListener("click", () => goToHistoryWith("suspect"));
    document.getElementById("tileDelivered")?.addEventListener("click", () => goToHistoryWith("processed"));
    document.getElementById("tileRejected")?.addEventListener("click", () => goToHistoryWith("rejected"));

    // apply / clear buttons
    document.getElementById("applyFilters")?.addEventListener("click", async () => {
      const f = getFilters();
      const onlyOneDate = (!!f.from && !f.to) || (!f.from && !!f.to);
      if (onlyOneDate) {
        if (typeof showWarning === 'function') {
          showWarning("Please select both Start and End date.");
        } else {
          alert("Please select both Start and End date.");
        }
        return;
      }

      // Save QC-specific filters and mark as applied (so this page is independent)
      try {
        saveQcFiltersToStorage(f);
        setQcAppliedFlag(true);
      } catch (e) { /* ignore */ }

      await loadQcDataAndRender();
    });

    document.getElementById("clearFilters")?.addEventListener("click", async () => {
      // Clear UI and QC-specific storage/flag
      clearUiAndStorageForQc();
      await loadQcDataAndRender();
    });

    // restore filters if QC-specific saved and applied
    try {
      if (isQcAppliedFlagSet()) {
        restoreUiFromSavedFilters();
      } else {
        // ensure independent start (don't read generic 'filters' or other pages' keys)
        clearUiAndStorageForQc();
      }
    } catch (e) { /* ignore */ }

    // initial load
    await loadQcDataAndRender();

    // Listen to storage events to remain isolated:
    // - ONLY react to QC-specific keys or the global login broadcast.
    window.addEventListener('storage', function (e) {
      try {
        if (!e || !e.key) {
          return;
        }

        // If a login happened in another tab, reset QC UI immediately
        if (e.key === VITU_CLEAR_KEY) {
          clearUiAndStorageForQc();
          // reload empty/cleared view
          loadQcDataAndRender().catch(() => {});
          return;
        }

        // Only react to QC-specific filter changes
        if (e.key === QC_FILTERS_KEY || e.key === QC_FILTERS_APPLIED_KEY) {
          // If applied flag exists, restore and apply; otherwise clear
          if (isQcAppliedFlagSet()) {
            restoreUiFromSavedFilters();
            loadQcDataAndRender().catch(() => {});
          } else {
            clearUiAndStorageForQc();
            loadQcDataAndRender().catch(() => {});
          }
        }

        // IGNORE all other storage keys so changes on other pages won't affect QC.
      } catch (err) {
        console.warn("Error handling storage event in final_qc_page:", err);
      }
    }, false);
  });

  // expose loader for debugging
  window.loadQcDataAndRender = loadQcDataAndRender;
})();
