'use client';

import { memo, useEffect, useLayoutEffect } from 'react';
import { createStoreUpdater } from 'zustand-utils';

import { useFetchThreads } from '@/hooks/useFetchThreads';
import { useQueryState } from '@/hooks/useQueryParam';
import { useChatStore } from '@/store/chat';
import { PortalViewType } from '@/store/chat/slices/portal/initialState';

// sync outside state to useChatStore
const ThreadHydration = memo(() => {
  const useStoreUpdater = createStoreUpdater(useChatStore);

  // two-way bindings the topic params to chat store
  const [portalThread, setThread] = useQueryState('portalThread');
  useStoreUpdater('portalThreadId', portalThread!);

  useLayoutEffect(() => {
    const unsubscribe = useChatStore.subscribe(
      (s) => s.portalThreadId,
      (state) => {
        setThread(!state ? null : state);
      },
    );

    return () => {
      unsubscribe();
    };
  }, [setThread]); // ✅ Now setValue is stable, can be safely added to the dependency array

  // should open portal automatically when portalThread is set
  useEffect(() => {
    if (!!portalThread && !useChatStore.getState().showPortal) {
      useChatStore
        .getState()
        .pushPortalView({ threadId: portalThread, type: PortalViewType.Thread });
    }
  }, [portalThread]);

  const activeTopicId = useChatStore((s) => s.activeTopicId);

  useFetchThreads(activeTopicId);

  return null;
});

export default ThreadHydration;
