"use client";
import React, { useState, useEffect } from "react";
import "./knowledge.css";
import { fetchAllSignals, Signal, formatRelativeTime } from "../lib/api";

export default function FloatingControls() {
  const [activeView, setActiveView] = useState("Graph View");
  const [recentSignals, setRecentSignals] = useState<Signal[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function load() {
      try {
        const all = await fetchAllSignals();
        const flat = all
          .flatMap((g) => g.signals)
          .sort(
            (a, b) =>
              new Date(b.metadata.timestamp).getTime() -
              new Date(a.metadata.timestamp).getTime()
          )
          .slice(0, 6); // enough for seamless looping
        setRecentSignals(flat);
      } catch {
        // ignore
      } finally {
        setLoading(false);
      }
    }
    load();
  }, []);

  const handleAction = (action: string) => {
    // visual feedback only
    console.log(`Graph action: ${action}`);
  };

  // Format a signal into a short log line
  function signalToLogLine(sig: Signal): string {
    const type = sig.metadata.type.toUpperCase().replace(/_/g, "_");
    const groupShort = sig.metadata.group_id.split("-").slice(-1)[0]?.toUpperCase() || "?";
    const time = formatRelativeTime(sig.metadata.timestamp);
    return `[${time}] ${type} · ${groupShort}`;
  }

  // Fallback static lines when no data
  const fallbackLines = [
    "[waiting] NODE_ATTACH",
    "[waiting] EDGE_UPDATE",
    "[waiting] SIGNAL_LOCKED",
  ];

  const logLines =
    recentSignals.length > 0
      ? recentSignals.map(signalToLogLine)
      : fallbackLines;

  // Duplicate for seamless scroll
  const displayLines = [...logLines, ...logLines];

  return (
    <div className="absolute bottom-4 left-4 flex items-end gap-4 z-40 animate-fade-in-up delay-100">
      {/* View Toggle & Graph Controls */}
      

      <style dangerouslySetInnerHTML={{
        __html: `
          @keyframes scroll-up {
            0% { transform: translateY(0); }
            100% { transform: translateY(-50%); }
          }
        `,
      }} />
    </div>
  );
}
