/**
 * Hydration provider for Zustand stores - COOP-CA AMIFOND
 *
 * Handles proper hydration of persisted stores on the client side
 * to prevent SSR hydration mismatches
 */

"use client";

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

import { useAuthStore } from "@/stores/auth/auth-store";

interface HydrationProviderProps {
  readonly children: ReactNode;
}

export function HydrationProvider({ children }: HydrationProviderProps) {
  const [isHydrated, setIsHydrated] = useState(false);

  useEffect(() => {
    // Manually rehydrate the auth store after component mount
    const unsubHydrate = useAuthStore.persist.onHydrate(() => {
      console.log("Hydrating auth store...");
    });

    const unsubFinishHydration = useAuthStore.persist.onFinishHydration((state) => {
      console.log("Auth store hydration completed", state);
      setIsHydrated(true);
    });

    // Trigger rehydration
    useAuthStore.persist.rehydrate();

    return () => {
      unsubHydrate();
      unsubFinishHydration();
    };
  }, []);

  // Show loading placeholder until hydration is complete
  if (!isHydrated) {
    return <div className="bg-background min-h-screen" />; // Loading placeholder
  }

  return <>{children}</>;
}
