"use client";

import { useEffect, useState } from "react";

export default function StreamDebugger() {
  const [logs, setLogs] = useState<string[]>([]);

  const log = (msg: string) => {
    setLogs((prev) => [...prev, msg]);
  };

  useEffect(() => {
    const url = "http://192.168.1.135:3000/api/orders/stream";
    log(`Opening EventSource to ${url}`);

    // Use fetch once to peek at headers
    fetch(url, { method: "GET" })
      .then((res) => {
        log("=== Response headers ===");
        res.headers.forEach((val, key) => log(`${key}: ${val}`));
      })
      .catch((err) => log(`Failed to fetch headers: ${err}`));

    const es = new EventSource(url);

    es.onopen = () => {
      log("✅ SSE connection opened");
    };

    es.onmessage = (e) => {
      log(`📩 message: ${e.data}`);
    };

    es.onerror = (err) => {
      log(`❌ SSE error: ${JSON.stringify(err)}`);
      es.close();
    };

    // Catch all custom events (in case server sends named events)
    es.addEventListener("ping", (e) => {
      log(`📡 ping event: ${(e as MessageEvent).data}`);
    });

    return () => {
      log("Closing SSE connection…");
      es.close();
    };
  }, []);

  return (
    <div className="p-4 bg-black text-green-400 font-mono text-xs space-y-1 max-h-[80vh] overflow-y-auto">
      {logs.map((m, i) => (
        <div key={i}>{m}</div>
      ))}
    </div>
  );
}
