import { useEffect, useMemo, useState } from 'react';
import { useAppStore } from '../../store';
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
  );
}

function getLivePageFocusState() {
  if (typeof document === 'undefined' || typeof document.hasFocus !== 'function') {
    return 'focused' as const;
  }

  return document.hasFocus() ? ('focused' as const) : ('blurred' as const);
}

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

  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',
      pageFocusState: getLivePageFocusState(),
      chatTypeId: null,
      chatTypeLabel: '',
      chatTypeDescription: '',
    }),
    [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;
}
