import { Form, Head, Link, router, useForm } from '@inertiajs/react';
import {
    ArrowLeft,
    BookOpen,
    Check,
    ChevronDown,
    ChevronRight,
    ClipboardCheck,
    ExternalLink,
    FileText,
    GraduationCap,
    GripVertical,
    LayoutList,
    Link2,
    Lock,
    Pencil,
    Play,
    Plus,
    Save,
    Tag,
    Trash2,
    Users,
    X,
    ImagePlus,
    ShieldCheck,
} from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import InputError from '@/components/input-error';
import { DeleteConfirmModal } from '@/components/delete-confirm-modal';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Spinner } from '@/components/ui/spinner';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';

type Lesson = { id: number; title: string; type: string; duration_minutes: number; order: number };
type Quiz = { id: number; title: string; duration_minutes: number; passing_score: number; order: number };
type Assignment = { id: number; title: string; deadline: string | null; max_score: number; order: number };
type Chapter = { id: number; title: string; order: number; lessons: Lesson[]; quizzes: Quiz[]; assignments: Assignment[] };

type Course = {
    id: number;
    title: string;
    slug: string;
    description: string | null;
    thumbnail: string | null;
    status: string;
    price_type: string;
    price: number;
    level: string;
    is_sequential: boolean;
    affiliate_enabled: boolean;
    alumni_commission_rate: number | null;
    non_alumni_commission_rate: number | null;
    bank_name: string | null;
    bank_account: string | null;
    bank_holder: string | null;
    category: { id: number; name: string } | null;
    chapters: Chapter[];
};

type MergedItem =
    | (Lesson & { kind: 'lesson' })
    | (Quiz & { kind: 'quiz' })
    | (Assignment & { kind: 'assignment' });

type Props = { course: Course; enrollmentCount: number; categories: { id: number; name: string }[] };

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Instruktur', href: '/instructor/dashboard' },
    { title: 'Kelas Saya', href: '/instructor/courses' },
    { title: 'Detail Kelas', href: '#' },
];

const STATUS_CONFIG: Record<string, { label: string; badge: string; dot: string; select: string }> = {
    draft:          { label: 'Draft',           badge: 'bg-zinc-100 text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400',                dot: 'bg-zinc-400',    select: 'text-zinc-600' },
    pending_review: { label: 'Menunggu Review', badge: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-400',         dot: 'bg-amber-400',   select: 'text-amber-700' },
    published:      { label: 'Published',       badge: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-400', dot: 'bg-emerald-500', select: 'text-emerald-700' },
    rejected:       { label: 'Ditolak',         badge: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-400',                dot: 'bg-red-500',     select: 'text-red-700' },
    archived:       { label: 'Diarsipkan',      badge: 'bg-zinc-100 text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400',               dot: 'bg-zinc-400',    select: 'text-zinc-600' },
};

const LEVEL_LABELS: Record<string, string> = { beginner: 'Pemula', intermediate: 'Menengah', advanced: 'Lanjutan' };

const CARD_GRADIENTS = [
    'from-blue-200 to-sky-200',
    'from-sky-200 to-cyan-200',
    'from-teal-200 to-emerald-200',
    'from-rose-200 to-pink-200',
    'from-amber-200 to-orange-200',
    'from-cyan-200 to-sky-200',
    'from-slate-200 to-gray-200',
    'from-green-200 to-teal-200',
];

const selectCls = 'border-input bg-background focus-visible:border-ring focus-visible:ring-ring/50 h-9 w-full rounded-md border px-3 py-1 text-sm shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px]';
const textareaCls = 'border-input bg-background focus-visible:border-ring focus-visible:ring-ring/50 w-full rounded-md border px-3 py-2 text-sm shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] placeholder:text-muted-foreground';

const ITEM_TYPE: Record<string, { icon: React.ElementType; color: string; label: string }> = {
    video:      { icon: Play,           color: 'text-blue-500 bg-blue-50 dark:bg-blue-950/40',        label: 'Video' },
    text:       { icon: FileText,       color: 'text-slate-500 bg-slate-50 dark:bg-slate-800/50',     label: 'Teks' },
    pdf:        { icon: FileText,       color: 'text-red-500 bg-red-50 dark:bg-red-950/40',           label: 'PDF' },
    quiz:       { icon: ClipboardCheck, color: 'text-orange-500 bg-orange-50 dark:bg-orange-950/40',  label: 'Kuis' },
    assignment: { icon: GraduationCap,  color: 'text-teal-500 bg-teal-50 dark:bg-teal-950/40',  label: 'Tugas' },
};

function ItemIcon({ type }: { type: string }) {
    const meta = ITEM_TYPE[type] ?? ITEM_TYPE.text;
    const Icon = meta.icon;
    return (
        <span className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-md ${meta.color}`}>
            <Icon className="h-3.5 w-3.5" />
        </span>
    );
}

function buildItems(chapter: Chapter): MergedItem[] {
    const lessons = chapter.lessons.map(l => ({ kind: 'lesson' as const, ...l }));
    const quizzes = chapter.quizzes.map(q => ({ kind: 'quiz' as const, ...q }));
    const assignments = chapter.assignments.map(a => ({ kind: 'assignment' as const, ...a }));
    const all = [...lessons, ...quizzes, ...assignments];
    const orders = all.map(i => i.order);
    if (new Set(orders).size === orders.length && all.length > 0) {
        return all.sort((a, b) => a.order - b.order);
    }
    return [
        ...lessons.sort((a, b) => a.order - b.order),
        ...quizzes.sort((a, b) => a.order - b.order),
        ...assignments.sort((a, b) => a.order - b.order),
    ];
}

// ── Modals ──────────────────────────────────────────────────────────────────
function AddChapterModal({ courseSlug }: { courseSlug: string }) {
    const [open, setOpen] = useState(false);
    const { data, setData, post, processing, errors, reset } = useForm({ title: '' });

    function submit(e: React.FormEvent) {
        e.preventDefault();
        post(`/instructor/courses/${courseSlug}/chapters`, {
            preserveScroll: true,
            onSuccess: () => { setOpen(false); reset(); },
        });
    }

    return (
        <Dialog open={open} onOpenChange={(v) => { if (!v) reset(); setOpen(v); }}>
            <DialogTrigger asChild>
                <Button variant="outline" size="sm" className="gap-1.5">
                    <Plus className="h-3.5 w-3.5" /> Tambah Chapter
                </Button>
            </DialogTrigger>
            <DialogContent className="max-w-sm">
                <DialogTitle>Tambah Chapter</DialogTitle>
                <form onSubmit={submit} className="mt-3 flex flex-col gap-4">
                    <div className="grid gap-1.5">
                        <Label htmlFor="ch-title">Judul Chapter *</Label>
                        <Input id="ch-title" required autoFocus value={data.title} onChange={e => setData('title', e.target.value)} placeholder="Mis: Pendahuluan, Bab 1, ..." />
                        <InputError message={errors.title} />
                    </div>
                    <div className="flex justify-end gap-2">
                        <Button type="button" variant="outline" onClick={() => setOpen(false)}>Batal</Button>
                        <Button type="submit" disabled={processing}>{processing && <Spinner />} Tambah</Button>
                    </div>
                </form>
            </DialogContent>
        </Dialog>
    );
}

function AddQuizModal({ courseSlug, chapterId }: { courseSlug: string; chapterId: number }) {
    const [open, setOpen] = useState(false);
    const { data, setData, post, processing, errors, reset } = useForm({
        title: '',
        description: '',
        duration_minutes: 30,
        passing_score: 70,
        max_attempts: 3,
        deadline: '',
        late_policy: 'closed',
    });

    function submit(e: React.FormEvent) {
        e.preventDefault();
        post(`/instructor/courses/${courseSlug}/chapters/${chapterId}/quizzes`, {
            preserveScroll: true,
            onSuccess: () => { setOpen(false); reset(); },
        });
    }

    return (
        <Dialog open={open} onOpenChange={(v) => { if (!v) reset(); setOpen(v); }}>
            <DialogTrigger asChild>
                <button className="flex items-center gap-1.5 rounded-md bg-amber-500 px-2.5 py-1.5 text-xs font-medium text-white transition-colors hover:bg-amber-600">
                    <Plus className="h-3.5 w-3.5" /> Kuis
                </button>
            </DialogTrigger>
            <DialogContent className="max-w-md">
                <DialogTitle>Tambah Kuis</DialogTitle>
                <form onSubmit={submit} className="mt-3 flex flex-col gap-4">
                    <div className="grid gap-1.5">
                        <Label>Judul *</Label>
                        <Input required autoFocus value={data.title} onChange={e => setData('title', e.target.value)} placeholder="Kuis Bab 1" />
                        <InputError message={errors.title} />
                    </div>
                    <div className="grid gap-1.5">
                        <Label>Deskripsi</Label>
                        <textarea value={data.description} onChange={e => setData('description', e.target.value)} rows={2} className={textareaCls} placeholder="Opsional" />
                    </div>
                    <div className="grid grid-cols-3 gap-3">
                        <div className="grid gap-1.5">
                            <Label>Durasi (mnt)</Label>
                            <Input type="number" min="1" value={data.duration_minutes} onChange={e => setData('duration_minutes', Number(e.target.value))} />
                        </div>
                        <div className="grid gap-1.5">
                            <Label>Lulus (%)</Label>
                            <Input type="number" min="0" max="100" value={data.passing_score} onChange={e => setData('passing_score', Number(e.target.value))} />
                        </div>
                        <div className="grid gap-1.5">
                            <Label>Maks Coba</Label>
                            <Input type="number" min="1" value={data.max_attempts} onChange={e => setData('max_attempts', Number(e.target.value))} />
                        </div>
                    </div>
                    <div className="grid gap-1.5">
                        <Label>Batas Waktu Pengerjaan (Hari setelah mendaftar - opsional)</Label>
                        <Input type="number" min="0" placeholder="Contoh: 7" value={data.deadline} onChange={e => setData('deadline', e.target.value)} />
                        <InputError message={errors.deadline} />
                    </div>
                    <div className="grid gap-1.5">
                        <Label>Kebijakan Setelah Deadline</Label>
                        <select value={data.late_policy} onChange={e => setData('late_policy', e.target.value)} className={selectCls}>
                            <option value="closed">Ditutup — tidak bisa dikerjakan setelah deadline</option>
                            <option value="allowed">Boleh terlambat — tetap bisa dikerjakan</option>
                        </select>
                    </div>
                    <div className="flex justify-end gap-2">
                        <Button type="button" variant="outline" onClick={() => setOpen(false)}>Batal</Button>
                        <Button type="submit" disabled={processing}>{processing && <Spinner />} Tambah</Button>
                    </div>
                </form>
            </DialogContent>
        </Dialog>
    );
}

function AddAssignmentModal({ courseSlug, chapterId }: { courseSlug: string; chapterId: number }) {
    const [open, setOpen] = useState(false);
    const { data, setData, post, processing, errors, reset } = useForm({
        title: '',
        instructions: '',
        deadline: '',
        late_policy: 'closed',
        max_score: 100,
        submission_type: 'file',
    });

    function submit(e: React.FormEvent) {
        e.preventDefault();
        post(`/instructor/courses/${courseSlug}/chapters/${chapterId}/assignments`, {
            preserveScroll: true,
            onSuccess: () => { setOpen(false); reset(); },
        });
    }

    return (
        <Dialog open={open} onOpenChange={(v) => { if (!v) reset(); setOpen(v); }}>
            <DialogTrigger asChild>
                <button className="flex items-center gap-1.5 rounded-md bg-indigo-500 px-2.5 py-1.5 text-xs font-medium text-white transition-colors hover:bg-indigo-600">
                    <Plus className="h-3.5 w-3.5" /> Tugas
                </button>
            </DialogTrigger>
            <DialogContent className="max-w-md">
                <DialogTitle>Tambah Tugas</DialogTitle>
                <form onSubmit={submit} className="mt-3 flex flex-col gap-4">
                    <div className="grid gap-1.5">
                        <Label>Judul *</Label>
                        <Input required autoFocus value={data.title} onChange={e => setData('title', e.target.value)} placeholder="Tugas Praktik Bab 1" />
                        <InputError message={errors.title} />
                    </div>
                    <div className="grid gap-1.5">
                        <Label>Instruksi</Label>
                        <textarea value={data.instructions} onChange={e => setData('instructions', e.target.value)} rows={3} className={textareaCls} placeholder="Langkah-langkah pengerjaan..." />
                    </div>
                    <div className="grid grid-cols-2 gap-3">
                        <div className="grid gap-1.5">
                            <Label>Deadline (Hari setelah mendaftar)</Label>
                            <Input type="number" min="0" placeholder="Contoh: 7" value={data.deadline} onChange={e => setData('deadline', e.target.value)} />
                            <InputError message={errors.deadline} />
                        </div>
                        <div className="grid gap-1.5">
                            <Label>Nilai Maks</Label>
                            <Input type="number" min="1" value={data.max_score} onChange={e => setData('max_score', Number(e.target.value))} />
                        </div>
                    </div>
                    <div className="grid gap-1.5">
                        <Label>Tipe Pengumpulan</Label>
                        <select value={data.submission_type} onChange={e => setData('submission_type', e.target.value)} className={selectCls}>
                            <option value="file">File Upload</option>
                            <option value="text">Teks Online</option>
                        </select>
                    </div>
                    <div className="flex justify-end gap-2">
                        <Button type="button" variant="outline" onClick={() => setOpen(false)}>Batal</Button>
                        <Button type="submit" disabled={processing}>{processing && <Spinner />} Tambah</Button>
                    </div>
                </form>
            </DialogContent>
        </Dialog>
    );
}

// ── Chapter Card ──
function ChapterCard({
    chapter,
    courseSlug,
    chapterIndex,
    globalLessonOffset,
    isSequential,
    isDragging,
    isDragOver,
    onDragStart,
    onDragOver,
    onDragEnd,
    onDrop,
    canEdit,
}: {
    chapter: Chapter;
    courseSlug: string;
    chapterIndex: number;
    globalLessonOffset: number;
    isSequential: boolean;
    isDragging: boolean;
    isDragOver: boolean;
    onDragStart: () => void;
    onDragOver: (e: React.DragEvent) => void;
    onDragEnd: () => void;
    onDrop: () => void;
    canEdit: boolean;
}) {
    const [expanded, setExpanded] = useState(true);
    const [editing, setEditing] = useState(false);
    const [delChapterModal, setDelChapterModal] = useState(false);
    const [delItemModal, setDelItemModal] = useState<MergedItem | null>(null);

    const { data: editData, setData: setEditData, patch: patchChapter, processing: editProcessing, errors: editErrors, reset: resetEdit } = useForm({
        title: chapter.title,
    });

    const items = buildItems(chapter);

    const [draggingIdx, setDraggingIdx] = useState<number | null>(null);
    const dragItemRef = useRef<number | null>(null);

    function handleItemDragStart(index: number) {
        if (!canEdit) return;
        dragItemRef.current = index;
        setDraggingIdx(index);
    }

    function handleItemDragOver(e: React.DragEvent, overIndex: number) {
        e.preventDefault();
        const from = dragItemRef.current;
        if (from === null || from === overIndex) return;

        // Reorder locally
        const next = [...items];
        const [moved] = next.splice(from, 1);
        next.splice(overIndex, 0, moved);

        dragItemRef.current = overIndex;
        setDraggingIdx(overIndex);
    }

    function handleItemDrop() {
        setDraggingIdx(null);
        dragItemRef.current = null;

        const orderedIds = items.map(item => ({
            id: item.id,
            type: item.kind,
        }));

        router.patch(`/instructor/courses/${courseSlug}/chapters/${chapter.id}/items/reorder`, {
            items: orderedIds,
        }, { preserveScroll: true });
    }

    function handleItemDragEnd() {
        setDraggingIdx(null);
        dragItemRef.current = null;
    }

    const isFirstChapter = chapterIndex === 0;

    function del(e: React.MouseEvent) {
        e.stopPropagation();
        setDelChapterModal(true);
    }

    function confirmDel() {
        router.delete(`/instructor/courses/${courseSlug}/chapters/${chapter.id}`, {
            preserveScroll: true,
            onSuccess: () => setDelChapterModal(false),
        });
    }

    const chapterBlockedReason = items.length > 0
        ? 'Chapter tidak dapat dihapus karena masih memiliki materi, kuis, atau tugas di dalamnya.'
        : undefined;

    function delItem(item: MergedItem) {
        setDelItemModal(item);
    }

    function confirmDelItem() {
        if (!delItemModal) return;
        const typePlural = delItemModal.kind === 'lesson' ? 'lessons' : delItemModal.kind === 'quiz' ? 'quizzes' : 'assignments';
        router.delete(`/instructor/courses/${courseSlug}/chapters/${chapter.id}/${typePlural}/${delItemModal.id}`, {
            preserveScroll: true,
            onSuccess: () => setDelItemModal(null),
        });
    }

    function startEdit(e: React.MouseEvent) {
        e.stopPropagation();
        setEditData('title', chapter.title);
        setEditing(true);
    }

    function saveEdit(e: React.FormEvent) {
        e.preventDefault();
        patchChapter(`/instructor/courses/${courseSlug}/chapters/${chapter.id}`, {
            preserveScroll: true,
            onSuccess: () => { setEditing(false); resetEdit(); },
        });
    }

    function itemMeta(item: MergedItem): { sub: string; href: string | null } {
        if (item.kind === 'lesson') {
            const type = ITEM_TYPE[item.type]?.label ?? item.type;
            const dur = item.duration_minutes > 0 ? ` · ${item.duration_minutes} mnt` : '';
            return { sub: `${type}${dur}`, href: `/instructor/courses/${courseSlug}/lessons/${item.id}` };
        }
        if (item.kind === 'quiz') {
            return { sub: `Kuis · ${item.duration_minutes} mnt · Lulus ${item.passing_score}%`, href: `/instructor/courses/${courseSlug}/quizzes/${item.id}` };
        }
        const deadline = item.deadline ? ` · Deadline ${item.deadline} hari setelah mendaftar` : '';
        return { sub: `Tugas · Nilai maks ${item.max_score}${deadline}`, href: `/instructor/courses/${courseSlug}/assignments/${item.id}/submissions` };
    }

    function itemIcon(item: MergedItem) {
        if (item.kind === 'quiz') return <ItemIcon type="quiz" />;
        if (item.kind === 'assignment') return <ItemIcon type="assignment" />;
        return <ItemIcon type={item.type} />;
    }

    let lessonCounter = globalLessonOffset;
    const totalItems = items.length;

    return (
        <div
            className={[
                'overflow-hidden rounded-xl border bg-card shadow-xs transition-all duration-150 select-none',
                isDragging ? 'opacity-40 scale-[0.99] shadow-none' : 'opacity-100',
                isDragOver && !isDragging ? 'border-blue-300/60 ring-2 ring-blue-100 shadow-md' : '',
            ].join(' ')}
            onDragOver={e => { e.preventDefault(); onDragOver(e); }}
            onDrop={onDrop}
        >
            {/* Chapter header */}
            {editing ? (
                <form onSubmit={saveEdit} className="flex items-center gap-2 px-4 py-2.5">
                    <div className="cursor-grab touch-none text-muted-foreground/30 shrink-0">
                        <GripVertical className="h-4 w-4" />
                    </div>
                    <span className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-xs font-bold ${
                        isSequential && !isFirstChapter ? 'bg-amber-100 text-amber-700' : 'bg-blue-100 text-blue-700'
                    }`}>
                        {chapterIndex + 1}
                    </span>
                    <Input
                        autoFocus
                        value={editData.title}
                        onChange={e => setEditData('title', e.target.value)}
                        className="h-8 flex-1 text-sm font-semibold"
                        onClick={e => e.stopPropagation()}
                    />
                    <button type="submit" disabled={editProcessing} className="shrink-0 rounded-md p-1.5 text-emerald-600 hover:bg-emerald-50 transition-colors">
                        <Check className="h-4 w-4" />
                    </button>
                    <button type="button" onClick={() => setEditing(false)} className="shrink-0 rounded-md p-1.5 text-muted-foreground hover:bg-muted transition-colors">
                        <X className="h-4 w-4" />
                    </button>
                </form>
            ) : (
                <div className="flex items-center gap-3 px-4 py-3 select-none">
                    <div
                        draggable={canEdit}
                        onDragStart={onDragStart}
                        onDragEnd={onDragEnd}
                        className="cursor-grab touch-none text-muted-foreground/30 hover:text-muted-foreground/60 active:cursor-grabbing shrink-0"
                    >
                        <GripVertical className="h-4 w-4" />
                    </div>

                    {/* Chapter number badge */}
                    <span className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-xs font-bold ${
                        isSequential && !isFirstChapter
                            ? 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400'
                            : 'bg-blue-100 text-blue-700'
                    }`}>
                        {chapterIndex + 1}
                    </span>

                    {/* Title area */}
                    <div
                        className="flex flex-1 cursor-pointer items-center gap-2 overflow-hidden"
                        onClick={() => setExpanded(v => !v)}
                    >
                        <p className="flex-1 truncate text-sm font-semibold">{chapter.title}</p>
                        {isSequential && !isFirstChapter && (
                            <span className="hidden sm:flex items-center gap-1 rounded-full bg-amber-50 px-2 py-0.5 text-[10px] font-medium text-amber-600 dark:bg-amber-900/20 dark:text-amber-400 shrink-0">
                                <Lock className="h-2.5 w-2.5" /> Terkunci
                            </span>
                        )}
                        <span className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground font-medium">
                            {totalItems} item
                        </span>
                    </div>

                    {canEdit && (
                        <>
                            <button
                                onClick={startEdit}
                                className="shrink-0 rounded-md p-1.5 text-blue-600 bg-blue-50/50 hover:bg-blue-100 hover:text-blue-700 border border-blue-200/60 dark:text-blue-400 dark:bg-blue-950/20 dark:hover:bg-blue-950/40 transition-colors"
                            >
                                <Pencil className="h-3.5 w-3.5" />
                            </button>
                            <button
                                onClick={del}
                                className="shrink-0 rounded-md p-1.5 text-destructive bg-destructive/5 hover:bg-destructive/15 hover:text-destructive border border-destructive/20 dark:text-red-400 dark:bg-red-950/20 dark:hover:bg-red-950/40 transition-colors"
                            >
                                <Trash2 className="h-3.5 w-3.5" />
                            </button>
                        </>
                    )}
                    <button
                        onClick={() => setExpanded(v => !v)}
                        className="shrink-0 rounded-md p-1.5 text-muted-foreground hover:bg-muted transition-colors"
                    >
                        <ChevronDown className={`h-4 w-4 transition-transform duration-200 ${expanded ? '' : '-rotate-90'}`} />
                    </button>
                </div>
            )}

            {expanded && (
                <>
                    <div className="border-t">
                        {items.length === 0 && (
                            <div className="flex items-center gap-2 px-12 py-5">
                                <p className="text-xs italic text-muted-foreground">Belum ada konten di chapter ini</p>
                            </div>
                        )}

                        {items.map((item, i) => {
                            const { sub, href } = itemMeta(item);
                            const isDragging = draggingIdx === i;
                            let lessonSeqNum: number | null = null;
                            let isLessonLocked = false;
                            if (item.kind === 'lesson') {
                                lessonSeqNum = lessonCounter + 1;
                                isLessonLocked = isSequential && lessonCounter > 0;
                                lessonCounter++;
                            }

                            return (
                                <div
                                    key={`${item.kind}-${item.id}`}
                                    draggable={canEdit}
                                    onDragStart={() => handleItemDragStart(i)}
                                    onDragOver={e => handleItemDragOver(e, i)}
                                    onDrop={handleItemDrop}
                                    onDragEnd={handleItemDragEnd}
                                    className={[
                                        'group flex items-center gap-3 border-b px-4 py-2.5 last:border-0 select-none',
                                        'transition-all duration-150',
                                        isDragging
                                            ? 'opacity-40 bg-muted/40 scale-[0.99]'
                                            : 'opacity-100 hover:bg-muted/20',
                                    ].join(' ')}
                                >
                                    <div className="cursor-grab text-muted-foreground/25 hover:text-muted-foreground/60 active:cursor-grabbing shrink-0">
                                        <GripVertical className="h-3.5 w-3.5" />
                                    </div>

                                    {isSequential && item.kind === 'lesson' && (
                                        <span className={`flex h-5 w-5 shrink-0 items-center justify-center rounded text-[10px] font-bold ${
                                            isLessonLocked
                                                ? 'bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400'
                                                : 'bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400'
                                        }`}>
                                            {isLessonLocked ? <Lock className="h-2.5 w-2.5" /> : lessonSeqNum}
                                        </span>
                                    )}
                                    {isSequential && item.kind !== 'lesson' && (
                                        <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded bg-muted text-[10px]">
                                            <Lock className="h-2.5 w-2.5 text-muted-foreground" />
                                        </span>
                                    )}

                                    {itemIcon(item)}

                                    <div className="min-w-0 flex-1">
                                        {href ? (
                                            <Link href={href} className="block truncate text-sm font-medium hover:text-blue-600 hover:underline underline-offset-2">{item.title}</Link>
                                        ) : (
                                            <p className="truncate text-sm font-medium">{item.title}</p>
                                        )}
                                        <p className="text-xs text-muted-foreground">{sub}</p>
                                    </div>

                                    {canEdit && (
                                        <button
                                            onClick={() => delItem(item)}
                                            className="hidden rounded-md p-1.5 text-destructive bg-destructive/5 hover:bg-destructive/15 hover:text-destructive border border-destructive/20 dark:text-red-400 dark:bg-red-950/20 dark:hover:bg-red-950/40 transition-colors shrink-0 group-hover:flex"
                                        >
                                            <Trash2 className="h-3.5 w-3.5" />
                                        </button>
                                    )}
                                </div>
                            );
                        })}
                    </div>

                    {/* Add content row */}
                    {canEdit && (
                        <div className="flex items-center gap-2 border-t bg-muted/10 px-4 py-2.5">
                            <span className="mr-1 text-xs text-muted-foreground font-medium">Tambah:</span>
                            <Link
                                href={`/instructor/courses/${courseSlug}/chapters/${chapter.id}/lessons/create`}
                                className="flex items-center gap-1.5 rounded-md bg-blue-200 px-2.5 py-1.5 text-xs font-medium text-blue-700 transition-colors hover:bg-blue-300 dark:bg-blue-900/40 dark:text-blue-300 dark:hover:bg-blue-900/60"
                            >
                                <Plus className="h-3.5 w-3.5" /> Materi
                            </Link>
                            <AddQuizModal courseSlug={courseSlug} chapterId={chapter.id} />
                            <AddAssignmentModal courseSlug={courseSlug} chapterId={chapter.id} />
                        </div>
                    )}
                </>
            )}

            <DeleteConfirmModal
                open={delChapterModal}
                onClose={() => setDelChapterModal(false)}
                onConfirm={confirmDel}
                title={`Hapus chapter "${chapter.title}"?`}
                description="Chapter dan semua isinya akan dihapus permanen."
                blockedReason={chapterBlockedReason}
            />
            <DeleteConfirmModal
                open={!!delItemModal}
                onClose={() => setDelItemModal(null)}
                onConfirm={confirmDelItem}
                title={delItemModal ? `Hapus ${delItemModal.kind === 'lesson' ? 'materi' : delItemModal.kind === 'quiz' ? 'kuis' : 'tugas'} "${delItemModal.title}"?` : ''}
                description="Item ini akan dihapus permanen."
            />
        </div>
    );
}

// ── Stat Card ──
function StatCard({ value, label, bgClass, textClass }: { value: number; label: string; bgClass: string; textClass: string }) {
    return (
        <div className={`rounded-xl p-4 shadow-xs ${bgClass}`}>
            <p className={`text-2xl font-bold tracking-tight ${textClass}`}>{value}</p>
            <p className={`mt-0.5 text-xs opacity-70 ${textClass}`}>{label}</p>
        </div>
    );
}

// ── Edit Course Dialog Modal ──
function EditCourseDialog({
    course,
    categories,
}: {
    course: Course;
    categories: { id: number; name: string }[];
}) {
    const [open, setOpen] = useState(false);
    const [thumbPreview, setThumbPreview] = useState<string | null>(course.thumbnail);
    const [priceType, setPriceType] = useState<string>(course.price_type);
    const thumbInputRef = useRef<HTMLInputElement>(null);

    function handleThumbChange(e: React.ChangeEvent<HTMLInputElement>) {
        const file = e.target.files?.[0];
        if (!file) return;
        setThumbPreview(URL.createObjectURL(file));
    }

    function clearThumb() {
        setThumbPreview(null);
        if (thumbInputRef.current) thumbInputRef.current.value = '';
    }

    function handleClose(val: boolean) {
        if (!val) {
            setThumbPreview(course.thumbnail);
            if (thumbInputRef.current) thumbInputRef.current.value = '';
        }
        setOpen(val);
    }

    return (
        <Dialog open={open} onOpenChange={handleClose}>
            <DialogTrigger asChild>
                <Button variant="outline" size="sm" className="gap-1.5 w-full text-blue-600 border-blue-200 bg-blue-50/50 hover:bg-blue-100 hover:text-blue-700 dark:border-blue-900/50 dark:text-blue-400 dark:bg-blue-950/20 dark:hover:bg-blue-950/40 shadow-xs">
                    <Pencil className="h-3.5 w-3.5" /> Edit Informasi
                </Button>
            </DialogTrigger>
            <DialogContent className="max-h-[90vh] max-w-md overflow-y-auto">
                <DialogTitle>Edit Informasi Kelas</DialogTitle>
                <Form
                    action={`/instructor/courses/${course.slug}`}
                    method="post"
                    onSuccess={() => { setOpen(false); router.reload({ preserveScroll: true }); }}
                    className="mt-3 flex flex-col gap-3"
                >
                    {({ errors, processing }) => (
                        <>
                            <input type="hidden" name="_method" value="PATCH" />
                            <div className="grid gap-1.5">
                                <Label>Gambar Cover Kelas</Label>
                                <input
                                    ref={thumbInputRef}
                                    type="file"
                                    name="thumbnail"
                                    accept="image/*"
                                    className="hidden"
                                    onChange={handleThumbChange}
                                />
                                {thumbPreview ? (
                                    <div className="relative w-full overflow-hidden rounded-xl border">
                                        <img src={thumbPreview} alt="Preview" className="h-36 w-full object-cover" />
                                        <button
                                            type="button"
                                            onClick={clearThumb}
                                            className="absolute right-2 top-2 flex h-7 w-7 items-center justify-center rounded-full bg-black/60 text-white hover:bg-black/80"
                                        >
                                            <X className="h-4 w-4" />
                                        </button>
                                    </div>
                                ) : (
                                    <button
                                        type="button"
                                        onClick={() => thumbInputRef.current?.click()}
                                        className="flex h-36 w-full flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed transition-colors hover:border-blue-400 hover:bg-blue-50/50 dark:hover:bg-blue-950/20"
                                    >
                                        <ImagePlus className="h-7 w-7 text-muted-foreground" />
                                        <span className="text-sm text-muted-foreground">Klik untuk upload gambar cover</span>
                                        <span className="text-xs text-muted-foreground">PNG, JPG, WEBP — maks. 2MB</span>
                                    </button>
                                )}
                                <InputError message={errors.thumbnail} />
                            </div>
                            <div className="grid gap-1.5">
                                <Label htmlFor="title_edit">Judul *</Label>
                                <Input id="title_edit" name="title" defaultValue={course.title} required />
                                <InputError message={errors.title} />
                            </div>
                            <div className="grid gap-1.5">
                                <Label htmlFor="description_edit">Deskripsi</Label>
                                <textarea id="description_edit" name="description" rows={3} defaultValue={course.description ?? ''} className={textareaCls} />
                                <InputError message={errors.description} />
                            </div>
                            <div className="grid gap-1.5">
                                <Label htmlFor="category_id_edit">Kategori</Label>
                                <select id="category_id_edit" name="category_id" defaultValue={course.category?.id ?? ''} className={selectCls}>
                                    <option value="">-- Pilih --</option>
                                    {categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                                </select>
                                <InputError message={errors.category_id} />
                            </div>
                            <div className="grid grid-cols-2 gap-3">
                                <div className="grid gap-1.5">
                                    <Label htmlFor="level_edit">Level *</Label>
                                    <select id="level_edit" name="level" defaultValue={course.level} required className={selectCls}>
                                        <option value="beginner">Pemula</option>
                                        <option value="intermediate">Menengah</option>
                                        <option value="advanced">Lanjutan</option>
                                    </select>
                                    <InputError message={errors.level} />
                                </div>
                                <div className="grid gap-1.5">
                                    <Label htmlFor="price_type_edit">Tipe Harga *</Label>
                                    <select 
                                        id="price_type_edit" 
                                        name="price_type" 
                                        defaultValue={course.price_type} 
                                        required 
                                        className={selectCls}
                                        onChange={(e) => setPriceType(e.target.value)}
                                    >
                                        <option value="free">Gratis</option>
                                        <option value="paid">Berbayar</option>
                                    </select>
                                    <InputError message={errors.price_type} />
                                </div>
                            </div>

                            {priceType === 'paid' && (
                                <div className="rounded-xl border bg-blue-50/50 p-4 dark:bg-blue-950/20 mt-2 flex flex-col gap-3">
                                    <div className="grid gap-1">
                                        <Label htmlFor="price_input" className="text-xs font-semibold">Harga (Rp) *</Label>
                                        <Input id="price_input" name="price" type="number" min="0" defaultValue={course.price} required />
                                        <InputError message={errors.price} />
                                    </div>
                                </div>
                            )}

                            <div className="flex justify-end gap-2 pt-1">
                                <Button type="button" variant="outline" onClick={() => handleClose(false)}>Batal</Button>
                                <Button type="submit" disabled={processing} className="gap-1.5 bg-blue-600 hover:bg-blue-700 text-white shadow-xs">
                                    {processing ? <Spinner /> : <Save className="h-3.5 w-3.5" />} Simpan
                                </Button>
                            </div>
                        </>
                    )}
                </Form>
            </DialogContent>
        </Dialog>
    );
}

function InfoRow({ label, value, valueClass }: { label: string; value: string; valueClass?: string }) {
    return (
        <div className="flex items-center justify-between gap-3 py-2.5">
            <span className="text-xs text-muted-foreground shrink-0">{label}</span>
            <span className={`text-xs font-medium text-right truncate ${valueClass ?? 'text-foreground'}`}>{value}</span>
        </div>
    );
}

function ToggleSwitch({ checked, onChange, disabled }: { checked: boolean; onChange: (v: boolean) => void; disabled: boolean }) {
    return (
        <button
            type="button"
            role="switch"
            aria-checked={checked}
            disabled={disabled}
            onClick={() => onChange(!checked)}
            className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ${checked ? 'bg-blue-600' : 'bg-input'} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
        >
            <span
                className={`pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow-sm ring-0 transition duration-200 ${checked ? 'translate-x-4' : 'translate-x-0'}`}
            />
        </button>
    );
}

// ── Main Page ──
export default function InstructorCourseShow({ course, enrollmentCount, categories }: Props) {
    const sc = STATUS_CONFIG[course.status] ?? STATUS_CONFIG.draft;
    const [isSequential, setIsSequential] = useState(course.is_sequential);
    const [chapters, setChapters] = useState<Chapter[]>(course.chapters);
    const dragChapterRef = useRef<number | null>(null);
    const [draggingChapterIdx, setDraggingChapterIdx] = useState<number | null>(null);

    useEffect(() => { setChapters(course.chapters); }, [course.chapters]);
    useEffect(() => { setIsSequential(course.is_sequential); }, [course.is_sequential]);

    const [deleteModal, setDeleteModal] = useState(false);

    const totalLessons = chapters.reduce((a, c) => a + c.lessons.length, 0);
    const totalQuizzesAssignments = chapters.reduce((a, c) => a + c.quizzes.length + c.assignments.length, 0);

    const courseBlockedReason = chapters.length > 0
        ? `Kelas tidak dapat dihapus karena masih memiliki ${chapters.length} chapter. Hapus semua chapter terlebih dahulu.`
        : enrollmentCount > 0
        ? `Kelas tidak dapat dihapus karena ada ${enrollmentCount} siswa yang terdaftar.`
        : undefined;

    const canEdit = course.status !== 'published' && course.status !== 'pending_review';
    const canSubmit = course.status === 'draft' && chapters.length > 0;

    function changeStatus(status: string) {
        router.patch(`/instructor/courses/${course.slug}/status`, { status }, { preserveScroll: true });
    }

    function toggleSequential(value: boolean) {
        if (!canEdit) return;
        setIsSequential(value);
        router.patch(`/instructor/courses/${course.slug}`, { is_sequential: value }, { preserveScroll: true });
    }

    const [showSubmitReview, setShowSubmitReview] = useState(false);

    function submitReview() {
        router.post(`/instructor/courses/${course.slug}/submit-review`);
        setShowSubmitReview(false);
    }

    function confirmDeleteCourse() {
        router.delete(`/instructor/courses/${course.slug}`, {
            onSuccess: () => router.visit('/instructor/courses'),
        });
    }

    function handleChapterDragStart(index: number) {
        if (!canEdit) return;
        dragChapterRef.current = index;
        setDraggingChapterIdx(index);
    }

    function handleChapterDragOver(overIndex: number, e: React.DragEvent) {
        e.preventDefault();
        const from = dragChapterRef.current;
        if (from === null || from === overIndex) return;
        setChapters(prev => {
            const next = [...prev];
            const [moved] = next.splice(from, 1);
            next.splice(overIndex, 0, moved);
            return next;
        });
        dragChapterRef.current = overIndex;
        setDraggingChapterIdx(overIndex);
    }

    function handleChapterDrop() {
        setDraggingChapterIdx(null);
        dragChapterRef.current = null;
        router.patch(`/instructor/courses/${course.slug}/chapters/reorder`, {
            order: chapters.map(ch => ch.id),
        }, { preserveScroll: true });
    }

    function handleChapterDragEnd() {
        setDraggingChapterIdx(null);
        dragChapterRef.current = null;
    }

    const lessonOffsets = chapters.reduce<{ offsets: number[]; total: number }>(
        (acc, ch) => {
            acc.offsets.push(acc.total);
            acc.total += ch.lessons.length;
            return acc;
        },
        { offsets: [], total: 0 },
    );

    return (
        <>
            <Head title={course.title} />

            <div className="flex flex-col gap-0">
                {/* ── Page Header ── */}
                <div className="border-b border-blue-100 bg-gradient-to-br from-blue-50 via-white to-indigo-50 px-4 py-5 dark:border-blue-900/30 dark:from-blue-950/30 dark:via-card dark:to-indigo-950/20 md:px-8">
                    {/* Back link */}
                    <Link
                        href="/instructor/courses"
                        className="mb-4 inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors"
                    >
                        <ArrowLeft className="h-3.5 w-3.5" /> Kembali ke daftar kelas
                    </Link>

                    <div className="flex flex-wrap items-start justify-between gap-4">
                        {/* Title + meta */}
                        <div className="min-w-0 flex-1">
                            <div className="flex flex-wrap items-center gap-2.5">
                                <h1 className="text-xl font-bold tracking-tight sm:text-2xl">{course.title}</h1>
                                <span className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-semibold ${sc.badge}`}>
                                    <span className={`h-1.5 w-1.5 rounded-full ${sc.dot}`} />
                                    {sc.label}
                                </span>
                                {isSequential && (
                                    <span className="inline-flex items-center gap-1 rounded-full bg-amber-100 px-2.5 py-1 text-xs font-semibold text-amber-700 dark:bg-amber-900/30 dark:text-amber-400">
                                        <Lock className="h-3 w-3" /> Berurutan
                                    </span>
                                )}
                            </div>

                            {/* Meta chips */}
                            <div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-sm text-muted-foreground">
                                <span className="flex items-center gap-1">
                                    <Users className="h-3.5 w-3.5 shrink-0" />
                                    <span className="font-medium text-foreground">{enrollmentCount}</span> siswa
                                </span>
                                <span className="flex items-center gap-1">
                                    <span className="h-3.5 w-px bg-border" />
                                    {LEVEL_LABELS[course.level] ?? course.level}
                                </span>
                                {course.category && (
                                    <span className="flex items-center gap-1">
                                        <span className="h-3.5 w-px bg-border" />
                                        <Tag className="h-3 w-3 shrink-0" />
                                        {course.category.name}
                                    </span>
                                )}
                                <span className="flex items-center gap-1">
                                    <span className="h-3.5 w-px bg-border" />
                                    <span className={`font-semibold ${course.price_type === 'free' ? 'text-emerald-600 dark:text-emerald-400' : 'text-foreground'}`}>
                                        {course.price_type === 'free' ? 'Gratis' : `Rp ${course.price.toLocaleString('id-ID')}`}
                                    </span>
                                </span>
                            </div>
                        </div>

                        {/* Actions */}
                        <div className="flex flex-wrap items-center gap-2 shrink-0">
                            {canSubmit && (
                                <Button size="sm" onClick={() => setShowSubmitReview(true)} className="gap-1.5 bg-blue-600 hover:bg-blue-700 text-white shadow-xs">
                                    Submit Review
                                </Button>
                            )}

                            <div className="relative flex items-center">
                                <span className={`pointer-events-none absolute left-3 h-2 w-2 rounded-full ${sc.dot}`} />
                                <select
                                    value={course.status}
                                    onChange={e => changeStatus(e.target.value)}
                                    className="h-8 rounded-md border bg-background pl-7 pr-8 text-sm shadow-xs focus:outline-none focus:ring-2 focus:ring-ring/50 cursor-pointer appearance-none"
                                >
                                    <option value="draft">Draft</option>
                                    <option value="pending_review">Perlu Review</option>
                                    <option value="archived">Arsip</option>
                                    {course.status === 'published' && <option value="published">Aktif</option>}
                                    {course.status === 'rejected' && <option value="rejected">Ditolak</option>}
                                </select>
                                <ChevronDown className="pointer-events-none absolute right-2.5 h-3.5 w-3.5 text-muted-foreground" />
                            </div>

                            <Button variant="outline" size="sm" asChild className="text-zinc-600 border-zinc-200 bg-zinc-50/50 hover:bg-zinc-100 hover:text-zinc-700 dark:border-zinc-800 dark:text-zinc-400 dark:bg-zinc-950/20 dark:hover:bg-zinc-950/40 shadow-xs">
                                <Link href={`/courses/${course.slug}`} target="_blank" className="gap-1.5">
                                    <ExternalLink className="h-3.5 w-3.5" /> Lihat Publik
                                </Link>
                            </Button>

                            {enrollmentCount === 0 && course.status !== 'published' && (
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() => setDeleteModal(true)}
                                    className="gap-1.5 text-red-600 border-red-200 bg-red-50/50 hover:bg-red-100 hover:text-red-700 dark:border-red-900/50 dark:text-red-400 dark:bg-red-950/20 dark:hover:bg-red-950/40 shadow-xs"
                                >
                                    <Trash2 className="h-3.5 w-3.5" /> Hapus
                                </Button>
                            )}
                        </div>
                    </div>
                </div>

                {/* Notifications & warnings */}
                <div className="px-4 pt-6 md:px-8">
                    {course.status === 'rejected' && (
                        <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700 dark:border-red-800 dark:bg-red-900/20 dark:text-red-400">
                            Kelas ini ditolak admin. Perbaiki materi lalu submit ulang.
                        </div>
                    )}
                    {course.status === 'pending_review' && (
                        <div className="rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-700 dark:border-amber-800 dark:bg-amber-900/20 dark:text-amber-400">
                            Kelas sedang dalam review admin. Anda tidak bisa mengedit materi saat ini.
                        </div>
                    )}
                </div>

                {/* ── Main Content ── */}
                <div className="px-4 py-6 md:px-8">
                    <div className="grid gap-6 lg:grid-cols-[1fr_288px]">

                        {/* ── Curriculum Panel ── */}
                        <div className="flex flex-col gap-4">
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-2.5">
                                    <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-blue-100 dark:bg-blue-900/30">
                                        <LayoutList className="h-4 w-4 text-blue-600 dark:text-blue-400" />
                                    </div>
                                    <div>
                                        <h2 className="text-sm font-semibold leading-none">Kurikulum</h2>
                                        <p className="mt-0.5 text-xs text-muted-foreground">
                                            {chapters.length} chapter · {totalLessons} materi
                                        </p>
                                    </div>
                                </div>
                                {canEdit && <AddChapterModal courseSlug={course.slug} />}
                            </div>

                            {chapters.length === 0 ? (
                                <div className="rounded-xl border border-dashed border-blue-200 bg-blue-50/40 p-14 text-center dark:border-blue-800/50 dark:bg-blue-950/20">
                                    <div className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-blue-100 dark:bg-blue-900/30">
                                        <BookOpen className="h-6 w-6 text-blue-400" />
                                    </div>
                                    <p className="text-sm font-medium text-blue-900 dark:text-blue-200">Belum ada chapter</p>
                                    <p className="mt-1 text-xs text-blue-600/70 dark:text-blue-400/70">Klik "+ Tambah Chapter" untuk mulai menyusun materi</p>
                                </div>
                            ) : (
                                <div className="flex flex-col gap-2.5">
                                    {isSequential && (
                                        <div className="flex items-start gap-2.5 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-xs text-amber-700 dark:border-amber-800/40 dark:bg-amber-900/20 dark:text-amber-400">
                                            <Lock className="mt-0.5 h-3.5 w-3.5 shrink-0" />
                                            <p>
                                                <strong>Mode Berurutan aktif.</strong>{' '}
                                                Siswa harus menyelesaikan semua materi di setiap chapter sebelum bisa mengakses chapter berikutnya.
                                                Seret chapter untuk mengatur urutan.
                                            </p>
                                        </div>
                                    )}

                                    {chapters.map((ch, i) => (
                                        <ChapterCard
                                            key={ch.id}
                                            chapter={ch}
                                            courseSlug={course.slug}
                                            chapterIndex={i}
                                            globalLessonOffset={lessonOffsets.offsets[i] ?? 0}
                                            isSequential={isSequential}
                                            isDragging={draggingChapterIdx === i}
                                            isDragOver={draggingChapterIdx !== null && draggingChapterIdx !== i}
                                            onDragStart={() => handleChapterDragStart(i)}
                                            onDragOver={e => handleChapterDragOver(i, e)}
                                            onDragEnd={handleChapterDragEnd}
                                            onDrop={handleChapterDrop}
                                            canEdit={canEdit}
                                        />
                                    ))}
                                </div>
                            )}
                        </div>

                        {/* ── Sidebar ── */}
                        <div className="flex flex-col gap-4 lg:sticky lg:top-20 self-start">

                            {/* Stats Grid */}
                            <div className="grid grid-cols-2 gap-3">
                                <StatCard value={chapters.length} label="Chapter" bgClass="bg-blue-100 dark:bg-blue-900/30" textClass="text-blue-800 dark:text-blue-200" />
                                <StatCard value={enrollmentCount} label="Siswa Aktif" bgClass="bg-emerald-100 dark:bg-emerald-900/30" textClass="text-emerald-800 dark:text-emerald-200" />
                                <StatCard value={totalLessons} label="Materi" bgClass="bg-teal-100 dark:bg-teal-900/30" textClass="text-teal-800 dark:text-teal-200" />
                                <StatCard value={totalQuizzesAssignments} label="Kuis & Tugas" bgClass="bg-amber-100 dark:bg-amber-900/30" textClass="text-amber-800 dark:text-amber-200" />
                            </div>

                            {/* Course Info Card */}
                            <div className="rounded-xl border border-blue-100 bg-white shadow-xs dark:border-blue-900/30 dark:bg-card overflow-hidden">
                                <div className="flex items-center justify-between border-b border-blue-100 bg-blue-50/60 px-4 py-3 dark:border-blue-900/20 dark:bg-blue-950/20">
                                    <p className="text-sm font-semibold text-blue-900 dark:text-blue-100">Informasi Kelas</p>
                                </div>
                                {course.thumbnail ? (
                                    <div className="relative w-full aspect-video border-b overflow-hidden bg-slate-100 dark:bg-slate-900">
                                        <img src={course.thumbnail} alt={course.title} className="w-full h-full object-cover" />
                                    </div>
                                ) : (
                                    <div className={`relative w-full aspect-video border-b overflow-hidden bg-gradient-to-br ${CARD_GRADIENTS[course.id % CARD_GRADIENTS.length]} flex items-center justify-center`}>
                                        <BookOpen className="h-10 w-10 text-slate-500/50" />
                                    </div>
                                )}
                                <div className="divide-y px-4 py-1">
                                    <InfoRow label="Kategori" value={course.category?.name ?? 'Tanpa kategori'} />
                                    <InfoRow label="Level" value={LEVEL_LABELS[course.level] ?? course.level} />
                                    <InfoRow
                                        label="Harga"
                                        value={course.price_type === 'free' ? 'Gratis' : `Rp ${course.price.toLocaleString('id-ID')}`}
                                        valueClass={course.price_type === 'free' ? 'text-emerald-600 dark:text-emerald-400 font-semibold' : undefined}
                                    />
                                </div>
                                {course.description && (
                                    <div className="border-t px-4 py-3">
                                        <p className="text-xs text-muted-foreground line-clamp-4 leading-relaxed">{course.description}</p>
                                    </div>
                                )}
                                {canEdit && (
                                    <div className="border-t px-4 py-3">
                                        <EditCourseDialog course={course} categories={categories} />
                                    </div>
                                )}
                            </div>

                            {/* Access Settings Card */}
                            <div className="rounded-xl border border-teal-100 bg-white shadow-xs dark:border-teal-900/30 dark:bg-card">
                                <div className="border-b border-teal-100 bg-teal-50/60 px-4 py-3 dark:border-teal-900/20 dark:bg-teal-950/20">
                                    <p className="text-sm font-semibold text-teal-900 dark:text-teal-100">Pengaturan Akses</p>
                                </div>
                                <div className="px-4 py-4">
                                    <div className="flex items-center justify-between gap-3">
                                        <div className="min-w-0">
                                            <p className="text-sm font-medium">Mode Berurutan</p>
                                            <p className="mt-0.5 text-xs text-muted-foreground leading-relaxed">
                                                Materi terkunci hingga chapter sebelumnya selesai
                                            </p>
                                        </div>
                                        <ToggleSwitch checked={isSequential} onChange={toggleSequential} disabled={!canEdit} />
                                    </div>

                                    {isSequential && (
                                        <div className="mt-3 rounded-lg bg-amber-50 px-3 py-2.5 dark:bg-amber-900/20">
                                            <p className="text-xs text-amber-700 dark:text-amber-400 leading-relaxed">
                                                Siswa harus menyelesaikan semua lesson di Chapter 1 sebelum bisa membuka Chapter 2, dan seterusnya.
                                            </p>
                                        </div>
                                    )}
                                </div>
                            </div>

                            {/* Affiliate Info (read-only, admin manages this) */}
                            <div className="rounded-xl border border-slate-100 bg-white shadow-xs dark:border-slate-800 dark:bg-card">
                                <div className="border-b border-slate-100 bg-slate-50/60 px-4 py-3 dark:border-slate-800 dark:bg-slate-950/20 flex items-center gap-2">
                                    <Link2 className="h-4 w-4 text-slate-400" />
                                    <p className="text-sm font-semibold text-slate-700 dark:text-slate-300">Affiliate</p>
                                    <span className="ml-auto flex items-center gap-1 rounded-full bg-slate-100 px-2 py-0.5 text-[10px] font-semibold text-slate-500 dark:bg-slate-800 dark:text-slate-400">
                                        <ShieldCheck className="h-3 w-3" /> Diatur Admin
                                    </span>
                                </div>
                                <div className="px-4 py-3 flex flex-col gap-2">
                                    <div className="flex items-center justify-between">
                                        <span className="text-xs text-muted-foreground">Status</span>
                                        {course.affiliate_enabled ? (
                                            <span className="rounded-full bg-emerald-100 px-2 py-0.5 text-[11px] font-semibold text-emerald-700">Aktif</span>
                                        ) : (
                                            <span className="rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-semibold text-slate-500">Nonaktif</span>
                                        )}
                                    </div>
                                    {course.affiliate_enabled && (
                                        <>
                                            {course.alumni_commission_rate !== null && (
                                                <div className="flex items-center justify-between">
                                                    <span className="text-xs text-muted-foreground">Komisi Alumni</span>
                                                    <span className="text-xs font-semibold">{course.alumni_commission_rate}%</span>
                                                </div>
                                            )}
                                            {course.non_alumni_commission_rate !== null && (
                                                <div className="flex items-center justify-between">
                                                    <span className="text-xs text-muted-foreground">Komisi Non-alumni</span>
                                                    <span className="text-xs font-semibold">{course.non_alumni_commission_rate}%</span>
                                                </div>
                                            )}
                                        </>
                                    )}
                                    <p className="text-[11px] text-muted-foreground/70 mt-1">
                                        Pengaturan affiliate dikelola oleh admin.
                                    </p>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>

            <DeleteConfirmModal
                open={deleteModal}
                onClose={() => setDeleteModal(false)}
                onConfirm={confirmDeleteCourse}
                title={`Hapus kelas "${course.title}"?`}
                description="Tindakan ini tidak dapat dibatalkan."
                blockedReason={courseBlockedReason}
            />

            <DeleteConfirmModal
                open={showSubmitReview}
                onClose={() => setShowSubmitReview(false)}
                onConfirm={submitReview}
                title="Submit untuk Review Admin?"
                description="Kelas akan dikirim ke admin untuk ditinjau. Pastikan semua konten sudah lengkap."
                confirmLabel="Ya, Submit"
            />
        </>
    );
}

InstructorCourseShow.layout = (page: React.ReactNode) => (
    <AppLayout breadcrumbs={breadcrumbs}>{page}</AppLayout>
);
