import { useEffect, useMemo, useState } from 'react';
import { useAppStore } from '../../store';
import { getChatClientSessionId } from './mainChatPanel';
import { chatConnectionGateway, chatGateway } from './chatV2';
import type { ChatMessage, ChatViewContext } from './mainChatPanel/types';

function isStandaloneDisplayMode() {
  if (typeof window === 'undefined') {
    return false;
  }

  return (
    window.matchMedia?.('(display-mode: standalone)').matches === true ||
    (window.navigator as Navigator & { standalone?: boolean }).standalone === true
  );
}

export function ChatRuntimeBridgeV2() {
  const { currentPage, focusedComponentId } = useAppStore();
  const [sessionId] = useState(() => getChatClientSessionId());
  const [, setMessages] = useState<ChatMessage[]>([]);

  const currentContext: ChatViewContext = useMemo(
    () => ({
      pageId: currentPage.id,
      pageTitle: currentPage.title,
      topMenu: currentPage.topMenu,
      focusedComponentId,
      pageUrl: typeof window !== 'undefined' ? window.location.href : '',
      isStandaloneMode: isStandaloneDisplayMode(),
      pageVisibilityState:
        typeof document !== 'undefined' && document.visibilityState === 'hidden' ? 'hidden' : 'visible',
      chatTypeId: null,
      chatTypeLabel: '',
      chatTypeDescription: '',
      chatTypeIsTemplate: false,
    }),
    [currentPage, focusedComponentId],
  );

  useEffect(() => {
    let cancelled = false;

    void chatGateway.fetchRuntimeSnapshot()
      .then((snapshot) => {
        if (!cancelled) {
          chatConnectionGateway.setSharedRuntimeSnapshot(snapshot);
        }
      })
      .catch(() => undefined);

    return () => {
      cancelled = true;
    };
  }, []);

  chatConnectionGateway.useConnection({
    sessionId,
    currentContext,
    setMessages,
  });

  return null;
}
