"use client";

import React, { useEffect, useState } from "react";
import "./knowledge.css";
import { fetchGroups, fetchAllSignals, Group } from "../lib/api";

export default function SystemTickerKnowledge() {
  const [groups, setGroups] = useState<Group[]>([]);
  const [totalSignals, setTotalSignals] = useState(0);
  const [healthy, setHealthy] = useState(true);
  const [latency, setLatency] = useState<number | null>(null);

  useEffect(() => {
    async function load() {
      const t0 = Date.now();
      try {
        const [grps, all] = await Promise.all([fetchGroups(), fetchAllSignals()]);
        setGroups(grps);
        setTotalSignals(all.flatMap((g) => g.signals).length);
        setHealthy(true);
      } catch {
        setHealthy(false);
      }
      setLatency(Date.now() - t0);
    }
    load();
  }, []);

  const logLine =
    groups.length > 0
      ? `LOG_STREAM: GROUPS_ACTIVE=${groups.length} // SIGNALS_INDEXED=${totalSignals} // ` +
        groups.map((g) => `[${g.group_name.toUpperCase()}] LENS=${g.lens?.toUpperCase() || "?"} SIGNALS=${g.signal_count}`).join(" // ") +
        " // GRAPH_ENGINE=ONLINE // VECTOR_DB=CONNECTED"
      : "LOG_STREAM: Waiting for group connections... Connect Telegram groups to populate the knowledge graph.";

  return (
    <footer className="fixed bottom-0 left-[240px] right-0 h-8 bg-zinc-950/80 backdrop-blur-md border-t border-violet-500/10 flex items-center px-4 z-50">
      <div className="flex items-center gap-4 w-full">
        <div className="flex items-center gap-2">
          <span className="text-[9px] font-mono-data text-violet-500 font-bold whitespace-nowrap">
            SYSTEM_STATUS:
          </span>
          <span
            className="text-[9px] font-mono-data whitespace-nowrap"
            style={{ color: healthy ? "#10b981" : "#ff6f78" }}
          >
            {healthy ? "OPERATIONAL" : "DEGRADED"}
          </span>
        </div>
        <div className="h-3 w-[1px] bg-zinc-800" />
        <div className="flex-1 overflow-hidden">
          <div className="text-[9px] font-mono-data text-zinc-500 whitespace-nowrap animate-marquee">
            {logLine}
          </div>
        </div>
        <div className="h-3 w-[1px] bg-zinc-800" />
        <div className="flex items-center gap-2">
          <span className="text-[9px] font-mono-data text-zinc-500 whitespace-nowrap">NODES:</span>
          <span className="text-[9px] font-mono-data text-violet-400 whitespace-nowrap">
            {groups.length + 1}
          </span>
        </div>
        <div className="h-3 w-[1px] bg-zinc-800" />
        <div className="flex items-center gap-2">
          <span className="text-[9px] font-mono-data text-zinc-500 whitespace-nowrap">LATENCY:</span>
          <span className="text-[9px] font-mono-data text-violet-400 whitespace-nowrap">
            {latency !== null ? `${latency}ms` : "—"}
          </span>
        </div>
      </div>
    </footer>
  );
}
