"use client";

import type { ReactNode } from "react";
import { useEffect } from "react";

import { useWorkspaceStore } from "@/lib/stores/workspace-store";
import { api } from "@/lib/trpc";

export function WorkspaceSync({
  workspaceSlug,
  children,
}: {
  workspaceSlug: string;
  children: ReactNode;
}) {
  const setWorkspace = useWorkspaceStore((s) => s.setWorkspace);

  const { data } = api.workspaces.getById.useQuery({ id: workspaceSlug });

  useEffect(() => {
    if (data) {
      setWorkspace({
        id: data.id,
        slug: data.id,
        name: data.title,
      });
    }
    return () => setWorkspace(null);
  }, [workspaceSlug, data, setWorkspace]);

  return <>{children}</>;
}
