import { Form, Head, Link, router, usePage } from '@inertiajs/react';
import {
    Award,
    BookOpen,
    Check,
    CheckCircle2,
    ChevronDown,
    ClipboardList,
    Clock,
    Copy,
    FileText,
    GraduationCap,
    Link2,
    Lock,
    Play,
    Settings,
    Users,
} from 'lucide-react';
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import GuestLayout from '@/layouts/guest-layout';

type Lesson = {
    id: number;
    title: string;
    type: string;
    duration_minutes: number;
    order: number;
};
type Quiz = {
    id: number;
    title: string;
    duration_minutes: number;
    order: number;
};
type Assignment = {
    id: number;
    title: string;
    deadline: string | null;
    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;
    objectives: string | null;
    thumbnail: string | null;
    level: string;
    price_type: 'free' | 'paid';
    price: number;
    bank_name: string | null;
    bank_account: string | null;
    bank_holder: string | null;
    duration_minutes: number;
    enrollments_count: number;
    lessons_count: number;
    affiliate_enabled: boolean;
    instructor: {
        id: number;
        name: string;
        avatar: string | null;
        bio: string | null;
    };
    category: { id: number; name: string } | null;
    chapters: Chapter[];
};

type Enrollment = {
    id: number;
    status: 'pending' | 'active' | 'completed';
    payment_confirmation: {
        status: 'pending' | 'approved' | 'rejected';
    } | null;
} | null;

type Props = {
    course: Course;
    enrollment: Enrollment;
    isInCart: boolean;
    adminPreview?: boolean;
    affiliateCode: string | null;
    affiliateStatus: 'pending' | 'approved' | 'rejected' | null;
};

const BRAND = '#118AB2';
const BRAND_DARK = '#0A2540';

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

const levelColors: Record<string, { bg: string; text: string }> = {
    beginner: { bg: 'rgba(6,214,160,0.15)', text: '#05A57D' },
    intermediate: { bg: 'rgba(255,183,3,0.15)', text: '#B8820A' },
    advanced: { bg: 'rgba(230,57,70,0.15)', text: '#C0303B' },
};

function formatPrice(price: number): string {
    return new Intl.NumberFormat('id-ID', {
        style: 'currency',
        currency: 'IDR',
        maximumFractionDigits: 0,
    }).format(price);
}

function formatDuration(minutes: number): string {
    if (minutes < 60) return `${minutes} mnt`;
    const h = Math.floor(minutes / 60);
    const m = minutes % 60;
    return m > 0 ? `${h}j ${m}mnt` : `${h} jam`;
}

function LessonIcon({ type }: { type: string }) {
    if (type === 'video') return <Play className="h-3.5 w-3.5" />;
    if (type === 'pdf') return <FileText className="h-3.5 w-3.5" />;
    return <BookOpen className="h-3.5 w-3.5" />;
}

export default function CourseShow({
    course,
    enrollment,
    isInCart,
    adminPreview,
    affiliateCode,
    affiliateStatus,
}: Props) {
    const { auth } = usePage().props;
    const [openChapter, setOpenChapter] = useState<number | null>(
        course.chapters[0]?.id ?? null,
    );
    const [copied, setCopied] = useState(false);

    function copyAffiliateLink() {
        const link = `${window.location.origin}/ref/${affiliateCode}?to=/courses/${course.slug}`;
        navigator.clipboard.writeText(link);
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
    }

    const isAdmin = auth.user?.role === 'admin';
    const isEnrolled = !!enrollment;
    const isActive = enrollment?.status === 'active';
    const isPending = enrollment?.status === 'pending';

    function handleBuyNow() {
        router.post(`/cart/${course.id}`, { redirect_to: '/checkout' });
    }

    const totalLessons = course.chapters.reduce(
        (sum, ch) => sum + ch.lessons.length,
        0,
    );
    const totalQuizzes = course.chapters.reduce(
        (sum, ch) => sum + ch.quizzes.length,
        0,
    );
    const totalAssignments = course.chapters.reduce(
        (sum, ch) => sum + ch.assignments.length,
        0,
    );
    const objectives = course.objectives
        ? course.objectives.split('\n').filter(Boolean)
        : [];
    const level = levelColors[course.level] ?? {
        bg: 'rgba(0,0,0,0.08)',
        text: '#555555',
    };

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

            {adminPreview && (
                <div className="sticky top-0 z-50 flex items-center justify-between gap-3 bg-amber-500 px-5 py-2.5 text-sm font-medium text-white shadow-md">
                    <span>
                        Pratinjau admin — kelas ini belum dipublikasikan dan
                        tidak terlihat oleh pengguna umum.
                    </span>
                    <Link
                        href={`/admin/courses/${course.id}`}
                        className="shrink-0 rounded-md bg-white/20 px-3 py-1 text-xs font-semibold transition-colors hover:bg-white/30"
                    >
                        Kembali ke Admin
                    </Link>
                </div>
            )}

            {/* ── HERO ──────────────────────────────────────────────────── */}
            <section
                style={{
                    background:
                        'linear-gradient(135deg, #0A2540 0%, #0D3D63 100%)',
                    paddingTop: '48px',
                    paddingBottom: '48px',
                }}
            >
                <div className="mx-auto max-w-7xl px-5 md:px-8">
                    <div className="grid items-center gap-8 lg:grid-cols-[1fr_340px]">
                        {/* Left: Meta */}
                        <div>
                            {course.category && (
                                <Link
                                    href={`/courses?category=${course.category.name}`}
                                    className="mb-3 inline-block rounded-full px-3 py-1 text-xs font-semibold tracking-wide uppercase transition-opacity hover:opacity-80"
                                    style={{
                                        backgroundColor:
                                            'rgba(17,138,178,0.25)',
                                        color: '#60CDEE',
                                    }}
                                >
                                    {course.category.name}
                                </Link>
                            )}

                            <h1
                                className="text-2xl leading-snug font-bold md:text-3xl lg:text-4xl"
                                style={{ color: '#FFFFFF' }}
                            >
                                {course.title}
                            </h1>

                            {course.description && (
                                <p
                                    className="mt-3 line-clamp-3 text-sm leading-relaxed md:text-base"
                                    style={{ color: 'rgba(255,255,255,0.62)' }}
                                >
                                    {course.description}
                                </p>
                            )}

                            {/* Stats row */}
                            <div
                                className="mt-5 flex flex-wrap items-center gap-4 text-sm"
                                style={{ color: 'rgba(255,255,255,0.7)' }}
                            >
                                <span className="flex items-center gap-1.5">
                                    <Users
                                        className="h-4 w-4"
                                        style={{ color: '#06D6A0' }}
                                    />
                                    {course.enrollments_count.toLocaleString(
                                        'id-ID',
                                    )}{' '}
                                    siswa
                                </span>
                                <span className="flex items-center gap-1.5">
                                    <BookOpen
                                        className="h-4 w-4"
                                        style={{ color: '#FFB703' }}
                                    />
                                    {totalLessons} lesson
                                </span>
                                <span className="flex items-center gap-1.5">
                                    <Clock
                                        className="h-4 w-4"
                                        style={{ color: '#60CDEE' }}
                                    />
                                    {formatDuration(course.duration_minutes)}
                                </span>
                                <span
                                    className="rounded-full px-2.5 py-0.5 text-xs font-semibold"
                                    style={{
                                        backgroundColor: level.bg,
                                        color: level.text,
                                    }}
                                >
                                    {levelLabels[course.level] ?? course.level}
                                </span>
                            </div>

                            {/* Instructor */}
                            <div className="mt-5 flex items-center gap-2.5">
                                <div
                                    className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-sm font-bold text-white"
                                    style={{ backgroundColor: BRAND }}
                                >
                                    {course.instructor.name[0]}
                                </div>
                                <span
                                    className="text-sm"
                                    style={{ color: 'rgba(255,255,255,0.62)' }}
                                >
                                    Instruktur:{' '}
                                    <span
                                        className="font-medium"
                                        style={{
                                            color: 'rgba(255,255,255,0.88)',
                                        }}
                                    >
                                        {course.instructor.name}
                                    </span>
                                </span>
                            </div>
                        </div>

                        {/* Right: Thumbnail (desktop hero) */}
                        <div className="hidden lg:block">
                            {course.thumbnail ? (
                                <img
                                    src={course.thumbnail}
                                    alt={course.title}
                                    className="w-full rounded-2xl object-cover shadow-2xl"
                                    style={{ aspectRatio: '16/9' }}
                                />
                            ) : (
                                <div
                                    className="flex w-full items-center justify-center rounded-2xl shadow-2xl"
                                    style={{
                                        aspectRatio: '16/9',
                                        background:
                                            'linear-gradient(135deg, rgba(17,138,178,0.3) 0%, rgba(6,214,160,0.15) 100%)',
                                        border: '1px solid rgba(255,255,255,0.08)',
                                    }}
                                >
                                    <GraduationCap
                                        className="h-16 w-16"
                                        style={{
                                            color: 'rgba(255,255,255,0.25)',
                                        }}
                                    />
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </section>

            {/* ── CONTENT ───────────────────────────────────────────────── */}
            <div className="mx-auto max-w-7xl px-5 py-10 md:px-8">
                <div className="grid gap-8 lg:grid-cols-[1fr_340px]">
                    {/* ── MAIN LEFT ───────────────────────────────────────── */}
                    <div className="flex min-w-0 flex-col gap-10">
                        {/* Thumbnail (mobile) */}
                        {course.thumbnail && (
                            <img
                                src={course.thumbnail}
                                alt={course.title}
                                className="w-full rounded-2xl object-cover shadow-sm lg:hidden"
                                style={{ aspectRatio: '16/9' }}
                            />
                        )}

                        {/* Objectives */}
                        {objectives.length > 0 && (
                            <section
                                className="rounded-2xl p-6"
                                style={{
                                    backgroundColor: 'rgba(17,138,178,0.05)',
                                    border: '1px solid rgba(17,138,178,0.12)',
                                }}
                            >
                                <h2
                                    className="mb-4 text-base font-bold"
                                    style={{ color: '#1A1A1A' }}
                                >
                                    Yang Akan Kamu Pelajari
                                </h2>
                                <ul className="grid gap-2.5 sm:grid-cols-2">
                                    {objectives.map((obj, i) => (
                                        <li
                                            key={i}
                                            className="flex items-start gap-2.5 text-sm"
                                            style={{ color: '#333333' }}
                                        >
                                            <CheckCircle2
                                                className="mt-0.5 h-4 w-4 shrink-0"
                                                style={{ color: '#06D6A0' }}
                                            />
                                            <span>{obj}</span>
                                        </li>
                                    ))}
                                </ul>
                            </section>
                        )}

                        {/* Description */}
                        {course.description && (
                            <section>
                                <h2
                                    className="mb-3 text-base font-bold"
                                    style={{ color: '#1A1A1A' }}
                                >
                                    Deskripsi Kelas
                                </h2>
                                <p
                                    className="text-sm leading-relaxed"
                                    style={{ color: '#555555' }}
                                >
                                    {course.description}
                                </p>
                            </section>
                        )}

                        {/* Curriculum */}
                        <section>
                            <div className="mb-4 flex items-end justify-between">
                                <h2
                                    className="text-base font-bold"
                                    style={{ color: '#1A1A1A' }}
                                >
                                    Kurikulum
                                </h2>
                                <p
                                    className="text-xs"
                                    style={{ color: '#888888' }}
                                >
                                    {course.chapters.length} bab &middot;{' '}
                                    {totalLessons} lesson
                                    {totalQuizzes > 0 &&
                                        ` · ${totalQuizzes} quiz`}
                                    {totalAssignments > 0 &&
                                        ` · ${totalAssignments} tugas`}
                                </p>
                            </div>

                            <div
                                className="overflow-hidden rounded-2xl border"
                                style={{ borderColor: 'rgba(0,0,0,0.08)' }}
                            >
                                {course.chapters.map((chapter, idx) => {
                                    const isOpen = openChapter === chapter.id;
                                    const itemCount =
                                        chapter.lessons.length +
                                        chapter.quizzes.length +
                                        chapter.assignments.length;

                                    return (
                                        <div
                                            key={chapter.id}
                                            style={{
                                                borderTop:
                                                    idx > 0
                                                        ? '1px solid rgba(0,0,0,0.06)'
                                                        : undefined,
                                            }}
                                        >
                                            <button
                                                onClick={() =>
                                                    setOpenChapter(
                                                        isOpen
                                                            ? null
                                                            : chapter.id,
                                                    )
                                                }
                                                className="flex w-full items-center justify-between px-5 py-4 text-left transition-colors"
                                                style={{
                                                    backgroundColor: isOpen
                                                        ? 'rgba(17,138,178,0.04)'
                                                        : '#FFFFFF',
                                                }}
                                                onMouseEnter={(e) => {
                                                    if (!isOpen)
                                                        (
                                                            e.currentTarget as HTMLButtonElement
                                                        ).style.backgroundColor =
                                                            'rgba(0,0,0,0.02)';
                                                }}
                                                onMouseLeave={(e) => {
                                                    if (!isOpen)
                                                        (
                                                            e.currentTarget as HTMLButtonElement
                                                        ).style.backgroundColor =
                                                            '#FFFFFF';
                                                }}
                                            >
                                                <div className="flex items-center gap-3">
                                                    <span
                                                        className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-xs font-bold"
                                                        style={{
                                                            backgroundColor:
                                                                isOpen
                                                                    ? BRAND
                                                                    : 'rgba(0,0,0,0.06)',
                                                            color: isOpen
                                                                ? '#FFFFFF'
                                                                : '#555555',
                                                        }}
                                                    >
                                                        {idx + 1}
                                                    </span>
                                                    <span
                                                        className="text-sm font-semibold"
                                                        style={{
                                                            color: '#1A1A1A',
                                                        }}
                                                    >
                                                        {chapter.title}
                                                    </span>
                                                </div>
                                                <div className="ml-3 flex shrink-0 items-center gap-3">
                                                    <span
                                                        className="text-xs"
                                                        style={{
                                                            color: '#888888',
                                                        }}
                                                    >
                                                        {itemCount} item
                                                    </span>
                                                    <ChevronDown
                                                        className="h-4 w-4 transition-transform"
                                                        style={{
                                                            color: '#888888',
                                                            transform: isOpen
                                                                ? 'rotate(180deg)'
                                                                : 'rotate(0deg)',
                                                        }}
                                                    />
                                                </div>
                                            </button>

                                            {isOpen && (
                                                <div
                                                    style={{
                                                        borderTop:
                                                            '1px solid rgba(0,0,0,0.06)',
                                                        backgroundColor:
                                                            '#FAFAFA',
                                                    }}
                                                >
                                                    {chapter.lessons.map(
                                                        (lesson, li) => (
                                                            <div
                                                                key={lesson.id}
                                                                className="flex items-center gap-3 px-5 py-3 text-sm"
                                                                style={{
                                                                    borderTop:
                                                                        li > 0
                                                                            ? '1px solid rgba(0,0,0,0.04)'
                                                                            : undefined,
                                                                }}
                                                            >
                                                                <span
                                                                    className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full"
                                                                    style={{
                                                                        backgroundColor:
                                                                            'rgba(17,138,178,0.1)',
                                                                        color: BRAND,
                                                                    }}
                                                                >
                                                                    <LessonIcon
                                                                        type={
                                                                            lesson.type
                                                                        }
                                                                    />
                                                                </span>
                                                                <span
                                                                    className="flex-1 leading-snug"
                                                                    style={{
                                                                        color: '#333333',
                                                                    }}
                                                                >
                                                                    {
                                                                        lesson.title
                                                                    }
                                                                </span>
                                                                <div className="flex shrink-0 items-center gap-2">
                                                                    {!isActive && (
                                                                        <Lock
                                                                            className="h-3.5 w-3.5"
                                                                            style={{
                                                                                color: '#BBBBBB',
                                                                            }}
                                                                        />
                                                                    )}
                                                                    {lesson.duration_minutes >
                                                                        0 && (
                                                                        <span
                                                                            className="text-xs"
                                                                            style={{
                                                                                color: '#AAAAAA',
                                                                            }}
                                                                        >
                                                                            {
                                                                                lesson.duration_minutes
                                                                            }
                                                                            mnt
                                                                        </span>
                                                                    )}
                                                                </div>
                                                            </div>
                                                        ),
                                                    )}

                                                    {chapter.quizzes.map(
                                                        (quiz, qi) => (
                                                            <div
                                                                key={`q-${quiz.id}`}
                                                                className="flex items-center gap-3 px-5 py-3 text-sm"
                                                                style={{
                                                                    borderTop:
                                                                        '1px solid rgba(0,0,0,0.04)',
                                                                }}
                                                            >
                                                                <span
                                                                    className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full"
                                                                    style={{
                                                                        backgroundColor:
                                                                            'rgba(255,183,3,0.12)',
                                                                        color: '#B8820A',
                                                                    }}
                                                                >
                                                                    <ClipboardList className="h-3.5 w-3.5" />
                                                                </span>
                                                                <span
                                                                    className="flex-1 leading-snug"
                                                                    style={{
                                                                        color: '#333333',
                                                                    }}
                                                                >
                                                                    {quiz.title}
                                                                </span>
                                                                <div className="flex shrink-0 items-center gap-2">
                                                                    {!isActive && (
                                                                        <Lock
                                                                            className="h-3.5 w-3.5"
                                                                            style={{
                                                                                color: '#BBBBBB',
                                                                            }}
                                                                        />
                                                                    )}
                                                                    <span
                                                                        className="text-xs"
                                                                        style={{
                                                                            color: '#AAAAAA',
                                                                        }}
                                                                    >
                                                                        {
                                                                            quiz.duration_minutes
                                                                        }
                                                                        mnt
                                                                    </span>
                                                                </div>
                                                            </div>
                                                        ),
                                                    )}

                                                    {chapter.assignments.map(
                                                        (assignment) => (
                                                            <div
                                                                key={`a-${assignment.id}`}
                                                                className="flex items-center gap-3 px-5 py-3 text-sm"
                                                                style={{
                                                                    borderTop:
                                                                        '1px solid rgba(0,0,0,0.04)',
                                                                }}
                                                            >
                                                                <span
                                                                    className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full"
                                                                    style={{
                                                                        backgroundColor:
                                                                            'rgba(99,102,241,0.12)',
                                                                        color: '#6366F1',
                                                                    }}
                                                                >
                                                                    <FileText className="h-3.5 w-3.5" />
                                                                </span>
                                                                {isActive ? (
                                                                    <Link
                                                                        href={`/courses/${course.slug}/assignment/${assignment.id}`}
                                                                        className="flex-1 leading-snug underline-offset-2 transition-colors hover:underline"
                                                                        style={{
                                                                            color: BRAND,
                                                                        }}
                                                                    >
                                                                        {
                                                                            assignment.title
                                                                        }
                                                                    </Link>
                                                                ) : (
                                                                    <span
                                                                        className="flex-1 leading-snug"
                                                                        style={{
                                                                            color: '#333333',
                                                                        }}
                                                                    >
                                                                        {
                                                                            assignment.title
                                                                        }
                                                                    </span>
                                                                )}
                                                                {!isActive && (
                                                                    <Lock
                                                                        className="h-3.5 w-3.5 shrink-0"
                                                                        style={{
                                                                            color: '#BBBBBB',
                                                                        }}
                                                                    />
                                                                )}
                                                            </div>
                                                        ),
                                                    )}
                                                </div>
                                            )}
                                        </div>
                                    );
                                })}
                            </div>
                        </section>

                        {/* Instructor */}
                        <section>
                            <h2
                                className="mb-4 text-base font-bold"
                                style={{ color: '#1A1A1A' }}
                            >
                                Instruktur
                            </h2>
                            <div
                                className="flex items-start gap-4 rounded-2xl p-5"
                                style={{
                                    border: '1px solid rgba(0,0,0,0.07)',
                                    backgroundColor: '#FFFFFF',
                                }}
                            >
                                <div
                                    className="flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl text-xl font-bold text-white"
                                    style={{ backgroundColor: BRAND }}
                                >
                                    {course.instructor.name[0]}
                                </div>
                                <div className="min-w-0">
                                    <p
                                        className="font-semibold"
                                        style={{ color: '#1A1A1A' }}
                                    >
                                        {course.instructor.name}
                                    </p>
                                    <p
                                        className="text-xs font-medium"
                                        style={{ color: BRAND }}
                                    >
                                        Instruktur Natagara LMS
                                    </p>
                                    {course.instructor.bio && (
                                        <p
                                            className="mt-2 text-sm leading-relaxed"
                                            style={{ color: '#555555' }}
                                        >
                                            {course.instructor.bio}
                                        </p>
                                    )}
                                </div>
                            </div>
                        </section>
                    </div>

                    {/* ── SIDEBAR RIGHT ───────────────────────────────────── */}
                    <div className="lg:sticky lg:top-[92px] lg:self-start">
                        <div
                            className="overflow-hidden rounded-2xl"
                            style={{
                                border: '1px solid rgba(0,0,0,0.08)',
                                backgroundColor: '#FFFFFF',
                                boxShadow: '0 4px 24px rgba(0,0,0,0.08)',
                            }}
                        >
                            {/* Thumbnail inside card (desktop) */}
                            {course.thumbnail ? (
                                <img
                                    src={course.thumbnail}
                                    alt={course.title}
                                    className="hidden w-full object-cover lg:block"
                                    style={{ aspectRatio: '16/9' }}
                                />
                            ) : (
                                <div
                                    className="hidden w-full items-center justify-center lg:flex"
                                    style={{
                                        aspectRatio: '16/9',
                                        background: `linear-gradient(135deg, rgba(17,138,178,0.12) 0%, rgba(6,214,160,0.08) 100%)`,
                                    }}
                                >
                                    <GraduationCap
                                        className="h-12 w-12"
                                        style={{
                                            color: 'rgba(17,138,178,0.3)',
                                        }}
                                    />
                                </div>
                            )}

                            <div className="p-5">
                                {/* Price */}
                                <div className="mb-5">
                                    {course.price_type === 'free' ? (
                                        <div className="flex items-baseline gap-2">
                                            <span
                                                className="text-3xl font-bold"
                                                style={{ color: '#06D6A0' }}
                                            >
                                                Gratis
                                            </span>
                                            <span
                                                className="text-sm"
                                                style={{ color: '#888888' }}
                                            >
                                                selamanya
                                            </span>
                                        </div>
                                    ) : (
                                        <span
                                            className="text-3xl font-bold"
                                            style={{ color: '#1A1A1A' }}
                                        >
                                            {formatPrice(course.price)}
                                        </span>
                                    )}
                                </div>

                                {/* Admin */}
                                {isAdmin && (
                                    <Link href={`/admin/courses/${course.id}`}>
                                        <Button
                                            variant="outline"
                                            className="w-full gap-2"
                                        >
                                            <Settings className="h-4 w-4" />
                                            Kelola Kelas
                                        </Button>
                                    </Link>
                                )}

                                {/* Pending notice */}
                                {!isAdmin && isPending && (
                                    <div
                                        className="mb-4 rounded-xl p-3.5 text-sm"
                                        style={{
                                            backgroundColor:
                                                'rgba(255,183,3,0.1)',
                                            color: '#8A5C00',
                                        }}
                                    >
                                        <p className="font-semibold">
                                            Menunggu Konfirmasi
                                        </p>
                                        <p className="mt-0.5 text-xs opacity-80">
                                            Admin sedang memverifikasi
                                            pembayaran kamu.
                                        </p>
                                    </div>
                                )}

                                {/* Active — lanjutkan */}
                                {!isAdmin && isActive && (
                                    <>
                                        <Link
                                            href={`/my-courses/${course.slug}`}
                                        >
                                            <button
                                                className="w-full rounded-xl py-3 text-sm font-semibold text-white transition-all hover:-translate-y-0.5 active:translate-y-0"
                                                style={{
                                                    backgroundColor: BRAND,
                                                    boxShadow: `0 4px 16px rgba(17,138,178,0.3)`,
                                                }}
                                            >
                                                Lanjutkan Belajar
                                            </button>
                                        </Link>
                                        {course.affiliate_enabled &&
                                            !affiliateCode &&
                                            affiliateStatus !== 'rejected' && (
                                                <div
                                                    className="mt-3 rounded-xl border p-3"
                                                    style={{
                                                        backgroundColor:
                                                            'rgba(6,214,160,0.06)',
                                                        borderColor:
                                                            'rgba(6,214,160,0.2)',
                                                    }}
                                                >
                                                    {affiliateStatus ===
                                                    'pending' ? (
                                                        <div className="flex items-center gap-2">
                                                            <div className="h-1.5 w-1.5 shrink-0 animate-pulse rounded-full bg-amber-400" />
                                                            <p className="text-xs text-amber-700">
                                                                Pendaftaran
                                                                affiliate kamu
                                                                sedang
                                                                ditinjau...
                                                            </p>
                                                        </div>
                                                    ) : (
                                                        <div className="flex items-center justify-between gap-2">
                                                            <p
                                                                className="text-xs font-medium"
                                                                style={{
                                                                    color: '#047857',
                                                                }}
                                                            >
                                                                Suka kelas ini?
                                                                Rekomendasikan
                                                                &amp; dapat
                                                                komisi!
                                                            </p>
                                                            <Link
                                                                href="/affiliate"
                                                                className="shrink-0 text-xs font-semibold underline"
                                                                style={{
                                                                    color: '#059669',
                                                                }}
                                                            >
                                                                Daftar →
                                                            </Link>
                                                        </div>
                                                    )}
                                                </div>
                                            )}
                                    </>
                                )}

                                {/* Not enrolled */}
                                {!isAdmin && !isEnrolled && (
                                    <>
                                        {course.price_type === 'free' ? (
                                            <Form
                                                action={`/courses/${course.slug}/enroll`}
                                                method="post"
                                            >
                                                {({ processing }) => (
                                                    <button
                                                        type="submit"
                                                        disabled={processing}
                                                        className="flex w-full items-center justify-center gap-2 rounded-xl py-3 text-sm font-semibold text-white transition-all hover:-translate-y-0.5 active:translate-y-0 disabled:opacity-60"
                                                        style={{
                                                            backgroundColor:
                                                                BRAND,
                                                            boxShadow: `0 4px 16px rgba(17,138,178,0.3)`,
                                                        }}
                                                    >
                                                        {processing && (
                                                            <Spinner />
                                                        )}
                                                        Daftar Gratis Sekarang
                                                    </button>
                                                )}
                                            </Form>
                                        ) : isInCart ? (
                                            <div className="flex flex-col gap-2">
                                                <Link
                                                    href="/checkout"
                                                    className="flex w-full items-center justify-center gap-2 rounded-xl py-3 text-sm font-semibold text-white transition-all hover:-translate-y-0.5 active:translate-y-0"
                                                    style={{
                                                        backgroundColor: BRAND,
                                                        boxShadow: `0 4px 16px rgba(17,138,178,0.3)`,
                                                    }}
                                                >
                                                    Lanjut ke Checkout
                                                </Link>
                                                <Link
                                                    href="/cart"
                                                    className="flex w-full items-center justify-center rounded-xl py-2.5 text-sm font-medium transition-colors"
                                                    style={{ color: BRAND }}
                                                >
                                                    Lihat Keranjang
                                                </Link>
                                            </div>
                                        ) : (
                                            <div className="flex flex-col gap-2">
                                                <Form
                                                    action={`/cart/${course.id}`}
                                                    method="post"
                                                >
                                                    {({ processing }) => (
                                                        <button
                                                            type="submit"
                                                            disabled={
                                                                processing
                                                            }
                                                            className="flex w-full items-center justify-center gap-2 rounded-xl py-3 text-sm font-semibold text-white transition-all hover:-translate-y-0.5 active:translate-y-0 disabled:opacity-60"
                                                            style={{
                                                                backgroundColor:
                                                                    BRAND,
                                                                boxShadow: `0 4px 16px rgba(17,138,178,0.3)`,
                                                            }}
                                                        >
                                                            {processing && (
                                                                <Spinner />
                                                            )}
                                                            Tambah ke Keranjang
                                                        </button>
                                                    )}
                                                </Form>
                                                <button
                                                    onClick={handleBuyNow}
                                                    className="flex w-full cursor-pointer items-center justify-center rounded-xl border py-2.5 text-sm font-medium transition-colors hover:bg-gray-50"
                                                    style={{
                                                        borderColor:
                                                            'rgba(0,0,0,0.12)',
                                                        color: '#333333',
                                                    }}
                                                >
                                                    Beli Langsung
                                                </button>
                                            </div>
                                        )}
                                    </>
                                )}

                                {/* Course includes */}
                                <div
                                    className="mt-5 space-y-2.5 border-t pt-5 text-sm"
                                    style={{
                                        borderColor: 'rgba(0,0,0,0.06)',
                                        color: '#555555',
                                    }}
                                >
                                    <p
                                        className="mb-3 text-xs font-semibold tracking-wide uppercase"
                                        style={{ color: '#AAAAAA' }}
                                    >
                                        Kelas ini termasuk
                                    </p>
                                    <div className="flex items-center gap-2.5">
                                        <BookOpen
                                            className="h-4 w-4 shrink-0"
                                            style={{ color: BRAND }}
                                        />
                                        <span>
                                            {totalLessons} video &amp; materi
                                            lesson
                                        </span>
                                    </div>
                                    <div className="flex items-center gap-2.5">
                                        <Clock
                                            className="h-4 w-4 shrink-0"
                                            style={{ color: BRAND }}
                                        />
                                        <span>
                                            {formatDuration(
                                                course.duration_minutes,
                                            )}{' '}
                                            total durasi
                                        </span>
                                    </div>
                                    {totalQuizzes > 0 && (
                                        <div className="flex items-center gap-2.5">
                                            <ClipboardList
                                                className="h-4 w-4 shrink-0"
                                                style={{ color: BRAND }}
                                            />
                                            <span>
                                                {totalQuizzes} kuis interaktif
                                            </span>
                                        </div>
                                    )}
                                    {totalAssignments > 0 && (
                                        <div className="flex items-center gap-2.5">
                                            <FileText
                                                className="h-4 w-4 shrink-0"
                                                style={{ color: BRAND }}
                                            />
                                            <span>
                                                {totalAssignments} tugas praktek
                                            </span>
                                        </div>
                                    )}
                                    <div className="flex items-center gap-2.5">
                                        <Award
                                            className="h-4 w-4 shrink-0"
                                            style={{ color: '#FFB703' }}
                                        />
                                        <span>Sertifikat kelulusan resmi</span>
                                    </div>
                                </div>

                                {/* Affiliate copy link */}
                                {affiliateCode && (
                                    <div
                                        className="mt-4 rounded-xl border p-4"
                                        style={{
                                            backgroundColor:
                                                'rgba(17,138,178,0.04)',
                                            borderColor:
                                                'rgba(17,138,178,0.12)',
                                        }}
                                    >
                                        <div className="mb-2 flex items-center gap-1.5">
                                            <Link2
                                                className="h-3.5 w-3.5"
                                                style={{ color: BRAND }}
                                            />
                                            <p
                                                className="text-xs font-semibold"
                                                style={{ color: BRAND }}
                                            >
                                                Link Affiliate Kamu
                                            </p>
                                        </div>
                                        <p
                                            className="mb-3 font-mono text-[11px] leading-relaxed break-all"
                                            style={{ color: '#555555' }}
                                        >
                                            {window.location.origin}/ref/
                                            {affiliateCode}?to=/courses/
                                            {course.slug}
                                        </p>
                                        <button
                                            onClick={copyAffiliateLink}
                                            className="flex w-full items-center justify-center gap-2 rounded-lg py-2 text-xs font-semibold transition-colors"
                                            style={{
                                                backgroundColor: copied
                                                    ? 'rgba(6,214,160,0.12)'
                                                    : 'rgba(17,138,178,0.1)',
                                                color: copied
                                                    ? '#05A57D'
                                                    : BRAND,
                                            }}
                                        >
                                            {copied ? (
                                                <>
                                                    <Check className="h-3.5 w-3.5" />
                                                    Tersalin!
                                                </>
                                            ) : (
                                                <>
                                                    <Copy className="h-3.5 w-3.5" />
                                                    Salin Link Affiliate
                                                </>
                                            )}
                                        </button>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}

CourseShow.layout = (page: React.ReactNode) => (
    <GuestLayout>{page}</GuestLayout>
);
