'use client';

import {useCallback} from 'react';
import {useRouter} from 'next/navigation';
import {useSession} from '@/features/auth/providers/SessionProvider';
import type {AccountLeaf} from './account-menu';
import {useAccountMenu} from './AccountMenuProvider';

/**
 * What a leaf row actually does, in one place.
 *
 * The popover and the mobile sheet are two containers around the same rows, so
 * "close, then resolve" is written once here rather than twice. Closing first
 * is deliberate in every branch: a menu left floating over the page it just
 * opened is the thing this menu exists to stop doing.
 *
 * External rows never reach this — they stay real anchors so middle-click and
 * "open in new tab" behave. See LeafRow in AccountPanels.
 */
export function useAccountActions(close: () => void) {
  const router = useRouter();
  const {logout} = useSession();
  const {openDialog} = useAccountMenu();

  return useCallback(
    (leaf: AccountLeaf) => {
      close();

      if (leaf.action === 'signOut') {
        // Ending the session is a server round trip (the cookie is httpOnly,
        // so only the server can revoke it) and the redirect happens inside
        // logout() once it has. Awaiting is deliberately skipped: the menu has
        // already closed, and logout resolves even when the request fails.
        void logout();
        return;
      }

      if (leaf.action === 'shortcuts' || leaf.action === 'about') {
        openDialog(leaf.action);
        return;
      }

      if (leaf.href) {
        router.push(leaf.href);
      }
    },
    [close, logout, openDialog, router],
  );
}
