import { Head, Link, useForm } from '@inertiajs/react';
import { useState } from 'react';
import { motion, useReducedMotion, type MotionProps } from 'framer-motion';
import {
    BadgeCheck,
    CalendarDays,
    Copy,
    Download,
    FileText,
    FlagTriangleRight,
    Phone,
    Share2,
    ShieldCheck,
    Trophy,
} from 'lucide-react';
import { QRCodeSVG } from 'qrcode.react';
import { SiteActionLink, SiteButton } from '@/components/site-action';
import SiteLayout from '@/components/site-layout';

type ProfileData = {
    id: number;
    type: 'rider' | 'driver';
    display_name: string;
    slug: string;
    hometown: string | null;
    nationality: string;
    verification_status: string;
    photo_url: string | null;
    share_url: string;
    contact: { has_mobile: boolean; mobile?: string };
    bio: string | null;
    disciplines: string[];
    teams: { name: string; slug: string; role: string }[];
    results: {
        event: string;
        event_slug: string;
        class: string | null;
        position: number | null;
        points: number;
    }[];
    can_manage: boolean;
};

type VerificationDocument = {
    id: number;
    type: string;
    status: string;
    mime_type: string | null;
    uploaded_at: string | null;
    preview_url: string | null;
};

type VerificationMessage = {
    id: number;
    kind: string;
    body: string;
    sender: string;
    sender_role: string;
    created_at: string | null;
};

type VerificationRequest = {
    id: number;
    status: string;
    event: {
        title: string;
        starts_at: string | null;
        organizer: string;
    } | null;
    reviewed_at: string | null;
    reviewer: string | null;
    documents: VerificationDocument[];
    messages: VerificationMessage[];
};

type VerificationData = {
    status: string;
    requests: VerificationRequest[];
};

type VerificationFiles = {
    fmssl_licence: File | null;
    nic: File | null;
    birth_certificate: File | null;
    vehicle_permit: File | null;
};

type VerificationForm = {
    event_id: number | '';
    documents: VerificationFiles;
};

type VerificationEvent = {
    id: number;
    title: string;
    starts_at: string | null;
    organizer: string;
};

const documentLabels: Record<string, string> = {
    fmssl_licence: 'FMSSL racing licence',
    nic: 'National identity card',
    birth_certificate: 'Birth document',
    vehicle_permit: 'Vehicle permit',
    licence: 'Previously submitted licence',
    identity: 'Previously submitted identity document',
};

const driverImage =
    'https://images.unsplash.com/photo-1503376780353-7e6692767b70?auto=format&fit=crop&w=1400&q=85';
const riderImage =
    'https://images.unsplash.com/photo-1558981806-ec527fa84c39?auto=format&fit=crop&w=1400&q=85';

export default function ProfileShow({
    profile,
    verification,
    verification_events,
}: {
    profile: ProfileData;
    verification: VerificationData | null;
    verification_events: VerificationEvent[];
}) {
    const emptyFiles = (): VerificationFiles => ({
        fmssl_licence: null,
        nic: null,
        birth_certificate: null,
        vehicle_permit: null,
    });
    const form = useForm<VerificationForm>({
        event_id: '',
        documents: emptyFiles(),
    });
    const replyForm = useForm({ message: '', documents: emptyFiles() });
    const [shareOpen, setShareOpen] = useState(false);
    const reduceMotion = useReducedMotion();
    const isOwner = profile.can_manage;
    const totalPoints = profile.results.reduce(
        (total, result) => total + result.points,
        0,
    );
    const podiums = profile.results.filter(
        (result) => result.position !== null && result.position <= 3,
    ).length;
    const profileImage =
        profile.photo_url ||
        (profile.type === 'rider' ? riderImage : driverImage);
    const reveal: MotionProps = reduceMotion
        ? {}
        : {
              initial: { opacity: 0, y: 24 },
              whileInView: { opacity: 1, y: 0 },
              viewport: { once: true, amount: 0.18 },
              transition: { duration: 0.55, ease: 'easeOut' },
          };
    const activeRequest = verification?.requests.find((request) =>
        ['pending', 'needs_information'].includes(request.status),
    );

    function formatDate(date: string | null): string {
        return date
            ? new Date(date).toLocaleDateString('en-LK', {
                  day: 'numeric',
                  month: 'short',
                  year: 'numeric',
              })
            : 'Date not available';
    }

    return (
        <SiteLayout pageClassName="paddock-page">
            <Head title={`${profile.display_name} · ${profile.type}`}>
                <meta
                    name="description"
                    content={`${profile.display_name}, a ${profile.type} from ${profile.hometown || 'Sri Lanka'}. View racing profile, events and results.`}
                />
            </Head>
            <header className="relative isolate overflow-hidden bg-[#090c0d] text-white">
                <div className="absolute inset-0 -z-20 bg-[radial-gradient(circle_at_16%_18%,#e8422b55,transparent_28%),linear-gradient(115deg,#090c0d_8%,#131a1c_65%,#1b2020_100%)]" />
                <div
                    aria-hidden="true"
                    className="race-track-detail race-track-detail--inverse opacity-30"
                />
                <div className="mx-auto grid max-w-[1440px] items-center gap-8 px-5 py-10 sm:px-8 sm:py-14 lg:grid-cols-[1.1fr_.9fr] lg:gap-12 lg:px-10 lg:py-16">
                    <motion.div
                        initial={reduceMotion ? false : { opacity: 0, x: -24 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{
                            duration: reduceMotion ? 0 : 0.55,
                            ease: 'easeOut',
                        }}
                    >
                        <div className="flex flex-wrap items-center gap-3">
                            <span className="inline-flex items-center gap-2 rounded-full border border-[#e8422b]/50 bg-[#e8422b]/10 px-3 py-1.5 text-[10px] font-black tracking-[.18em] text-[#ff7668] uppercase">
                                <span className="size-1.5 rounded-full bg-[#e8422b]" />
                                {profile.type} · {profile.nationality}
                            </span>
                            {profile.verification_status === 'verified' && (
                                <span className="inline-flex items-center gap-2 rounded-full border border-[#f6c84f]/45 bg-[#f6c84f]/10 px-3 py-1.5 text-xs font-extrabold text-[#ffe18b]">
                                    <BadgeCheck size={15} />
                                    Verified by Racing.lk
                                </span>
                            )}
                        </div>
                        <h1 className="mt-6 max-w-4xl text-5xl leading-[.88] font-black tracking-[-.085em] uppercase sm:text-7xl lg:text-8xl">
                            {profile.display_name}
                        </h1>
                        <p className="mt-5 flex items-center gap-2 text-sm font-semibold text-white/65 sm:text-base">
                            <span className="size-2 rounded-full bg-[#f6c84f]" />
                            {profile.hometown || 'Sri Lanka'} ·{' '}
                            {profile.type === 'rider'
                                ? 'Two-wheel competitor'
                                : 'Four-wheel competitor'}
                        </p>
                        <div className="mt-8 flex flex-wrap gap-3">
                            <SiteActionLink
                                href={`/people?type=${profile.type}`}
                                variant="primary"
                                size="sm"
                            >
                                Explore {profile.type}s
                            </SiteActionLink>
                            <SiteActionLink
                                href="/events"
                                variant="outline"
                                size="sm"
                                className="border-white/20 text-white hover:border-[#f6c84f] hover:text-[#f6c84f]"
                            >
                                Race calendar
                            </SiteActionLink>
                            <SiteButton
                                variant="hover-outline-inverse"
                                size="sm"
                                onClick={() => setShareOpen((open) => !open)}
                                aria-expanded={shareOpen}
                            >
                                <Share2 size={15} />
                                Share profile
                            </SiteButton>
                        </div>
                        {shareOpen && (
                            <div className="mt-5 flex max-w-xl flex-wrap items-center gap-4 rounded-2xl border border-white/15 bg-white/[.06] p-4">
                                <div
                                    className="rounded-xl bg-white p-2"
                                    id="profile-qr-code"
                                >
                                    <QRCodeSVG
                                        value={profile.share_url}
                                        size={116}
                                        level="M"
                                        includeMargin
                                        title={`QR code for ${profile.display_name}'s public racing.lk profile`}
                                    />
                                </div>
                                <div className="min-w-44 flex-1">
                                    <p className="text-sm font-black">
                                        Scan to open this profile
                                    </p>
                                    <p className="mt-1 text-xs leading-5 break-all text-white/55">
                                        The QR contains only this public profile
                                        link.
                                    </p>
                                    <div className="mt-3 flex flex-wrap gap-2">
                                        <SiteButton
                                            variant="signal"
                                            size="sm"
                                            onClick={() => {
                                                const svg =
                                                    document.querySelector(
                                                        '#profile-qr-code svg',
                                                    );
                                                if (!svg) return;
                                                const content =
                                                    new XMLSerializer().serializeToString(
                                                        svg,
                                                    );
                                                const file = new Blob(
                                                    [content],
                                                    {
                                                        type: 'image/svg+xml;charset=utf-8',
                                                    },
                                                );
                                                const url =
                                                    URL.createObjectURL(file);
                                                const link =
                                                    document.createElement('a');
                                                link.href = url;
                                                link.download = `${profile.slug}-racing-lk.svg`;
                                                link.click();
                                                URL.revokeObjectURL(url);
                                            }}
                                        >
                                            <Download size={14} />
                                            Download QR
                                        </SiteButton>
                                        <SiteButton
                                            variant="hover-outline-inverse"
                                            size="sm"
                                            onClick={() =>
                                                void navigator.clipboard?.writeText(
                                                    profile.share_url,
                                                )
                                            }
                                        >
                                            <Copy size={14} />
                                            Copy link
                                        </SiteButton>
                                    </div>
                                </div>
                            </div>
                        )}
                        <dl className="mt-9 grid max-w-2xl grid-cols-3 divide-x divide-white/15 border-t border-white/15 pt-5">
                            {[
                                {
                                    label: 'Race results',
                                    value: profile.results.length,
                                },
                                { label: 'Career points', value: totalPoints },
                                { label: 'Podiums', value: podiums },
                            ].map((stat) => (
                                <div
                                    key={stat.label}
                                    className="px-3 first:pl-0"
                                >
                                    <dt className="text-[9px] font-bold tracking-[.1em] text-white/45 uppercase sm:text-[10px]">
                                        {stat.label}
                                    </dt>
                                    <dd className="mt-1 text-2xl font-black tabular-nums sm:text-3xl">
                                        {stat.value}
                                    </dd>
                                </div>
                            ))}
                        </dl>
                    </motion.div>
                    <motion.figure
                        initial={
                            reduceMotion ? false : { opacity: 0, scale: 1.025 }
                        }
                        animate={{ opacity: 1, scale: 1 }}
                        transition={{
                            duration: reduceMotion ? 0 : 0.75,
                            ease: 'easeOut',
                        }}
                        className="relative mx-auto w-full max-w-[620px] overflow-hidden rounded-2xl border border-white/10 bg-[#171b1c] shadow-[0_30px_80px_rgba(0,0,0,.4)] lg:ml-auto"
                    >
                        <img
                            src={profileImage}
                            alt={`Portrait of ${profile.display_name}`}
                            className="aspect-[16/10] w-full object-cover grayscale-[15%]"
                        />
                        <div className="absolute inset-0 bg-gradient-to-t from-[#080b0c]/90 via-transparent to-[#080b0c]/10" />
                        <div className="absolute bottom-0 left-0 h-1 w-2/3 bg-[#e8422b]" />
                        <figcaption className="absolute inset-x-0 bottom-0 flex items-end justify-between gap-4 p-5 sm:p-7">
                            <span>
                                <span className="block text-[9px] font-black tracking-[.2em] text-[#f6c84f] uppercase">
                                    Racer profile
                                </span>
                                <span className="mt-1 block text-lg font-black tracking-tight sm:text-2xl">
                                    {profile.display_name}
                                </span>
                            </span>
                            <span className="font-mono text-[10px] tracking-[.16em] text-white/60 uppercase">
                                LK · {profile.type === 'rider' ? '2W' : '4W'}
                            </span>
                        </figcaption>
                    </motion.figure>
                </div>
            </header>
            <section className="bg-[#e9e6dc] py-16 sm:py-20">
                <div className="mx-auto grid max-w-7xl gap-6 px-5 lg:grid-cols-[.72fr_1.28fr] lg:px-8">
                    <aside className="space-y-6">
                        <motion.article
                            {...reveal}
                            className="rounded-[1.7rem] bg-[#f7f5ef] p-7 shadow-sm shadow-[#111516]/5"
                        >
                            <p className="text-[10px] font-black tracking-[.24em] text-[#e8422b] uppercase">
                                Racer briefing
                            </p>
                            <h2 className="mt-4 text-3xl leading-none font-black tracking-[-.06em]">
                                Built for
                                <br />
                                race day.
                            </h2>
                            <p className="mt-6 leading-7 text-[#545c57]">
                                {profile.bio ||
                                    'A racer profile on racing.lk. More of the story is coming soon.'}
                            </p>
                        </motion.article>
                        {profile.contact.has_mobile && (
                            <motion.article
                                {...reveal}
                                className="rounded-2xl border border-[#d8d2c4] bg-[#f7f5ef] p-5 shadow-sm sm:p-6"
                            >
                                <div className="flex items-start gap-3">
                                    <span className="grid size-10 shrink-0 place-items-center rounded-lg bg-[#111516] text-[#f6c84f]">
                                        <Phone size={18} />
                                    </span>
                                    <div className="min-w-0">
                                        <p className="text-[10px] font-black tracking-[.2em] text-[#c83221] uppercase">
                                            Racer contact
                                        </p>
                                        {profile.contact.mobile ? (
                                            <a
                                                className="mt-2 block font-bold text-[#17191b] underline decoration-[#e8422b]/50 underline-offset-4"
                                                href={`tel:${profile.contact.mobile}`}
                                            >
                                                {profile.contact.mobile}
                                            </a>
                                        ) : (
                                            <p className="mt-2 text-sm leading-6 text-[#545c57]">
                                                Contact details are private.
                                                Sign in with a verified email
                                                address to view them.
                                            </p>
                                        )}
                                    </div>
                                </div>
                            </motion.article>
                        )}
                        <motion.article
                            {...reveal}
                            className="rounded-[1.7rem] bg-[#101416] p-7 text-white"
                        >
                            <p className="text-[10px] font-black tracking-[.24em] text-[#f6c84f] uppercase">
                                Race DNA
                            </p>
                            {profile.disciplines.length ? (
                                <div className="mt-5 flex flex-wrap gap-2">
                                    {profile.disciplines.map((discipline) => (
                                        <span
                                            key={discipline}
                                            className="rounded-full border border-white/15 bg-white/5 px-3 py-2 text-xs font-bold"
                                        >
                                            {discipline}
                                        </span>
                                    ))}
                                </div>
                            ) : (
                                <p className="mt-5 text-sm leading-6 text-white/55">
                                    Racing disciplines will appear here as this
                                    profile grows.
                                </p>
                            )}
                            {profile.teams.length > 0 && (
                                <div className="mt-7 border-t border-white/10 pt-6">
                                    <p className="text-[10px] font-black tracking-[.2em] text-white/45 uppercase">
                                        Team garage
                                    </p>
                                    <div className="mt-3 grid gap-2">
                                        {profile.teams.map((team) => (
                                            <Link
                                                key={team.slug}
                                                href={`/teams/${team.slug}`}
                                                className="flex items-center justify-between rounded-xl bg-white/5 px-4 py-3 transition hover:bg-white/10"
                                            >
                                                <span className="font-bold">
                                                    {team.name}
                                                </span>
                                                <span className="text-xs text-[#f6c84f]">
                                                    {team.role}
                                                </span>
                                            </Link>
                                        ))}
                                    </div>
                                </div>
                            )}
                        </motion.article>
                        {isOwner && verification && (
                            <motion.section
                                {...reveal}
                                className="rounded-2xl border border-[#d8d2c4] bg-[#f7f5ef] p-5 shadow-sm sm:p-6"
                            >
                                <div className="flex items-start gap-3">
                                    <span className="grid size-10 shrink-0 place-items-center rounded-lg bg-[#111516] text-[#f6c84f]">
                                        <ShieldCheck size={20} />
                                    </span>
                                    <div>
                                        <p className="text-[10px] font-black tracking-[.2em] text-[#c83221] uppercase">
                                            Racer verification
                                        </p>
                                        <h2 className="mt-1 text-xl font-black tracking-tight text-[#17191b]">
                                            {verification.status === 'verified'
                                                ? 'Verified profile'
                                                : activeRequest
                                                  ? activeRequest.status ===
                                                    'needs_information'
                                                      ? 'Action required'
                                                      : 'Under review'
                                                  : 'Apply for verification'}
                                        </h2>
                                    </div>
                                </div>
                                <p className="mt-4 text-xs leading-5 text-[#626963]">
                                    Identity and licence files are encrypted and
                                    kept private. Only you, Racing.lk staff, and
                                    the organizer of your selected event can
                                    review them. Organizers may request
                                    information; Racing.lk staff issue the
                                    public badge.
                                </p>

                                {verification.status === 'verified' ? (
                                    <div className="mt-4 flex items-center gap-2 rounded-xl border border-[#9cbd9e] bg-[#e6f0e5] px-4 py-3 text-sm font-bold text-[#2e653a]">
                                        <BadgeCheck size={18} />
                                        Your profile is verified by Racing.lk
                                        staff.
                                    </div>
                                ) : activeRequest ? (
                                    <div className="mt-4 space-y-4">
                                        <div
                                            className={`rounded-xl px-4 py-3 text-xs font-bold ${activeRequest.status === 'needs_information' ? 'bg-[#fff0c5] text-[#725615]' : 'bg-[#e8ecea] text-[#45544a]'}`}
                                        >
                                            {activeRequest.status ===
                                            'needs_information'
                                                ? 'Your event organizer needs more information. Review the note below and reply or upload a replacement.'
                                                : `Request submitted for ${activeRequest.event?.title ?? 'Racing.lk staff review'}. We’ll update this page when it moves forward.`}
                                        </div>
                                        <div className="space-y-2">
                                            {activeRequest.documents.map(
                                                (document) => (
                                                    <a
                                                        key={document.id}
                                                        href={
                                                            document.preview_url ??
                                                            undefined
                                                        }
                                                        target="_blank"
                                                        rel="noreferrer"
                                                        className="flex items-center gap-3 rounded-lg border border-[#ded9ce] bg-white px-3 py-2.5 transition hover:border-[#aaa397]"
                                                    >
                                                        <FileText
                                                            size={17}
                                                            className="shrink-0 text-[#c83221]"
                                                        />
                                                        <span className="min-w-0 flex-1 truncate text-xs font-bold text-[#272b28]">
                                                            {documentLabels[
                                                                document.type
                                                            ] ??
                                                                'Racer document'}
                                                        </span>
                                                        <span className="text-[10px] font-bold text-[#737a74]">
                                                            {document.status}
                                                        </span>
                                                    </a>
                                                ),
                                            )}
                                        </div>
                                        {activeRequest.messages.map(
                                            (message) => (
                                                <div
                                                    key={message.id}
                                                    className="rounded-xl border-l-2 border-[#e8422b] bg-white p-3"
                                                >
                                                    <p className="text-[10px] font-bold text-[#737a74]">
                                                        {message.sender} ·{' '}
                                                        {formatDate(
                                                            message.created_at,
                                                        )}
                                                    </p>
                                                    <p className="mt-1 text-xs leading-5 whitespace-pre-wrap text-[#343a36]">
                                                        {message.body}
                                                    </p>
                                                </div>
                                            ),
                                        )}
                                        {activeRequest.status ===
                                            'needs_information' && (
                                            <form
                                                onSubmit={(event) => {
                                                    event.preventDefault();
                                                    replyForm.post(
                                                        `/verification-requests/${activeRequest.id}/reply`,
                                                        {
                                                            forceFormData: true,
                                                            preserveScroll: true,
                                                            onSuccess: () =>
                                                                replyForm.reset(),
                                                        },
                                                    );
                                                }}
                                                className="space-y-3 rounded-xl bg-[#111516] p-4 text-white"
                                            >
                                                <label
                                                    htmlFor="verification-reply"
                                                    className="block text-xs font-extrabold"
                                                >
                                                    Reply to the organizer
                                                </label>
                                                <textarea
                                                    id="verification-reply"
                                                    value={
                                                        replyForm.data.message
                                                    }
                                                    onChange={(event) =>
                                                        replyForm.setData(
                                                            'message',
                                                            event.target.value,
                                                        )
                                                    }
                                                    rows={3}
                                                    maxLength={2000}
                                                    className="w-full rounded-lg border border-white/15 bg-white/10 px-3 py-2.5 text-xs text-white outline-none placeholder:text-white/40 focus:border-[#f6c84f]"
                                                    placeholder="Add a message (or attach a replacement document below)."
                                                />
                                                {(
                                                    [
                                                        'fmssl_licence',
                                                        'nic',
                                                        'birth_certificate',
                                                        'vehicle_permit',
                                                    ] as const
                                                ).map((type) => (
                                                    <label
                                                        key={type}
                                                        className="block text-[10px] font-bold text-white/70"
                                                    >
                                                        Replace{' '}
                                                        {documentLabels[type]}
                                                        <input
                                                            type="file"
                                                            accept=".jpg,.jpeg,.png,.pdf"
                                                            onChange={(event) =>
                                                                replyForm.setData(
                                                                    'documents',
                                                                    {
                                                                        ...replyForm
                                                                            .data
                                                                            .documents,
                                                                        [type]:
                                                                            event
                                                                                .target
                                                                                .files?.[0] ??
                                                                            null,
                                                                    },
                                                                )
                                                            }
                                                            className="mt-1.5 block w-full text-xs file:mr-2 file:rounded-md file:border-0 file:bg-white/10 file:px-2 file:py-1.5 file:text-[10px] file:font-bold file:text-white"
                                                        />
                                                    </label>
                                                ))}
                                                {replyForm.errors.message && (
                                                    <p className="text-xs font-bold text-[#ffb5a9]">
                                                        {
                                                            replyForm.errors
                                                                .message
                                                        }
                                                    </p>
                                                )}
                                                <button
                                                    disabled={
                                                        replyForm.processing
                                                    }
                                                    className="min-h-10 rounded-lg bg-[#e8422b] px-4 py-2 text-xs font-extrabold text-white transition hover:bg-[#c83221] disabled:opacity-50"
                                                >
                                                    Send reply
                                                </button>
                                            </form>
                                        )}
                                    </div>
                                ) : (
                                    <form
                                        onSubmit={(event) => {
                                            event.preventDefault();
                                            form.post(
                                                `/profiles/${profile.id}/documents`,
                                                {
                                                    forceFormData: true,
                                                    preserveScroll: true,
                                                    onSuccess: () =>
                                                        form.reset(),
                                                },
                                            );
                                        }}
                                        className="mt-4 space-y-4"
                                    >
                                        <label className="block text-xs font-extrabold text-[#343a36]">
                                            {verification_events.length
                                                ? 'Event for organizer review'
                                                : 'Review destination'}
                                            {verification_events.length ? (
                                                <select
                                                    required
                                                    value={form.data.event_id}
                                                    onChange={(event) =>
                                                        form.setData(
                                                            'event_id',
                                                            event.target.value
                                                                ? Number(
                                                                      event
                                                                          .target
                                                                          .value,
                                                                  )
                                                                : '',
                                                        )
                                                    }
                                                    className="mt-1.5 h-11 w-full rounded-lg border border-[#d3cec3] bg-white px-3 text-sm font-semibold text-[#17191b] focus:border-[#c83221] focus:outline-none"
                                                >
                                                    <option value="">
                                                        Select an upcoming event
                                                    </option>
                                                    {verification_events.map(
                                                        (event) => (
                                                            <option
                                                                key={event.id}
                                                                value={event.id}
                                                            >
                                                                {event.title} ·{' '}
                                                                {formatDate(
                                                                    event.starts_at,
                                                                )}{' '}
                                                                ·{' '}
                                                                {
                                                                    event.organizer
                                                                }
                                                            </option>
                                                        ),
                                                    )}
                                                </select>
                                            ) : (
                                                <span className="mt-1.5 block rounded-lg border border-[#d3cec3] bg-white px-3 py-3 text-xs font-semibold text-[#4e5650]">
                                                    No upcoming events are open;
                                                    Racing.lk staff will review
                                                    your request.
                                                </span>
                                            )}
                                        </label>
                                        {(
                                            [
                                                'fmssl_licence',
                                                'nic',
                                                'birth_certificate',
                                                'vehicle_permit',
                                            ] as const
                                        ).map((type) => (
                                            <label
                                                key={type}
                                                className="block rounded-xl border border-[#ded9ce] bg-white p-3 text-xs font-extrabold text-[#343a36]"
                                            >
                                                <span className="flex items-center justify-between gap-2">
                                                    {documentLabels[type]}
                                                    {type ===
                                                    'vehicle_permit' ? (
                                                        <span className="text-[9px] font-bold text-[#777d77]">
                                                            IF APPLICABLE
                                                        </span>
                                                    ) : type === 'nic' ||
                                                      type ===
                                                          'birth_certificate' ? (
                                                        <span className="text-[9px] font-bold text-[#c83221]">
                                                            UPLOAD ONE
                                                        </span>
                                                    ) : (
                                                        <span className="text-[9px] font-bold text-[#c83221]">
                                                            REQUIRED
                                                        </span>
                                                    )}
                                                </span>
                                                <input
                                                    type="file"
                                                    accept=".jpg,.jpeg,.png,.pdf"
                                                    required={
                                                        type === 'fmssl_licence'
                                                    }
                                                    onChange={(event) =>
                                                        form.setData(
                                                            'documents',
                                                            {
                                                                ...form.data
                                                                    .documents,
                                                                [type]:
                                                                    event.target
                                                                        .files?.[0] ??
                                                                    null,
                                                            },
                                                        )
                                                    }
                                                    className="mt-2 block w-full text-[10px] file:mr-2 file:rounded-md file:border-0 file:bg-[#efede6] file:px-2 file:py-1.5 file:text-[10px] file:font-bold file:text-[#454c47]"
                                                />
                                                {form.errors[
                                                    `documents.${type}`
                                                ] && (
                                                    <span className="mt-1 block text-[10px] font-bold text-red-700">
                                                        {
                                                            form.errors[
                                                                `documents.${type}`
                                                            ]
                                                        }
                                                    </span>
                                                )}
                                            </label>
                                        ))}
                                        <p className="flex items-start gap-2 text-[10px] leading-4 text-[#6c736d]">
                                            <CalendarDays
                                                size={14}
                                                className="mt-0.5 shrink-0"
                                            />
                                            The event organizer can request
                                            additional information. Racing.lk
                                            staff will review the complete
                                            request and issue your verified
                                            badge.
                                        </p>
                                        {(form.errors.event_id ||
                                            form.errors['documents.nic']) && (
                                            <p className="text-xs font-bold text-red-700">
                                                {form.errors.event_id ||
                                                    form.errors[
                                                        'documents.nic'
                                                    ]}
                                            </p>
                                        )}
                                        <button
                                            disabled={form.processing}
                                            className="min-h-11 w-full rounded-lg bg-[#111516] px-4 py-3 text-xs font-black tracking-wide text-white transition hover:bg-[#e8422b] disabled:opacity-50"
                                        >
                                            {form.processing
                                                ? 'Submitting…'
                                                : 'Submit secure verification request'}
                                        </button>
                                    </form>
                                )}
                                {verification.requests.some(
                                    (request) =>
                                        request.id !== activeRequest?.id,
                                ) && (
                                    <div className="mt-5 border-t border-[#ded9ce] pt-4">
                                        <h3 className="text-[10px] font-black tracking-[.16em] text-[#626963] uppercase">
                                            Request history
                                        </h3>
                                        <div className="mt-3 space-y-2">
                                            {verification.requests
                                                .filter(
                                                    (request) =>
                                                        request.id !==
                                                        activeRequest?.id,
                                                )
                                                .map((request) => (
                                                    <article
                                                        key={request.id}
                                                        className="rounded-lg border border-[#ded9ce] bg-white p-3"
                                                    >
                                                        <div className="flex flex-wrap items-center justify-between gap-2">
                                                            <strong className="text-xs text-[#292d2a]">
                                                                {request.event
                                                                    ?.title ??
                                                                    'Racing.lk staff review'}
                                                            </strong>
                                                            <span className="text-[9px] font-black tracking-wide text-[#737a74] uppercase">
                                                                {request.status.replace(
                                                                    '_',
                                                                    ' ',
                                                                )}
                                                            </span>
                                                        </div>
                                                        {request.messages.map(
                                                            (message) => (
                                                                <div
                                                                    key={
                                                                        message.id
                                                                    }
                                                                    className="mt-2 border-l-2 border-[#e8422b] pl-2"
                                                                >
                                                                    <p className="text-[9px] font-bold text-[#737a74]">
                                                                        {
                                                                            message.sender
                                                                        }{' '}
                                                                        ·{' '}
                                                                        {formatDate(
                                                                            message.created_at,
                                                                        )}
                                                                    </p>
                                                                    <p className="mt-1 text-xs leading-5 whitespace-pre-wrap text-[#626963]">
                                                                        {
                                                                            message.body
                                                                        }
                                                                    </p>
                                                                </div>
                                                            ),
                                                        )}
                                                    </article>
                                                ))}
                                        </div>
                                    </div>
                                )}
                            </motion.section>
                        )}
                    </aside>
                    <div className="space-y-6">
                        <motion.article
                            {...reveal}
                            className="overflow-hidden rounded-[1.7rem] bg-[#f7f5ef] p-7 sm:p-9"
                        >
                            <div className="flex flex-wrap items-end justify-between gap-4">
                                <div>
                                    <p className="text-[10px] font-black tracking-[.24em] text-[#e8422b] uppercase">
                                        Race record
                                    </p>
                                    <h2 className="mt-4 text-3xl leading-none font-black tracking-[-.06em]">
                                        Results & achievements
                                    </h2>
                                </div>
                                <span className="grid size-12 place-items-center rounded-sm bg-[#e8422b] text-white">
                                    <Trophy size={21} />
                                </span>
                            </div>
                            {profile.results.length ? (
                                <div className="mt-8 overflow-hidden rounded-2xl border border-[#111516]/10">
                                    {profile.results.map((result, index) => (
                                        <Link
                                            key={`${result.event_slug}-${index}`}
                                            href={`/events/${result.event_slug}`}
                                            className="group grid grid-cols-[auto_1fr_auto] items-center gap-4 border-b border-[#111516]/10 bg-white px-4 py-4 transition last:border-0 hover:bg-[#f5ecd4] sm:px-5"
                                        >
                                            <span
                                                className={`grid size-12 place-items-center rounded-sm text-sm font-black italic ${result.position !== null && result.position <= 3 ? 'bg-[#f6c84f] text-[#111516]' : 'bg-[#e9e6dc] text-[#111516]'}`}
                                            >
                                                {result.position
                                                    ? `P${result.position}`
                                                    : '—'}
                                            </span>
                                            <span className="min-w-0">
                                                <strong className="block truncate text-sm sm:text-base">
                                                    {result.event}
                                                </strong>
                                                <small className="mt-1 block text-[10px] font-bold tracking-[.14em] text-[#717874] uppercase">
                                                    {result.class ||
                                                        'Open class'}
                                                </small>
                                            </span>
                                            <span className="text-right">
                                                <strong className="block text-sm">
                                                    {result.points}
                                                </strong>
                                                <small className="text-[10px] font-bold tracking-[.12em] text-[#717874] uppercase">
                                                    points
                                                </small>
                                            </span>
                                        </Link>
                                    ))}
                                </div>
                            ) : (
                                <div className="mt-8 rounded-2xl border border-dashed border-[#111516]/20 bg-[#e9e6dc] p-10 text-center">
                                    <FlagTriangleRight className="mx-auto text-[#e8422b]" />
                                    <p className="mt-4 text-lg font-black">
                                        The next result is still to come.
                                    </p>
                                    <p className="mt-2 text-sm text-[#5d655f]">
                                        Confirmed results will appear here after
                                        events.
                                    </p>
                                </div>
                            )}
                        </motion.article>
                        <motion.article
                            {...reveal}
                            className="relative overflow-hidden rounded-[1.7rem] bg-[#e8422b] p-7 text-white sm:p-9"
                        >
                            <div className="absolute inset-0 [background-image:linear-gradient(45deg,transparent_46%,white_47%,white_53%,transparent_54%)] [background-size:26px_26px] opacity-20" />
                            <div className="relative flex flex-wrap items-center justify-between gap-6">
                                <div>
                                    <p className="text-[10px] font-black tracking-[.24em] text-white/70 uppercase">
                                        Follow the grid
                                    </p>
                                    <h2 className="mt-3 max-w-md text-3xl leading-none font-black tracking-[-.06em]">
                                        Find the next event. Be there for the
                                        next green flag.
                                    </h2>
                                </div>
                                <SiteActionLink
                                    href="/events"
                                    variant="dark"
                                    className="shrink-0 hover:bg-white hover:text-[#111516]"
                                >
                                    Race calendar
                                </SiteActionLink>
                            </div>
                        </motion.article>
                    </div>
                </div>
            </section>
        </SiteLayout>
    );
}
