"use client";

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

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

function formatNameFromSlug(slug: string) {
  return slug
    .split("-")
    .filter(Boolean)
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
    .join(" ");
}

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

  useEffect(() => {
    setWorkspace({
      id: workspaceSlug,
      slug: workspaceSlug,
      name: formatNameFromSlug(workspaceSlug),
    });
    return () => setWorkspace(null);
  }, [workspaceSlug, setWorkspace]);

  return <>{children}</>;
}
