'use client';

import { TooltipProvider } from '@radix-ui/react-tooltip';
import { usePathname, useRouter } from 'next/navigation';
import { useEffect } from 'react';
import { LoginModal } from '@/components/auth/LoginModal';
import { ToastHost } from '@/components/feedback/ToastHost';
import { ErrorBoundary } from '@/components/providers/ErrorBoundary';
import { registerAuthEvents } from '@/lib/notify/auth-events';
import { subscribeRemoteLogout } from '@/lib/sync/logout-broadcast';
import { useAuthStore } from '@/stores/auth-store';
import { useAuthUiStore } from '@/stores/auth-ui-store';
import { useToastStore } from '@/stores/toast-store';

export function AppProviders({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const pathname = usePathname() ?? '';

  useEffect(() => {
    registerAuthEvents({
      on401: (msg) => {
        useAuthUiStore.getState().openLoginModal(msg);
      },
      on403: (msg) => {
        useToastStore.getState().show(msg || '禁止访问', 'error');
      },
    });
  }, []);

  useEffect(() => {
    return subscribeRemoteLogout(() => {
      useAuthStore.getState().setTokens(null, null);
      useToastStore.getState().show('已在其他标签退出登录', 'info');
      if (pathname.startsWith('/dashboard')) {
        router.replace(`/login?from=${encodeURIComponent(pathname)}`);
      }
    });
  }, [pathname, router]);

  return (
    <TooltipProvider delayDuration={300}>
      <ErrorBoundary>{children}</ErrorBoundary>
      <ToastHost />
      <LoginModal />
    </TooltipProvider>
  );
}
