"use client";

import { useEffect, useState } from "react";
import { io } from "socket.io-client";
import type { Dictionary, Locale } from "@/lib/i18n";

export function StatusClient({
  locale,
  labels,
  accessToken,
}: {
  locale: Locale;
  labels: Dictionary["status"];
  accessToken: string;
}) {
  const [api, setApi] = useState<string>(labels.checking);
  const [realtime, setRealtime] = useState<string>(labels.connecting);

  useEffect(() => {
    fetch(
      `${process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:3001/api/v1"}/health/live`,
      { headers: { "Accept-Language": locale } },
    )
      .then((response) => setApi(response.ok ? labels.active : labels.error))
      .catch(() => setApi(labels.unavailable));
    const socket = io(
      process.env.NEXT_PUBLIC_REALTIME_URL ?? "http://localhost:3002",
      {
        auth: { token: accessToken, locale },
        extraHeaders: { "Accept-Language": locale },
        reconnection: true,
      },
    );
    socket.on("connection.ready", () => setRealtime(labels.connected));
    socket.on("disconnect", () => setRealtime(labels.disconnected));
    socket.on("connect_error", () => setRealtime(labels.unavailable));
    return () => {
      socket.disconnect();
    };
  }, [accessToken, labels, locale]);

  return (
    <section className="stat-grid">
      <article>
        <div className="service-status-row">
          <span className="service-dot" />
          <span>{labels.api}</span>
        </div>
        <strong>{api}</strong>
        <small>/health/live</small>
      </article>
      <article>
        <div className="service-status-row">
          <span className="service-dot" />
          <span>{labels.realtime}</span>
        </div>
        <strong>{realtime}</strong>
        <small>Socket.IO</small>
      </article>
    </section>
  );
}
