/**
 * System tray event hook for desktop wallet.
 *
 * Handles events triggered from the system tray menu.
 */

import { useEffect } from 'react';
import { listen } from '@tauri-apps/api/event';
import { useNavigate } from 'react-router-dom';
import { useWalletStore } from '../store/wallet';

export function useTrayEvents() {
  const navigate = useNavigate();
  const { lockWallet, isUnlocked } = useWalletStore();

  useEffect(() => {
    const unlisteners: (() => void)[] = [];

    // Handle wallet lock from tray
    listen('wallet-lock', async () => {
      if (isUnlocked) {
        await lockWallet();
        navigate('/unlock');
      }
    }).then((unlisten) => unlisteners.push(unlisten));

    // Handle app quit from tray
    listen('app-quit', async () => {
      // Perform cleanup if wallet is unlocked
      if (isUnlocked) {
        await lockWallet();
      }
      // The backend will handle the actual quit
    }).then((unlisten) => unlisteners.push(unlisten));

    return () => {
      unlisteners.forEach((unlisten) => unlisten());
    };
  }, [isUnlocked, lockWallet, navigate]);
}
