'use client';

import { useState, useMemo } from 'react';
import { useTranslations, useLocale } from 'next-intl';
import { cn } from '@/lib/cn';
import { 
    ChevronRight, 
    ChevronLeft, 
    Trophy, 
    Users, 
    Zap,
    MessageSquare,
    Puzzle,
    Compass,
    Activity,
    Play,
    RotateCcw,
    CheckCircle2,
    AlertCircle,
    Info,
    LayoutGrid,
    Target
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';

const Progress = ({ value, className }: { value: number, className?: string }) => (
    <div className={cn("w-full bg-slate-200 rounded-full h-2 overflow-hidden", className)}>
        <div 
            className="bg-purple-600 h-full transition-all duration-500 ease-out" 
            style={{ width: `${value}%` }} 
        />
    </div>
);

// Game Data
const STAGES = [
    {
        id: 'forming',
        title_ar: "مرحلة التشكيل (Forming)",
        title_en: "Forming Stage",
        color: "bg-emerald-500",
        icon: Users,
        desc_ar: "مرحلة البداية، يسودها الترقب والحذر. الفريق يحتاج للتوجيه والوضوح.",
        desc_en: "The initial stage, characterized by anticipation and caution. The team needs direction and clarity."
    },
    {
        id: 'storming',
        title_ar: "مرحلة الصراع (Storming)",
        title_en: "Storming Stage",
        color: "bg-rose-500",
        icon: Activity,
        desc_ar: "ظهور الخلافات وتصادم الآراء. مرحلة حرجة لتحديد الأدوار والحدود.",
        desc_en: "Emergence of conflicts and clashing opinions. A critical stage for defining roles and boundaries."
    },
    {
        id: 'norming',
        title_ar: "مرحلة التطبيع (Norming)",
        title_en: "Norming Stage",
        color: "bg-blue-500",
        icon: Puzzle,
        desc_ar: "تعزيز التماسك والتعاون. وضوح المعايير وبدء بناء الثقة الحقيقية.",
        desc_en: "Strengthening cohesion and cooperation. Standards are clear and true trust starts building."
    },
    {
        id: 'performing',
        title_ar: "مرحلة الإنجاز (Performing)",
        title_en: "Performing Stage",
        color: "bg-amber-500",
        icon: Target,
        desc_ar: "أداء عالٍ وتركيز على النتائج. الفريق يعمل بانسجام واستقلالية كبيرة.",
        desc_en: "High performance and focus on results. The team works in harmony with great autonomy."
    }
];

const ROLES = [
    {
        id: 'contributor',
        title_ar: "المساهم (Contributor)",
        title_en: "Contributor",
        color: "bg-indigo-500",
        icon: Info,
        desc_ar: "يوفر المعلومات والموارد. يركز على إنجاز المهام بدقة.",
        desc_en: "Provides information and resources. Focuses on completing tasks accurately."
    },
    {
        id: 'collaborator',
        title_ar: "المتعاون (Collaborator)",
        title_en: "Collaborator",
        color: "bg-cyan-500",
        icon: Compass,
        desc_ar: "يركز على الرؤية الكبيرة والأهداف. مرن ومنفتح على الأفكار.",
        desc_en: "Focuses on the big vision and goals. Flexible and open to ideas."
    },
    {
        id: 'communicator',
        title_ar: "المتصل (Communicator)",
        title_en: "Communicator",
        color: "bg-pink-500",
        icon: MessageSquare,
        desc_ar: "يبني الروابط ويدير العلاقات. مستمع جيد ووسيط للسلام.",
        desc_en: "Builds bonds and manages relationships. A good listener and a peacemaker."
    },
    {
        id: 'challenger',
        title_ar: "المتحدي (Challenger)",
        title_en: "Challenger",
        color: "bg-orange-500",
        icon: Zap,
        desc_ar: "يشكك في الافتراضات ويدفع نحو معايير أعلى.",
        desc_en: "Questions assumptions and pushes for higher standards."
    }
];

const SCENARIOS = [
    {
        id: 1,
        context_ar: "تم تعيين 4 موظفين جدد في قسم التسويق. في الاجتماع الأول، كان الجميع يسأل عن مكان المكتب وساعات العمل، ولا أحد يتحدث عن خطة التسويق.",
        context_en: "4 new employees were assigned to the marketing department. In the first meeting, everyone was asking about desk locations and office hours, and no one was talking about the marketing plan.",
        correctStage: 'forming',
        correctRole: 'collaborator',
        feedback_ar: "هذا هو التشكيل (Forming). الفريق يحتاج إلى 'متعاون' (Collaborator) يذكرهم بالرؤية والأهداف الكبيرة ليتحركوا نحو الأمام.",
        feedback_en: "This is Forming. The team needs a Collaborator to remind them of the big vision and goals to move forward."
    },
    {
        id: 2,
        context_ar: "الفريق يعمل على مشروع منذ أسبوعين. ارتفعت نبرة الصوت في الاجتماع الأخير حول من يجب أن يقدم العرض النهائي. بدأ البعض يقول: 'أنا قمت بالعمل الأهم!'.",
        context_en: "The team has been on a project for two weeks. Voices went up in the last meeting about who should present the final deck. Some said: 'I did the most important work!'.",
        correctStage: 'storming',
        correctRole: 'communicator',
        feedback_ar: "هذا صراع (Storming). الفريق يحتاج إلى 'متصل' (Communicator) لتهدئة الأوضاع وإدارة العلاقات والتركيز على الروابط بين الأعضاء.",
        feedback_en: "This is Storming. The team needs a Communicator to calm things down, manage relationships, and focus on the bonds between members."
    },
    {
        id: 3,
        context_ar: "وافق الفريق أخيراً على استخدام نظام سحابي جديد. الآن هم يتناقشون بهدوء حول كيفية توزيع الملفات. أحدهم اقترح هيكلية واضحة والجميع بدأ يدون ملاحظات.",
        context_en: "The team finally agreed to use a new cloud system. Now they are calmly discussing how to distribute files. One suggested a clear structure and everyone started taking notes.",
        correctStage: 'norming',
        correctRole: 'contributor',
        feedback_ar: "هذا تطبيع (Norming). الفريق يحتاج إلى 'مساهم' (Contributor) يوفر البيانات والهيكلية العملية لنقل الأفكار إلى تنفيذ حقيقي.",
        feedback_en: "This is Norming. The team needs a Contributor to provide data and practical structure to turn ideas into actual implementation."
    },
    {
        id: 4,
        context_ar: "المشروع يسير بسلاسة تامة. الفريق يتخذ قرارات سريعة وصحيحة دون تدخل المدير. لكن المدير يخشى أن الفريق أصبح 'مرتاحاً جداً' ولا يرى المخاطر المستقبلية.",
        context_en: "The project is running perfectly smooth. The team makes quick, correct decisions without manager intervention. But the manager fears the team has become 'too comfortable' and doesn't see future risks.",
        correctStage: 'performing',
        correctRole: 'challenger',
        feedback_ar: "هذا إنجاز (Performing). الفريق يحتاج إلى 'متحدي' (Challenger) ليشجع التفكير النقدي ويمنع التراخي أو 'التفكير الجماعي' المفرط.",
        feedback_en: "This is Performing. The team needs a Challenger to encourage critical thinking and prevent complacency or excessive 'groupthink'."
    }
];

export default function TeamworkCodeGame() {
    const locale = useLocale();
    const isArabic = locale === 'ar';
    const [gameState, setGameState] = useState<'intro' | 'concepts' | 'play' | 'result'>('intro');
    const [currentScenarioIdx, setCurrentScenarioIdx] = useState(0);
    const [step, setStep] = useState<'stage' | 'role' | 'feedback'>('stage');
    const [selectedStage, setSelectedStage] = useState<string | null>(null);
    const [selectedRole, setSelectedRole] = useState<string | null>(null);
    const [score, setScore] = useState(0);
    const [history, setHistory] = useState<any[]>([]);

    const currentScenario = SCENARIOS[currentScenarioIdx];

    const handleStageSelect = (id: string) => {
        if (step !== 'stage') return;
        setSelectedStage(id);
        setStep('role');
    };

    const handleRoleSelect = (id: string) => {
        if (step !== 'role') return;
        setSelectedRole(id);
        
        // Calculate points (up to 2 per scenario: 1 for stage, 1 for role)
        let scenarioPoints = 0;
        if (id === currentScenario.correctRole) scenarioPoints += 1;
        if (selectedStage === currentScenario.correctStage) scenarioPoints += 1;
        
        setScore(prev => prev + scenarioPoints);
        setHistory(prev => [...prev, { 
            scenarioId: currentScenario.id, 
            stageId: selectedStage, 
            roleId: id,
            points: scenarioPoints
        }]);
        setStep('feedback');
    };

    const handleNext = () => {
        if (currentScenarioIdx < SCENARIOS.length - 1) {
            setCurrentScenarioIdx(prev => prev + 1);
            setStep('stage');
            setSelectedStage(null);
            setSelectedRole(null);
        } else {
            setGameState('result');
        }
    };

    const handleRestart = () => {
        setGameState('intro');
        setCurrentScenarioIdx(0);
        setStep('stage');
        setSelectedStage(null);
        setSelectedRole(null);
        setScore(0);
        setHistory([]);
    };

    const totalPossible = SCENARIOS.length * 2;
    const scorePercentage = (score / totalPossible) * 100;

    return (
        <div className="min-h-screen bg-slate-50 py-10 px-4 md:px-8 font-sans" dir={isArabic ? 'rtl' : 'ltr'}>
            <div className="max-w-5xl mx-auto space-y-8">
                
                {/* Header */}
                <div className="text-center space-y-4">
                    <h1 className="text-4xl md:text-5xl font-black text-slate-900 tracking-tight">
                        {isArabic ? "شفرة العمل الجماعي" : "Teamwork Code Game"}
                    </h1>
                    <div className="flex items-center justify-center gap-2">
                         <span className="h-1 w-12 bg-purple-500 rounded-full" />
                         <p className="text-lg text-slate-500 font-medium">
                            {isArabic ? "فك رموز ديناميكيات الفريق والقيادة الموقفية" : "Decoding team dynamics and situational leadership"}
                        </p>
                         <span className="h-1 w-12 bg-purple-500 rounded-full" />
                    </div>
                </div>

                {gameState === 'intro' && (
                    <Card className="border-none shadow-xl overflow-hidden animate-in fade-in zoom-in duration-500">
                        <div className="flex flex-col md:flex-row">
                            <div className="md:w-1/2 p-12 bg-white flex flex-col justify-center space-y-6">
                                <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-purple-100 text-purple-700 text-xs font-bold w-fit">
                                    <Trophy className="size-3" />
                                    {isArabic ? "تحدي القادة" : "LEADERS CHALLENGE"}
                                </div>
                                <h2 className="text-3xl font-bold text-slate-800">
                                    {isArabic ? "اكتشف 'الشفرة' الخفية لفريقك" : "Discover your team's hidden 'Code'"}
                                </h2>
                                <p className="text-slate-600 leading-relaxed">
                                    {isArabic ? "هل تعرف في أي مرحلة يمر فريقك الآن؟ وهل تقدم لهم الدعم الصحيح؟ هذه اللعبة ستختبر قدرتك على تشخيص حالة الفريق واختيار الدور القيادي الأنسب." : "Do you know what stage your team is going through right now? Are you giving them the right support? This game tests your ability to diagnose team status and choose the best leadership role."}
                                </p>
                                <Button size="lg" onClick={() => setGameState('concepts')} className="bg-purple-600 hover:bg-purple-700 h-14 rounded-xl px-10 text-lg font-bold">
                                    {isArabic ? "ابدأ الرحلة" : "Start Journey"}
                                    {isArabic ? <ChevronLeft className="mr-2" /> : <ChevronRight className="ml-2" />}
                                </Button>
                            </div>
                            <div className="md:w-1/2 bg-purple-900 p-12 text-white flex items-center justify-center relative overflow-hidden">
                                <LayoutGrid className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 size-80 text-white/5" />
                                <div className="grid grid-cols-2 gap-4 relative z-10 w-full">
                                    {STAGES.map((s, i) => (
                                        <div key={i} className={cn("p-6 rounded-2xl flex flex-col items-center gap-3 text-center transition-transform hover:scale-105", s.color)}>
                                            <s.icon className="size-8" />
                                            <span className="font-bold text-xs">{isArabic ? s.title_ar.split('(')[0] : s.id.toUpperCase()}</span>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </div>
                    </Card>
                )}

                {gameState === 'concepts' && (
                    <div className="space-y-10 animate-in fade-in slide-in-from-bottom-4">
                        <div className="text-center space-y-2">
                             <h2 className="text-2xl font-bold text-slate-800">{isArabic ? "أساسيات اللعبة" : "Game Fundamentals"}</h2>
                             <p className="text-slate-500">{isArabic ? "تعرف على المراحل الأربع والأدوار الأربعة لتتمكن من اللعب" : "Learn the 4 stages and 4 roles to be able to play"}</p>
                        </div>
                        
                        <div className="grid md:grid-cols-2 gap-8">
                             {/* Stages */}
                             <div className="space-y-4">
                                 <h3 className="font-black text-purple-700 uppercase tracking-widest text-sm flex items-center gap-2">
                                     <Activity className="size-4" />
                                     {isArabic ? "مراحل بناء الفريق" : "Stages of Building"}
                                 </h3>
                                 <div className="grid gap-3">
                                     {STAGES.map((s, i) => (
                                         <div key={i} className="bg-white p-4 rounded-xl border border-slate-100 flex gap-4 items-center">
                                             <div className={cn("size-10 rounded-lg flex items-center justify-center text-white shrink-0", s.color)}>
                                                 <s.icon className="size-5" />
                                             </div>
                                             <div>
                                                 <div className="font-bold text-slate-800">{isArabic ? s.title_ar : s.title_en}</div>
                                                 <div className="text-xs text-slate-500">{isArabic ? s.desc_ar : s.desc_en}</div>
                                             </div>
                                         </div>
                                     ))}
                                 </div>
                             </div>

                             {/* Roles */}
                             <div className="space-y-4">
                                 <h3 className="font-black text-purple-700 uppercase tracking-widest text-sm flex items-center gap-2">
                                     <Users className="size-4" />
                                     {isArabic ? "أداور الفاعلية" : "Effectiveness Roles"}
                                 </h3>
                                 <div className="grid gap-3">
                                     {ROLES.map((r, i) => (
                                         <div key={i} className="bg-white p-4 rounded-xl border border-slate-100 flex gap-4 items-center">
                                             <div className={cn("size-10 rounded-lg flex items-center justify-center text-white shrink-0", r.color)}>
                                                 <r.icon className="size-5" />
                                             </div>
                                             <div>
                                                 <div className="font-bold text-slate-800">{isArabic ? r.title_ar : r.title_en}</div>
                                                 <div className="text-xs text-slate-500">{isArabic ? r.desc_ar : r.desc_en}</div>
                                             </div>
                                         </div>
                                     ))}
                                 </div>
                             </div>
                        </div>

                        <div className="flex justify-center">
                            <Button size="lg" onClick={() => setGameState('play')} className="bg-slate-900 hover:bg-black px-12 h-14 rounded-2xl text-lg font-bold shadow-xl">
                                {isArabic ? "أنا مستعد، لنبدأ التحليل" : "I'm ready, let's start analysis"}
                            </Button>
                        </div>
                    </div>
                )}

                {gameState === 'play' && (
                    <div className="max-w-4xl mx-auto space-y-8 animate-in fade-in zoom-in-95">
                        
                         {/* Progress */}
                         <div className="space-y-2">
                            <div className="flex justify-between text-sm font-bold text-slate-400">
                                <span>{isArabic ? `السيناريو ${currentScenarioIdx + 1} من ${SCENARIOS.length}` : `Scenario ${currentScenarioIdx + 1} of ${SCENARIOS.length}`}</span>
                                <span>{Math.round(((currentScenarioIdx + 0.5) / SCENARIOS.length) * 100)}%</span>
                            </div>
                            <Progress value={((currentScenarioIdx + 0.5) / SCENARIOS.length) * 100} />
                        </div>

                        <Card className="border-none shadow-2xl overflow-hidden bg-white">
                            <div className="p-1 w-full bg-gradient-to-r from-purple-600 via-indigo-600 to-blue-600" />
                            <CardHeader className="p-10 pb-6 space-y-4 text-center">
                                <div className="flex justify-center">
                                    <div className="bg-purple-50 text-purple-600 p-3 rounded-full">
                                        <MessageSquare className="size-8" />
                                    </div>
                                </div>
                                <CardTitle className="text-2xl font-bold text-slate-800 leading-relaxed italic">
                                    "{isArabic ? currentScenario.context_ar : currentScenario.context_en}"
                                </CardTitle>
                            </CardHeader>
                            
                            <CardContent className="p-10 pt-0 space-y-10">
                                
                                {step === 'stage' && (
                                    <div className="space-y-6 animate-in slide-in-from-bottom-2">
                                        <div className="text-center">
                                            <h4 className="text-lg font-bold text-slate-700">1. {isArabic ? "في أي مرحلة يعيش الفريق الآن؟" : "What stage is the team in?"}</h4>
                                        </div>
                                        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                                            {STAGES.map((s) => (
                                                <button
                                                    key={s.id}
                                                    onClick={() => handleStageSelect(s.id)}
                                                    className="group flex flex-col items-center gap-4 p-6 rounded-2xl border-2 border-slate-100 hover:border-purple-300 hover:bg-purple-50 transition-all"
                                                >
                                                    <div className={cn("size-12 rounded-xl flex items-center justify-center text-white transition-transform group-hover:scale-110", s.color)}>
                                                        <s.icon className="size-6" />
                                                    </div>
                                                    <span className="font-bold text-xs md:text-sm text-slate-700 leading-tight">
                                                        {isArabic ? s.title_ar.split('(')[0] : s.title_en.split(' ')[0]}
                                                    </span>
                                                </button>
                                            ))}
                                        </div>
                                    </div>
                                )}

                                {step === 'role' && (
                                    <div className="space-y-6 animate-in slide-in-from-right-4">
                                        <div className="text-center">
                                            <h4 className="text-lg font-bold text-slate-700">2. {isArabic ? "أي دور يحتاجونه للتحرك للأمام؟" : "Which role do they need to move forward?"}</h4>
                                            <p className="text-sm text-slate-400 mt-1">{isArabic ? `لقد اخترت مرحلة: ${STAGES.find(s => s.id === selectedStage)?.title_ar}` : `You chose stage: ${STAGES.find(s => s.id === selectedStage)?.title_en}`}</p>
                                        </div>
                                        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                                            {ROLES.map((r) => (
                                                <button
                                                    key={r.id}
                                                    onClick={() => handleRoleSelect(r.id)}
                                                    className="group flex flex-col items-center gap-4 p-6 rounded-2xl border-2 border-slate-100 hover:border-indigo-300 hover:bg-indigo-50 transition-all"
                                                >
                                                    <div className={cn("size-12 rounded-xl flex items-center justify-center text-white transition-transform group-hover:scale-110", r.color)}>
                                                        <r.icon className="size-6" />
                                                    </div>
                                                    <span className="font-bold text-xs md:text-sm text-slate-700 leading-tight">
                                                        {isArabic ? r.title_ar.split('(')[0] : r.title_en}
                                                    </span>
                                                </button>
                                            ))}
                                        </div>
                                    </div>
                                )}

                                {step === 'feedback' && (
                                    <div className="space-y-8 animate-in zoom-in-95">
                                        <div className="grid grid-cols-2 gap-6">
                                            <div className={cn(
                                                "p-6 rounded-2xl border-2 flex flex-col items-center gap-2",
                                                selectedStage === currentScenario.correctStage ? "border-emerald-200 bg-emerald-50" : "border-rose-200 bg-rose-50"
                                            )}>
                                                <span className="text-xs font-bold text-slate-400">{isArabic ? "التشخيص (المرحلة)" : "Diagnosis (Stage)"}</span>
                                                <div className="font-bold text-slate-800">
                                                    {isArabic ? STAGES.find(s => s.id === selectedStage)?.title_ar.split('(')[0] : STAGES.find(s => s.id === selectedStage)?.title_en}
                                                </div>
                                                {selectedStage === currentScenario.correctStage ? <CheckCircle2 className="size-5 text-emerald-500" /> : <AlertCircle className="size-5 text-rose-500" />}
                                            </div>

                                            <div className={cn(
                                                "p-6 rounded-2xl border-2 flex flex-col items-center gap-2",
                                                selectedRole === currentScenario.correctRole ? "border-emerald-200 bg-emerald-50" : "border-rose-200 bg-rose-50"
                                            )}>
                                                <span className="text-xs font-bold text-slate-400">{isArabic ? "الحل (الدور)" : "Solution (Role)"}</span>
                                                <div className="font-bold text-slate-800">
                                                    {isArabic ? ROLES.find(r => r.id === selectedRole)?.title_ar.split('(')[0] : ROLES.find(r => r.id === selectedRole)?.title_en}
                                                </div>
                                                {selectedRole === currentScenario.correctRole ? <CheckCircle2 className="size-5 text-emerald-500" /> : <AlertCircle className="size-5 text-rose-500" />}
                                            </div>
                                        </div>

                                        <div className="bg-slate-900 text-white p-8 rounded-2xl space-y-4">
                                            <div className="flex items-center gap-2 text-purple-400 font-black tracking-widest text-sm">
                                                <Info className="size-4" />
                                                {isArabic ? "تفسير الشفرة" : "CODE EXPLANATION"}
                                            </div>
                                            <p className="text-lg leading-relaxed">
                                                {isArabic ? currentScenario.feedback_ar : currentScenario.feedback_en}
                                            </p>
                                        </div>

                                        <div className="flex justify-end">
                                            <Button size="lg" onClick={handleNext} className="bg-purple-600 hover:bg-purple-700 h-14 px-10 rounded-xl font-bold">
                                                {currentScenarioIdx < SCENARIOS.length - 1 ? (isArabic ? "السيناريو التالي" : "Next Scenario") : (isArabic ? "عرض النتائج" : "Show Results")}
                                                {isArabic ? <ChevronLeft className="mr-2" /> : <ChevronRight className="ml-2" />}
                                            </Button>
                                        </div>
                                    </div>
                                )}
                            </CardContent>
                        </Card>
                    </div>
                )}

                {gameState === 'result' && (
                    <Card className="border-none shadow-2xl overflow-hidden bg-white animate-in zoom-in duration-700">
                         <div className="bg-slate-900 p-16 text-center text-white space-y-8">
                             <div className="inline-block relative">
                                <Trophy className="size-24 text-yellow-400" />
                                <div className="absolute -top-4 -right-4 bg-purple-600 size-10 rounded-full flex items-center justify-center font-black text-sm ring-4 ring-slate-900 animate-bounce">
                                    {score}
                                </div>
                             </div>
                             <div className="space-y-4">
                                 <h2 className="text-4xl font-black">{isArabic ? "مستوى الوعي الديناميكي" : "Dynamic Awareness Level"}</h2>
                                 <div className="h-2 w-48 bg-white/10 rounded-full mx-auto overflow-hidden">
                                     <div className="h-full bg-purple-500" style={{ width: `${scorePercentage}%` }} />
                                 </div>
                             </div>
                             
                             <div className="max-w-xl mx-auto">
                                 <p className="text-2xl font-bold text-purple-200 leading-tight">
                                     {scorePercentage === 100 ? (isArabic ? "أنت سيد شفرات العمل الجماعي! لديك بصيرة قيادية استثنائية." : "You are the Master of Teamwork Codes! You have exceptional leadership insight.") :
                                      scorePercentage >= 70 ? (isArabic ? "أداء رائع، أنت تفهم كيف تتحرك الفرق وتعرف متى تتدخل." : "Great performance, you understand how teams move and know when to intervene.") :
                                      (isArabic ? "بداية جيدة، تحتاج إلى التعمق أكثر في فهم احتياجات الفريق في كل مرحلة." : "Good start, you need to dive deeper into understanding team needs at each stage.")}
                                 </p>
                             </div>

                             <div className="pt-8">
                                 <Button onClick={handleRestart} variant="outline" className="text-black border-white/20 hover:bg-white/10 h-14 px-10 rounded-2xl font-bold gap-2">
                                     <RotateCcw className="size-5" />
                                     {isArabic ? "إعادة التحدي" : "Restart Challenge"}
                                 </Button>
                             </div>
                         </div>

                         <CardContent className="p-16">
                            <h3 className="text-2xl font-black text-slate-800 mb-10 flex items-center gap-3">
                                <LayoutGrid className="size-6 text-purple-600" />
                                {isArabic ? "تحليل أدائك القيادي" : "Leadership Performance Analysis"}
                            </h3>
                            
                            <div className="grid gap-8">
                                {history.map((h, i) => (
                                    <div key={i} className="flex gap-6 p-6 rounded-3xl border border-slate-100 bg-slate-50/50">
                                        <div className={cn(
                                            "size-16 rounded-2xl flex items-center justify-center font-black text-2xl shrink-0",
                                            h.points === 2 ? "bg-emerald-100 text-emerald-600" : h.points === 1 ? "bg-amber-100 text-amber-600" : "bg-rose-100 text-rose-600"
                                        )}>
                                            {h.points}/2
                                        </div>
                                        <div className="space-y-3 flex-1">
                                            <div className="font-bold text-lg text-slate-800">
                                                {isArabic ? `السيناريو ${h.scenarioId}` : `Scenario ${h.scenarioId}`}
                                            </div>
                                            <p className="text-slate-500 text-sm italic">
                                                "{isArabic ? SCENARIOS[i].context_ar : SCENARIOS[i].context_en}"
                                            </p>
                                            <div className="flex flex-wrap gap-2">
                                                <span className={cn("px-3 py-1 rounded-full text-xs font-bold", h.stageId === SCENARIOS[i].correctStage ? "bg-emerald-100 text-emerald-700" : "bg-rose-100 text-rose-700")}>
                                                    {isArabic ? STAGES.find(s => s.id === h.stageId)?.title_ar.split('(')[0] : STAGES.find(s => s.id === h.stageId)?.title_en}
                                                </span>
                                                <span className={cn("px-3 py-1 rounded-full text-xs font-bold", h.roleId === SCENARIOS[i].correctRole ? "bg-emerald-100 text-emerald-700" : "bg-rose-100 text-rose-700")}>
                                                    {isArabic ? ROLES.find(r => r.id === h.roleId)?.title_ar.split('(')[0] : ROLES.find(r => r.id === h.roleId)?.title_en}
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                ))}
                            </div>

                            <div className="mt-16 bg-gradient-to-br from-purple-50 to-blue-50 p-10 rounded-3xl border border-purple-100 flex flex-col md:flex-row items-center gap-8">
                                <div className="bg-white p-6 rounded-full shadow-lg">
                                    <Puzzle className="size-16 text-purple-600" />
                                </div>
                                <div className="space-y-4">
                                    <h4 className="text-xl font-bold text-slate-800">
                                        {isArabic ? "هل تريد تفعيل 'الشفرة' في مؤسستك؟" : "Want to activate the 'Code' in your organization?"}
                                    </h4>
                                    <p className="text-slate-600 leading-relaxed">
                                        {isArabic ? "دراسة النظريات شيء، وتطبيقها في بيئة عمل حقيقية شيء آخر. نحن في IVORY نستخدم هذه اللعبة كأداة تشخيصية قوية في جلسات الكوتشينج للفرق لمساعدة القادة على القفز بمجموعاتهم إلى مرحلة الإنجاز القصوى." : "Studying theories is one thing, and applying them in a real work environment is another. At IVORY, we use this game as a powerful diagnostic tool in team coaching sessions to help leaders jump their groups to the maximum performing stage."}
                                    </p>
                                    <Button className="bg-purple-600 hover:bg-purple-700 font-bold h-12 px-8 rounded-xl shadow-lg">
                                        {isArabic ? "اطلب ورشة عمل لفريقك" : "Request a workshop for your team"}
                                    </Button>
                                </div>
                            </div>
                         </CardContent>
                    </Card>
                )}
            </div>
        </div>
    );
}
