const { useState, useEffect } = React;







// Application states
const APP_STATES = {
  LANDING: 'landing',
  QUIZ: 'quiz',
  RESULTS: 'results',
  LEARN_MORE: 'learn_more'
};


// Access components and utilities from global scope
const LandingPage = window.LandingPage;
const QuizEngine = window.QuizEngine;
const ResultsPage = window.ResultsPage;
const LearnMore = window.LearnMore;
const { loadProgress, clearProgress, validateQuizData } = window.quizLogic;
const apiIntegration = window.apiIntegration;

function App() {
  const [currentState, setCurrentState] = useState(APP_STATES.LANDING);
  const [quizResults, setQuizResults] = useState(null);
  const [hasValidData, setHasValidData] = useState(false);
  const [apiConfigured, setApiConfigured] = useState(false);
  const [showApiSettings, setShowApiSettings] = useState(false);

  // Validate data on app initialization
  useEffect(() => {
    const isValid = validateQuizData();
    setHasValidData(isValid);
    
    if (!isValid) {
      console.error('Quiz data validation failed. Please check the data files.');
    }

    // Check if API is configured
    setApiConfigured(apiIntegration.isReady());
  }, []);

  // Check for saved progress on app load
  useEffect(() => {
    const savedProgress = loadProgress();
    if (savedProgress && savedProgress.currentState) {
      // If user has saved progress, ask if they want to continue
      const shouldContinue = window.confirm(
        'You have a quiz in progress. Would you like to continue where you left off?'
      );
      
      if (shouldContinue) {
        setCurrentState(savedProgress.currentState);
        if (savedProgress.quizResults) {
          setQuizResults(savedProgress.quizResults);
        }
      } else {
        clearProgress();
      }
    }
  }, []);

  // Handle navigation between app states
  const handleNavigation = (newState, data = null) => {
    setCurrentState(newState);
    
    if (data) {
      setQuizResults(data);
    }
  };

  // Handle starting the quiz
  const handleStartQuiz = () => {
    clearProgress(); // Clear any previous progress
    handleNavigation(APP_STATES.QUIZ);
  };

  // Handle quiz completion
  const handleQuizComplete = (results) => {
    setQuizResults(results);
    handleNavigation(APP_STATES.RESULTS, results);
    clearProgress(); // Clear progress since quiz is complete
  };

  // Handle returning to landing page
  const handleReturnHome = () => {
    setQuizResults(null);
    clearProgress();
    handleNavigation(APP_STATES.LANDING);
  };

  // Handle retaking quiz
  const handleRetakeQuiz = () => {
    setQuizResults(null);
    clearProgress();
    handleNavigation(APP_STATES.QUIZ);
  };

  // Handle API key configuration
  const handleConfigureApi = (apiKey) => {
    const success = apiIntegration.setApiKey(apiKey);
    if (success) {
      setApiConfigured(true);
      setShowApiSettings(false);
      return { success: true, message: 'API key configured successfully!' };
    } else {
      return { 
        success: false, 
        message: apiIntegration.getLastError() || 'Failed to configure API key' 
      };
    }
  };

  // Handle clearing API key
  const handleClearApi = () => {
    apiIntegration.clearApiKey();
    setApiConfigured(false);
  };

  // Test API connection
  const handleTestApi = async () => {
    const success = await apiIntegration.testConnection();
    if (success) {
      return { success: true, message: 'API connection successful!' };
    } else {
      return { 
        success: false, 
        message: apiIntegration.getLastError() || 'API connection failed' 
      };
    }
  };

  // Show error state if data validation failed
  if (!hasValidData) {
    return (
      <div className="min-h-screen flex items-center justify-center p-4" 
           style={{ backgroundColor: 'var(--color-light)' }}>
        <div className="max-w-md mx-auto text-center">
          <div className="bg-white border rounded-lg p-6 shadow-md"
               style={{ 
                 borderColor: 'var(--color-error)',
                 backgroundColor: 'var(--color-white)'
               }}>
            <div className="text-xl font-semibold mb-2"
                 style={{ color: 'var(--color-error)' }}>
              Data Loading Error
            </div>
            <p className="mb-4" style={{ color: 'var(--color-medium)' }}>
              There was an issue loading the quiz data. Please ensure the data files are properly configured.
            </p>
            <button 
              onClick={() => window.location.reload()}
              className="px-6 py-3 rounded-lg font-medium transition-all"
              style={{
                backgroundColor: 'var(--color-primary)',
                color: 'var(--color-white)'
              }}
              onMouseEnter={(e) => e.target.style.backgroundColor = 'var(--color-primary-dark)'}
              onMouseLeave={(e) => e.target.style.backgroundColor = 'var(--color-primary)'}
            >
              Reload Application
            </button>
          </div>
        </div>
      </div>
    );
  }

  // Render current screen based on application state
  const renderCurrentScreen = () => {
    switch (currentState) {
      case APP_STATES.LANDING:
        return (
          <LandingPage 
            onStartQuiz={handleStartQuiz}
            onLearnMore={() => handleNavigation(APP_STATES.LEARN_MORE)}
            apiConfigured={apiConfigured}
            onConfigureApi={() => setShowApiSettings(true)}
          />
        );
      
      case APP_STATES.QUIZ:
        return (
          <QuizEngine 
            onComplete={handleQuizComplete}
            onBack={handleReturnHome}
          />
        );
      
      case APP_STATES.RESULTS:
        return (
          <ResultsPage 
            results={quizResults}
            onRetakeQuiz={handleRetakeQuiz}
            onLearnMore={() => handleNavigation(APP_STATES.LEARN_MORE)}
            onBackHome={handleReturnHome}
            apiConfigured={apiConfigured}
            apiIntegration={apiIntegration}
          />
        );
      
      case APP_STATES.LEARN_MORE:
        return (
          <LearnMore 
            onBack={() => {
              // Return to results if we have them, otherwise landing
              const previousState = quizResults ? APP_STATES.RESULTS : APP_STATES.LANDING;
              handleNavigation(previousState);
            }}
            onStartQuiz={handleStartQuiz}
          />
        );
      
      default:
        return (
          <LandingPage 
            onStartQuiz={handleStartQuiz}
            onLearnMore={() => handleNavigation(APP_STATES.LEARN_MORE)}
            apiConfigured={apiConfigured}
            onConfigureApi={() => setShowApiSettings(true)}
          />
        );
    }
  };

  return (
    <div className="App">
      {renderCurrentScreen()}
      
      {/* API Settings Modal */}
      {showApiSettings && (
        <ApiSettingsModal
          onClose={() => setShowApiSettings(false)}
          onSave={handleConfigureApi}
          onClear={handleClearApi}
          onTest={handleTestApi}
          isConfigured={apiConfigured}
        />
      )}
    </div>
  );
}

/**
 * API Settings Modal Component
 */
function ApiSettingsModal({ onClose, onSave, onClear, onTest, isConfigured }) {
  const [apiKey, setApiKey] = useState('');
  const [message, setMessage] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  const handleSave = () => {
    if (!apiKey.trim()) {
      setMessage({ type: 'error', text: 'Please enter an API key' });
      return;
    }

    const result = onSave(apiKey);
    setMessage({ type: result.success ? 'success' : 'error', text: result.message });
    
    if (result.success) {
      setTimeout(() => {
        onClose();
      }, 1500);
    }
  };

  const handleTest = async () => {
    setIsLoading(true);
    setMessage(null);
    
    const result = await onTest();
    setMessage({ type: result.success ? 'success' : 'error', text: result.message });
    setIsLoading(false);
  };

  const handleClear = () => {
    if (window.confirm('Are you sure you want to remove your API key?')) {
      onClear();
      setApiKey('');
      setMessage({ type: 'success', text: 'API key removed' });
      setTimeout(() => {
        onClose();
      }, 1500);
    }
  };

  return (
    <div 
      className="fixed inset-0 flex items-center justify-center p-4 z-50"
      style={{ backgroundColor: 'rgba(0, 0, 0, 0.5)' }}
      onClick={onClose}
    >
      <div 
        className="bg-white rounded-xl shadow-xl max-w-md w-full p-6"
        onClick={(e) => e.stopPropagation()}
        style={{ backgroundColor: 'var(--color-white)' }}
      >
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-2xl font-bold" style={{ color: 'var(--color-dark)' }}>
            API Configuration
          </h2>
          <button 
            onClick={onClose}
            className="text-2xl font-bold"
            style={{ color: 'var(--color-medium)' }}
          >
            ×
          </button>
        </div>

        <div className="mb-4">
          <p className="text-sm mb-4" style={{ color: 'var(--color-medium)' }}>
            Configure your OpenAI API key to enable AI-enhanced insights. Your key is stored locally and never sent to our servers.
          </p>

          <label className="block mb-2 font-medium" style={{ color: 'var(--color-dark)' }}>
            OpenAI API Key
          </label>
          <input
            type="password"
            value={apiKey}
            onChange={(e) => setApiKey(e.target.value)}
            placeholder="sk-..."
            className="w-full px-4 py-2 border rounded-lg mb-3"
            style={{
              borderColor: 'var(--color-medium)',
              color: 'var(--color-dark)'
            }}
          />

          {message && (
            <div 
              className="p-3 rounded-lg mb-3 text-sm"
              style={{
                backgroundColor: message.type === 'success' 
                  ? 'var(--color-primary-alpha-10)' 
                  : 'var(--color-error-alpha-10)',
                color: message.type === 'success' 
                  ? 'var(--color-success-dark)' 
                  : 'var(--color-error-dark)'
              }}
            >
              {message.text}
            </div>
          )}

          <div className="flex gap-2 mb-4">
            <button
              onClick={handleSave}
              className="flex-1 px-4 py-2 rounded-lg font-medium transition-all"
              style={{
                backgroundColor: 'var(--color-primary)',
                color: 'var(--color-white)'
              }}
              onMouseEnter={(e) => e.target.style.backgroundColor = 'var(--color-primary-dark)'}
              onMouseLeave={(e) => e.target.style.backgroundColor = 'var(--color-primary)'}
            >
              Save Key
            </button>
            
            {isConfigured && (
              <button
                onClick={handleTest}
                disabled={isLoading}
                className="flex-1 px-4 py-2 rounded-lg font-medium transition-all"
                style={{
                  backgroundColor: 'var(--color-accent)',
                  color: 'var(--color-white)',
                  opacity: isLoading ? 0.6 : 1
                }}
                onMouseEnter={(e) => !isLoading && (e.target.style.backgroundColor = 'var(--color-accent-dark)')}
                onMouseLeave={(e) => e.target.style.backgroundColor = 'var(--color-accent)'}
              >
                {isLoading ? 'Testing...' : 'Test'}
              </button>
            )}
          </div>

          {isConfigured && (
            <button
              onClick={handleClear}
              className="w-full px-4 py-2 rounded-lg font-medium transition-all"
              style={{
                backgroundColor: 'var(--color-error)',
                color: 'var(--color-white)'
              }}
              onMouseEnter={(e) => e.target.style.backgroundColor = 'var(--color-error-dark)'}
              onMouseLeave={(e) => e.target.style.backgroundColor = 'var(--color-error)'}
            >
              Remove API Key
            </button>
          )}
        </div>

        <div className="text-xs p-3 rounded-lg" 
             style={{ 
               backgroundColor: 'var(--color-accent-alpha-10)',
               color: 'var(--color-medium)' 
             }}>
          <strong>How to get an API key:</strong>
          <ol className="list-decimal ml-4 mt-2 space-y-1">
            <li>Visit <a href="https://platform.openai.com/" target="_blank" rel="noopener noreferrer" className="underline">platform.openai.com</a></li>
            <li>Sign up or log in</li>
            <li>Navigate to API Keys</li>
            <li>Create a new secret key</li>
          </ol>
        </div>
      </div>
    </div>
  );
}



// Expose App globally and mount to DOM
window.App = App;

// Initialize the application
(async function initApp() {
  try {
    // Wait for data to load
    await window.quizDataUtils.loadQuizData();
    
    // Mount React app
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(React.createElement(App));
    
    console.log('Love Languages Quiz loaded successfully!');
  } catch (error) {
    console.error('Failed to initialize app:', error);
    document.getElementById('root').innerHTML = `
      <div style="display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 20px; text-align: center; background: #F5F5F7;">
        <div style="max-width: 500px; background: white; padding: 40px; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
          <h1 style="color: #6B5B95; margin-bottom: 20px; font-size: 24px;">Loading Error</h1>
          <p style="color: #2C2C34; line-height: 1.6; margin-bottom: 20px;">
            Failed to load the quiz application. Please refresh the page to try again.
          </p>
          <button onclick="window.location.reload()" style="background: #6B5B95; color: white; padding: 12px 24px; border: none; border-radius: 8px; cursor: pointer; font-size: 16px;">
            Reload Page
          </button>
        </div>
      </div>
    `;
  }
})();
