import { confirmAction } from '@/lib/confirm-action';
import React, { useState, useRef, useEffect } from 'react';
import { Head, useForm, usePage, router } from '@inertiajs/react';
import { AlertTriangle, ArrowLeft, Check, ChevronRight, Clock, FileAudio, Image as ImageIcon, List, Plus, Save, Target, Trophy, Trash2, Upload, Users, X } from 'lucide-react';
import { toast } from 'sonner';
import AuthenticatedLayout from '@/layouts/AuthenticatedLayout';
import RichTextEditor from '@/components/RichTextEditor';
import type { PageProps } from '@/types';

interface FormProps extends PageProps {
    subjects: Array<{ id: number; name: string }>;
    classes: Array<{ id: number; name: string }>;
    game: any | null;
}

export default function Form() {
    const { subjects, classes, game } = usePage<FormProps>().props;
    const isEditing = !!game;

    const defaultOptions = [
        { text: '', is_correct: true },
        { text: '', is_correct: false },
        { text: '', is_correct: false },
        { text: '', is_correct: false },
    ];

    const queryParams = new URLSearchParams(window.location.search);
    const requestedStep = queryParams.get('step');
    const initialStep = requestedStep === '3' ? 'questions' : requestedStep === '2' ? 'mode' : 'settings';
    const [activeTab, setActiveTab] = useState<'settings' | 'mode' | 'questions'>(initialStep);
    
    // Derived state for classes grouped by grade level
    const gradeLevels = [7, 8, 9];
    const firstAssignedClass = game?.classes?.[0];
    const assignedClassName = String(firstAssignedClass?.name || '');
    const assignedClassLevel = Number(firstAssignedClass?.level);
    const initialSelectedGrade = gradeLevels.includes(assignedClassLevel)
        ? assignedClassLevel
        : /(^|\s)IX(\s|$)/.test(assignedClassName)
            ? 9
            : /(^|\s)VIII(\s|$)/.test(assignedClassName)
                ? 8
                : 7;
    const [selectedGrade, setSelectedGrade] = useState<number>(initialSelectedGrade);


    const { data, setData, post, processing, errors } = useForm({
        _method: isEditing ? 'put' : 'post',
        title: game?.title || '',
        subject_id: game?.subject_id || '',
        synced_class_ids: game?.classes?.map((c: any) => c.id) || [],
        game_mode: game?.game_mode || 'serious',
        status: game?.status || 'draft',
        settings: {
            timer_seconds: game?.settings?.timer_seconds || 15,
        },
        items: game?.items?.length > 0 ? game.items : [
            { item_type: 'multiple_choice', question_text: '', question_image: null, options: [...defaultOptions] }
        ]
    });

    useEffect(() => {
        setData('_method', isEditing ? 'put' : 'post');
    }, [isEditing]);

    const gameModes = [
        {
            value: 'serious',
            name: 'Mode Serius',
            summary: 'Mandiri',
            description: 'Siswa mengerjakan quiz secara mandiri dengan alur standar.',
            icon: Target,
            selectedClass: 'border-primary-500 bg-primary-500/10 shadow-primary-500/10',
            iconClass: 'bg-primary-500/20 text-primary-400',
            radioClass: 'border-primary-500 bg-primary-500',
        },
        {
            value: 'live',
            name: 'Live Arena',
            summary: 'Multiplayer Individu',
            description: 'Pertandingan langsung antarsiswa dengan kendali dari layar guru.',
            icon: Clock,
            selectedClass: 'border-purple-500 bg-purple-500/10 shadow-purple-500/10',
            iconClass: 'bg-purple-500/20 text-purple-400',
            radioClass: 'border-purple-500 bg-purple-500',
        },
        {
            value: 'faction',
            name: 'Faction',
            summary: 'Antar Kelas',
            description: 'Skor siswa digabungkan untuk kompetisi dan klasemen antarkelas.',
            icon: Trophy,
            selectedClass: 'border-amber-500 bg-amber-500/10 shadow-amber-500/10',
            iconClass: 'bg-amber-500/20 text-amber-400',
            radioClass: 'border-amber-500 bg-amber-500',
        },
        {
            value: 'team_live',
            name: 'Team Quest',
            summary: '1 HP per Kelompok',
            description: 'Kelompok berkolaborasi bergiliran menggunakan satu perangkat.',
            icon: Users,
            selectedClass: 'border-sky-500 bg-sky-500/10 shadow-sky-500/10',
            iconClass: 'bg-sky-500/20 text-sky-400',
            radioClass: 'border-sky-500 bg-sky-500',
        },
    ];
    const selectedClasses = classes.filter((classItem) => data.synced_class_ids.includes(classItem.id));
    const selectedGradeRoman = selectedGrade === 7 ? 'VII' : selectedGrade === 8 ? 'VIII' : 'IX';
    const visibleClasses = classes.filter((classItem) => (
        classItem.name.includes(` ${selectedGradeRoman} `)
        || classItem.name.startsWith(`${selectedGradeRoman} `)
        || classItem.name === selectedGradeRoman
        || classItem.name.includes(` ${selectedGrade}`)
        || classItem.name.startsWith(`${selectedGrade}`)
    ));

    const validateBasicSettings = () => {
        if (data.title === '' || data.subject_id === '' || data.synced_class_ids.length === 0) {
            toast.error('Harap lengkapi Pengaturan Dasar terlebih dahulu (Judul, Mapel, Kelas).');
            return false;
        }

        return true;
    };

    const validateGameMode = () => {
        if (data.game_mode === 'faction' && data.synced_class_ids.length < 2) {
            toast.error('Mode Faction membutuhkan minimal 2 kelas yang dipilih!');
            return false;
        }

        return true;
    };

    const goToModeStep = () => {
        if (!validateBasicSettings()) {
            return;
        }

        setActiveTab('mode');
        window.scrollTo(0, 0);
    };

    const goToQuestionStep = () => {
        if (!validateBasicSettings() || !validateGameMode()) {
            return;
        }

        if (!isEditing) {
            const formData = { ...data, _redirect_to_edit: true, status: 'draft', items: [] };
            router.post(route('games.store'), formData as any, {
                forceFormData: true,
            });
        } else {
            setActiveTab('questions');
            window.scrollTo(0, 0);
        }
    };

    const submit = (e?: React.FormEvent) => {
        if (e) e.preventDefault();
        
        if (activeTab === 'settings') {
            goToModeStep();
            return;
        }

        if (activeTab === 'mode') {
            goToQuestionStep();
            return;
        }

        if (activeTab === 'questions') {
            const isValid = data.items.every((item: any) => {
                if (['multiple_choice', 'true_false'].includes(item.item_type || 'multiple_choice')) {
                    return item.options.some((opt: any) => opt.is_correct);
                }
                return true; 
            });
            
            if (!isValid && data.items.length > 0) {
                toast.error('Setiap soal Pilihan Ganda/Benar Salah harus memiliki minimal 1 jawaban benar!');
                return;
            }
        }

        if (!validateBasicSettings() || !validateGameMode()) {
            return;
        }

        if (isEditing) {
            post(route('games.update', game.id), {
                forceFormData: true,
                preserveScroll: true,
            });
        } else {
            post(route('games.store'), {
                forceFormData: true,
            });
        }
    };

    const itemErrors = (index: number) => Object.entries(errors)
        .filter(([key]) => key.startsWith(`items.${index}.`))
        .map(([, message]) => String(message));

    const addItem = () => {
        if (data.items.length >= 20) {
            toast.error('Maksimal 20 soal per kuis.');
            return;
        }
        setData('items', [...data.items, { item_type: 'multiple_choice', question_text: '', question_image: null, options: [...defaultOptions] }]);
    };

    const minimumItemCount = isEditing ? 1 : 5;

    const itemHasContent = (item: any) => {
        const questionText = String(item.question_text || '').replace(/<[^>]*>/g, '').trim();
        const optionHasContent = Array.isArray(item.options) && item.options.some((option: any) => (
            Object.entries(option).some(([key, value]) => {
                if (key === 'is_correct' || key === 'order' || key === 'token_index') {
                    return false;
                }
                if (typeof value === 'string') {
                    return value.trim() !== '';
                }
                return Array.isArray(value) && value.length > 0;
            })
        ));
        const metadataHasContent = item.metadata && Object.values(item.metadata).some((value: any) => {
            if (typeof value === 'string') {
                return value.trim() !== '';
            }
            return Array.isArray(value) && value.some((entry) => String(entry).trim() !== '');
        });

        return Boolean(questionText || item.question_image || item.audio_file || item.audio_path || optionHasContent || metadataHasContent);
    };

    const removeItem = async (index: number) => {
        if (data.items.length <= minimumItemCount) {
            toast.error(`Minimal harus ada ${minimumItemCount} soal.`);
            return;
        }
        if (
            itemHasContent(data.items[index])
            && !(await confirmAction(`Hapus Soal #${index + 1}? Isi soal yang belum disimpan akan hilang.`))
        ) {
            return;
        }
        const newItems = [...data.items];
        newItems.splice(index, 1);
        setData('items', newItems);
    };

    const updateItemText = (index: number, text: string) => {
        const newItems = [...data.items];
        newItems[index].question_text = text;
        setData('items', newItems);
    };

    const updateItemImage = (index: number, file: File | null) => {
        const newItems = [...data.items];
        newItems[index].question_image = file;
        setData('items', newItems);
    };

    const updateItemAudio = (index: number, file: File | null) => {
        const newItems = [...data.items];
        newItems[index].audio_file = file;
        setData('items', newItems);
    };

    const updateItemMetadata = (index: number, field: string, value: any) => {
        const newItems = [...data.items];
        newItems[index].metadata = {
            ...(newItems[index].metadata || {}),
            [field]: value,
        };
        setData('items', newItems);
    };

    const updateItemType = (index: number, type: string) => {
        const newItems = [...data.items];
        newItems[index].item_type = type;
        newItems[index].audio_file = null;
        
        if (type === 'true_false') {
            newItems[index].options = [
                { text: 'Benar', is_correct: true },
                { text: 'Salah', is_correct: false }
            ];
        } else if (type === 'multiple_choice') {
            newItems[index].options = [
                { text: '', is_correct: true },
                { text: '', is_correct: false },
                { text: '', is_correct: false },
                { text: '', is_correct: false },
            ];
        } else if (type === 'matching') {
            newItems[index].options = [
                { left: '', right: '' },
                { left: '', right: '' },
                { left: '', right: '' },
                { left: '', right: '' },
            ];
        } else if (type === 'grouping') {
            newItems[index].options = [
                { category: '', items: [''] },
                { category: '', items: [''] },
            ];
        } else if (type === 'sequencing') {
            newItems[index].options = [
                { text: '', order: 1 },
                { text: '', order: 2 },
                { text: '', order: 3 },
                { text: '', order: 4 },
            ];
        } else if (type === 'fill_in_the_blank') {
            if (!newItems[index].question_text.includes('[')) {
                newItems[index].question_text = 'Ini adalah contoh [1] rumpang.';
            }
            newItems[index].options = [
                { id: '1', answer: '' }
            ];
        } else if (type === 'jumbled_word') {
            newItems[index].options = [
                { answer: '' }
            ];
        } else if (type === 'spelling_bee') {
            newItems[index].options = [
                { answer: '', accept_variants: [] }
            ];
        } else if (type === 'sentence_rearrange') {
            newItems[index].options = [
                { text: '', order: 1 },
                { text: '', order: 2 }
            ];
        } else if (type === 'listen_and_build') {
            newItems[index].options = [];
            newItems[index].metadata = { transcript: '', replay_limit: 2 };
        } else if (type === 'error_hunter') {
            newItems[index].options = [
                { token_index: 0, correction: '', explanation: '' }
            ];
            newItems[index].metadata = {};
        } else if (type === 'secret_taboo') {
            newItems[index].options = [];
            newItems[index].metadata = {
                answer: '',
                aliases: [],
                forbidden_words: [''],
                clue_seconds: 45,
            };
        }
        
        setData('items', newItems);
    };

    const updateOption = (itemIndex: number, optionIndex: number, field: string, value: any) => {
        const newItems = [...data.items];
        
        if (field === 'is_correct' && value === true) {
            // Uncheck others if this one is set to correct
            newItems[itemIndex].options.forEach((opt: any, idx: number) => {
                opt.is_correct = idx === optionIndex;
            });
        } else if (field === 'items_array') {
             // For grouping: value is a comma separated string
             newItems[itemIndex].options[optionIndex] = {
                 ...newItems[itemIndex].options[optionIndex],
                 items: value.split(',').map((s: string) => s.trim()).filter((s: string) => s !== '')
             };
        } else if (field === 'accept_variants_array') {
             newItems[itemIndex].options[optionIndex] = {
                 ...newItems[itemIndex].options[optionIndex],
                 accept_variants: value.split(',').map((s: string) => s.trim()).filter((s: string) => s !== '')
             };
        } else {
            newItems[itemIndex].options[optionIndex] = {
                ...newItems[itemIndex].options[optionIndex],
                [field]: value
            };
        }
        
        setData('items', newItems);
    };

    const addOptionItem = (itemIndex: number) => {
        const newItems = [...data.items];
        const type = newItems[itemIndex].item_type;
        if (type === 'matching') {
            newItems[itemIndex].options.push({ left: '', right: '' });
        } else if (type === 'grouping') {
            newItems[itemIndex].options.push({ category: '', items: [] });
        } else if (type === 'sequencing') {
            newItems[itemIndex].options.push({ text: '', order: newItems[itemIndex].options.length + 1 });
        } else if (type === 'fill_in_the_blank') {
            newItems[itemIndex].options.push({ id: String(newItems[itemIndex].options.length + 1), answer: '' });
        } else if (type === 'sentence_rearrange') {
            newItems[itemIndex].options.push({ text: '', order: newItems[itemIndex].options.length + 1 });
        } else if (type === 'error_hunter') {
            newItems[itemIndex].options.push({ token_index: 0, correction: '', explanation: '' });
        }
        setData('items', newItems);
    };

    const removeOptionItem = (itemIndex: number, optionIndex: number) => {
        const newItems = [...data.items];
        newItems[itemIndex].options.splice(optionIndex, 1);
        
        // Re-order for sequencing
        if (newItems[itemIndex].item_type === 'sequencing' || newItems[itemIndex].item_type === 'sentence_rearrange') {
            newItems[itemIndex].options.forEach((opt: any, idx: number) => {
                opt.order = idx + 1;
            });
        }
        
        setData('items', newItems);
    };

    return (
        <AuthenticatedLayout
            title={isEditing ? 'Edit Quiz' : 'Buat Quiz Baru'}
            backHref="/games"
            hideMobileDock
        >
            <Head title={isEditing ? 'Edit Quiz' : 'Buat Quiz Baru'} />

            <div className="mb-4 sm:mb-6">
                {/* Wizard Steps */}
                <div className="mx-auto grid w-full max-w-3xl grid-cols-[minmax(0,1fr)_0.75rem_minmax(0,1fr)_0.75rem_minmax(0,1fr)] items-center gap-1 sm:grid-cols-[minmax(0,1fr)_2.5rem_minmax(0,1fr)_2.5rem_minmax(0,1fr)] sm:gap-3">
                        <button
                            type="button"
                            onClick={() => {
                                setActiveTab('settings');
                                window.scrollTo(0, 0);
                            }}
                            className={`flex min-w-0 items-center justify-center gap-1.5 rounded-full px-2 py-2 text-xs font-bold transition-all sm:gap-2 sm:px-5 sm:text-sm ${
                                activeTab === 'settings'
                                    ? 'bg-primary-500 text-slate-950 shadow-lg shadow-primary-500/30 ring-2 ring-primary-400/40'
                                    : 'border border-border/80 bg-surface text-text-muted hover:bg-surface-hover hover:text-text'
                            }`}
                        >
                            <div className={`flex h-4.5 w-4.5 shrink-0 items-center justify-center rounded-full text-[10px] font-extrabold sm:h-5 sm:w-5 sm:text-xs ${
                                activeTab === 'settings'
                                    ? 'bg-slate-950 text-primary-400 shadow-sm'
                                    : 'border border-border bg-surface-hover text-text-muted'
                            }`}>
                                1
                            </div>
                            <span className="sm:hidden">Dasar</span>
                            <span className="hidden sm:inline">Pengaturan Dasar</span>
                        </button>
                        <div className="h-0.5 w-full rounded-full bg-border/50" />
                        <button
                            type="button"
                            onClick={goToModeStep}
                            className={`flex min-w-0 items-center justify-center gap-1.5 rounded-full px-2 py-2 text-xs font-bold transition-all sm:gap-2 sm:px-5 sm:text-sm ${
                                activeTab === 'mode'
                                    ? 'bg-primary-500 text-slate-950 shadow-lg shadow-primary-500/30 ring-2 ring-primary-400/40'
                                    : 'border border-border/80 bg-surface text-text-muted hover:bg-surface-hover hover:text-text'
                            }`}
                        >
                            <div className={`flex h-4.5 w-4.5 shrink-0 items-center justify-center rounded-full text-[10px] font-extrabold sm:h-5 sm:w-5 sm:text-xs ${
                                activeTab === 'mode'
                                    ? 'bg-slate-950 text-primary-400 shadow-sm'
                                    : 'border border-border bg-surface-hover text-text-muted'
                            }`}>
                                2
                            </div>
                            <span className="sm:hidden">Mode</span>
                            <span className="hidden sm:inline">Mode Permainan</span>
                        </button>
                        <div className="h-0.5 w-full rounded-full bg-border/50" />
                        <button
                            type="button"
                            onClick={() => {
                                if (!isEditing && activeTab === 'settings') {
                                    if (validateBasicSettings()) {
                                        setActiveTab('mode');
                                        window.scrollTo(0, 0);
                                        toast.info('Pilih mode permainan sebelum membuat soal.');
                                    }
                                    return;
                                }
                                goToQuestionStep();
                            }}
                            className={`flex min-w-0 items-center justify-center gap-1.5 rounded-full px-2 py-2 text-xs font-bold transition-all sm:gap-2 sm:px-5 sm:text-sm ${
                                activeTab === 'questions'
                                    ? 'bg-primary-500 text-slate-950 shadow-lg shadow-primary-500/30 ring-2 ring-primary-400/40'
                                    : 'border border-border/80 bg-surface text-text-muted hover:bg-surface-hover hover:text-text'
                            }`}
                        >
                            <div className={`flex h-4.5 w-4.5 shrink-0 items-center justify-center rounded-full text-[10px] font-extrabold sm:h-5 sm:w-5 sm:text-xs ${
                                activeTab === 'questions'
                                    ? 'bg-slate-950 text-primary-400 shadow-sm'
                                    : 'border border-border bg-surface-hover text-text-muted'
                            }`}>
                                3
                            </div>
                            <span className="sm:hidden">Soal</span>
                            <span className="hidden sm:inline">Pembuatan Soal</span>
                        </button>
                </div>
            </div>

            <form onSubmit={submit} className="pb-24">
                {/* Step 1: Pengaturan Dasar */}
                <div className={`mx-auto max-w-5xl ${activeTab === 'settings' ? 'block' : 'hidden'}`}>
                    <div className="glass space-y-4 rounded-2xl border border-border/40 p-4 sm:space-y-5 sm:p-6">
                        <div>
                            <h3 className="text-base font-bold text-text sm:text-xl">Pengaturan Dasar</h3>
                            <p className="mt-1 text-xs text-text-muted sm:text-sm">Lengkapi identitas quiz, kelas tujuan, dan status publikasinya.</p>
                        </div>

                        <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
                            <div>
                                <label className="mb-2 block text-sm font-medium text-text-muted">Judul Quiz</label>
                                <input
                                    type="text"
                                    value={data.title}
                                    onChange={e => setData('title', e.target.value)}
                                    placeholder="Judul Quiz..."
                                    className="w-full rounded-xl border border-border/60 bg-surface px-4 py-3 text-sm text-text focus:border-primary-500 focus:ring-primary-500"
                                    required
                                />
                                {errors.title && <p className="mt-1 text-xs text-rose-400">{errors.title}</p>}
                            </div>

                            <div>
                                <label className="mb-2 block text-sm font-medium text-text-muted">Mata Pelajaran</label>
                                <select
                                    value={data.subject_id}
                                    onChange={e => setData('subject_id', e.target.value)}
                                    className="w-full rounded-xl border border-border/60 bg-surface px-4 py-3 text-sm text-text focus:border-primary-500 focus:ring-primary-500"
                                    required
                                >
                                    <option value="">Pilih Mapel...</option>
                                    {subjects.map(subject => (
                                        <option key={subject.id} value={subject.id}>{subject.name}</option>
                                    ))}
                                </select>
                                {errors.subject_id && <p className="mt-1 text-xs text-rose-400">{errors.subject_id}</p>}
                            </div>

                            <div>
                                <label className="mb-2 block text-sm font-medium text-text-muted">Waktu per Soal (Detik)</label>
                                <input
                                    type="number"
                                    min="5"
                                    max="300"
                                    value={data.settings.timer_seconds}
                                    onChange={e => setData('settings', { ...data.settings, timer_seconds: parseInt(e.target.value) || 15 })}
                                    className="w-full rounded-xl border border-border/60 bg-surface px-4 py-3 text-sm text-text focus:border-primary-500 focus:ring-primary-500"
                                    required
                                />
                                {errors['settings.timer_seconds'] && <p className="mt-1 text-xs text-rose-400">{errors['settings.timer_seconds']}</p>}
                            </div>
                        </div>

                        <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_260px]">
                            <section className="rounded-2xl border border-border/40 bg-surface-hover/30 p-4">
                                <div className="flex flex-wrap items-center justify-between gap-2">
                                    <div>
                                        <h4 className="text-sm font-bold text-text">Kelas yang Ditugaskan</h4>
                                        <p className="mt-0.5 text-xs text-text-muted">Pilih satu atau beberapa kelas.</p>
                                    </div>
                                    <span className="rounded-full border border-primary-500/25 bg-primary-500/10 px-2.5 py-1 text-xs font-bold text-primary-300">
                                        {selectedClasses.length} terpilih
                                    </span>
                                </div>

                                <div className="mt-3 grid grid-cols-3 gap-2">
                                    {gradeLevels.map(grade => (
                                        <button
                                            key={grade}
                                            type="button"
                                            onClick={() => setSelectedGrade(grade)}
                                            className={`rounded-lg border px-3 py-2 text-xs font-bold transition-all ${
                                                selectedGrade === grade
                                                    ? 'border-primary-500 bg-primary-500/15 text-primary-300'
                                                    : 'border-border/60 bg-surface text-text-muted hover:bg-surface-hover'
                                            }`}
                                        >
                                            Kelas {grade}
                                        </button>
                                    ))}
                                </div>

                                <div className="mt-3 flex min-h-10 flex-wrap gap-2">
                                    {visibleClasses.length > 0 ? visibleClasses.map(classItem => {
                                        const isSelected = data.synced_class_ids.includes(classItem.id);

                                        return (
                                            <label
                                                key={classItem.id}
                                                className={`flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-2 text-xs font-bold transition-all ${
                                                    isSelected
                                                        ? 'border-primary-500 bg-primary-500/15 text-text'
                                                        : 'border-border/60 bg-surface text-text-muted hover:bg-surface-hover'
                                                }`}
                                            >
                                                <span className={`flex h-4 w-4 shrink-0 items-center justify-center rounded border ${
                                                    isSelected ? 'border-primary-500 bg-primary-500 text-slate-950' : 'border-border/80'
                                                }`}>
                                                    {isSelected && <Check className="h-3 w-3 stroke-[3]" />}
                                                </span>
                                                <input
                                                    type="checkbox"
                                                    className="hidden"
                                                    checked={isSelected}
                                                    onChange={() => {
                                                        setData(
                                                            'synced_class_ids',
                                                            isSelected
                                                                ? data.synced_class_ids.filter((id: number) => id !== classItem.id)
                                                                : [...data.synced_class_ids, classItem.id],
                                                        );
                                                    }}
                                                />
                                                {classItem.name}
                                            </label>
                                        );
                                    }) : (
                                        <span className="py-2 text-xs italic text-text-muted">Tidak ada kelas pada tingkat ini.</span>
                                    )}
                                </div>

                                {errors.synced_class_ids && <p className="mt-2 text-xs text-rose-400">{errors.synced_class_ids}</p>}

                                {selectedClasses.length > 0 && (
                                    <div className="mt-3 flex flex-wrap items-center gap-2 border-t border-border/40 pt-3">
                                        <span className="text-xs font-medium text-text-muted">Terpilih:</span>
                                        {selectedClasses.map(classItem => (
                                            <span key={classItem.id} className="flex items-center gap-1.5 rounded-lg border border-primary-500/30 bg-primary-500/20 px-2.5 py-1 text-xs font-semibold text-primary-300">
                                                {classItem.name}
                                                <button
                                                    type="button"
                                                    onClick={() => setData('synced_class_ids', data.synced_class_ids.filter((id: number) => id !== classItem.id))}
                                                    aria-label={`Hapus kelas ${classItem.name}`}
                                                    className="rounded-full p-0.5 transition-colors hover:bg-primary-500/30"
                                                >
                                                    <X className="h-3 w-3" />
                                                </button>
                                            </span>
                                        ))}
                                    </div>
                                )}
                            </section>

                            <section className="rounded-2xl border border-border/40 bg-surface-hover/30 p-4">
                                <label className="mb-2 block text-sm font-bold text-text">Status Quiz</label>
                                <select
                                    value={data.status}
                                    onChange={e => setData('status', e.target.value)}
                                    className="w-full rounded-xl border border-border/60 bg-surface px-4 py-3 text-sm text-text focus:border-primary-500 focus:ring-primary-500"
                                >
                                    <option value="draft">Draft (Disembunyikan)</option>
                                    <option value="published">Publish (Bisa Dimainkan)</option>
                                </select>
                                <p className="mt-2 text-xs leading-relaxed text-text-muted">
                                    Draft hanya terlihat oleh guru. Publish membuat quiz tersedia bagi siswa.
                                </p>
                            </section>
                        </div>
                    </div>
                </div>

                {/* Step 2: Mode Permainan */}
                <div className={`mx-auto max-w-5xl ${activeTab === 'mode' ? 'block' : 'hidden'}`}>
                    <div className="glass space-y-4 rounded-2xl border border-border/40 p-4 sm:space-y-5 sm:p-6">
                        <div>
                            <h3 className="text-base font-bold text-text sm:text-xl">Pilih Mode Permainan</h3>
                            <p className="mt-1 text-xs text-text-muted sm:text-sm">Mode menentukan cara siswa bermain dan bagaimana hasil quiz dihitung.</p>
                        </div>

                        <div className="grid gap-4 md:grid-cols-2">
                            {gameModes.map((mode) => {
                                const Icon = mode.icon;
                                const isSelected = data.game_mode === mode.value;

                                return (
                                    <label
                                        key={mode.value}
                                        className={`cursor-pointer rounded-2xl border-2 p-4 transition-all sm:p-5 ${
                                            isSelected
                                                ? `${mode.selectedClass} shadow-lg`
                                                : 'border-border/60 bg-surface hover:border-border hover:bg-surface-hover'
                                        }`}
                                    >
                                        <input
                                            type="radio"
                                            name="game_mode"
                                            value={mode.value}
                                            checked={isSelected}
                                            onChange={(event) => setData('game_mode', event.target.value)}
                                            className="sr-only"
                                        />
                                        <div className="flex items-start gap-4">
                                            <div className={`rounded-xl p-3 ${isSelected ? mode.iconClass : 'bg-surface-hover text-text-muted'}`}>
                                                <Icon className="h-6 w-6" />
                                            </div>
                                            <div className="min-w-0 flex-1">
                                                <div className="flex items-start justify-between gap-3">
                                                    <div>
                                                        <h4 className="font-black text-text">{mode.name}</h4>
                                                        <p className="mt-0.5 text-xs font-bold text-text-muted">{mode.summary}</p>
                                                    </div>
                                                    <span className={`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border ${
                                                        isSelected ? mode.radioClass : 'border-border/80'
                                                    }`}>
                                                        {isSelected && <span className="h-2 w-2 rounded-full bg-white" />}
                                                    </span>
                                                </div>
                                                <p className="mt-3 text-xs leading-relaxed text-text-muted sm:text-sm">{mode.description}</p>
                                            </div>
                                        </div>
                                    </label>
                                );
                            })}
                        </div>

                        {errors.game_mode && <p className="text-sm text-rose-400">{errors.game_mode}</p>}
                        {data.game_mode === 'faction' && data.synced_class_ids.length < 2 && (
                            <div className="flex items-start gap-2 rounded-xl border border-amber-500/30 bg-amber-500/10 p-3 text-sm text-amber-200">
                                <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
                                Mode Faction membutuhkan minimal dua kelas. Kembali ke Pengaturan Dasar untuk menambah kelas.
                            </div>
                        )}
                    </div>
                </div>

                {/* Step 3: Pembuatan Soal */}
                <div className={`space-y-6 max-w-5xl mx-auto ${activeTab === 'questions' ? 'block' : 'hidden'}`}>
                    {data.items.map((item: any, index: number) => (
                        <div key={index} className="glass relative rounded-2xl border border-border/40 p-4 sm:p-6">
                            {itemErrors(index).length > 0 && (
                                <div role="alert" className="mb-4 rounded-xl border border-rose-500/30 bg-rose-500/10 p-3 text-sm text-rose-300">
                                    {itemErrors(index).map((message, errorIndex) => <p key={`${index}-${errorIndex}`}>{message}</p>)}
                                </div>
                            )}

                            <div className="mb-5 flex flex-col md:flex-row md:items-center justify-between gap-3 border-b border-border/30 pb-4">
                                <h4 className="text-base font-bold sm:text-lg">Soal #{index + 1}</h4>

                                <div className="flex flex-wrap items-center gap-3 justify-end">
                                    <div className="flex items-center gap-2">
                                        <label htmlFor={`item-type-${index}`} className="text-xs text-text-muted font-medium shrink-0">Tipe Soal</label>
                                        <select
                                            id={`item-type-${index}`}
                                            value={item.item_type || 'multiple_choice'}
                                            onChange={e => updateItemType(index, e.target.value)}
                                            className="rounded-xl bg-surface/80 border border-border/50 px-3 py-2 text-sm font-semibold focus:border-emerald-500 focus:ring-emerald-500"
                                        >
                                            <optgroup label="Tipe Soal Umum">
                                                <option value="multiple_choice">Pilihan Ganda</option>
                                                <option value="true_false">Benar / Salah</option>
                                                <option value="matching">Menjodohkan</option>
                                                <option value="grouping">Mengelompokkan</option>
                                                <option value="sequencing">Mengurutkan</option>
                                                <option value="fill_in_the_blank">Kalimat Rumpang</option>
                                            </optgroup>
                                            <optgroup label="Khusus Bahasa & Kosakata">
                                                <option value="jumbled_word">Susun Kata (Jumbled Word)</option>
                                                <option value="spelling_bee">Spelling Bee (Dikte Audio)</option>
                                                <option value="sentence_rearrange">Susun Kalimat (Sentence Rearrange)</option>
                                            </optgroup>
                                            {data.game_mode === 'team_live' && (
                                                <optgroup label="Khusus Team Quest">
                                                    <option value="listen_and_build">Listen and Build</option>
                                                    <option value="error_hunter">Error Hunter</option>
                                                    <option value="secret_taboo">Secret Taboo</option>
                                                </optgroup>
                                            )}
                                        </select>
                                    </div>

                                    <button
                                        type="button"
                                        onClick={() => removeItem(index)}
                                        disabled={data.items.length <= minimumItemCount}
                                        aria-label={`Hapus Soal #${index + 1}`}
                                        className="inline-flex items-center gap-1.5 rounded-xl border border-rose-500/30 bg-rose-500/10 px-3.5 py-2 text-xs font-bold text-rose-400 transition-colors hover:border-rose-500/50 hover:bg-rose-500/20 disabled:cursor-not-allowed disabled:border-border/40 disabled:bg-surface/50 disabled:text-text-muted disabled:opacity-40"
                                    >
                                        <Trash2 className="h-3.5 w-3.5" />
                                        <span>Hapus soal</span>
                                    </button>
                                </div>
                            </div>
                            
                            <div className="mb-4">
                                <RichTextEditor
                                    compact={true}
                                    value={item.question_text}
                                    onChange={text => updateItemText(index, text)}
                                    placeholder="Tuliskan pertanyaan di sini..."
                                    className="mb-3"
                                />

                                {/* Upload Image Area */}
                                <div className="mt-2">
                                    {(item.question_image && typeof item.question_image === 'string') ? (
                                        <div className="relative inline-block">
                                            <img src={`/storage/${item.question_image}`} alt={`Soal ${index + 1}`} className="h-32 object-contain rounded-lg border border-border/50 bg-black/5" />
                                            <button 
                                                type="button" 
                                                onClick={() => updateItemImage(index, null)}
                                                className="absolute -top-2 -right-2 bg-rose-500 text-white p-1 rounded-full hover:bg-rose-600 shadow-md"
                                            >
                                                <X className="w-4 h-4" />
                                            </button>
                                        </div>
                                    ) : (item.question_image instanceof File) ? (
                                        <div className="relative inline-block">
                                            <img src={URL.createObjectURL(item.question_image)} alt="Preview" className="h-32 object-contain rounded-lg border border-border/50 bg-black/5" />
                                            <button 
                                                type="button" 
                                                onClick={() => updateItemImage(index, null)}
                                                className="absolute -top-2 -right-2 bg-rose-500 text-white p-1 rounded-full hover:bg-rose-600 shadow-md"
                                            >
                                                <X className="w-4 h-4" />
                                            </button>
                                        </div>
                                    ) : (
                                        <label className="flex items-center gap-2 cursor-pointer w-fit text-sm text-text-muted hover:text-primary-500 transition-colors border border-dashed border-border/60 rounded-lg px-4 py-2 hover:border-primary-500 hover:bg-primary-500/5">
                                            <ImageIcon className="w-4 h-4" />
                                            <span>Upload Gambar (Opsional)</span>
                                            <input 
                                                type="file" 
                                                accept="image/*" 
                                                className="hidden" 
                                                onChange={e => e.target.files && e.target.files[0] && updateItemImage(index, e.target.files[0])} 
                                            />
                                        </label>
                                    )}
                                </div>
                            </div>

                            {['multiple_choice', 'true_false'].includes(item.item_type || 'multiple_choice') && (
                                <div className={`grid gap-3 ${item.item_type === 'true_false' ? 'sm:grid-cols-2' : 'sm:grid-cols-2'}`}>
                                    {item.options.map((opt: any, optIndex: number) => (
                                        <div key={optIndex} className={`flex items-center gap-3 px-4 py-3 rounded-2xl border transition-all ${
                                            opt.is_correct
                                                ? 'border-2 border-primary-500 bg-primary-500/15 shadow-sm shadow-primary-500/20'
                                                : 'border-border/60 bg-surface hover:bg-surface-hover'
                                        }`}>
                                            <button
                                                type="button"
                                                onClick={() => updateOption(index, optIndex, 'is_correct', true)}
                                                className={`w-5 h-5 rounded-full border-2 flex items-center justify-center shrink-0 transition-all ${
                                                    opt.is_correct
                                                        ? 'border-primary-500 bg-primary-500 text-slate-950 font-bold'
                                                        : 'border-border/80 bg-surface'
                                                }`}
                                            >
                                                {opt.is_correct && <div className="w-2 h-2 rounded-full bg-slate-950 dark:bg-white" />}
                                            </button>
                                            
                                            {item.item_type === 'true_false' ? (
                                                <div className="w-full font-semibold text-center text-lg">
                                                    <span className={optIndex === 0 ? "text-blue-500" : "text-rose-500"}>{opt.text}</span>
                                                </div>
                                            ) : (
                                                <input
                                                    type="text"
                                                    value={opt.text}
                                                    onChange={e => updateOption(index, optIndex, 'text', e.target.value)}
                                                    placeholder={`Opsi ${optIndex + 1}`}
                                                    className="w-full bg-transparent border-none focus:ring-0 text-sm font-semibold text-text placeholder:text-text-muted/60"
                                                    required
                                                />
                                            )}
                                        </div>
                                    ))}
                                </div>
                            )}

                            {item.item_type === 'matching' && (
                                <div className="space-y-3">
                                    <div className="flex items-center justify-between">
                                        <span className="text-sm font-medium text-text-muted">Pasangan (Kiri - Kanan)</span>
                                        <button type="button" onClick={() => addOptionItem(index)} className="text-xs text-primary-500 hover:text-primary-600 flex items-center gap-1 font-medium"><Plus className="w-3 h-3"/> Tambah Pasangan</button>
                                    </div>
                                    {item.options.map((opt: any, optIndex: number) => (
                                        <div key={optIndex} className="flex items-center gap-2">
                                            <input
                                                type="text"
                                                value={opt.left || ''}
                                                onChange={e => updateOption(index, optIndex, 'left', e.target.value)}
                                                placeholder={`Istilah ${optIndex + 1}`}
                                                className="w-1/2 rounded-lg bg-surface border border-border/50 px-3 py-2 text-sm focus:border-primary-500"
                                                required
                                            />
                                            <span className="text-text-muted">-</span>
                                            <input
                                                type="text"
                                                value={opt.right || ''}
                                                onChange={e => updateOption(index, optIndex, 'right', e.target.value)}
                                                placeholder={`Definisi ${optIndex + 1}`}
                                                className="w-1/2 rounded-lg bg-surface border border-border/50 px-3 py-2 text-sm focus:border-primary-500"
                                                required
                                            />
                                            <button type="button" onClick={() => removeOptionItem(index, optIndex)} className="text-rose-400 hover:bg-rose-400/10 p-1.5 rounded-lg"><Trash2 className="w-4 h-4"/></button>
                                        </div>
                                    ))}
                                </div>
                            )}

                            {item.item_type === 'grouping' && (
                                <div className="space-y-3">
                                    <div className="flex items-center justify-between">
                                        <span className="text-sm font-medium text-text-muted">Kategori & Item (pisahkan item dengan koma)</span>
                                        <button type="button" onClick={() => addOptionItem(index)} className="text-xs text-primary-500 hover:text-primary-600 flex items-center gap-1 font-medium"><Plus className="w-3 h-3"/> Tambah Kategori</button>
                                    </div>
                                    {item.options.map((opt: any, optIndex: number) => (
                                        <div key={optIndex} className="flex flex-col gap-2 p-3 border border-border/50 rounded-xl bg-surface/50">
                                            <div className="flex items-center gap-2">
                                                <input
                                                    type="text"
                                                    value={opt.category || ''}
                                                    onChange={e => updateOption(index, optIndex, 'category', e.target.value)}
                                                    placeholder={`Nama Kategori ${optIndex + 1}`}
                                                    className="w-full rounded-lg bg-surface border border-border/50 px-3 py-2 text-sm font-bold focus:border-primary-500"
                                                    required
                                                />
                                                <button type="button" onClick={() => removeOptionItem(index, optIndex)} className="text-rose-400 hover:bg-rose-400/10 p-1.5 rounded-lg"><Trash2 className="w-4 h-4"/></button>
                                            </div>
                                            <input
                                                type="text"
                                                value={opt.items ? opt.items.join(', ') : ''}
                                                onChange={e => updateOption(index, optIndex, 'items_array', e.target.value)}
                                                placeholder="Apel, Jeruk, Mangga"
                                                className="w-full rounded-lg bg-surface border border-border/50 px-3 py-2 text-sm focus:border-primary-500"
                                                required
                                            />
                                        </div>
                                    ))}
                                </div>
                            )}

                            {item.item_type === 'sequencing' && (
                                <div className="space-y-3">
                                    <div className="text-xs text-primary-600 bg-primary-500/10 p-3 rounded-xl font-medium">
                                        💡 Tips: Bisa digunakan untuk <strong>menyusun kata menjadi kalimat</strong> (masukkan 1 kata per baris), atau <strong>menyusun kalimat menjadi paragraf / langkah-langkah</strong>.
                                    </div>
                                    <div className="flex items-center justify-between">
                                        <span className="text-sm font-medium text-text-muted">Urutan Benar (dari atas ke bawah)</span>
                                        <button type="button" onClick={() => addOptionItem(index)} className="text-xs text-primary-500 hover:text-primary-600 flex items-center gap-1 font-medium"><Plus className="w-3 h-3"/> Tambah Baris</button>
                                    </div>
                                    <div className="grid gap-2">
                                        {item.options.map((opt: any, optIndex: number) => (
                                            <div key={optIndex} className="flex items-center gap-2">
                                                <div className="w-8 h-8 rounded-lg bg-primary-500/10 text-primary-600 font-bold flex items-center justify-center shrink-0">
                                                    {opt.order}
                                                </div>
                                                <input
                                                    type="text"
                                                    value={opt.text || ''}
                                                    onChange={e => updateOption(index, optIndex, 'text', e.target.value)}
                                                    placeholder={`Kata / Kalimat ke-${optIndex + 1}`}
                                                    className="w-full rounded-lg bg-surface border border-border/50 px-3 py-2 text-sm focus:border-primary-500"
                                                    required
                                                />
                                                <button type="button" onClick={() => removeOptionItem(index, optIndex)} className="text-rose-400 hover:bg-rose-400/10 p-1.5 rounded-lg shrink-0"><Trash2 className="w-4 h-4"/></button>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {item.item_type === 'fill_in_the_blank' && (
                                <div className="space-y-3">
                                    <div className="text-xs text-primary-600 bg-primary-500/10 p-3 rounded-xl font-medium">
                                        Cara buat soal rumpang: Ketikkan tag [1], [2], dst pada teks soal di atas. Lalu masukkan jawaban untuk setiap tag di bawah ini.
                                    </div>
                                    <div className="flex items-center justify-between">
                                        <span className="text-sm font-medium text-text-muted">Kunci Jawaban</span>
                                        <button type="button" onClick={() => addOptionItem(index)} className="text-xs text-primary-500 hover:text-primary-600 flex items-center gap-1 font-medium"><Plus className="w-3 h-3"/> Tambah Jawaban</button>
                                    </div>
                                    <div className="grid gap-2">
                                        {item.options.map((opt: any, optIndex: number) => (
                                            <div key={optIndex} className="flex items-center gap-2">
                                                <span className="font-mono bg-surface-hover px-2 py-1.5 rounded-lg text-sm">[{opt.id}]</span>
                                                <input
                                                    type="text"
                                                    value={opt.answer || ''}
                                                    onChange={e => updateOption(index, optIndex, 'answer', e.target.value)}
                                                    placeholder="Kunci Jawaban"
                                                    className="w-full rounded-lg bg-surface border border-border/50 px-3 py-2 text-sm focus:border-primary-500"
                                                    required
                                                />
                                                <button type="button" onClick={() => removeOptionItem(index, optIndex)} className="text-rose-400 hover:bg-rose-400/10 p-1.5 rounded-lg shrink-0"><Trash2 className="w-4 h-4"/></button>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {item.item_type === 'jumbled_word' && (
                                <div className="space-y-3">
                                    <div className="text-xs text-primary-600 bg-primary-500/10 p-3 rounded-xl font-medium">
                                        💡 Ketikkan kata yang benar di bawah ini. Sistem akan mengacak huruf-hurufnya secara otomatis saat permainan dimulai.
                                    </div>
                                    <div className="flex flex-col gap-2">
                                        <label className="text-sm font-medium text-text-muted">Kata / Jawaban Benar</label>
                                        <input
                                            type="text"
                                            value={item.options[0]?.answer || ''}
                                            onChange={e => updateOption(index, 0, 'answer', e.target.value)}
                                            placeholder="Contoh: ELEPHANT"
                                            className="w-full rounded-lg bg-surface border border-border/50 px-3 py-2 text-sm focus:border-primary-500"
                                            required
                                        />
                                    </div>
                                </div>
                            )}

                            {item.item_type === 'spelling_bee' && (
                                <div className="space-y-4">
                                    <div className="text-xs text-primary-600 bg-primary-500/10 p-3 rounded-xl font-medium">
                                        💡 Tuliskan kata yang akan didengar oleh siswa (fitur TTS). Anda dapat menambahkan variasi jawaban jika ejaan mirip diizinkan.
                                    </div>
                                    <div className="flex flex-col gap-2">
                                        <label className="text-sm font-medium text-text-muted">Kata / Jawaban Benar Utama</label>
                                        <input
                                            type="text"
                                            value={item.options[0]?.answer || ''}
                                            onChange={e => updateOption(index, 0, 'answer', e.target.value)}
                                            placeholder="Contoh: ENVIRONMENT"
                                            className="w-full rounded-lg bg-surface border border-border/50 px-3 py-2 text-sm focus:border-primary-500"
                                            required
                                        />
                                    </div>
                                    <div className="flex flex-col gap-2">
                                        <label className="text-sm font-medium text-text-muted">Variasi Jawaban (Pisahkan dengan koma)</label>
                                        <input
                                            type="text"
                                            value={item.options[0]?.accept_variants ? item.options[0].accept_variants.join(', ') : ''}
                                            onChange={e => updateOption(index, 0, 'accept_variants_array', e.target.value)}
                                            placeholder="Contoh: envirnment, environmentt"
                                            className="w-full rounded-lg bg-surface border border-border/50 px-3 py-2 text-sm focus:border-primary-500"
                                        />
                                    </div>
                                </div>
                            )}

                            {item.item_type === 'sentence_rearrange' && (
                                <div className="space-y-3">
                                    <div className="text-xs text-primary-600 bg-primary-500/10 p-3 rounded-xl font-medium">
                                        💡 Game ini khusus untuk menyusun kalimat dari potongan kata-kata, berbeda dengan menyusun urutan (sequencing).
                                    </div>
                                    <div className="flex items-center justify-between">
                                        <span className="text-sm font-medium text-text-muted">Potongan Kata (Berdasarkan urutan benar dari kiri ke kanan)</span>
                                        <button type="button" onClick={() => addOptionItem(index)} className="text-xs text-primary-500 hover:text-primary-600 flex items-center gap-1 font-medium"><Plus className="w-3 h-3"/> Tambah Kata</button>
                                    </div>
                                    <div className="flex flex-wrap gap-2">
                                        {item.options.map((opt: any, optIndex: number) => (
                                            <div key={optIndex} className="flex items-center gap-1 bg-surface-hover p-1 rounded-lg border border-border/50">
                                                <div className="text-xs font-mono text-text-muted/50 px-1">{opt.order}</div>
                                                <input
                                                    type="text"
                                                    value={opt.text || ''}
                                                    onChange={e => updateOption(index, optIndex, 'text', e.target.value)}
                                                    placeholder={`Kata ${optIndex + 1}`}
                                                    className="w-24 rounded bg-surface border-none px-2 py-1 text-sm focus:ring-1 focus:ring-primary-500"
                                                    required
                                                />
                                                <button type="button" onClick={() => removeOptionItem(index, optIndex)} className="text-rose-400 hover:bg-rose-400/20 p-1 rounded"><X className="w-3 h-3"/></button>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {item.item_type === 'listen_and_build' && (
                                <div className="space-y-4 rounded-2xl border border-sky-500/25 bg-sky-500/5 p-4">
                                    <div className="flex items-start gap-3 text-sm text-sky-200">
                                        <FileAudio className="mt-0.5 h-5 w-5 shrink-0" />
                                        <p>Audio hanya diputar dari layar guru. Setelah putaran pertama selesai, token akan terbuka di HP kelompok.</p>
                                    </div>

                                    <div className="space-y-2">
                                        <label className="text-sm font-bold">Audio listening (MP3, WAV, atau M4A · maks. 10 MB)</label>
                                        {item.metadata?.audio_path && !item.audio_file && (
                                            <audio controls preload="metadata" src={`/storage/${item.metadata.audio_path}`} className="w-full" />
                                        )}
                                        {item.audio_file instanceof File && (
                                            <div className="flex items-center justify-between rounded-xl bg-surface px-4 py-3 text-sm">
                                                <span className="truncate">{item.audio_file.name}</span>
                                                <button type="button" onClick={() => updateItemAudio(index, null)} className="text-rose-300"><X className="h-4 w-4" /></button>
                                            </div>
                                        )}
                                        <label className="flex w-fit cursor-pointer items-center gap-2 rounded-xl border border-dashed border-sky-400/50 px-4 py-2 text-sm font-bold text-sky-200 hover:bg-sky-500/10">
                                            <Upload className="h-4 w-4" /> {item.metadata?.audio_path ? 'Ganti audio' : 'Pilih audio'}
                                            <input type="file" accept=".mp3,.wav,.m4a,audio/mpeg,audio/wav,audio/mp4" className="hidden" onChange={e => updateItemAudio(index, e.target.files?.[0] ?? null)} />
                                        </label>
                                    </div>

                                    <div className="space-y-2">
                                        <label className="text-sm font-bold">Transcript / kalimat benar</label>
                                        <textarea value={item.metadata?.transcript || ''} onChange={e => updateItemMetadata(index, 'transcript', e.target.value)} rows={3} placeholder="I went to the market yesterday." className="w-full rounded-xl border border-border/50 bg-surface px-4 py-3 text-sm focus:border-sky-400" required />
                                        <p className="text-xs text-text-muted">Transcript menjadi kunci jawaban dan tidak dikirim ke HP sebelum reveal.</p>
                                    </div>

                                    <div className="flex items-center gap-3">
                                        <label className="text-sm font-bold">Maksimal pemutaran</label>
                                        <input type="number" min={1} max={5} value={item.metadata?.replay_limit || 2} onChange={e => updateItemMetadata(index, 'replay_limit', Number(e.target.value))} className="w-20 rounded-lg border border-border/50 bg-surface px-3 py-2 text-sm" />
                                    </div>
                                </div>
                            )}

                            {item.item_type === 'error_hunter' && (
                                <div className="space-y-4 rounded-2xl border border-amber-500/25 bg-amber-500/5 p-4">
                                    <div className="flex items-start gap-3 text-sm text-amber-200">
                                        <AlertTriangle className="mt-0.5 h-5 w-5 shrink-0" />
                                        <p>Gunakan posisi kata berdasarkan nomor di bawah. Sistem menyimpan kata asli dari kalimat secara otomatis.</p>
                                    </div>

                                    <div className="flex flex-wrap gap-2">
                                        {String(item.question_text || '').replace(/<[^>]*>/g, ' ').trim().split(/\s+/).filter(Boolean).map((token: string, tokenIndex: number) => (
                                            <span key={`${token}-${tokenIndex}`} className="rounded-lg bg-surface px-3 py-2 text-sm"><span className="mr-1 text-xs text-text-muted">{tokenIndex + 1}</span>{token}</span>
                                        ))}
                                    </div>

                                    <div className="flex items-center justify-between">
                                        <span className="text-sm font-bold">Kunci kesalahan dan koreksi</span>
                                        <button type="button" onClick={() => addOptionItem(index)} className="flex items-center gap-1 text-xs font-bold text-amber-300"><Plus className="h-3 w-3" /> Tambah Kesalahan</button>
                                    </div>

                                    {item.options.map((opt: any, optIndex: number) => (
                                        <div key={optIndex} className="grid gap-2 rounded-xl border border-border/40 bg-surface/60 p-3 sm:grid-cols-[90px_1fr_1fr_auto]">
                                            <input type="number" min={1} value={Number(opt.token_index ?? 0) + 1} onChange={e => updateOption(index, optIndex, 'token_index', Math.max(0, Number(e.target.value) - 1))} aria-label="Posisi kata salah" className="rounded-lg border border-border/50 bg-surface px-3 py-2 text-sm" required />
                                            <input type="text" value={opt.correction || ''} onChange={e => updateOption(index, optIndex, 'correction', e.target.value)} placeholder="Koreksi, mis. went" className="rounded-lg border border-border/50 bg-surface px-3 py-2 text-sm" required />
                                            <input type="text" value={opt.explanation || ''} onChange={e => updateOption(index, optIndex, 'explanation', e.target.value)} placeholder="Penjelasan (opsional)" className="rounded-lg border border-border/50 bg-surface px-3 py-2 text-sm" />
                                            <button type="button" onClick={() => removeOptionItem(index, optIndex)} className="p-2 text-rose-300"><Trash2 className="h-4 w-4" /></button>
                                        </div>
                                    ))}
                                </div>
                            )}

                            {item.item_type === 'secret_taboo' && (
                                <div className="space-y-4 rounded-2xl border border-fuchsia-500/25 bg-fuchsia-500/5 p-4">
                                    <div className="flex items-start gap-3 text-sm text-fuchsia-200">
                                        <AlertTriangle className="mt-0.5 h-5 w-5 shrink-0" />
                                        <p>Secret word hanya tampil di HP clue-giver selama 5 detik. Sistem belum mendeteksi forbidden word secara otomatis; guru dan siswa memeriksanya dengan kejujuran kelas.</p>
                                    </div>

                                    <div className="grid gap-4 sm:grid-cols-2">
                                        <div className="space-y-2">
                                            <label className="text-sm font-bold">Secret word</label>
                                            <input type="text" maxLength={100} value={item.metadata?.answer || ''} onChange={e => updateItemMetadata(index, 'answer', e.target.value)} placeholder="elephant" className="w-full rounded-xl border border-border/50 bg-surface px-4 py-3 text-sm focus:border-fuchsia-400" required />
                                        </div>
                                        <div className="space-y-2">
                                            <label className="text-sm font-bold">Durasi memberi clue</label>
                                            <div className="flex items-center gap-2">
                                                <input type="number" min={15} max={120} value={item.metadata?.clue_seconds || 45} onChange={e => updateItemMetadata(index, 'clue_seconds', Number(e.target.value))} className="w-24 rounded-xl border border-border/50 bg-surface px-4 py-3 text-sm" required />
                                                <span className="text-sm text-text-muted">detik</span>
                                            </div>
                                        </div>
                                    </div>

                                    <div className="space-y-2">
                                        <label className="text-sm font-bold">Alias jawaban <span className="font-normal text-text-muted">(pisahkan dengan koma)</span></label>
                                        <input type="text" value={(item.metadata?.aliases || []).join(', ')} onChange={e => updateItemMetadata(index, 'aliases', e.target.value.split(',').map((value: string) => value.trim()).filter(Boolean))} placeholder="an elephant, the elephant" className="w-full rounded-xl border border-border/50 bg-surface px-4 py-3 text-sm focus:border-fuchsia-400" />
                                    </div>

                                    <div className="space-y-2">
                                        <label className="text-sm font-bold">Forbidden words <span className="font-normal text-text-muted">(pisahkan dengan koma)</span></label>
                                        <input type="text" value={(item.metadata?.forbidden_words || []).join(', ')} onChange={e => updateItemMetadata(index, 'forbidden_words', e.target.value.split(',').map((value: string) => value.trim()))} placeholder="animal, trunk, big" className="w-full rounded-xl border border-border/50 bg-surface px-4 py-3 text-sm focus:border-fuchsia-400" required />
                                    </div>
                                </div>
                            )}
                        </div>
                    ))}

                    <button
                        type="button"
                        onClick={addItem}
                        className="w-full flex items-center justify-center gap-2 rounded-2xl border-2 border-dashed border-border/50 p-6 text-text-muted hover:text-text-light hover:border-primary-500/50 hover:bg-surface-hover/30 transition-all"
                    >
                        <Plus className="h-6 w-6" />
                        <span className="font-medium">Tambah Soal ({data.items.length}/20)</span>
                    </button>
                </div>
                {/* Floating Action Bar */}
                <div className="app-eco-solid-surface mobile-safe-bottom mobile-safe-action-bar fixed left-0 right-0 z-40 border-t border-border bg-surface/90 p-4 backdrop-blur-md">
                    <div className="max-w-5xl mx-auto flex items-center justify-between">
                        <div className="flex items-center gap-2.5 text-sm text-text-muted font-medium">
                            <List className="w-4 h-4 text-primary-500" />
                            <span>
                                {activeTab === 'settings'
                                    ? 'Tahap 1: Pengaturan'
                                    : activeTab === 'mode'
                                        ? 'Tahap 2: Mode'
                                        : 'Tahap 3: Soal'}
                            </span>
                        </div>
                        <div className="flex items-center gap-3">
                            {activeTab === 'settings' ? (
                                <button
                                    type="button"
                                    onClick={goToModeStep}
                                    disabled={processing}
                                    className="flex items-center gap-2 rounded-full bg-primary-500 hover:bg-primary-600 px-6 py-2.5 font-extrabold text-slate-950 transition-all disabled:opacity-50 shadow-lg shadow-primary-500/25 text-sm"
                                >
                                    Lanjut Pilih Mode
                                    <ChevronRight className="h-4 w-4 stroke-[3]" />
                                </button>
                            ) : activeTab === 'mode' ? (
                                <>
                                    <button
                                        type="button"
                                        onClick={() => {
                                            setActiveTab('settings');
                                            window.scrollTo(0, 0);
                                        }}
                                        className="flex items-center gap-2 rounded-full border border-border/70 bg-surface px-4 py-2.5 text-sm font-bold text-text-muted transition-colors hover:bg-surface-hover hover:text-text"
                                    >
                                        <ArrowLeft className="h-4 w-4" />
                                        <span className="hidden sm:inline">Kembali</span>
                                    </button>
                                    <button
                                        type="button"
                                        onClick={goToQuestionStep}
                                        disabled={processing}
                                        className="flex items-center gap-2 rounded-full bg-primary-500 hover:bg-primary-600 px-6 py-2.5 font-extrabold text-slate-950 transition-all disabled:opacity-50 shadow-lg shadow-primary-500/25 text-sm"
                                    >
                                        {processing ? 'Menyimpan Draft...' : 'Lanjut Buat Soal'}
                                        <ChevronRight className="h-4 w-4 stroke-[3]" />
                                    </button>
                                </>
                            ) : (
                                <>
                                    <button
                                        type="button"
                                        onClick={() => {
                                            setActiveTab('mode');
                                            window.scrollTo(0, 0);
                                        }}
                                        className="flex items-center gap-2 rounded-full border border-border/70 bg-surface px-4 py-2.5 text-sm font-bold text-text-muted transition-colors hover:bg-surface-hover hover:text-text"
                                    >
                                        <ArrowLeft className="h-4 w-4" />
                                        <span className="hidden sm:inline">Mode</span>
                                    </button>
                                    <button
                                        type="button"
                                        onClick={() => submit()}
                                        disabled={processing}
                                        className="flex items-center gap-2 rounded-full bg-primary-500 hover:bg-primary-600 px-6 py-2.5 font-extrabold text-slate-950 transition-all disabled:opacity-50 shadow-lg shadow-primary-500/25 text-sm"
                                    >
                                        <Save className="h-4 w-4 stroke-[3]" />
                                        {processing ? 'Menyimpan...' : 'Simpan Semua'}
                                    </button>
                                </>
                            )}
                        </div>
                    </div>
                </div>
            </form>
        </AuthenticatedLayout>
    );
}
