// src/components/AppGuard.tsx
import React, { useCallback } from 'react';
import { Toaster } from 'react-hot-toast';
import { useAppInitialization } from '../hooks/useAppInitialization';
import { useModal } from '../hooks/useModal';
import { WhatsNewModal } from './WhatsNewModal';
import config from '../config';

interface AppGuardProps {
  children: React.ReactNode;
}

export const AppGuard: React.FC<AppGuardProps> = ({ children }) => {
  // This hook handles OAuth tokens, version checks, and returns theme state.
  const { isDarkMode } = useAppInitialization();
  const { isModalOpen, closeModal } = useModal();

  const handleCloseWhatsNew = useCallback(() => closeModal('whatsNew'), [closeModal]);

  const appVersion = config.app.version;
  const commitMessage = config.app.commitMessage;

  return (
    <div className="bg-slate-50 dark:bg-slate-900 min-h-screen font-sans text-gray-800 dark:text-gray-200 bg-[radial-gradient(ellipse_at_top_right,_var(--tw-gradient-stops))] from-slate-50 via-gray-100 to-slate-100 dark:from-slate-800 dark:via-slate-900 dark:to-black">
      {/* Toaster component for displaying notifications. It's placed at the top level. */}
      <Toaster position="top-center" reverseOrder={false} />
      {/* Add CSS variables for toast theming based on dark mode */}
      <style>{`
        :root {
          --toast-bg: ${isDarkMode ? '#4B5563' : '#FFFFFF'};
          --toast-color: ${isDarkMode ? '#F9FAFB' : '#1F2937'};
        }
      `}</style>

      {appVersion && commitMessage && (
        <WhatsNewModal
          isOpen={isModalOpen('whatsNew')}
          onClose={handleCloseWhatsNew}
          version={appVersion}
          commitMessage={commitMessage}
        />
      )}

      {children}
    </div>
  );
};
