// window.AuditLogPage — user activity / login audit trail.
// Props: { data, companyProfile, scopedCompanyId, globalPeriod, setPage }
//
// Reads from activity_audit_log (user-activity events) + login_events. Both are
// company-scoped via RLS and inserted only by the log-audit-event edge function.
(function () {
  const h = React.createElement;
  const { useState, useEffect, useMemo } = React;

  function AuditLogPage({ scopedCompanyId, companyProfile }) {
    const [events, setEvents] = useState([]);
    const [loginEvents, setLoginEvents] = useState([]);
    const [loading, setLoading] = useState(true);
    const [dateRange, setDateRange] = useState("30d");
    const [eventFilter, setEventFilter] = useState("all");
    const [userFilter, setUserFilter] = useState("all");
    const [search, setSearch] = useState("");
    const [page, setPageNum] = useState(1);
    const [queryError, setQueryError] = useState(null);
    const [authed, setAuthed] = useState(null); // null = unknown, false = no session
    const PAGE_SIZE = 50;

    // Admins / super-admins (no scoped company) read ALL events via RLS — never
    // constrain their query by company_id, which would exclude null-company rows.
    const isAdmin = (companyProfile && (companyProfile.role === "admin" || companyProfile.is_admin === true)) || !scopedCompanyId;

    useEffect(() => {
      const sb = window.supabaseClient;
      if (!sb) { setLoading(false); return; }
      setLoading(true);
      let cancelled = false;

      // Surface auth state: an unauthenticated session gets 0 rows from RLS with
      // NO error, which otherwise renders as a misleading "no events" message.
      sb.auth.getUser().then(function (r) { if (!cancelled) setAuthed(!!(r && r.data && r.data.user)); });

      const since = dateRange === "7d" ? new Date(Date.now() - 7 * 86400000).toISOString()
        : dateRange === "30d" ? new Date(Date.now() - 30 * 86400000).toISOString()
        : dateRange === "90d" ? new Date(Date.now() - 90 * 86400000).toISOString()
        : null;

      // Let RLS do the scoping. Only constrain by company_id for a non-admin user
      // with an explicit scope — null-company (super-admin) events must NOT be
      // excluded by a hard equality filter.
      let q = sb.from("activity_audit_log").select("*").order("created_at", { ascending: false }).limit(500);
      if (scopedCompanyId && !isAdmin) q = q.eq("company_id", scopedCompanyId);
      if (since) q = q.gte("created_at", since);

      let lq = sb.from("login_events").select("*").order("created_at", { ascending: false }).limit(100);
      if (scopedCompanyId && !isAdmin) lq = lq.eq("company_id", scopedCompanyId);

      Promise.all([q, lq]).then(function (res) {
        if (cancelled) return;
        const auditRes = res[0] || {}, loginRes = res[1] || {};
        if (auditRes.error) console.warn("[audit] read activity_audit_log failed:", auditRes.error.message);
        if (loginRes.error) console.warn("[audit] read login_events failed:", loginRes.error.message);
        setQueryError(auditRes.error ? auditRes.error.message : null);
        setEvents(auditRes.data || []);
        setLoginEvents(loginRes.data || []);
        setLoading(false);
      }, function () { if (!cancelled) { setQueryError("Could not reach the audit log."); setEvents([]); setLoginEvents([]); setLoading(false); } });

      return function () { cancelled = true; };
    }, [scopedCompanyId, dateRange, isAdmin]);

    // On open: log a normal page_view. (The global nav logger in app.jsx also
    // records this; kept here so the event fires even on direct deep-link open.)
    useEffect(function () {
      window.logAuditEvent && window.logAuditEvent("page_view", { category: "activity", page: "audit-log", detail: "Audit Log viewed" });
    }, []);

    const filtered = useMemo(function () {
      return events.filter(function (e) {
        if (eventFilter !== "all" && e.event_category !== eventFilter) return false;
        if (userFilter !== "all" && e.user_email !== userFilter) return false;
        if (search && !(
          (e.action_detail || "").toLowerCase().includes(search.toLowerCase()) ||
          (e.user_email || "").toLowerCase().includes(search.toLowerCase()) ||
          (e.page_or_resource || "").toLowerCase().includes(search.toLowerCase())
        )) return false;
        return true;
      });
    }, [events, eventFilter, userFilter, search]);

    const uniqueUsers = useMemo(function () { return Array.from(new Set(events.map(function (e) { return e.user_email; }).filter(Boolean))); }, [events]);

    const totalEvents = events.length;
    const uniqueUserCt = new Set(events.map(function (e) { return e.user_id; }).filter(Boolean)).size;
    const loginCt = loginEvents.length;
    const dataChangeCt = events.filter(function (e) { return e.event_category === "data" || e.event_category === "admin"; }).length;

    const EVENT_COLORS = {
      login: { bg: "#dbeafe", color: "#1d4ed8", label: "Login" },
      logout: { bg: "#f3f4f6", color: "#6b7280", label: "Logout" },
      page_view: { bg: "#f0fdf4", color: "#15803d", label: "Page View" },
      data_upload: { bg: "#dcfce7", color: "#16a34a", label: "Data Upload" },
      budget_upload: { bg: "#dcfce7", color: "#16a34a", label: "Budget Upload" },
      settings_change: { bg: "#fef9c3", color: "#ca8a04", label: "Settings" },
      account_mapping_change: { bg: "#fef3c7", color: "#d97706", label: "Mapping Change" },
      sync_triggered: { bg: "#ccfbf1", color: "#0d9488", label: "Sync" },
      data_export: { bg: "#ede9fe", color: "#7c3aed", label: "Export" },
      report_generated: { bg: "#e0e7ff", color: "#4338ca", label: "Report" },
    };

    function EventBadge(props) {
      const cfg = EVENT_COLORS[props.type] || { bg: "#f3f4f6", color: "#6b7280", label: props.type || "—" };
      return h("span", { style: { background: cfg.bg, color: cfg.color, padding: "2px 8px", borderRadius: "20px", fontSize: "10px", fontWeight: "700", whiteSpace: "nowrap" } }, cfg.label);
    }

    function fmtTime(ts) {
      if (!ts) return "—";
      const d = new Date(ts);
      if (isNaN(+d)) return String(ts);
      return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }) + " " + d.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" });
    }

    const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
    const curPage = Math.min(page, totalPages);
    const paginated = filtered.slice((curPage - 1) * PAGE_SIZE, curPage * PAGE_SIZE);

    const tile = function (label, value) {
      return h("div", { key: label, style: { flex: "1 1 160px", minWidth: "150px", background: "#fff", border: "1px solid #E4E8F0", borderRadius: "12px", padding: "14px 16px" } },
        h("div", { style: { fontSize: "10.5px", fontWeight: "700", color: "#6475a0", textTransform: "uppercase", letterSpacing: ".04em" } }, label),
        h("div", { style: { fontSize: "24px", fontWeight: "800", color: "#0d2040", marginTop: "3px" } }, value));
    };
    const selStyle = { padding: "5px 10px", fontSize: "11px", border: "1px solid rgba(13,32,64,.15)", borderRadius: "6px", background: "white", color: "#0d2040", cursor: "pointer" };
    const thStyle = { textAlign: "left", padding: "10px 14px", background: "#0d2040", color: "white", fontWeight: "700", fontSize: "10px", textTransform: "uppercase", letterSpacing: ".06em", whiteSpace: "nowrap" };

    return h("div", { style: { fontFamily: "Inter,sans-serif", minHeight: "100vh", background: "#f8f9fc" } },
      // Hero
      h("div", { className: "pa-hero", style: { marginBottom: "0" } },
        h("div", { className: "pa-hero-eyebrow" }, "Admin"),
        h("div", { className: "pa-hero-title" }, "Audit Log"),
        h("div", { className: "pa-hero-subtitle" }, "All user activity, logins, and data changes")),

      h("div", { style: { padding: "20px 28px 40px" } },
        // KPI tiles
        h("div", { style: { display: "flex", flexWrap: "wrap", gap: "12px", marginBottom: "20px" } },
          tile("Events (period)", totalEvents.toLocaleString()),
          tile("Unique Users", String(uniqueUserCt)),
          tile("Logins", String(loginCt)),
          tile("Data Changes", String(dataChangeCt))),

        // Filters
        h("div", { style: { background: "white", borderRadius: "10px", border: "1px solid rgba(13,32,64,.10)", padding: "14px 16px", marginBottom: "16px", display: "flex", gap: "10px", flexWrap: "wrap", alignItems: "center" } },
          h("div", { style: { display: "flex", gap: "4px" } },
            ["7d", "30d", "90d", "all"].map(function (r) {
              return h("button", { key: r, onClick: function () { setDateRange(r); setPageNum(1); }, style: { padding: "4px 10px", fontSize: "11px", fontWeight: "700", cursor: "pointer", borderRadius: "6px", border: "1px solid rgba(13,32,64,.15)", background: dateRange === r ? "#0d2040" : "rgba(13,32,64,.04)", color: dateRange === r ? "white" : "#6475a0" } }, r === "all" ? "All time" : "Last " + r);
            })),
          h("span", { style: { color: "rgba(13,32,64,.2)" } }, "|"),
          h("select", { value: eventFilter, onChange: function (e) { setEventFilter(e.target.value); setPageNum(1); }, style: selStyle },
            h("option", { value: "all" }, "All event types"),
            h("option", { value: "auth" }, "Logins / Auth"),
            h("option", { value: "activity" }, "Page activity"),
            h("option", { value: "data" }, "Data changes"),
            h("option", { value: "admin" }, "Admin actions"),
            h("option", { value: "export" }, "Exports")),
          uniqueUsers.length > 1 ? h("select", { value: userFilter, onChange: function (e) { setUserFilter(e.target.value); setPageNum(1); }, style: selStyle },
            [h("option", { key: "all", value: "all" }, "All users")].concat(uniqueUsers.map(function (u) { return h("option", { key: u, value: u }, u); }))) : null,
          h("input", { type: "text", placeholder: "Search events...", value: search, onChange: function (e) { setSearch(e.target.value); setPageNum(1); }, style: { padding: "5px 12px", fontSize: "11px", border: "1px solid rgba(13,32,64,.15)", borderRadius: "6px", flex: 1, minWidth: "150px", outline: "none" } }),
          h("span", { style: { fontSize: "11px", color: "#6475a0", marginLeft: "auto", whiteSpace: "nowrap" } }, filtered.length + " events")),

        // Main audit table
        h("div", { style: { background: "white", borderRadius: "12px", border: "1px solid rgba(13,32,64,.10)", overflow: "hidden", marginBottom: "24px" } },
          loading
            ? h("div", { style: { padding: "40px", textAlign: "center", color: "#6475a0" } }, "Loading audit log...")
            : filtered.length === 0
              ? h("div", { style: { padding: "40px", textAlign: "center", fontSize: "13px", lineHeight: 1.6, color: queryError ? "#dc2626" : "#6475a0" } },
                  queryError ? ("Couldn’t load the audit log: " + queryError + " — see the browser console for details.")
                    : authed === false ? "You’re not signed in, so the audit log can’t be read (events are visible only to an authenticated session). Sign in and reopen this page."
                    : events.length === 0 ? "No audit events recorded yet. Events appear here as users sign in, navigate and make changes."
                    : "No events match the current filters.")
              : h("div", null,
                h("div", { style: { overflowX: "auto" } }, h("table", { style: { width: "100%", borderCollapse: "collapse", fontSize: "11.5px" } },
                  h("thead", null, h("tr", null, ["Timestamp", "User", "Event", "Page / Resource", "Detail", "IP"].map(function (col) { return h("th", { key: col, style: thStyle }, col); }))),
                  h("tbody", null, paginated.map(function (e, i) {
                    return h("tr", { key: e.id || i, style: { background: i % 2 === 0 ? "white" : "rgba(248,249,252,1)", borderBottom: "1px solid rgba(13,32,64,.05)" } },
                      h("td", { style: { padding: "8px 14px", color: "#4a5680", whiteSpace: "nowrap" } }, fmtTime(e.created_at)),
                      h("td", { style: { padding: "8px 14px", color: "#0d2040", fontWeight: "500" } }, e.user_email || "—"),
                      h("td", { style: { padding: "8px 14px" } }, h(EventBadge, { type: e.event_type })),
                      h("td", { style: { padding: "8px 14px", color: "#4a5680" } }, e.page_or_resource || "—"),
                      h("td", { style: { padding: "8px 14px", color: "#1a2540", maxWidth: "320px" } }, e.action_detail || "—"),
                      h("td", { style: { padding: "8px 14px", color: "#6475a0", fontFamily: "monospace", fontSize: "10.5px" } }, e.ip_address || "—"));
                  })))),
                totalPages > 1 ? h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center", padding: "12px 16px", borderTop: "1px solid rgba(13,32,64,.08)" } },
                  h("span", { style: { fontSize: "11px", color: "#6475a0" } }, "Page " + curPage + " of " + totalPages + " · " + filtered.length + " total events"),
                  h("div", { style: { display: "flex", gap: "6px" } },
                    h("button", { onClick: function () { setPageNum(Math.max(1, curPage - 1)); }, disabled: curPage === 1, style: { padding: "5px 12px", fontSize: "11px", fontWeight: "700", cursor: curPage === 1 ? "not-allowed" : "pointer", borderRadius: "6px", border: "1px solid rgba(13,32,64,.15)", background: "white", color: curPage === 1 ? "#aab" : "#0d2040", opacity: curPage === 1 ? 0.5 : 1 } }, "← Prev"),
                    h("button", { onClick: function () { setPageNum(Math.min(totalPages, curPage + 1)); }, disabled: curPage === totalPages, style: { padding: "5px 12px", fontSize: "11px", fontWeight: "700", cursor: curPage === totalPages ? "not-allowed" : "pointer", borderRadius: "6px", border: "1px solid rgba(13,32,64,.15)", background: "white", color: curPage === totalPages ? "#aab" : "#0d2040", opacity: curPage === totalPages ? 0.5 : 1 } }, "Next →"))) : null)),

        // Login events section
        h("div", { style: { background: "white", borderRadius: "12px", border: "1px solid rgba(13,32,64,.10)", overflow: "hidden" } },
          h("div", { style: { padding: "14px 16px", borderBottom: "1px solid rgba(13,32,64,.08)", fontWeight: "800", fontSize: "12px", color: "#0d2040", textTransform: "uppercase", letterSpacing: ".06em" } }, "🔐 Login History"),
          loginEvents.length === 0
            ? h("div", { style: { padding: "24px", textAlign: "center", color: "#6475a0", fontSize: "12px" } }, "No login events recorded yet. Logins appear here automatically.")
            : h("div", { style: { overflowX: "auto" } }, h("table", { style: { width: "100%", borderCollapse: "collapse", fontSize: "11.5px" } },
              h("thead", null, h("tr", null, ["Timestamp", "User", "Event", "IP Address", "Browser / Device"].map(function (col) { return h("th", { key: col, style: Object.assign({}, thStyle, { padding: "9px 14px" }) }, col); }))),
              h("tbody", null, loginEvents.slice(0, 50).map(function (e, i) {
                return h("tr", { key: e.id || i, style: { background: i % 2 === 0 ? "white" : "rgba(248,249,252,1)", borderBottom: "1px solid rgba(13,32,64,.05)" } },
                  h("td", { style: { padding: "7px 14px", color: "#4a5680", whiteSpace: "nowrap" } }, fmtTime(e.created_at)),
                  h("td", { style: { padding: "7px 14px", color: "#0d2040", fontWeight: "500" } }, e.user_email || "—"),
                  h("td", { style: { padding: "7px 14px" } }, h("span", { style: { background: e.event_type === "login" ? "#dbeafe" : e.event_type === "login_failed" ? "#fee2e2" : "#f3f4f6", color: e.event_type === "login" ? "#1d4ed8" : e.event_type === "login_failed" ? "#dc2626" : "#6b7280", padding: "2px 8px", borderRadius: "20px", fontSize: "10px", fontWeight: "700" } }, e.event_type === "login" ? "✓ Login" : e.event_type === "login_failed" ? "✗ Failed" : e.event_type)),
                  h("td", { style: { padding: "7px 14px", color: "#6475a0", fontFamily: "monospace", fontSize: "10.5px" } }, e.ip_address || "—"),
                  h("td", { style: { padding: "7px 14px", color: "#6475a0", fontSize: "10.5px", maxWidth: "200px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, e.user_agent ? e.user_agent.split("/")[0] : "—"));
              })))))));
  }

  window.AuditLogPage = AuditLogPage;
})();
