"use client";

import { useRepo } from "@automerge/automerge-repo-react-hooks";
import { useEffect, useState, useCallback } from "react";

export default function ConnectionStatus() {
  const repo = useRepo();
  const [connected, setConnected] = useState(false);

  const updateStatus = useCallback(() => {
    setConnected(repo ? repo.peers.length > 0 : false);
  }, [repo]);

  useEffect(() => {
    updateStatus();

    const onChange = () => updateStatus();
    repo.networkSubsystem.on("peer", onChange);
    repo.networkSubsystem.on("peer-disconnected", onChange);

    return () => {
      repo.networkSubsystem.off("peer", onChange);
      repo.networkSubsystem.off("peer-disconnected", onChange);
    };
  }, [repo, updateStatus]);

  return (
    <div className="flex items-center gap-2 text-xs text-gray-500">
      <span
        className={`inline-block h-2 w-2 rounded-full ${
          connected ? "bg-green-500" : "bg-yellow-500"
        }`}
      />
      {connected ? "Connected" : "Connecting..."}
    </div>
  );
}
