"use client";

import { type ReactNode, useState, useEffect } from "react";
import { RepoContext } from "@automerge/automerge-repo-react-hooks";
import type { Repo } from "@automerge/automerge-repo";

export default function Providers({ children }: { children: ReactNode }) {
  const [repo, setRepo] = useState<Repo | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cleanup: (() => void) | undefined;
    let handleBeforeUnload: (() => void) | undefined;

    import("../lib/repo.js").then(({ getRepo, cleanupRepo }) => {
      const r = getRepo();
      setRepo(r);
      cleanup = cleanupRepo;

      handleBeforeUnload = () => {
        r.networkSubsystem.adapters.forEach((adapter) => adapter.disconnect());
      };
      window.addEventListener("beforeunload", handleBeforeUnload);
    }).catch(() => {
      setError("Failed to initialize. Please refresh the page.");
    });

    return () => {
      if (handleBeforeUnload) {
        window.removeEventListener("beforeunload", handleBeforeUnload);
      }
      cleanup?.();
    };
  }, []);

  if (error) {
    return <div className="flex min-h-screen items-center justify-center text-red-500">{error}</div>;
  }

  if (!repo) {
    return <div className="flex min-h-screen items-center justify-center text-gray-400">Loading...</div>;
  }

  return <RepoContext.Provider value={repo}>{children}</RepoContext.Provider>;
}
