// =================================================================
// screens-monitoring.jsx — Page Tracking (Firecrawl v2 monitors)
//
//   MonitoringScreen   /monitoring
//     Tab 1: Monitors  — create, list, pause/resume, manual run
//     Tab 2: Events    — change feed, filter by meaningful, reviewed
// =================================================================

const fmtDateM = (iso) => {
  if (!iso) return "—";
  try { return new Date(iso).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }); }
  catch { return "—"; }
};

const fmtTimeM = (iso) => {
  if (!iso) return "—";
  try {
    return new Date(iso).toLocaleString("en-US", {
      month: "short", day: "numeric", hour: "numeric", minute: "2-digit",
    });
  } catch { return "—"; }
};

const MONITOR_STATUS_COLORS = {
  active:  "var(--good)",
  paused:  "var(--warn)",
  deleted: "var(--muted)",
};

const CHANGE_STATUS_COLORS = {
  changed:  "var(--accent)",
  new:      "var(--good)",
  removed:  "var(--bad)",
  same:     "var(--muted)",
  error:    "var(--bad)",
};

const CHANGE_STATUS_LABELS = {
  changed: "Changed", new: "New page", removed: "Removed",
  same: "No change", error: "Error",
};

const WATCH_TARGET_LABELS = { client: "Client", competitor: "Competitor" };
const MONITOR_TYPE_LABELS  = { scrape: "Single page", crawl: "Full site" };

const MonitorStatusDot = ({ status }) => (
  <span style={{
    display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13,
    fontWeight: 500, color: MONITOR_STATUS_COLORS[status] || "var(--muted)",
  }}>
    <span style={{
      width: 7, height: 7, borderRadius: "50%",
      background: MONITOR_STATUS_COLORS[status] || "var(--muted)",
      flexShrink: 0,
    }}/>
    {status?.charAt(0).toUpperCase() + status?.slice(1)}
  </span>
);

const ChangeStatusBadge = ({ status }) => (
  <span style={{
    display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12,
    fontWeight: 600, color: CHANGE_STATUS_COLORS[status] || "var(--muted)",
    background: "transparent",
    border: `1px solid ${CHANGE_STATUS_COLORS[status] || "var(--line)"}`,
    borderRadius: 6, padding: "2px 7px",
  }}>
    {CHANGE_STATUS_LABELS[status] || status}
  </span>
);

const MeaningfulBadge = ({ is_meaningful }) => {
  if (is_meaningful === null || is_meaningful === undefined) return null;
  return is_meaningful
    ? <span style={{ fontSize: 11, fontWeight: 700, color: "var(--good)", background: "var(--good-soft)", borderRadius: 6, padding: "2px 7px" }}>✦ Meaningful</span>
    : <span style={{ fontSize: 11, color: "var(--muted)", background: "var(--hover)", borderRadius: 6, padding: "2px 7px" }}>Routine</span>;
};

// ---------- API helpers ----------

const monitoringApi = {
  listMonitors: () => api.tcall("listMonitors"),
  createMonitor: (body) => api.tcall("createMonitor", {}, body),
  updateMonitor: (id, body) => api.tcall("updateMonitor", { monitorId: id }, body),
  deleteMonitor: (id) => api.tcall("deleteMonitor", { monitorId: id }),
  runMonitor: (id) => api.tcall("runMonitor", { monitorId: id }),
  listEvents: (params) => api.tcall("listMonitorEvents", params),
  markEventReviewed: (id, reviewed) => api.tcall("markEventReviewed", { eventId: id }, { reviewed }),
};

// ---------- Create Monitor Modal ----------

const CreateMonitorModal = ({ onClose, onCreated, companies }) => {
  const [form, setForm] = React.useState({
    name: "", url: "", monitor_type: "scrape", schedule: "daily at 9am",
    change_mode: "markdown", watch_target: "client",
    goal: "", judge_enabled: true, company_id: "",
  });
  const [saving, setSaving] = React.useState(false);
  const [err, setErr] = React.useState("");

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = async () => {
    if (!form.name.trim() || !form.url.trim()) { setErr("Name and URL are required."); return; }
    setSaving(true); setErr("");
    try {
      const body = { ...form, company_id: form.company_id || null, goal: form.goal || null };
      const result = await monitoringApi.createMonitor(body);
      onCreated(result);
    } catch (e) {
      setErr(e.message || "Failed to create monitor.");
    } finally { setSaving(false); }
  };

  return (
    <div className="hx-modal-backdrop" onClick={onClose}>
      <div className="hx-modal" style={{ width: 520, maxWidth: "95vw" }} onClick={e => e.stopPropagation()}>
        <div className="hx-modal-header">
          <span style={{ fontWeight: 600, fontSize: 16 }}>New Page Monitor</span>
          <button className="hx-btn-ghost" onClick={onClose} style={{ padding: "4px 8px" }}>✕</button>
        </div>
        <div className="hx-modal-body" style={{ display: "flex", flexDirection: "column", gap: 14 }}>

          {err && <div style={{ color: "var(--bad)", fontSize: 13, padding: "8px 12px", background: "color-mix(in oklab, var(--bad) 8%, transparent)", borderRadius: 8 }}>{err}</div>}

          <label style={{ display: "flex", flexDirection: "column", gap: 5 }}>
            <span style={{ fontSize: 12.5, fontWeight: 500, color: "var(--muted)" }}>Monitor Name</span>
            <input className="hx-input" value={form.name} onChange={e => set("name", e.target.value)} placeholder="e.g. Rival Co Pricing Watch" />
          </label>

          <label style={{ display: "flex", flexDirection: "column", gap: 5 }}>
            <span style={{ fontSize: 12.5, fontWeight: 500, color: "var(--muted)" }}>URL to Watch</span>
            <input className="hx-input" value={form.url} onChange={e => set("url", e.target.value)} placeholder="https://competitor.com/pricing" />
          </label>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <label style={{ display: "flex", flexDirection: "column", gap: 5 }}>
              <span style={{ fontSize: 12.5, fontWeight: 500, color: "var(--muted)" }}>Type</span>
              <select className="hx-input" value={form.monitor_type} onChange={e => set("monitor_type", e.target.value)}>
                <option value="scrape">Single page</option>
                <option value="crawl">Full site crawl</option>
              </select>
            </label>
            <label style={{ display: "flex", flexDirection: "column", gap: 5 }}>
              <span style={{ fontSize: 12.5, fontWeight: 500, color: "var(--muted)" }}>Watch Target</span>
              <select className="hx-input" value={form.watch_target} onChange={e => set("watch_target", e.target.value)}>
                <option value="client">Client page</option>
                <option value="competitor">Competitor page</option>
              </select>
            </label>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <label style={{ display: "flex", flexDirection: "column", gap: 5 }}>
              <span style={{ fontSize: 12.5, fontWeight: 500, color: "var(--muted)" }}>Schedule</span>
              <input className="hx-input" value={form.schedule} onChange={e => set("schedule", e.target.value)} placeholder="daily at 9am" />
            </label>
            <label style={{ display: "flex", flexDirection: "column", gap: 5 }}>
              <span style={{ fontSize: 12.5, fontWeight: 500, color: "var(--muted)" }}>Change Mode</span>
              <select className="hx-input" value={form.change_mode} onChange={e => set("change_mode", e.target.value)}>
                <option value="markdown">Text diff (markdown)</option>
                <option value="json">Field-level (JSON)</option>
                <option value="mixed">Both</option>
              </select>
            </label>
          </div>

          {companies?.length > 0 && (
            <label style={{ display: "flex", flexDirection: "column", gap: 5 }}>
              <span style={{ fontSize: 12.5, fontWeight: 500, color: "var(--muted)" }}>Link to Company (optional)</span>
              <select className="hx-input" value={form.company_id} onChange={e => set("company_id", e.target.value)}>
                <option value="">— none —</option>
                {companies.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </label>
          )}

          <label style={{ display: "flex", flexDirection: "column", gap: 5 }}>
            <span style={{ fontSize: 12.5, fontWeight: 500, color: "var(--muted)" }}>Goal for AI Judging <span style={{ fontWeight: 400 }}>(optional)</span></span>
            <input className="hx-input" value={form.goal} onChange={e => set("goal", e.target.value)} placeholder="e.g. detect pricing changes or new product features" />
          </label>

          <label style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer" }}>
            <input type="checkbox" checked={form.judge_enabled} onChange={e => set("judge_enabled", e.target.checked)} style={{ width: 16, height: 16, accentColor: "var(--accent)" }}/>
            <span style={{ fontSize: 13 }}>Enable AI meaningful-change judging</span>
          </label>
        </div>
        <div className="hx-modal-footer">
          <button className="hx-btn" onClick={onClose} disabled={saving}>Cancel</button>
          <button className="hx-btn hx-btn-primary" onClick={submit} disabled={saving}>
            {saving ? "Creating…" : "Create Monitor"}
          </button>
        </div>
      </div>
    </div>
  );
};

// ---------- Monitors Tab ----------

const MonitorsTab = ({ companies }) => {
  const [monitors, setMonitors] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [showCreate, setShowCreate] = React.useState(false);
  const [actionId, setActionId] = React.useState(null);
  const [toast, setToast] = React.useState("");

  const showToast = (msg) => { setToast(msg); setTimeout(() => setToast(""), 3000); };

  const load = React.useCallback(async () => {
    setLoading(true);
    try {
      const data = await monitoringApi.listMonitors();
      setMonitors(Array.isArray(data) ? data : data?.items || []);
    } catch {
      setMonitors([]);
    } finally { setLoading(false); }
  }, []);

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

  const togglePause = async (m) => {
    setActionId(m.id);
    const newStatus = m.status === "active" ? "paused" : "active";
    try {
      await monitoringApi.updateMonitor(m.id, { status: newStatus });
      setMonitors(ms => ms.map(x => x.id === m.id ? { ...x, status: newStatus } : x));
      showToast(`Monitor ${newStatus === "paused" ? "paused" : "resumed"}.`);
    } catch (e) {
      showToast("Failed: " + (e.message || "unknown error"));
    } finally { setActionId(null); }
  };

  const runNow = async (m) => {
    setActionId(m.id);
    try {
      await monitoringApi.runMonitor(m.id);
      showToast("Manual check triggered.");
    } catch (e) {
      showToast("Run failed: " + (e.message || "unknown error"));
    } finally { setActionId(null); }
  };

  const deleteMonitor = async (m) => {
    if (!confirm(`Delete monitor "${m.name}"?`)) return;
    setActionId(m.id);
    try {
      await monitoringApi.deleteMonitor(m.id);
      setMonitors(ms => ms.filter(x => x.id !== m.id));
      showToast("Monitor deleted.");
    } catch (e) {
      showToast("Delete failed: " + (e.message || "unknown error"));
    } finally { setActionId(null); }
  };

  return (
    <div>
      {toast && (
        <div style={{ position: "fixed", bottom: 24, right: 24, background: "var(--ink)", color: "#fff", padding: "10px 18px", borderRadius: 10, fontSize: 13.5, zIndex: 9999, boxShadow: "var(--shadow-modal)" }}>
          {toast}
        </div>
      )}

      <div style={{ display: "flex", justifyContent: "flex-end", marginBottom: 16 }}>
        <button className="hx-btn hx-btn-primary" onClick={() => setShowCreate(true)}>
          + New Monitor
        </button>
      </div>

      {loading ? (
        <div style={{ padding: 48, textAlign: "center", color: "var(--muted)", fontSize: 14 }}>Loading monitors…</div>
      ) : monitors?.length === 0 ? (
        <div style={{ padding: "48px 24px", textAlign: "center", color: "var(--muted)" }}>
          <div style={{ fontSize: 32, marginBottom: 12 }}>📡</div>
          <div style={{ fontSize: 15, fontWeight: 600, color: "var(--ink)", marginBottom: 6 }}>No monitors yet</div>
          <div style={{ fontSize: 13.5 }}>Create your first monitor to track competitor or client page changes.</div>
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {monitors.map(m => {
            const busy = actionId === m.id;
            const company = companies?.find(c => c.id === m.company_id);
            return (
              <div key={m.id} style={{
                background: "var(--panel)", border: "1px solid var(--line)", borderRadius: 12,
                padding: "16px 20px", display: "flex", alignItems: "center", gap: 16,
              }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                    <span style={{ fontWeight: 600, fontSize: 14, color: "var(--ink)" }}>{m.name}</span>
                    <span style={{
                      fontSize: 11, fontWeight: 600, padding: "2px 7px", borderRadius: 6,
                      background: m.watch_target === "competitor" ? "color-mix(in oklab, var(--accent) 12%, transparent)" : "var(--good-soft)",
                      color: m.watch_target === "competitor" ? "var(--accent)" : "var(--good)",
                    }}>
                      {WATCH_TARGET_LABELS[m.watch_target] || m.watch_target}
                    </span>
                    <span style={{ fontSize: 11, color: "var(--muted)", background: "var(--hover)", padding: "2px 7px", borderRadius: 6 }}>
                      {MONITOR_TYPE_LABELS[m.monitor_type] || m.monitor_type}
                    </span>
                    <MonitorStatusDot status={m.status} />
                  </div>
                  <div style={{ fontSize: 12.5, color: "var(--muted)", marginTop: 4, display: "flex", gap: 16, flexWrap: "wrap" }}>
                    <span style={{ fontFamily: "var(--mono)", color: "var(--ink-2)" }}>{m.url}</span>
                    <span>⏱ {m.schedule}</span>
                    {company && <span>🏢 {company.name}</span>}
                    {m.last_check_at && <span>Last check: {fmtTimeM(m.last_check_at)}</span>}
                    {m.next_run_at && <span>Next: {fmtTimeM(m.next_run_at)}</span>}
                  </div>
                  {m.goal && (
                    <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 4, fontStyle: "italic" }}>
                      Goal: {m.goal}
                    </div>
                  )}
                </div>
                <div style={{ display: "flex", gap: 8, flexShrink: 0 }}>
                  <button
                    className="hx-btn"
                    style={{ fontSize: 12.5 }}
                    onClick={() => runNow(m)}
                    disabled={busy || m.status === "paused"}
                    title="Trigger immediate check"
                  >
                    {busy ? "…" : "Run now"}
                  </button>
                  <button
                    className="hx-btn"
                    style={{ fontSize: 12.5 }}
                    onClick={() => togglePause(m)}
                    disabled={busy}
                  >
                    {m.status === "active" ? "Pause" : "Resume"}
                  </button>
                  <button
                    className="hx-btn"
                    style={{ fontSize: 12.5, color: "var(--bad)" }}
                    onClick={() => deleteMonitor(m)}
                    disabled={busy}
                  >
                    Delete
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {showCreate && (
        <CreateMonitorModal
          companies={companies}
          onClose={() => setShowCreate(false)}
          onCreated={(m) => { setMonitors(ms => [m, ...(ms || [])]);  setShowCreate(false); showToast("Monitor created!"); }}
        />
      )}
    </div>
  );
};

// ---------- Events Tab ----------

const EventsTab = () => {
  const [events, setEvents] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [filter, setFilter] = React.useState("all"); // all | meaningful | unreviewed
  const [expanded, setExpanded] = React.useState(null);

  const load = React.useCallback(async () => {
    setLoading(true);
    try {
      const params = {};
      if (filter === "meaningful") params.is_meaningful = true;
      if (filter === "unreviewed") params.reviewed = false;
      const data = await monitoringApi.listEvents(params);
      setEvents(Array.isArray(data) ? data : data?.items || []);
    } catch {
      setEvents([]);
    } finally { setLoading(false); }
  }, [filter]);

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

  const markReviewed = async (e) => {
    try {
      await monitoringApi.markEventReviewed(e.id, true);
      setEvents(evs => evs.map(x => x.id === e.id ? { ...x, reviewed: true } : x));
    } catch {}
  };

  const toggleExpand = (id) => setExpanded(x => x === id ? null : id);

  return (
    <div>
      <div style={{ display: "flex", gap: 8, marginBottom: 16, alignItems: "center" }}>
        <span style={{ fontSize: 13, color: "var(--muted)", marginRight: 4 }}>Show:</span>
        {[
          { key: "all", label: "All events" },
          { key: "meaningful", label: "✦ Meaningful only" },
          { key: "unreviewed", label: "Unreviewed" },
        ].map(opt => (
          <button
            key={opt.key}
            onClick={() => setFilter(opt.key)}
            style={{
              fontSize: 13, padding: "5px 12px", borderRadius: 8, border: "1px solid",
              borderColor: filter === opt.key ? "var(--accent)" : "var(--line)",
              background: filter === opt.key ? "var(--accent-soft)" : "var(--panel)",
              color: filter === opt.key ? "var(--accent)" : "var(--ink-2)",
              fontWeight: filter === opt.key ? 600 : 400, cursor: "pointer",
            }}
          >{opt.label}</button>
        ))}
        <button className="hx-btn" style={{ marginLeft: "auto", fontSize: 12.5 }} onClick={load}>↻ Refresh</button>
      </div>

      {loading ? (
        <div style={{ padding: 48, textAlign: "center", color: "var(--muted)", fontSize: 14 }}>Loading events…</div>
      ) : events?.length === 0 ? (
        <div style={{ padding: "48px 24px", textAlign: "center", color: "var(--muted)" }}>
          <div style={{ fontSize: 32, marginBottom: 12 }}>🔔</div>
          <div style={{ fontSize: 15, fontWeight: 600, color: "var(--ink)", marginBottom: 6 }}>No events yet</div>
          <div style={{ fontSize: 13.5 }}>Events appear here when Firecrawl detects page changes.</div>
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {events.map(ev => {
            const isOpen = expanded === ev.id;
            const isCheckComplete = ev.event_type === "check_completed";
            return (
              <div key={ev.id} style={{
                background: ev.is_meaningful ? "color-mix(in oklab, var(--accent) 4%, var(--panel))" : "var(--panel)",
                border: `1px solid ${ev.is_meaningful ? "color-mix(in oklab, var(--accent) 18%, var(--line))" : "var(--line)"}`,
                borderRadius: 10, overflow: "hidden",
              }}>
                <div
                  style={{ padding: "12px 16px", display: "flex", alignItems: "center", gap: 12, cursor: ev.diff_summary || ev.judgment ? "pointer" : "default" }}
                  onClick={() => (ev.diff_summary || ev.judgment) && toggleExpand(ev.id)}
                >
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                      {!isCheckComplete && <ChangeStatusBadge status={ev.change_status} />}
                      {isCheckComplete && <span style={{ fontSize: 12, fontWeight: 600, color: "var(--muted)", border: "1px solid var(--line)", borderRadius: 6, padding: "2px 7px" }}>Check complete</span>}
                      <MeaningfulBadge is_meaningful={ev.is_meaningful} />
                      {ev.reviewed && <span style={{ fontSize: 11, color: "var(--muted)" }}>✓ Reviewed</span>}
                    </div>
                    <div style={{ fontSize: 12.5, color: "var(--muted)", marginTop: 4, display: "flex", gap: 12, flexWrap: "wrap" }}>
                      {ev.page_url && <span style={{ fontFamily: "var(--mono)", color: "var(--ink-2)", fontSize: 12 }}>{ev.page_url}</span>}
                      <span>{fmtTimeM(ev.created_at)}</span>
                      {ev.judgment?.reason && <span style={{ fontStyle: "italic" }}>{ev.judgment.reason}</span>}
                    </div>
                  </div>
                  <div style={{ display: "flex", gap: 8, flexShrink: 0, alignItems: "center" }}>
                    {(ev.diff_summary || ev.judgment) && (
                      <span style={{ fontSize: 11, color: "var(--muted)" }}>{isOpen ? "▲" : "▼"}</span>
                    )}
                    {!ev.reviewed && !isCheckComplete && (
                      <button className="hx-btn" style={{ fontSize: 12, padding: "4px 10px" }} onClick={(e) => { e.stopPropagation(); markReviewed(ev); }}>
                        Mark reviewed
                      </button>
                    )}
                  </div>
                </div>

                {isOpen && (
                  <div style={{ padding: "0 16px 14px", borderTop: "1px solid var(--line-2)" }}>
                    {ev.diff_summary && (
                      <div style={{ marginTop: 12 }}>
                        <div style={{ fontSize: 12, fontWeight: 600, color: "var(--muted)", marginBottom: 6 }}>DIFF</div>
                        <pre style={{
                          fontSize: 12, fontFamily: "var(--mono)", background: "var(--panel-2)",
                          border: "1px solid var(--line)", borderRadius: 8, padding: "10px 14px",
                          margin: 0, overflowX: "auto", whiteSpace: "pre-wrap", lineHeight: 1.6,
                          color: "var(--ink-2)", maxHeight: 320, overflowY: "auto",
                        }}>{ev.diff_summary}</pre>
                      </div>
                    )}
                    {ev.judgment && (
                      <div style={{ marginTop: 12, display: "flex", gap: 20, flexWrap: "wrap" }}>
                        <div style={{ fontSize: 12 }}>
                          <span style={{ color: "var(--muted)", fontWeight: 600 }}>CONFIDENCE </span>
                          <span style={{ fontWeight: 600, fontFamily: "var(--mono)" }}>
                            {ev.judgment.confidence != null ? Math.round(ev.judgment.confidence * 100) + "%" : "—"}
                          </span>
                        </div>
                        {ev.judgment.reason && (
                          <div style={{ fontSize: 12 }}>
                            <span style={{ color: "var(--muted)", fontWeight: 600 }}>REASON </span>
                            <span>{ev.judgment.reason}</span>
                          </div>
                        )}
                        {ev.judgment.meaningfulChanges?.length > 0 && (
                          <div style={{ fontSize: 12 }}>
                            <span style={{ color: "var(--muted)", fontWeight: 600 }}>CHANGES </span>
                            <span>{ev.judgment.meaningfulChanges.join(", ")}</span>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

// ---------- Main Screen ----------

const MonitoringScreen = () => {
  const [tab, setTab] = React.useState("monitors");
  const [companies, setCompanies] = React.useState([]);

  React.useEffect(() => {
    api.tcall("listCompanies").then(data => {
      setCompanies(Array.isArray(data) ? data : data?.items || []);
    }).catch(() => {});
  }, []);

  const tabs = [
    { id: "monitors", label: "Monitors" },
    { id: "events",   label: "Change Feed" },
  ];

  return (
    <div style={{ padding: "var(--pad)", maxWidth: 1100, margin: "0 auto" }}>
      <ScreenHeader
        icon={<span style={{ fontSize: 22 }}>📡</span>}
        title="Page Monitoring"
        subtitle="Track client and competitor pages for meaningful changes — pricing, product updates, press releases."
      />

      <div style={{ display: "flex", gap: 4, margin: "24px 0 20px", borderBottom: "1px solid var(--line)", paddingBottom: 1 }}>
        {tabs.map(t => (
          <button
            key={t.id}
            onClick={() => setTab(t.id)}
            style={{
              fontSize: 13.5, fontWeight: tab === t.id ? 600 : 400,
              color: tab === t.id ? "var(--accent)" : "var(--muted)",
              background: "none", border: "none", padding: "8px 16px",
              borderBottom: `2px solid ${tab === t.id ? "var(--accent)" : "transparent"}`,
              cursor: "pointer", marginBottom: -1,
            }}
          >
            {t.label}
          </button>
        ))}
      </div>

      {tab === "monitors" && <MonitorsTab companies={companies} />}
      {tab === "events"   && <EventsTab />}
    </div>
  );
};
