import { useEffect } from 'react';
import { useNodeStore } from '../store/node';

/**
 * Hook to setup and cleanup node event listeners
 * Should be called once at the app level
 */
export function useNodeEvents() {
  const setupEventListeners = useNodeStore((state) => state.setupEventListeners);
  const cleanupEventListeners = useNodeStore(
    (state) => state.cleanupEventListeners
  );

  useEffect(() => {
    setupEventListeners();
    return () => cleanupEventListeners();
  }, [setupEventListeners, cleanupEventListeners]);
}

/**
 * Hook to auto-connect to the last used node on startup
 */
export function useAutoConnect() {
  const preferredMode = useNodeStore((state) => state.preferredMode);
  const lastExternalUrl = useNodeStore((state) => state.lastExternalUrl);
  const lastNetwork = useNodeStore((state) => state.lastNetwork);
  const status = useNodeStore((state) => state.status);
  const connectExternal = useNodeStore((state) => state.connectExternal);
  const startEmbeddedNode = useNodeStore((state) => state.startEmbeddedNode);

  useEffect(() => {
    // Only auto-connect if not already connected
    if (status.isConnected) return;

    const autoConnect = async () => {
      try {
        if (preferredMode === 'external' && lastExternalUrl) {
          await connectExternal(lastExternalUrl);
        } else if (preferredMode === 'embedded' && lastNetwork) {
          await startEmbeddedNode({ network: lastNetwork });
        }
      } catch (error) {
        // Silently fail auto-connect - user can manually connect
        console.debug('Auto-connect failed:', error);
      }
    };

    // Delay auto-connect to allow app to fully initialize
    const timeout = setTimeout(autoConnect, 1000);
    return () => clearTimeout(timeout);
  }, [
    preferredMode,
    lastExternalUrl,
    lastNetwork,
    status.isConnected,
    connectExternal,
    startEmbeddedNode,
  ]);
}
