// screens-activity.jsx — Unified Activity Log
// Shows all system events: task executions, emails sent/confirmed, cron runs, API calls.
// Pulls from workspace_tasks (via listWorkspaceTasks per workspace) + tenantAuditLogs.

function ActivityLogScreen() {
  const [events, setEvents] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [filter, setFilter] = React.useState("all");
  const [search, setSearch] = React.useState("");

  React.useEffect(() => {
    loadActivity();
  }, []);

  const loadActivity = async () => {
    setLoading(true);
    const merged = [];

    // Pull audit logs (cron, api, user actions)
    try {
      const logs = await api.tcall("tenantAuditLogs");
      (logs || []).forEach(l => {
        merged.push({
          id: "audit-" + l.id,
          type: _classifyAuditLog(l),
          title: l.action || l.event_type || "System event",
          detail: l.detail || l.description || null,
          status: l.status || "info",
          actor: l.user_email || l.actor || "System",
          ts: l.created_at,
          meta: l,
        });
      });
    } catch (_) {}

    // Pull workspace task events (emails, content generation, completions)
    try {
      const workspaces = await api.tcall("listWorkspaces");
      await Promise.all((workspaces || []).map(async ws => {
        try {
          const tasks = await api.tcall("listWorkspaceTasks", { workspaceId: ws.id });
          (tasks || []).forEach(t => {
            // Content generation event
            if (t.generated_at) {
              merged.push({
                id: "gen-" + t.id,
                type: "task",
                title: `Content generated: ${t.title}`,
                detail: `Workspace: ${ws.name}${t.publisher_name ? ` · Publisher: ${t.publisher_name}` : ""}`,
                status: "success",
                actor: "AI",
                ts: t.generated_at,
                meta: t,
              });
            }
            // Email sent event
            if (t.target_email) {
              merged.push({
                id: "email-" + t.id,
                type: "email",
                title: `Email dispatched: ${t.title}`,
                detail: `To: ${t.target_email}${t.publisher_name ? ` (${t.publisher_name})` : ""}`,
                status: t.status === "failed" ? "error" : t.completed_at ? "confirmed" : t.status === "in_progress" ? "sent" : "pending",
                actor: "System",
                ts: t.updated_at || t.created_at,
                meta: t,
              });
            }
            // Completion confirmation event
            if (t.completed_at && t.completed_by_name) {
              merged.push({
                id: "done-" + t.id,
                type: "email",
                title: `Published confirmed: ${t.title}`,
                detail: `By ${t.completed_by_name}${t.completed_url ? " · " + t.completed_url : ""}`,
                status: "confirmed",
                actor: t.completed_by_name,
                ts: t.completed_at,
                meta: t,
              });
            }
            // Task failure
            if (t.status === "failed") {
              merged.push({
                id: "fail-" + t.id,
                type: "task",
                title: `Task failed: ${t.title}`,
                detail: t.notes ? t.notes.replace(/\[Error\]/g, "").trim().slice(0, 120) : null,
                status: "error",
                actor: "System",
                ts: t.updated_at || t.created_at,
                meta: t,
              });
            }
          });
        } catch (_) {}
      }));
    } catch (_) {}

    // Sort newest first
    merged.sort((a, b) => new Date(b.ts || 0) - new Date(a.ts || 0));
    setEvents(merged);
    setLoading(false);
  };

  const _classifyAuditLog = (l) => {
    const action = (l.action || l.event_type || "").toLowerCase();
    if (action.includes("cron") || action.includes("job") || action.includes("schedule")) return "cron";
    if (action.includes("api") || action.includes("webhook") || action.includes("request")) return "api";
    if (action.includes("email") || action.includes("mail")) return "email";
    return "system";
  };

  const FILTERS = [
    { id: "all",    label: "All" },
    { id: "task",   label: "Tasks" },
    { id: "email",  label: "Emails" },
    { id: "cron",   label: "Cron Jobs" },
    { id: "api",    label: "API Calls" },
    { id: "system", label: "System" },
  ];

  const filtered = events.filter(e => {
    if (filter !== "all" && e.type !== filter) return false;
    if (search.trim()) {
      const q = search.toLowerCase();
      return (e.title + " " + (e.detail || "") + " " + (e.actor || "")).toLowerCase().includes(q);
    }
    return true;
  });

  const statusStyle = {
    success:   { bg: "var(--good-soft)",   color: "var(--good)",   icon: "✓" },
    confirmed: { bg: "var(--good-soft)",   color: "var(--good)",   icon: "✓" },
    sent:      { bg: "var(--accent-soft)", color: "var(--accent)", icon: "→" },
    pending:   { bg: "var(--line)",        color: "var(--muted)",  icon: "○" },
    error:     { bg: "#fef2f2",            color: "var(--bad)",    icon: "✕" },
    info:      { bg: "var(--line)",        color: "var(--muted)",  icon: "·" },
  };

  const typeIcon = { task: "⚙", email: "✉", cron: "⏱", api: "⇄", system: "◎" };
  const typeLabel = { task: "Task", email: "Email", cron: "Cron", api: "API", system: "System" };
  const typeColor = {
    task:   ["var(--accent-soft)", "var(--accent)"],
    email:  ["var(--good-soft)",   "var(--good)"],
    cron:   ["var(--warn-soft)",   "var(--warn)"],
    api:    ["var(--info-soft)",   "var(--info-ink)"],
    system: ["var(--line)",        "var(--muted)"],
  };

  const fmt = (ts) => {
    if (!ts) return "—";
    const d = new Date(ts);
    const now = new Date();
    const diffMs = now - d;
    const diffMin = Math.floor(diffMs / 60000);
    if (diffMin < 1)  return "just now";
    if (diffMin < 60) return `${diffMin}m ago`;
    const diffH = Math.floor(diffMin / 60);
    if (diffH < 24)   return `${diffH}h ago`;
    return d.toLocaleDateString("en-GB", { day: "numeric", month: "short" });
  };

  return (
    <div style={{ padding: "var(--pad)", maxWidth: 1000 }}>
      {/* Header */}
      <div style={{ marginBottom: 24 }}>
        <h1 style={{ fontSize: 22, fontWeight: 700, margin: 0 }}>Activity Log</h1>
        <div style={{ color: "var(--muted)", fontSize: 14, marginTop: 4 }}>
          All system events — task executions, emails dispatched, cron runs, API calls.
        </div>
      </div>

      {/* Filter bar */}
      <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 16, flexWrap: "wrap" }}>
        <div style={{ display: "flex", gap: 4 }}>
          {FILTERS.map(f => (
            <button key={f.id} onClick={() => setFilter(f.id)}
              style={{
                background: filter === f.id ? "var(--accent)" : "var(--line)",
                color: filter === f.id ? "var(--accent-ink)" : "var(--muted)",
                border: "none", borderRadius: 20, padding: "5px 14px",
                fontSize: 13, fontWeight: 600, cursor: "pointer",
              }}>{f.label}</button>
          ))}
        </div>
        <input
          value={search}
          onChange={e => setSearch(e.target.value)}
          placeholder="Search events…"
          style={{ marginLeft: "auto", padding: "7px 12px", borderRadius: 8, border: "1px solid var(--line)", fontSize: 13, background: "var(--panel)", color: "var(--ink)", width: 220 }}
        />
        <button
          onClick={loadActivity}
          style={{ background: "none", border: "1px solid var(--line)", borderRadius: 8, padding: "7px 12px", fontSize: 13, cursor: "pointer", color: "var(--muted)" }}
        >↻ Refresh</button>
      </div>

      {/* Count */}
      <div style={{ fontSize: 12, color: "var(--muted-2)", marginBottom: 12 }}>
        {loading ? "Loading…" : `${filtered.length} event${filtered.length !== 1 ? "s" : ""}${filter !== "all" ? ` · ${FILTERS.find(f => f.id === filter)?.label}` : ""}`}
      </div>

      {/* Event feed */}
      {loading ? (
        <div style={{ padding: 48, textAlign: "center", color: "var(--muted)" }}>Loading activity…</div>
      ) : filtered.length === 0 ? (
        <div style={{ textAlign: "center", padding: 64, color: "var(--muted)" }}>
          <div style={{ fontSize: 32, marginBottom: 12 }}>📋</div>
          <div style={{ fontWeight: 600 }}>No events yet</div>
          <div style={{ fontSize: 14, marginTop: 6 }}>Activity will appear here as tasks run, emails are sent, and crons fire.</div>
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 1 }}>
          {filtered.map((ev, i) => {
            const ss = statusStyle[ev.status] || statusStyle.info;
            const [typeBg, typeC] = typeColor[ev.type] || typeColor.system;
            const isLast = i === filtered.length - 1;
            return (
              <div key={ev.id} style={{
                display: "flex", gap: 14, padding: "12px 16px",
                background: "var(--panel)",
                border: "1px solid var(--line)",
                borderRadius: i === 0 ? "10px 10px 0 0" : isLast ? "0 0 10px 10px" : 0,
                borderTop: i > 0 ? "none" : undefined,
              }}>
                {/* Type icon */}
                <div style={{
                  width: 32, height: 32, borderRadius: 8,
                  background: typeBg, color: typeC,
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 14, flexShrink: 0, fontWeight: 700,
                }}>
                  {typeIcon[ev.type] || "·"}
                </div>

                {/* Content */}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 2, flexWrap: "wrap" }}>
                    <span style={{
                      background: typeBg, color: typeC,
                      borderRadius: 4, padding: "1px 6px", fontSize: 10, fontWeight: 700, textTransform: "uppercase",
                    }}>{typeLabel[ev.type]}</span>
                    <span style={{ fontWeight: 600, fontSize: 13 }}>{ev.title}</span>
                  </div>
                  {ev.detail && (
                    <div style={{ fontSize: 12, color: "var(--muted)", lineHeight: 1.4, wordBreak: "break-word" }}>{ev.detail}</div>
                  )}
                  <div style={{ fontSize: 11, color: "var(--muted-2)", marginTop: 4, display: "flex", gap: 12 }}>
                    {ev.actor && ev.actor !== "System" && <span>by {ev.actor}</span>}
                    <span>{fmt(ev.ts)}</span>
                  </div>
                </div>

                {/* Status badge */}
                <div style={{ flexShrink: 0, display: "flex", alignItems: "center" }}>
                  <span style={{
                    background: ss.bg, color: ss.color,
                    borderRadius: 6, padding: "3px 10px", fontSize: 11, fontWeight: 700,
                    display: "flex", alignItems: "center", gap: 4,
                  }}>
                    <span>{ss.icon}</span>
                    <span style={{ textTransform: "capitalize" }}>{ev.status}</span>
                  </span>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
