import { useEffect, useRef, useState } from 'react';
import { useClient } from 'hooks/useClient';
import { ChevronLeft } from 'lucide-react';

const MAX_LINES = 1200;

// Generic live log viewer: SSE-tails `${streamUrl}&token=…` (server sends one `data:` frame per line),
// on a solid-black terminal-style pane. Used for both pm2 and docker logs.
export const LogStream = ({ streamUrl, title, backLabel, onBack }: { streamUrl: string; title: string; backLabel: string; onBack: () => void }) => {
  const { token } = useClient();
  const [lines, setLines] = useState<string[]>([]);
  const scrollRef = useRef<HTMLPreElement | null>(null);

  useEffect(() => {
    setLines([]);
    const es = new EventSource(`${streamUrl}&token=${encodeURIComponent(token ?? '')}`);
    es.onmessage = (ev) => setLines((prev) => [...prev.slice(-(MAX_LINES - 1)), ev.data]);
    return () => es.close();
  }, [streamUrl, token]);

  useEffect(() => {
    scrollRef.current?.scrollTo(0, scrollRef.current.scrollHeight);
  }, [lines]);

  return (
    <div className="flex h-full w-full flex-col">
      <div className="flex shrink-0 items-center gap-2 border-b border-border p-3">
        <button type="button" onClick={onBack} className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground">
          <ChevronLeft size={16} /> {backLabel}
        </button>
        <span className="truncate font-mono text-sm text-foreground">{title}</span>
        <span className="ml-auto inline-flex h-2 w-2 animate-pulse rounded-full bg-emerald-500" title="live" />
      </div>
      <pre ref={scrollRef} className="m-0 min-h-0 flex-1 overflow-auto whitespace-pre-wrap break-words bg-black p-3 font-mono text-xs text-neutral-200">
        {lines.length === 0 ? <span className="text-neutral-500">connecting…</span> : lines.join('\n')}
      </pre>
    </div>
  );
};
