// 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-gray-100 dark:bg-gray-950 min-h-screen font-sans text-gray-800 dark:text-gray-200">
      {/* 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>
  );
};
