import React, { useState, useEffect, useRef } from 'react';
import { useExam } from '../../contexts/ExamContext';
import { InteractiveQuestion, Consequence } from '../../types';
import { cn } from '../../utils/cn';
import { 
  ChefHat, 
  Clock, 
  Thermometer, 
  AlertTriangle, 
  AlertCircle,
  CheckCircle, 
  XCircle,
  Play,
  Pause,
  RotateCcw,
  Lightbulb,
  Users,
  Utensils,
  Snowflake,
  Timer,
  Star,
  TrendingUp,
  TrendingDown,
  HelpCircle,
  Target,
  Award,
  Activity,
  Zap
} from 'lucide-react';
import ScenarioIntroGuide from './ScenarioIntroGuide';

interface ScenarioSimulationProps {
  question: InteractiveQuestion;
  questionIndex: number;
  onAnswerChange: (answer: any) => void;
  adminLanguage: string;
}

interface ScenarioState {
  currentStep: number;
  decisions: { [stepId: string]: string };
  score: number;
  timeElapsed: number;
  isRunning: boolean;
  completedSteps: string[];
  kitchenState: KitchenState;
  customerSatisfaction: number;
  efficiency: number;
  consequences: Consequence[];
}

interface KitchenState {
  temperature: number;
  cleanliness: number;
  inventory: { [item: string]: number };
  equipment: { [equipment: string]: boolean };
  staff: { [role: string]: boolean };
  orders: Order[];
}

interface Order {
  id: string;
  items: string[];
  priority: 'low' | 'medium' | 'high';
  timeRemaining: number;
  status: 'pending' | 'in_progress' | 'completed' | 'failed';
}

interface ScenarioStep {
  id: string;
  title: string;
  description: string;
  situation: string;
  options: ScenarioOption[];
  timeLimit?: number;
  consequences: { [optionId: string]: Consequence };
}

interface ScenarioOption {
  id: string;
  text: string;
  description?: string;
  icon?: string;
  risk: 'low' | 'medium' | 'high';
  cost?: number;
  timeRequired?: number;
}



const ScenarioSimulation: React.FC<ScenarioSimulationProps> = ({
  question,
  questionIndex,
  onAnswerChange,
  adminLanguage
}) => {
  const { state, setScenarioState } = useExam();
  const [scenarioState, setLocalScenarioState] = useState<ScenarioState>({
    currentStep: 0,
    decisions: {},
    score: 100,
    timeElapsed: 0,
    isRunning: false,
    completedSteps: [],
    kitchenState: {
      temperature: 22,
      cleanliness: 85,
      inventory: {},
      equipment: {},
      staff: {},
      orders: []
    },
    customerSatisfaction: 80,
    efficiency: 75,
    consequences: []
  });
  const [selectedOption, setSelectedOption] = useState<string | null>(null);
  const [showConsequence, setShowConsequence] = useState(false);
  const [consequenceMessage, setConsequenceMessage] = useState('');
  const [showIntroGuide, setShowIntroGuide] = useState(false);
  const [hasStarted, setHasStarted] = useState(false);
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  // Initialize scenario
  useEffect(() => {
    if (question.scenarioData) {
      const savedState = state.scenarioStates?.[questionIndex];
      if (savedState) {
        setLocalScenarioState(savedState);
        setHasStarted(true);
      } else {
        // Show intro guide for first-time users
        setShowIntroGuide(true);
      }
    }
  }, [question.scenarioData, questionIndex]);

  // Timer effect
  useEffect(() => {
    if (scenarioState.isRunning) {
      timerRef.current = setInterval(() => {
        setLocalScenarioState(prev => ({
          ...prev,
          timeElapsed: prev.timeElapsed + 1,
          kitchenState: {
            ...prev.kitchenState,
            orders: prev.kitchenState.orders.map(order => ({
              ...order,
              timeRemaining: Math.max(0, order.timeRemaining - 1)
            }))
          }
        }));
      }, 1000);
    } else {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    }

    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, [scenarioState.isRunning]);

  // Initialize scenario
  const initializeScenario = () => {
    if (!question.scenarioData) return;

    const initialKitchenState: KitchenState = {
      temperature: question.scenarioData.initialState?.temperature || 22,
      cleanliness: question.scenarioData.initialState?.cleanliness || 85,
      inventory: question.scenarioData.initialState?.inventory || {},
      equipment: question.scenarioData.initialState?.equipment || {},
      staff: question.scenarioData.initialState?.staff || {},
      orders: question.scenarioData.initialState?.orders || []
    };

    const newState: ScenarioState = {
      currentStep: 0,
      decisions: {},
      score: 100,
      timeElapsed: 0,
      isRunning: false,
      completedSteps: [],
      kitchenState: initialKitchenState,
      customerSatisfaction: 80,
      efficiency: 75,
      consequences: []
    };

    setLocalScenarioState(newState);
    setScenarioState(questionIndex.toString(), newState);
  };

  // Start scenario after intro
  const handleStartScenario = () => {
    setShowIntroGuide(false);
    setHasStarted(true);
    initializeScenario();
  };

  // Show help guide
  const handleShowHelp = () => {
    setShowIntroGuide(true);
  };

  // Handle option selection
  const handleOptionSelection = (optionId: string) => {
    setSelectedOption(optionId);
    
    // Find the selected option
    const currentStepData = question.scenarioData?.steps?.[scenarioState.currentStep];
    const selectedOptionData = currentStepData?.options?.find(opt => opt.id === optionId);
    
    if (selectedOptionData) {
      // Execute the decision after a short delay to show selection
      setTimeout(() => {
        executeDecision(selectedOptionData);
      }, 500);
    }
  };

  // Execute decision with enhanced consequences
  const executeDecision = (option: ScenarioOption) => {
    // Get consequence from current step data
    const currentStepData = question.scenarioData?.steps?.[scenarioState.currentStep];
    const stepConsequence = currentStepData?.consequences?.[option.id];
    
    const consequence: Consequence = {
      scoreChange: stepConsequence?.scoreChange || 0,
      kitchenStateChanges: stepConsequence?.kitchenStateChanges || {},
      message: stepConsequence?.message || `You chose: ${option.text}`,
      nextStep: stepConsequence?.nextStep
    };

    // Update scenario state with consequences
    setLocalScenarioState(prev => ({
      ...prev,
      consequences: [...prev.consequences, consequence],
      score: Math.max(0, Math.min(100, prev.score + consequence.scoreChange)),
      currentStep: prev.currentStep + 1,
      // Update kitchen state based on changes
      kitchenState: {
        ...prev.kitchenState,
        ...consequence.kitchenStateChanges
      },
      customerSatisfaction: Math.max(0, Math.min(100, prev.customerSatisfaction + (consequence.scoreChange > 0 ? 5 : -3))),
      efficiency: Math.max(0, Math.min(100, prev.efficiency + (consequence.scoreChange > 0 ? 3 : -2)))
    }));

    // Clear selection
    setSelectedOption(null);

    // Call the parent's answer change handler
    onAnswerChange(option.id);
  };

  // Start/pause scenario
  const toggleScenario = () => {
    const newState = {
      ...scenarioState,
      isRunning: !scenarioState.isRunning
    };
    setLocalScenarioState(newState);
    setScenarioState(questionIndex.toString(), newState);
  };

  // Reset scenario
  const resetScenario = () => {
    initializeScenario();
    setSelectedOption(null);
    setShowConsequence(false);
    setConsequenceMessage('');
  };

  // Calculate customer satisfaction
  const calculateCustomerSatisfaction = (kitchenState: KitchenState, score: number): number => {
    const baseScore = score;
    const cleanlinessBonus = (kitchenState.cleanliness - 50) * 0.3;
    const temperatureBonus = Math.abs(kitchenState.temperature - 22) < 3 ? 10 : -5;
    
    return Math.max(0, Math.min(100, baseScore + cleanlinessBonus + temperatureBonus));
  };

  // Calculate efficiency
  const calculateEfficiency = (timeElapsed: number, completedSteps: number): number => {
    if (timeElapsed === 0) return 75;
    const timePerStep = timeElapsed / Math.max(1, completedSteps);
    const idealTimePerStep = 30; // seconds
    
    return Math.max(0, Math.min(100, 100 - (timePerStep - idealTimePerStep) * 2));
  };

  // Render progress tracker
  const renderProgressTracker = () => {
    const totalSteps = question.scenarioData?.steps?.length || 0;
    const currentStepIndex = scenarioState.currentStep;
    const progressPercentage = totalSteps > 0 ? ((currentStepIndex + 1) / totalSteps) * 100 : 0;

    return (
      <div className="bg-white rounded-xl p-6 border border-gray-200 shadow-sm mb-6">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold text-gray-900 flex items-center space-x-2">
            <Target className="text-blue-600" size={20} />
            <span>{adminLanguage === 'id' ? 'Progress Simulasi' : 'Simulation Progress'}</span>
          </h3>
          <div className="flex items-center space-x-2 text-sm text-gray-600">
            <span>{adminLanguage === 'id' ? 'Langkah' : 'Step'}</span>
            <span className="font-semibold text-blue-600">{currentStepIndex + 1}</span>
            <span>{adminLanguage === 'id' ? 'dari' : 'of'}</span>
            <span className="font-semibold">{totalSteps}</span>
          </div>
        </div>

        {/* Progress bar */}
        <div className="mb-4">
          <div className="flex justify-between text-sm text-gray-600 mb-2">
            <span>{adminLanguage === 'id' ? 'Kemajuan' : 'Progress'}</span>
            <span>{Math.round(progressPercentage)}%</span>
          </div>
          <div className="w-full bg-gray-200 rounded-full h-3">
            <div 
              className="bg-gradient-to-r from-blue-500 to-blue-600 h-3 rounded-full transition-all duration-500 ease-out"
              style={{ width: `${progressPercentage}%` }}
            />
          </div>
        </div>

        {/* Step indicators */}
        <div className="flex items-center justify-between">
          {Array.from({ length: totalSteps }, (_, index) => (
            <div key={index} className="flex flex-col items-center">
              <div className={cn(
                'w-8 h-8 rounded-full flex items-center justify-center text-sm font-semibold transition-all',
                index < currentStepIndex ? 'bg-green-500 text-white' :
                index === currentStepIndex ? 'bg-blue-500 text-white' :
                'bg-gray-200 text-gray-500'
              )}>
                {index < currentStepIndex ? (
                  <Award size={16} />
                ) : (
                  index + 1
                )}
              </div>
              <div className={cn(
                'mt-2 text-xs text-center max-w-16',
                index === currentStepIndex ? 'text-blue-600 font-medium' : 'text-gray-500'
              )}>
                {adminLanguage === 'id' ? `Langkah ${index + 1}` : `Step ${index + 1}`}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  };
  const renderEnhancedKitchenDashboard = () => {
    if (!question.scenarioData?.initialState) return null;

    return (
      <div className="bg-gradient-to-br from-gray-50 to-gray-100 rounded-xl p-6 border border-gray-200 shadow-sm">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold text-gray-900 flex items-center space-x-2">
            <Activity className="text-blue-600" size={20} />
            <span>{adminLanguage === 'id' ? 'Status Dapur' : 'Kitchen Status'}</span>
          </h3>
          <button
            onClick={handleShowHelp}
            className="p-2 text-gray-500 hover:text-blue-600 hover:bg-blue-50 rounded-full transition-colors"
            title={adminLanguage === 'id' ? 'Bantuan' : 'Help'}
          >
            <HelpCircle size={18} />
          </button>
        </div>

        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {/* Temperature */}
          <div className="bg-white rounded-lg p-4 border border-gray-200">
            <div className="flex items-center space-x-2 mb-2">
              <Thermometer className={cn(
                scenarioState.kitchenState.temperature > 25 ? 'text-red-500' :
                scenarioState.kitchenState.temperature < 18 ? 'text-blue-500' : 'text-green-500'
              )} size={20} />
              <span className="text-sm font-medium text-gray-700">
                {adminLanguage === 'id' ? 'Suhu' : 'Temperature'}
              </span>
            </div>
            <p className="text-2xl font-bold text-gray-900">{scenarioState.kitchenState.temperature}°C</p>
            <div className="mt-2 w-full bg-gray-200 rounded-full h-2">
              <div 
                className={cn(
                  'h-2 rounded-full transition-all',
                  scenarioState.kitchenState.temperature > 25 ? 'bg-red-500' :
                  scenarioState.kitchenState.temperature < 18 ? 'bg-blue-500' : 'bg-green-500'
                )}
                style={{ width: `${Math.min(100, (scenarioState.kitchenState.temperature / 30) * 100)}%` }}
              />
            </div>
          </div>

          {/* Cleanliness */}
          <div className="bg-white rounded-lg p-4 border border-gray-200">
            <div className="flex items-center space-x-2 mb-2">
              <Utensils className={cn(
                scenarioState.kitchenState.cleanliness > 80 ? 'text-green-500' :
                scenarioState.kitchenState.cleanliness > 60 ? 'text-yellow-500' : 'text-red-500'
              )} size={20} />
              <span className="text-sm font-medium text-gray-700">
                {adminLanguage === 'id' ? 'Kebersihan' : 'Cleanliness'}
              </span>
            </div>
            <p className="text-2xl font-bold text-gray-900">{scenarioState.kitchenState.cleanliness}%</p>
            <div className="mt-2 w-full bg-gray-200 rounded-full h-2">
              <div 
                className={cn(
                  'h-2 rounded-full transition-all',
                  scenarioState.kitchenState.cleanliness > 80 ? 'bg-green-500' :
                  scenarioState.kitchenState.cleanliness > 60 ? 'bg-yellow-500' : 'bg-red-500'
                )}
                style={{ width: `${scenarioState.kitchenState.cleanliness}%` }}
              />
            </div>
          </div>

          {/* Customer Satisfaction */}
          <div className="bg-white rounded-lg p-4 border border-gray-200">
            <div className="flex items-center space-x-2 mb-2">
              {scenarioState.customerSatisfaction > 80 ? 
                <Star className="text-green-500" size={20} /> :
                scenarioState.customerSatisfaction > 60 ? 
                <Star className="text-yellow-500" size={20} /> : 
                <Star className="text-red-500" size={20} />
              }
              <span className="text-sm font-medium text-gray-700">
                {adminLanguage === 'id' ? 'Kepuasan' : 'Satisfaction'}
              </span>
            </div>
            <p className="text-2xl font-bold text-gray-900">{scenarioState.customerSatisfaction}%</p>
            <div className="mt-2 w-full bg-gray-200 rounded-full h-2">
              <div 
                className={cn(
                  'h-2 rounded-full transition-all',
                  scenarioState.customerSatisfaction > 80 ? 'bg-green-500' :
                  scenarioState.customerSatisfaction > 60 ? 'bg-yellow-500' : 'bg-red-500'
                )}
                style={{ width: `${scenarioState.customerSatisfaction}%` }}
              />
            </div>
          </div>

          {/* Efficiency */}
          <div className="bg-white rounded-lg p-4 border border-gray-200">
            <div className="flex items-center space-x-2 mb-2">
              {scenarioState.efficiency > 75 ? 
                <TrendingUp className="text-green-500" size={20} /> :
                <TrendingDown className="text-red-500" size={20} />
              }
              <span className="text-sm font-medium text-gray-700">
                {adminLanguage === 'id' ? 'Efisiensi' : 'Efficiency'}
              </span>
            </div>
            <p className="text-2xl font-bold text-gray-900">{scenarioState.efficiency}%</p>
            <div className="mt-2 w-full bg-gray-200 rounded-full h-2">
              <div 
                className={cn(
                  'h-2 rounded-full transition-all',
                  scenarioState.efficiency > 75 ? 'bg-green-500' : 'bg-red-500'
                )}
                style={{ width: `${scenarioState.efficiency}%` }}
              />
            </div>
          </div>
        </div>
      </div>
    );
  };

  // Render current orders
  const renderOrders = () => {
    if (scenarioState.kitchenState.orders.length === 0) return null;

    return (
      <div className="space-y-2">
        <h4 className="font-medium text-gray-900">
          {adminLanguage === 'id' ? 'Pesanan Aktif' : 'Active Orders'}
        </h4>
        {scenarioState.kitchenState.orders.map(order => (
          <div
            key={order.id}
            className={cn(
              'p-3 rounded border-l-4',
              order.priority === 'high' ? 'border-red-400 bg-red-50' :
              order.priority === 'medium' ? 'border-yellow-400 bg-yellow-50' :
              'border-green-400 bg-green-50'
            )}
          >
            <div className="flex items-center justify-between">
              <div>
                <p className="font-medium text-sm">Order #{order.id}</p>
                <p className="text-xs text-gray-600">{order.items.join(', ')}</p>
              </div>
              <div className="text-right">
                <div className="flex items-center space-x-1">
                  <Timer size={12} />
                  <span className="text-xs">{order.timeRemaining}s</span>
                </div>
                <span className={cn(
                  'text-xs px-2 py-1 rounded',
                  order.priority === 'high' ? 'bg-red-100 text-red-800' :
                  order.priority === 'medium' ? 'bg-yellow-100 text-yellow-800' :
                  'bg-green-100 text-green-800'
                )}>
                  {order.priority}
                </span>
              </div>
            </div>
          </div>
        ))}
      </div>
    );
  };

  // Render enhanced scenario steps
  const renderEnhancedScenarioSteps = () => {
    const currentStepData = question.scenarioData?.steps?.[scenarioState.currentStep];
    if (!currentStepData) return null;

    return (
      <div className="bg-white rounded-xl p-6 border border-gray-200 shadow-sm mb-6">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold text-gray-900 flex items-center space-x-2">
            <Zap className="text-orange-500" size={20} />
            <span>{adminLanguage === 'id' ? 'Situasi Saat Ini' : 'Current Situation'}</span>
          </h3>
          <div className="flex items-center space-x-2">
            <div className="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm font-medium">
              {adminLanguage === 'id' ? 'Aktif' : 'Active'}
            </div>
          </div>
        </div>

        {/* Scenario description */}
        <div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg p-4 mb-6 border-l-4 border-blue-500">
          <h4 className="font-semibold text-gray-900 mb-2">
            {adminLanguage === 'id' ? 'Deskripsi Situasi:' : 'Situation Description:'}
          </h4>
          <p className="text-gray-700 leading-relaxed">{currentStepData.description}</p>
        </div>

        {/* Action options */}
        <div className="space-y-3">
          <h4 className="font-semibold text-gray-900 flex items-center space-x-2">
            <span>{adminLanguage === 'id' ? 'Pilihan Tindakan:' : 'Action Options:'}</span>
            <span className="text-sm text-gray-500 font-normal">
              ({adminLanguage === 'id' ? 'Pilih satu tindakan' : 'Choose one action'})
            </span>
          </h4>
          
          {currentStepData.options?.map((option, index) => (
            <button
              key={index}
              onClick={() => handleOptionSelection(option.id)}
              className={cn(
                'w-full text-left p-4 rounded-lg border-2 transition-all duration-200 hover:shadow-md',
                'bg-white hover:bg-gray-50 border-gray-200 hover:border-blue-300',
                'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500',
                selectedOption === option.id ? 'border-blue-500 bg-blue-50' : ''
              )}
            >
              <div className="flex items-start space-x-3">
                <div className={cn(
                  'flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center font-semibold text-sm',
                  selectedOption === option.id ? 'bg-blue-600 text-white' : 'bg-blue-100 text-blue-600'
                )}>
                  {String.fromCharCode(65 + index)}
                </div>
                <div className="flex-1">
                  <p className="font-medium text-gray-900 mb-1">{option.text}</p>
                </div>
                <div className="flex-shrink-0">
                  <div className={cn(
                    'w-6 h-6 border-2 rounded-full flex items-center justify-center',
                    selectedOption === option.id ? 'border-blue-500' : 'border-gray-300'
                  )}>
                    <div className={cn(
                      'w-2 h-2 rounded-full',
                      selectedOption === option.id ? 'bg-blue-500' : 'bg-transparent'
                    )}></div>
                  </div>
                </div>
              </div>
            </button>
          ))}
        </div>

        {/* Help text */}
        <div className="mt-6 p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
          <div className="flex items-start space-x-2">
            <HelpCircle className="text-yellow-600 flex-shrink-0 mt-0.5" size={16} />
            <p className="text-sm text-yellow-800">
              {adminLanguage === 'id' 
                ? 'Tip: Baca setiap pilihan dengan cermat. Keputusan Anda akan mempengaruhi kondisi dapur dan kepuasan pelanggan.'
                : 'Tip: Read each option carefully. Your decisions will affect kitchen conditions and customer satisfaction.'
              }
            </p>
          </div>
        </div>
      </div>
    );
  };

  // Render enhanced consequences
  const renderEnhancedConsequences = () => {
    if (scenarioState.consequences.length === 0) return null;

    return (
      <div className="space-y-4 mb-6">
        <h3 className="text-lg font-semibold text-gray-900 flex items-center space-x-2">
          <Activity className="text-green-600" size={20} />
          <span>{adminLanguage === 'id' ? 'Hasil Tindakan' : 'Action Results'}</span>
        </h3>
        
        {scenarioState.consequences.map((consequence, index) => {
          const isPositive = consequence.scoreChange > 0;
          const isNeutral = consequence.scoreChange === 0;
          
          return (
            <div
              key={index}
              className={cn(
                'rounded-xl p-6 border-l-4 shadow-sm transition-all duration-300',
                isPositive ? 'bg-green-50 border-green-500 border border-green-200' :
                isNeutral ? 'bg-blue-50 border-blue-500 border border-blue-200' :
                'bg-red-50 border-red-500 border border-red-200'
              )}
            >
              <div className="flex items-start space-x-4">
                <div className={cn(
                  'flex-shrink-0 w-10 h-10 rounded-full flex items-center justify-center',
                  isPositive ? 'bg-green-100 text-green-600' :
                  isNeutral ? 'bg-blue-100 text-blue-600' :
                  'bg-red-100 text-red-600'
                )}>
                  {isPositive ? (
                    <TrendingUp size={20} />
                  ) : isNeutral ? (
                    <Activity size={20} />
                  ) : (
                    <TrendingDown size={20} />
                  )}
                </div>
                
                <div className="flex-1">
                  <div className="flex items-center justify-between mb-2">
                    <h4 className={cn(
                      'font-semibold',
                      isPositive ? 'text-green-800' :
                      isNeutral ? 'text-blue-800' :
                      'text-red-800'
                    )}>
                      {consequence.message}
                    </h4>
                    <div className={cn(
                      'px-3 py-1 rounded-full text-sm font-medium',
                      isPositive ? 'bg-green-100 text-green-800' :
                      isNeutral ? 'bg-blue-100 text-blue-800' :
                      'bg-red-100 text-red-800'
                    )}>
                      {isPositive ? '+' : ''}{consequence.scoreChange}
                      {adminLanguage === 'id' ? ' poin' : ' points'}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    );
  };
  const renderScenarioStep = () => {
    if (!question.scenarioData || 
        !question.scenarioData.steps || 
        scenarioState.currentStep >= question.scenarioData.steps.length ||
        scenarioState.currentStep < 0) {
      return renderScenarioComplete();
    }

    const currentStepData = question.scenarioData.steps[scenarioState.currentStep];
    
    // Additional safety check for currentStepData
    if (!currentStepData) {
      return renderScenarioComplete();
    }

    return (
      <div className="space-y-4">
        {/* Enhanced scenario steps */}
        {renderEnhancedScenarioSteps()}

        {/* Step header */}
        <div className="border-b pb-4">
          <h3 className="text-lg font-semibold text-gray-900">{currentStepData.title || 'Untitled Step'}</h3>
          <p className="text-gray-600 mt-1">{currentStepData.description || 'No description available'}</p>
        </div>

        {/* Situation */}
        <div className="p-4 bg-blue-50 border-l-4 border-blue-400 rounded-r">
          <h4 className="font-medium text-blue-900 mb-2">
            {adminLanguage === 'id' ? 'Situasi:' : 'Situation:'}
          </h4>
          <p className="text-blue-800">{currentStepData.situation || 'No situation described'}</p>
        </div>

        {/* Options */}
        <div className="space-y-3">
          <h4 className="font-medium text-gray-900">
            {adminLanguage === 'id' ? 'Pilihan Tindakan:' : 'Action Options:'}
          </h4>
          {(currentStepData.options || []).map((option, index) => (
          <div
            key={option.id}
            onClick={() => handleOptionSelection(option.id)}
            className={cn(
              'p-4 border-2 rounded-lg cursor-pointer transition-all',
              selectedOption === option.id 
                ? 'border-blue-500 bg-blue-50' 
                : 'border-gray-200 bg-white hover:border-gray-300 hover:shadow-md'
            )}
          >
            <div className="flex items-start space-x-3">
              <div className={cn(
                'w-6 h-6 rounded-full flex items-center justify-center text-xs font-semibold',
                selectedOption === option.id 
                  ? 'bg-blue-600 text-white' 
                  : 'bg-gray-200 text-gray-700'
              )}>
                {String.fromCharCode(65 + index)}
              </div>
              
              <div className="flex-1">
                <p className="text-gray-900">{option.text}</p>
                
                <div className="flex items-center space-x-4 mt-2 text-xs text-gray-600">
                  <span className={cn(
                    'px-2 py-1 rounded',
                    option.risk === 'high' ? 'bg-red-100 text-red-800' :
                    option.risk === 'medium' ? 'bg-yellow-100 text-yellow-800' :
                    'bg-green-100 text-green-800'
                  )}>
                    {adminLanguage === 'id' ? 'Risiko' : 'Risk'}: {option.risk}
                  </span>
                  
                  {option.timeRequired && (
                    <span className="flex items-center space-x-1">
                      <Clock size={12} />
                      <span>{option.timeRequired}s</span>
                    </span>
                  )}
                  
                  {option.cost && (
                    <span className="flex items-center space-x-1">
                      <span>💰</span>
                      <span>${option.cost}</span>
                    </span>
                  )}
                </div>
              </div>
            </div>
          </div>
        ))}
        </div>

        {/* Execute button */}
        {selectedOption && (
          <button
            onClick={() => {
              const currentStepData = question.scenarioData?.steps?.[scenarioState.currentStep];
              const selectedOptionData = currentStepData?.options?.find(opt => opt.id === selectedOption);
              if (selectedOptionData) {
                executeDecision(selectedOptionData);
              }
            }}
            className="w-full py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium"
          >
            {adminLanguage === 'id' ? 'Jalankan Tindakan' : 'Execute Action'}
          </button>
        )}
      </div>
    );
  };

  // Render scenario complete
  const renderScenarioComplete = () => {
    const finalGrade = scenarioState.score >= 80 ? 'A' : 
                     scenarioState.score >= 70 ? 'B' : 
                     scenarioState.score >= 60 ? 'C' : 'D';

    return (
      <div className="text-center space-y-4">
        <div className="p-6 bg-green-50 border border-green-200 rounded-lg">
          <CheckCircle className="mx-auto text-green-600 mb-4" size={48} />
          <h3 className="text-xl font-semibold text-green-900 mb-2">
            {adminLanguage === 'id' ? 'Skenario Selesai!' : 'Scenario Complete!'}
          </h3>
          
          <div className="grid grid-cols-2 gap-4 mt-4">
            <div className="text-center">
              <p className="text-2xl font-bold text-green-600">{scenarioState.score}</p>
              <p className="text-sm text-gray-600">
                {adminLanguage === 'id' ? 'Skor Akhir' : 'Final Score'}
              </p>
            </div>
            <div className="text-center">
              <p className="text-2xl font-bold text-blue-600">{finalGrade}</p>
              <p className="text-sm text-gray-600">
                {adminLanguage === 'id' ? 'Nilai' : 'Grade'}
              </p>
            </div>
          </div>
          
          <div className="mt-4 text-sm text-gray-700">
            <p>
              {adminLanguage === 'id' ? 'Waktu: ' : 'Time: '}
              {Math.floor(scenarioState.timeElapsed / 60)}:{(scenarioState.timeElapsed % 60).toString().padStart(2, '0')}
            </p>
            <p>
              {adminLanguage === 'id' ? 'Langkah diselesaikan: ' : 'Steps completed: '}
              {scenarioState.completedSteps.length}
            </p>
          </div>
        </div>
      </div>
    );
  };

  // Early return if no scenario data
  if (!question.scenarioData) {
    return (
      <div className="text-center p-8">
        <AlertCircle className="mx-auto text-yellow-500 mb-4" size={48} />
        <p className="text-gray-600">
          {adminLanguage === 'id' ? 'Data skenario tidak tersedia' : 'No scenario data available'}
        </p>
      </div>
    );
  }

  // Main component render
  return (
    <div className="space-y-6">
      {/* Intro Guide Modal */}
      {showIntroGuide && (
        <ScenarioIntroGuide
          isOpen={showIntroGuide}
          onClose={() => setShowIntroGuide(false)}
          onStart={handleStartScenario}
          scenarioType="kitchen"
          adminLanguage={adminLanguage}
        />
      )}

      {/* Start button for new users */}
      {!hasStarted && (
        <div className="text-center py-12">
          <div className="bg-white rounded-xl p-8 border border-gray-200 shadow-sm">
            <h3 className="text-xl font-semibold text-gray-900 mb-4">
              {adminLanguage === 'id' ? 'Simulasi Manajemen Dapur' : 'Kitchen Management Simulation'}
            </h3>
            <p className="text-gray-600 mb-6">
              {adminLanguage === 'id' 
                ? 'Selamat datang di simulasi manajemen dapur. Klik tombol di bawah untuk memulai panduan dan simulasi.'
                : 'Welcome to the kitchen management simulation. Click the button below to start the guide and simulation.'
              }
            </p>
            <button
              onClick={() => setShowIntroGuide(true)}
              className="px-8 py-3 bg-blue-500 hover:bg-blue-600 text-white rounded-lg font-medium transition-all duration-200 flex items-center space-x-2 mx-auto"
            >
              <span>{adminLanguage === 'id' ? 'Mulai Simulasi' : 'Start Simulation'}</span>
            </button>
          </div>
        </div>
      )}

      {/* Control panel */}
      {hasStarted && (
        <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
          <div className="flex items-center space-x-4">
            <button
              onClick={toggleScenario}
              className={cn(
                'flex items-center space-x-2 px-4 py-2 rounded font-medium transition-colors',
                scenarioState.isRunning 
                  ? 'bg-red-600 text-white hover:bg-red-700'
                  : 'bg-green-600 text-white hover:bg-green-700'
              )}
            >
              {scenarioState.isRunning ? <Pause size={16} /> : <Play size={16} />}
              <span>
                {scenarioState.isRunning 
                  ? (adminLanguage === 'id' ? 'Jeda' : 'Pause')
                  : (adminLanguage === 'id' ? 'Mulai' : 'Start')}
              </span>
            </button>
            
            <button
              onClick={resetScenario}
              className="flex items-center space-x-2 px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700 transition-colors"
            >
              <RotateCcw size={16} />
              <span>{adminLanguage === 'id' ? 'Reset' : 'Reset'}</span>
            </button>

            <button
              onClick={handleShowHelp}
              className="flex items-center space-x-2 px-4 py-2 bg-blue-100 hover:bg-blue-200 text-blue-700 rounded font-medium transition-colors"
            >
              <HelpCircle size={16} />
              <span>{adminLanguage === 'id' ? 'Bantuan' : 'Help'}</span>
            </button>
          </div>
          
          <div className="flex items-center space-x-4 text-sm text-gray-600">
            <div className="flex items-center space-x-1">
              <Timer size={16} />
              <span>
                {Math.floor(scenarioState.timeElapsed / 60)}:{(scenarioState.timeElapsed % 60).toString().padStart(2, '0')}
              </span>
            </div>
            
            <div className="flex items-center space-x-1">
              <Star size={16} />
              <span>{scenarioState.score}/100</span>
            </div>
          </div>
        </div>
      )}

      {/* Progress Tracker */}
      {hasStarted && renderProgressTracker()}

      {/* Kitchen dashboard */}
      {hasStarted && renderEnhancedKitchenDashboard()}

      {/* Active orders */}
      {hasStarted && renderOrders()}

      {/* Enhanced Consequences */}
      {hasStarted && renderEnhancedConsequences()}

      {/* Scenario content */}
      {hasStarted && renderScenarioStep()}

      {/* Consequence modal */}
      {showConsequence && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 max-w-md w-full mx-4">
            <div className="text-center">
              <AlertTriangle className="mx-auto text-yellow-600 mb-4" size={48} />
              <h3 className="text-lg font-semibold mb-2">
                {adminLanguage === 'id' ? 'Konsekuensi' : 'Consequence'}
              </h3>
              <p className="text-gray-700">{consequenceMessage}</p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ScenarioSimulation;