'use client';

import { useState, useMemo } from 'react';
import { useTranslations, useLocale } from 'next-intl';
import { cn } from '@/lib/cn';
import { 
    ChevronRight, 
    ChevronLeft, 
    Trophy, 
    Users, 
    Target, 
    Swords, 
    ShieldCheck, 
    Play,
    RotateCcw,
    CheckCircle2,
    AlertCircle,
    XCircle,
    Info,
    ArrowRight,
    ArrowLeft
} 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-indigo-600 h-full transition-all duration-500 ease-out" 
            style={{ width: `${value}%` }} 
        />
    </div>
);

// Game Data
const DYSFUNCTIONS = [
    {
        id: 5,
        title_ar: "عدم الاهتمام بالنتائج",
        title_en: "Inattention to Results",
        color: "bg-emerald-500",
        icon: Trophy,
        desc_ar: "التركيز على المكانة الشخصية أو نجاح الأقسام الفردية بدلاً من النجاح الكلي للفريق.",
        desc_en: "Focusing on personal status or individual success instead of collective team outcomes."
    },
    {
        id: 4,
        title_ar: "تجنب المساءلة",
        title_en: "Avoidance of Accountability",
        color: "bg-amber-500",
        icon: Users,
        desc_ar: "التردد في لفت انتباه الزملاء إلى الأداء غير المرضي أو السلوكيات التي تضر الفريق.",
        desc_en: "Hesitating to call out peers on counterproductive behaviors or low performance."
    },
    {
        id: 3,
        title_ar: "نقص الالتزام",
        title_en: "Lack of Commitment",
        color: "bg-orange-500",
        icon: Target,
        desc_ar: "الغموض في الاتجاه والأولويات مما يؤدي إلى نقص الثقة في القرارات المتخذة.",
        desc_en: "Lack of clarity or buy-in, leading to ambiguity about direction and priorities."
    },
    {
        id: 2,
        title_ar: "الخوف من الصراع",
        title_en: "Fear of Conflict",
        color: "bg-rose-500",
        icon: Swords,
        desc_ar: "السعي وراء 'الانسجام المصطنع' وتجنب النقاشات الأيديولوجية الساخنة والضرورية.",
        desc_en: "Seeking artificial harmony over constructive, unfiltered debate of ideas."
    },
    {
        id: 1,
        title_ar: "غياب الثقة",
        title_en: "Absence of Trust",
        color: "bg-blue-600",
        icon: ShieldCheck,
        desc_ar: "عدم رغبة الأعضاء في الانفتاح أمام بعضهم البعض بشأن أخطائهم ونقاط ضعفهم.",
        desc_en: "Unwillingness to be vulnerable or open about mistakes and weaknesses."
    }
];

const SCENARIOS = [
    {
        id: 1,
        title_ar: "المشروع المتعثر",
        title_en: "The Stalled Project",
        context_ar: "مشروع مشترك بين الأقسام تأخر بشكل كبير. الجميع يوافق في الاجتماعات ولكن لا يوجد تقدم. يتبادل الأعضاء الأعذار أو يلومون الأقسام الأخرى.",
        context_en: "A cross-departmental project is significantly delayed. Everyone agrees in meetings but no progress is made. Members offer excuses or blame other departments.",
        choices: [
            {
                id: 'A',
                text_ar: "تصعيد الأمر للإدارة العليا لاتخاذ قرارات حازمة.",
                text_en: "Escalate the matter to senior management for firm decisions.",
                points: 1,
                card: 'red',
                feedback_ar: "البطاقة الحمراء: هذا حل مؤقت يتجاهل جذور المشكلة وقد يضعف ثقة الفريق.",
                feedback_en: "Red Card: This is a temporary fix that ignores the root cause and may damage team trust."
            },
            {
                id: 'B',
                text_ar: "تعديل الجدول الزمني دون مناقشة أسباب الفشل.",
                text_en: "Adjust the schedule without discussing the reasons for failure.",
                points: 2,
                card: 'orange',
                feedback_ar: "البطاقة البرتقالية: حل مقبول لكنه قد لا يمنع تكرار المشكلة في المستقبل.",
                feedback_en: "Orange Card: Acceptable solution but may not prevent the problem from recurring."
            },
            {
                id: 'C',
                text_ar: "تسهيل مناقشة صريحة ومباشرة حول العوائق الحقيقية والمسؤوليات.",
                text_en: "Facilitate a candid and direct discussion about real obstacles and responsibilities.",
                points: 3,
                card: 'green',
                feedback_ar: "البطاقة الخضراء: الحل الأمثل! يعالج المشكلة من جذورها ويعزز المساءلة.",
                feedback_en: "Green Card: Ideal solution! Addresses the root cause and fosters accountability."
            }
        ]
    },
    {
        id: 2,
        title_ar: "مخاوف صامتة",
        title_en: "Unspoken Concerns",
        context_ar: "خلال جلسة تخطيط استراتيجي، تم عرض فرصة جديدة. البعض وافق بحماس، والبعض الآخر ظل صامتاً. لاحقاً، علم القائد أن الصامتين لديهم شكوك كبيرة.",
        context_en: "During a strategic planning session, a new opportunity was presented. Some agreed enthusiastically, others remained silent. Later, the leader learns the silent ones have major doubts.",
        choices: [
            {
                id: 'A',
                text_ar: "المضي قدماً في التنفيذ طالما لم يعترض أحد رسمياً.",
                text_en: "Proceed with implementation as long as no one formally objected.",
                points: 1,
                card: 'red',
                feedback_ar: "البطاقة الحمراء: تجاهل الصمت يؤدي إلى نقص الالتزام وفشل المبادرة لاحقاً.",
                feedback_en: "Red Card: Ignoring silence leads to lack of commitment and future failure."
            },
            {
                id: 'B',
                text_ar: "سؤال الأعضاء الصامتين بشكل فردي لاحقاً لمعرفة رأيهم.",
                text_en: "Individually ask the silent members later to know their opinion.",
                points: 2,
                card: 'orange',
                feedback_ar: "البطاقة البرتقالية: خطوة جيدة لكنها لا تبني شجاعة المواجهة داخل الفريق.",
                feedback_en: "Orange Card: Good step but doesn't build courage for face-to-face team conflict."
            },
            {
                id: 'C',
                text_ar: "استدعاء الصمت في الاجتماع وتشجيع الآراء المعارضة وتعدين الصراع.",
                text_en: "Call out the silence in the meeting and encourage dissenting views to mine conflict.",
                points: 3,
                card: 'green',
                feedback_ar: "البطاقة الخضراء: رائع! يحول 'الانسجام المصطنع' إلى صراع بناء يؤدي لالتزام حقيقي.",
                feedback_en: "Green Card: Great! Converts 'artificial harmony' into healthy conflict leading to true buy-in."
            }
        ]
    },
    {
        id: 3,
        title_ar: "النجم الصاعد مقابل الفريق",
        title_en: "The Star vs The Team",
        context_ar: "مندوب مبيعات يحقق أرقاماً خيالية لكنه يستهلك موارد الفريق بشكل غير عادل ويخالف الأهداف الجماعية. أداء الفريق الكلي يعاني.",
        context_en: "A star performer hits amazing numbers but unfairly consumes team resources and conflicts with collective goals. Overall team performance suffers.",
        choices: [
            {
                id: 'A',
                text_ar: "الاحتفاء بنجاحاته الفردية كقدوة للآخرين.",
                text_en: "Celebrate his individual success as a role model for others.",
                points: 1,
                card: 'red',
                feedback_ar: "البطاقة الحمراء: هذا يعزز اختيار المصالح الشخصية على نتائج الفريق.",
                feedback_en: "Red Card: This reinforces prioritizing personal interests over team results."
            },
            {
                id: 'B',
                text_ar: "تعديل أهداف الفريق لتناسب مساره الناجح.",
                text_en: "Adjust team goals to fit his successful path.",
                points: 2,
                card: 'orange',
                feedback_ar: "البطاقة البرتقالية: قد ينقذ الأرقام قصيرة المدى لكنه يدمر تماسك الفريق.",
                feedback_en: "Orange Card: May save short-term numbers but destroys team cohesion."
            },
            {
                id: 'C',
                text_ar: "ربط أهدافه الفردية بالنتائج الجماعية ومعالجة استنزاف الموارد.",
                text_en: "Align individual targets with collective results and address resource drains.",
                points: 3,
                card: 'green',
                feedback_ar: "البطاقة الخضراء: ممتاز! يضع 'النتائج الجماعية' فوق الغرور الشخصي.",
                feedback_en: "Green Card: Excellent! Puts 'collective results' above personal ego."
            }
        ]
    },
    {
        id: 4,
        title_ar: "لحظة ضعف",
        title_en: "Moment of Vulnerability",
        context_ar: "فشل أحد القادة في الفريق في الوفاء بوعود مهمة بسبب ظروف شخصية، وهو يخشى الاعتراف بذلك خوفاً من اهتزاز صورته.",
        context_en: "A team leader failed to meet key promises due to personal circumstances and is afraid to admit it for fear of damaging his image.",
        choices: [
            {
                id: 'A',
                text_ar: "محاولة إخفاء الخطأ وتمريره بجهد إضافي.",
                text_en: "Try to hide the mistake and cover it with extra effort.",
                points: 1,
                card: 'red',
                feedback_ar: "البطاقة الحمراء: إخفاء الأخطاء يدمر الثقة ويمنع الفريق من تقديم المساعدة.",
                feedback_en: "Red Card: Hiding mistakes destroys trust and prevents the team from helping."
            },
            {
                id: 'B',
                text_ar: "الاعتذار بشكل عام دون توضيح الأسباب أو المشاعر.",
                text_en: "Apologize generally without clarifying reasons or feelings.",
                points: 2,
                card: 'orange',
                feedback_ar: "البطاقة البرتقالية: اعتذار جيد، لكنه يفتقد للشفافية المطلوبة لبناء ثقة عميقة.",
                feedback_en: "Orange Card: Good apology, but lacks the transparency needed for deep trust."
            },
            {
                id: 'C',
                text_ar: "مشاركة الفشل بصراحة وإظهار الضعف لطلب الدعم من الزملاء.",
                text_en: "Sincerely share the failure and show vulnerability to ask for peer support.",
                points: 3,
                card: 'green',
                feedback_ar: "البطاقة الخضراء: رائع! الضعف هو أساس الثقة. هذا التصرف يقوي الروابط الإنسانية.",
                feedback_en: "Green Card: Great! Vulnerability is the foundation of trust. This builds human bonds."
            }
        ]
    },
    {
        id: 5,
        title_ar: "اتفاق غير مقتنع",
        title_en: "Disagree and Commit",
        context_ar: "اتخذ الفريق قراراً بالأغلبية حول استراتيجية جديدة، لكن هناك عضوين لا يزالان غير مقتنعين تماماً.",
        context_en: "The team made a majority decision on a new strategy, but two members remain unconvinced.",
        choices: [
            {
                id: 'A',
                text_ar: "تجاهل آرائهم طالما أن الأغلبية وافقت.",
                text_en: "Ignore their views as long as the majority agreed.",
                points: 1,
                card: 'red',
                feedback_ar: "البطاقة الحمراء: تجاهل الاعتراضات يؤدي لضعف الالتزام والانسحاب النفسي.",
                feedback_en: "Red Card: Ignoring objections leads to poor commitment and mental withdrawal."
            },
            {
                id: 'B',
                text_ar: "محاولة إقناعهم بالقوة بالقرار المتخذ.",
                text_en: "Try to force them to agree with the decision.",
                points: 2,
                card: 'orange',
                feedback_ar: "البطاقة البرتقالية: الإقناع القسري لا يصنع التزاماً حقيقياً.",
                feedback_en: "Orange Card: Forced persuasion doesn't create true commitment."
            },
            {
                id: 'C',
                text_ar: "الاستماع لمخاوفهم ثم الطلب منهم 'عدم الموافقة والالتزام' بالقرار الجماعي.",
                text_en: "Listen to their concerns, then ask them to 'disagree and commit' to the collective decision.",
                points: 3,
                card: 'green',
                feedback_ar: "البطاقة الخضراء: الحل المثالي! يسمح بسماع صوت الجميع مع ضمان التحرك الموحد.",
                feedback_en: "Green Card: Ideal solution! Allows all voices to be heard while ensuring unified action."
            }
        ]
    }
];

export default function FiveDysfunctionsGame() {
    const locale = useLocale();
    const isArabic = locale === 'ar';
    const [gameState, setGameState] = useState<'intro' | 'pyramid' | 'play' | 'result'>('intro');
    const [currentScenarioIdx, setCurrentScenarioIdx] = useState(0);
    const [score, setScore] = useState(0);
    const [answers, setAnswers] = useState<any[]>([]);
    const [selectedChoice, setSelectedChoice] = useState<string | null>(null);
    const [showFeedback, setShowFeedback] = useState(false);

    const currentScenario = SCENARIOS[currentScenarioIdx];

    const handleStart = () => setGameState('pyramid');
    const handleNextToPlay = () => setGameState('play');

    const handleChoiceSelect = (choiceId: string) => {
        if (showFeedback) return;
        setSelectedChoice(choiceId);
    };

    const handleConfirmChoice = () => {
        if (!selectedChoice) return;
        const choice = currentScenario.choices.find(c => c.id === selectedChoice);
        if (!choice) return;

        setScore(prev => prev + choice.points);
        setAnswers(prev => [...prev, { scenarioId: currentScenario.id, choice }]);
        setShowFeedback(true);
    };

    const handleNextScenario = () => {
        if (currentScenarioIdx < SCENARIOS.length - 1) {
            setCurrentScenarioIdx(prev => prev + 1);
            setSelectedChoice(null);
            setShowFeedback(false);
        } else {
            setGameState('result');
        }
    };

    const handleRestart = () => {
        setGameState('intro');
        setCurrentScenarioIdx(0);
        setScore(0);
        setAnswers([]);
        setSelectedChoice(null);
        setShowFeedback(false);
    };

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

    const resultMessage = useMemo(() => {
        if (scorePercentage >= 85) return isArabic ? "فريق استثنائي! متماسك وفعال." : "Exceptional Team! Cohesive and effective.";
        if (scorePercentage >= 60) return isArabic ? "فريق جيد، يحتاج لبعض الضبط في المساءلة والثقة." : "Good Team, needs some fine-tuning in accountability and trust.";
        return isArabic ? "فريق يعاني من اختلالات عميقة، يتطلب تدخل جذري." : "Team suffering from deep dysfunctions, requires radical intervention.";
    }, [scorePercentage, isArabic]);

    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-extrabold text-slate-900 bg-clip-text text-transparent bg-gradient-to-r from-purple-600 to-indigo-600">
                        {isArabic ? "لعبة الاختلالات الخمسة" : "The Five Dysfunctions Game"}
                    </h1>
                    <p className="text-lg text-slate-600 max-w-2xl mx-auto">
                        {isArabic ? "لعبة تفاعلية لاستكشاف مشاكل فرق العمل وبناء منظومة عمل قوية وفعالة." : "An interactive game to explore team dysfunctions and build a strong, effective workplace."}
                    </p>
                </div>

                {/* GAME STAGES */}
                
                {gameState === 'intro' && (
                    <Card className="border-none shadow-2xl overflow-hidden animate-in fade-in slide-in-from-bottom-4 duration-700">
                        <div className="grid md:grid-cols-2">
                            <div className="bg-gradient-to-br from-purple-700 to-indigo-800 p-12 text-white flex flex-col justify-center gap-6">
                                <h2 className="text-3xl font-bold">
                                    {isArabic ? "هل فريقك مستعد للمواجهة؟" : "Is your team ready?"}
                                </h2>
                                <p className="text-purple-100 leading-relaxed text-lg">
                                    {isArabic ? "مستوحاة من كتاب باتريك لينسيوني، هذه اللعبة ستضعك أمام سيناريوهات واقعية لتكتشف كيف تنهار الفرق وكيف تنهض." : "Inspired by Patrick Lencioni's book, this game puts you in front of realistic scenarios to discover how teams fail and how they rise."}
                                </p>
                                <div className="space-y-3">
                                    <div className="flex items-center gap-3">
                                        <CheckCircle2 className="size-5 text-emerald-400" />
                                        <span>{isArabic ? "3 سيناريوهات واقعية" : "3 Realistic Scenarios"}</span>
                                    </div>
                                    <div className="flex items-center gap-3">
                                        <CheckCircle2 className="size-5 text-emerald-400" />
                                        <span>{isArabic ? "نظام تقييم البطاقات" : "Card Scoring System"}</span>
                                    </div>
                                    <div className="flex items-center gap-3">
                                        <CheckCircle2 className="size-5 text-emerald-400" />
                                        <span>{isArabic ? "تحليل نهائي للأداء" : "Final Performance Analysis"}</span>
                                    </div>
                                </div>
                                <Button size="lg" onClick={handleStart} className="w-fit bg-emerald-500 hover:bg-emerald-600 text-white font-bold px-10 h-14 rounded-xl shadow-lg mt-4 group">
                                    {isArabic ? "ابدأ اللعبة" : "Start Game"}
                                    {isArabic ? <ChevronLeft className="mr-2 group-hover:-translate-x-1 transition-transform" /> : <ChevronRight className="ml-2 group-hover:translate-x-1 transition-transform" />}
                                </Button>
                            </div>
                            <div className="relative h-[400px] md:h-auto bg-slate-100 flex items-center justify-center p-10">
                                <div className="relative w-full max-w-xs flex flex-col-reverse gap-1">
                                    {[1, 2, 3, 4, 5].map((level, idx) => (
                                        <div 
                                            key={level} 
                                            className={cn(
                                                "h-16 rounded-lg shadow-md flex items-center justify-center text-white font-bold text-xs md:text-sm animate-in zoom-in-50 duration-500",
                                                DYSFUNCTIONS[4-idx].color
                                            )}
                                            style={{ 
                                                width: `${100 - (level-1)*15}%`,
                                                margin: '0 auto',
                                                animationDelay: `${idx * 150}ms`
                                            }}
                                        >
                                            {isArabic ? DYSFUNCTIONS[4-idx].title_ar : DYSFUNCTIONS[4-idx].title_en}
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </div>
                    </Card>
                )}

                {gameState === 'pyramid' && (
                    <div className="space-y-8 animate-in fade-in slide-in-from-right-4 duration-500">
                        <div className="flex items-center justify-between">
                            <h2 className="text-2xl font-bold text-slate-800">
                                {isArabic ? "افهم الهرم: الاختلالات الخمسة" : "Understand the Pyramid: The 5 Dysfunctions"}
                            </h2>
                            <Button variant="outline" onClick={handleNextToPlay} className="font-bold gap-2">
                                {isArabic ? "تجاوز للمهام" : "Skip to Tasks"}
                                {isArabic ? <ChevronLeft className="size-4" /> : <ChevronRight className="size-4" />}
                            </Button>
                        </div>

                        <div className="grid md:grid-cols-5 gap-4">
                            {DYSFUNCTIONS.slice().reverse().map((d, idx) => (
                                <Card key={d.id} className="hover:shadow-lg transition-all border-none group overflow-hidden">
                                    <div className={cn("h-2", d.color)} />
                                    <CardContent className="p-6 space-y-4">
                                        <div className={cn("size-12 rounded-xl flex items-center justify-center text-white", d.color)}>
                                            <d.icon className="size-6" />
                                        </div>
                                        <h3 className="font-bold text-lg leading-tight">{isArabic ? d.title_ar : d.title_en}</h3>
                                        <p className="text-sm text-slate-500 leading-relaxed">
                                            {isArabic ? d.desc_ar : d.desc_en}
                                        </p>
                                    </CardContent>
                                </Card>
                            ))}
                        </div>

                        <div className="flex justify-center pt-8">
                             <Button size="lg" onClick={handleNextToPlay} className="bg-indigo-600 hover:bg-indigo-700 text-white font-bold px-12 h-14 rounded-2xl shadow-xl">
                                {isArabic ? "مستعد للتحدي؟ ابدأ المهام!" : "Ready for the challenge? Start tasks!"}
                            </Button>
                        </div>
                    </div>
                )}

                {gameState === 'play' && (
                    <div className="max-w-3xl mx-auto space-y-8 animate-in fade-in zoom-in-95 duration-500">
                        
                        {/* Progress */}
                        <div className="space-y-2">
                            <div className="flex justify-between text-sm font-bold text-slate-500">
                                <span>{isArabic ? `المهمة ${currentScenarioIdx + 1} من ${SCENARIOS.length}` : `Task ${currentScenarioIdx + 1} of ${SCENARIOS.length}`}</span>
                                <span>{Math.round(((currentScenarioIdx) / SCENARIOS.length) * 100)}%</span>
                            </div>
                            <Progress value={((currentScenarioIdx) / SCENARIOS.length) * 100} className="h-2 bg-slate-200" />
                        </div>

                        <Card className="border-none shadow-2xl">
                            <CardHeader className="bg-slate-900 text-white p-8 space-y-2">
                                <div className="flex items-center gap-2 text-indigo-400 font-bold mb-2">
                                    <Play className="size-4" />
                                    {isArabic ? "سيناريو واقعي" : "Realistic Scenario"}
                                </div>
                                <CardTitle className="text-3xl font-bold">
                                    {isArabic ? currentScenario.title_ar : currentScenario.title_en}
                                </CardTitle>
                                <CardDescription className="text-slate-300 text-lg leading-relaxed">
                                    {isArabic ? currentScenario.context_ar : currentScenario.context_en}
                                </CardDescription>
                            </CardHeader>
                            <CardContent className="p-8 space-y-6">
                                <h4 className="font-bold text-slate-700 text-lg">
                                    {isArabic ? "ماذا ستفعل كقائد للفريق؟" : "What would you do as a team leader?"}
                                </h4>
                                <div className="grid gap-4">
                                    {currentScenario.choices.map((choice) => (
                                        <button
                                            key={choice.id}
                                            onClick={() => handleChoiceSelect(choice.id)}
                                            disabled={showFeedback}
                                            className={cn(
                                                "w-full text-start p-5 rounded-2xl border-2 transition-all flex items-center gap-4 relative overflow-hidden group",
                                                selectedChoice === choice.id 
                                                    ? "border-indigo-600 bg-indigo-50" 
                                                    : "border-slate-100 hover:border-slate-300 bg-white",
                                                showFeedback && choice.id === selectedChoice && choice.card === 'green' && "border-emerald-500 bg-emerald-50",
                                                showFeedback && choice.id === selectedChoice && choice.card === 'orange' && "border-orange-500 bg-orange-50",
                                                showFeedback && choice.id === selectedChoice && choice.card === 'red' && "border-rose-500 bg-rose-50"
                                            )}
                                        >
                                            <div className={cn(
                                                "size-10 rounded-full flex items-center justify-center font-bold text-lg shrink-0",
                                                selectedChoice === choice.id ? "bg-indigo-600 text-white" : "bg-slate-100 text-slate-500"
                                            )}>
                                                {choice.id}
                                            </div>
                                            <span className="font-semibold text-slate-800 flex-1">
                                                {isArabic ? choice.text_ar : choice.text_en}
                                            </span>
                                            
                                            {showFeedback && choice.id === selectedChoice && (
                                                <div className="absolute right-4 top-1/2 -translate-y-1/2">
                                                    {choice.card === 'green' && <CheckCircle2 className="size-8 text-emerald-500" />}
                                                    {choice.card === 'orange' && <AlertCircle className="size-8 text-orange-500" />}
                                                    {choice.card === 'red' && <XCircle className="size-8 text-rose-500" />}
                                                </div>
                                            )}
                                        </button>
                                    ))}
                                </div>

                                {showFeedback && (
                                    <div className={cn(
                                        "p-6 rounded-2xl animate-in slide-in-from-top-2 duration-300 flex gap-4",
                                        answers[answers.length-1].choice.card === 'green' ? "bg-emerald-50" : 
                                        answers[answers.length-1].choice.card === 'orange' ? "bg-orange-50" : "bg-rose-50"
                                    )}>
                                        <Info className={cn("size-6 shrink-0 mt-1", 
                                            answers[answers.length-1].choice.card === 'green' ? "text-emerald-600" : 
                                            answers[answers.length-1].choice.card === 'orange' ? "text-orange-600" : "text-rose-600"
                                        )} />
                                        <p className={cn("font-medium", 
                                            answers[answers.length-1].choice.card === 'green' ? "text-emerald-800" : 
                                            answers[answers.length-1].choice.card === 'orange' ? "text-orange-800" : "text-rose-800"
                                        )}>
                                            {isArabic ? answers[answers.length-1].choice.feedback_ar : answers[answers.length-1].choice.feedback_en}
                                        </p>
                                    </div>
                                )}

                                <div className="flex justify-end pt-4">
                                    {!showFeedback ? (
                                        <Button 
                                            size="lg" 
                                            disabled={!selectedChoice} 
                                            onClick={handleConfirmChoice}
                                            className="bg-indigo-600 hover:bg-indigo-700 font-bold px-10 h-14 rounded-xl shadow-lg"
                                        >
                                            {isArabic ? "تأكيد الاختيار" : "Confirm Choice"}
                                        </Button>
                                    ) : (
                                        <Button 
                                            size="lg" 
                                            onClick={handleNextScenario}
                                            className="bg-slate-900 hover:bg-black font-bold px-10 h-14 rounded-xl shadow-lg group"
                                        >
                                            {currentScenarioIdx < SCENARIOS.length - 1 ? (isArabic ? "المهمة التالية" : "Next Task") : (isArabic ? "اعرض النتيجة" : "Show Results")}
                                            {isArabic ? <ChevronLeft className="mr-2 group-hover:-translate-x-1 transition-transform" /> : <ChevronRight className="ml-2 group-hover:translate-x-1 transition-transform" />}
                                        </Button>
                                    )}
                                </div>
                            </CardContent>
                        </Card>
                    </div>
                )}

                {gameState === 'result' && (
                    <div className="max-w-4xl mx-auto space-y-8 animate-in fade-in scale-95 duration-700">
                         <Card className="border-none shadow-2xl overflow-hidden">
                            <div className="bg-gradient-to-br from-slate-900 to-indigo-900 p-12 text-center text-white space-y-6">
                                <div className="size-24 rounded-full bg-indigo-500/20 flex items-center justify-center mx-auto ring-8 ring-indigo-500/10">
                                    <Trophy className="size-12 text-yellow-400" />
                                </div>
                                <div className="space-y-2">
                                    <h2 className="text-4xl font-black">
                                        {isArabic ? "تحليل أداء الفريق" : "Team Performance Analysis"}
                                    </h2>
                                    <p className="text-indigo-200 text-lg">
                                        {isArabic ? "بناءً على اختياراتك، إليك حالة فريقك:" : "Based on your choices, here is your team's state:"}
                                    </p>
                                </div>
                                
                                <div className="bg-white/10 rounded-3xl p-8 backdrop-blur-sm border border-white/10 max-w-xl mx-auto space-y-6">
                                    <div className="flex items-center justify-center gap-6">
                                        <div className="text-center">
                                            <div className="text-5xl font-black text-white">{score}</div>
                                            <div className="text-xs uppercase tracking-widest text-indigo-300 font-bold mt-1">{isArabic ? "النقاط" : "Points"}</div>
                                        </div>
                                        <div className="h-10 w-px bg-white/20" />
                                        <div className="text-center">
                                            <div className="text-5xl font-black text-white">{Math.round(scorePercentage)}%</div>
                                            <div className="text-xs uppercase tracking-widest text-indigo-300 font-bold mt-1">{isArabic ? "الكفاءة" : "Efficiency"}</div>
                                        </div>
                                    </div>
                                    <div className="h-1 bg-white/10 rounded-full overflow-hidden">
                                        <div className="h-full bg-emerald-400 transition-all duration-1000" style={{ width: `${scorePercentage}%` }} />
                                    </div>
                                    <h3 className="text-2xl font-bold leading-tight">
                                        {resultMessage}
                                    </h3>
                                </div>

                                <div className="pt-6">
                                    <Button onClick={handleRestart} variant="secondary" size="lg" className="bg-white text-slate-900 hover:bg-slate-100 px-10 h-14 rounded-2xl font-bold gap-2">
                                        <RotateCcw className="size-5" />
                                        {isArabic ? "إعادة اللعبة" : "Restart Game"}
                                    </Button>
                                </div>
                            </div>
                            <CardContent className="p-12 bg-white">
                                <h3 className="text-2xl font-bold text-slate-800 mb-8 border-b pb-4">
                                    {isArabic ? "ملخص القرارات" : "Decision Summary"}
                                </h3>
                                <div className="space-y-6">
                                    {answers.map((ans, idx) => (
                                        <div key={idx} className="flex gap-6 items-start">
                                            <div className={cn(
                                                "size-12 rounded-2xl shrink-0 flex items-center justify-center",
                                                ans.choice.card === 'green' ? "bg-emerald-100 text-emerald-600" : 
                                                ans.choice.card === 'orange' ? "bg-orange-100 text-orange-600" : "bg-rose-100 text-rose-600"
                                            )}>
                                                {ans.choice.card === 'green' ? <CheckCircle2 /> : <AlertCircle />}
                                            </div>
                                            <div className="space-y-1 flex-1">
                                                <div className="flex items-center justify-between">
                                                    <h4 className="font-bold text-slate-900 text-lg">
                                                        {isArabic ? SCENARIOS[idx].title_ar : SCENARIOS[idx].title_en}
                                                    </h4>
                                                    <span className="text-xs font-black uppercase text-slate-400">{ans.choice.points} pts</span>
                                                </div>
                                                <p className="text-slate-600 leading-relaxed font-medium">
                                                    "{isArabic ? ans.choice.text_ar : ans.choice.text_en}"
                                                </p>
                                                <p className="text-sm italic text-slate-400 pt-2 border-t mt-2">
                                                    {isArabic ? answers[idx].choice.feedback_ar : answers[idx].choice.feedback_en}
                                                </p>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                                <div className="mt-12 p-8 bg-indigo-50 rounded-3xl overflow-hidden relative">
                                    <div className="relative z-10 space-y-4">
                                        <h4 className="text-xl font-bold text-indigo-900">
                                            {isArabic ? "هل تريد تطوير فريقك فعلياً؟" : "Want to truly develop your team?"}
                                        </h4>
                                        <p className="text-indigo-700 leading-relaxed">
                                            {isArabic ? "هذه اللعبة هي مجرد بداية. التواصل الحقيقي يبدأ ببناء الثقة وتقبل الصراع البناء. نحن في IVORY نقدم ورش عمل متخصصة لتطبيق هذه المبادئ عملياً." : "This game is just the beginning. Real communication starts with building trust and embracing healthy conflict. At IVORY, we offer specialized workshops to apply these principles practically."}
                                        </p>
                                        <Button className="bg-indigo-600 hover:bg-indigo-700 text-white font-bold h-12 px-8 rounded-xl">
                                            {isArabic ? "تواصل معنا للمزيد" : "Contact us for more"}
                                        </Button>
                                    </div>
                                    <ShieldCheck className="absolute -bottom-10 -right-10 size-60 text-indigo-500/10 rotate-12" />
                                </div>
                            </CardContent>
                         </Card>
                    </div>
                )}
            </div>
        </div>
    );
}
