"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import {
    ArrowLeft,
    ArrowRight,
    Bell,
    Building2,
    Briefcase,
    Calendar,
    CheckCircle2,
    Circle,
    Clock,
    DollarSign,
    Hash,
    Mail,
    MapPin,
    MessageSquare,
    Pencil,
    Phone,
    Sparkles,
    Tag,
    Trash2,
    UserCheck,
    UserPlus,
    Users,
    Users2,
    XCircle,
} from "lucide-react"
import { toast } from "sonner"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { ButtonGroup } from "@/components/ui/button-group"
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from "@/components/ui/tooltip"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { cn } from "@/lib/utils"
import { Deal, Stage } from "./types"
import { DealBantSidebar } from "./deal-bant-sidebar"
import { DealTasksWidget } from "@/components/tasks/deal-tasks-widget"
import { LeadDetailNotesDialog } from "./lead-detail-notes-dialog"
import { LeadDetailRemindersDialog } from "./lead-detail-reminders-dialog"
import { formatTeamLabelForUi } from "@/lib/deal-display"
import { resolveLeadStageDisplayName } from "@/lib/deal-stage-labels"
import { useAppDispatch } from "@/store/hooks"
import { EditDealModal } from "./edit-deal-modal"
import { useTeamsQuery } from "@/hooks/use-teams-query"
import { useUpdateDealMutation } from "@/api/endpoints/deals-api"
import { buildLeadUpdatePayload } from "@/lib/lead-update-payload"
import { openMoveToLostDialog } from "@/store/slices/move-to-lost-dialog-slice"
import { openDiscoveryMeetingBookedDialog } from "@/store/slices/discovery-meeting-booked-dialog-slice"
import { useGetPipelineStagesQuery } from "@/api/endpoints/pipelines-api"
import { useMoveLeadMutation } from "@/features/leads/hooks/use-move-lead-mutation"
import {
    isDiscoverMeetingBookedStage,
    isEnteringDiscoverMeetingBookedStage,
    isLostDestinationStageId,
} from "@/lib/deal-stage-labels"
import { hasPermission, type PermissionSource } from "@/lib/permissions"
import { DiscoveryMeetingBookedAlert } from "@/components/deals/discovery-meeting-booked-alert"
import { isLostStage, buildPipelineTimelineStages, resolveTimelineStageIndex, canAdvancePipelineTimeline } from "./deal-utils"

function formatDealBudget(val?: number | null): string {
    if (val == null) return "—"
    const n = Number(val)
    if (!Number.isFinite(n)) return "—"
    return new Intl.NumberFormat("en-US", {
        style: "currency",
        currency: "USD",
        minimumFractionDigits: 0,
        maximumFractionDigits: 2,
    }).format(n)
}

function resolveServiceName(deal: Deal): string | undefined {
    if (typeof deal.service === "object" && deal.service !== null && "name" in deal.service) {
        return deal.service.name ?? undefined
    }
    if (typeof deal.service === "string" && deal.service.trim()) return deal.service
    return deal.serviceName?.trim() || undefined
}

function resolveLeadTypeName(deal: Deal): string | undefined {
    return deal.leadType?.name?.trim() || undefined
}

function resolveProjectTypeName(deal: Deal): string | undefined {
    return deal.projectType?.name?.trim() || undefined
}

function formatDisplayDate(value?: string | null): string {
    if (!value?.trim()) return "—"
    const d = new Date(value)
    if (Number.isNaN(d.getTime())) return "—"
    return d.toLocaleDateString(undefined, {
        year: "numeric",
        month: "short",
        day: "numeric",
    })
}

function InfoTags({
    label,
    items,
    emptyLabel = "—",
    badgeClassName,
}: {
    label: string
    items: string[]
    emptyLabel?: string
    badgeClassName?: string
}) {
    return (
        <div className="min-w-0 py-2 sm:col-span-2">
            <div className="mb-1.5 flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-widest text-gray-400">
                <Tag size={12} />
                {label}
            </div>
            {items.length > 0 ? (
                <div className="flex flex-wrap gap-1.5">
                    {items.map((item) => (
                        <Badge
                            key={item}
                            variant="secondary"
                            className={cn(
                                "rounded-md px-2.5 py-0.5 text-[12px] font-medium",
                                badgeClassName,
                            )}
                        >
                            {item}
                        </Badge>
                    ))}
                </div>
            ) : (
                <div className="text-[14px] font-medium text-gray-800">{emptyLabel}</div>
            )}
        </div>
    )
}

function pipelineRowsToStages(
    rows: { id: string; stageName: string; color: string | null; prob: number | null }[],
): Stage[] {
    return rows.map((r) => ({
        id: r.id,
        name: r.stageName,
        color: r.color ?? "#6C63FF",
        prob: r.prob ?? 0,
    }))
}

function InfoCell({
    label,
    value,
    icon,
}: {
    label: string
    value: React.ReactNode
    icon?: React.ReactNode
}) {
    return (
        <div className="min-w-0 py-2">
            <div className="mb-0.5 flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-widest text-gray-400">
                {icon}
                {label}
            </div>
            <div className="text-[14px] font-medium text-gray-800 break-words">{value || "—"}</div>
        </div>
    )
}

function SectionCard({
    title,
    children,
    className,
}: {
    title: string
    children: React.ReactNode
    className?: string
}) {
    return (
        <section
            className={cn(
                "rounded-2xl bg-white/40 backdrop-blur-[15px] shadow-[0px_2px_20px_0px_rgba(0,0,0,0.06)] p-4 sm:p-5",
                className,
            )}
        >
            <h3 className="mb-3 text-[11px] font-bold uppercase tracking-widest text-gray-400">
                {title}
            </h3>
            {children}
        </section>
    )
}

export interface LeadDetailPageLayoutProps {
    deal: Deal
    stages?: Stage[]
    onClose: () => void
    teamDisplayName: string
    allUsers: { id: string; name: string; email?: string }[]
    assigneeAeNames: string[]
    assigneeBdrNames: string[]
    assigneeContributorNames: string[]
    pipelineTimeline: Stage[]
    currentStage?: Stage
    stageIndex: number
    lastStageMove?: { addedByName?: string; date: string }
    isScopingStage: boolean
    isAlreadyCustomer: boolean
    canCreateCustomer: boolean
    canViewUserActivity: boolean
    canEditNotes: boolean
    onMoveToCustomer: () => void
    onRefetch: () => void
    onAssignTask: () => void
    dealMemberUserIds: string[]
    apiBaseUrl: string
    notesProps: Omit<
        React.ComponentProps<typeof LeadDetailNotesDialog>,
        "open" | "onOpenChange" | "deal"
    >
    remindersProps: Omit<
        React.ComponentProps<typeof LeadDetailRemindersDialog>,
        "open" | "onOpenChange" | "deal"
    >
    permissionSource?: PermissionSource | null
    onCreateBusinessDeal?: () => void
}

export function LeadDetailPageLayout({
    deal,
    stages: stagesProp = [],
    onClose,
    teamDisplayName,
    allUsers,
    assigneeAeNames,
    assigneeBdrNames,
    assigneeContributorNames,
    pipelineTimeline: _pipelineTimeline,
    currentStage,
    stageIndex: _stageIndex,
    lastStageMove,
    isScopingStage,
    isAlreadyCustomer,
    canCreateCustomer,
    canViewUserActivity,
    canEditNotes,
    onMoveToCustomer,
    onRefetch,
    onAssignTask,
    dealMemberUserIds,
    apiBaseUrl,
    notesProps,
    remindersProps,
    permissionSource = null,
    onCreateBusinessDeal,
}: LeadDetailPageLayoutProps) {
    const router = useRouter()
    const dispatch = useAppDispatch()
    const [notesOpen, setNotesOpen] = React.useState(false)
    const [remindersOpen, setRemindersOpen] = React.useState(false)
    const [editOpen, setEditOpen] = React.useState(false)
    const { mutateAsync: moveLead, isPending: isMoving } = useMoveLeadMutation()
    const [updateDeal] = useUpdateDealMutation()
    const { data: teamsData } = useTeamsQuery()
    const teams = teamsData ?? []

    const { data: pipelineStagePage } = useGetPipelineStagesQuery(
        { pipelineId: deal.pipelineId, stageType: "Lead", limit: 100 },
        { skip: !deal.pipelineId },
    )

    const fetchedStages = React.useMemo(
        () => (pipelineStagePage?.data ? pipelineRowsToStages(pipelineStagePage.data) : []),
        [pipelineStagePage],
    )
    const stages = stagesProp.length > 0 ? stagesProp : fetchedStages

    const effectivePipelineTimeline = React.useMemo(
        () => buildPipelineTimelineStages(stages),
        [stages],
    )

    const effectiveStageIndex = React.useMemo(
        () =>
            resolveTimelineStageIndex(
                deal.stage,
                effectivePipelineTimeline,
                stages,
            ),
        [deal.stage, effectivePipelineTimeline, stages],
    )

    const stageLabel = React.useMemo(() => {
        if (currentStage?.name) {
            if (currentStage.isSubStage && currentStage.parentStageName) {
                return `${currentStage.parentStageName} › ${currentStage.name}`
            }
            return currentStage.name
        }
        return resolveLeadStageDisplayName(deal, stages)
    }, [currentStage, deal, stages])

    const isClosedLost = React.useMemo(() => isLostStage(deal, stages), [deal, stages])
    const canAdvanceStage =
        canAdvancePipelineTimeline(
            effectiveStageIndex,
            effectivePipelineTimeline.length,
        ) && !isClosedLost
    const isDiscoverMeetingBooked = React.useMemo(
        () => isDiscoverMeetingBookedStage(deal, currentStage, stages),
        [deal, currentStage, stages],
    )
    const canCreateBusinessDeal = hasPermission(permissionSource, "CREATE", "DEAL")
    const closedLostReason = deal.lostReason?.trim() ?? ""

    const channelName =
        typeof deal.leadChannel === "object" && deal.leadChannel !== null
            ? (deal.leadChannel as { name?: string }).name
            : (deal.leadChannel as unknown as string | undefined)

    const noteCount = deal.dealNotes?.length ?? 0
    const reminderCount = deal.dealReminders?.length ?? 0

    const handleEdit = () => {
        setEditOpen(true)
    }

    const handleSaveEdit = async (updated: Deal) => {
        try {
            const { id, ...rest } = updated
            await updateDeal({ id, body: buildLeadUpdatePayload(rest) }).unwrap()
            toast.success("Lead updated")
            setEditOpen(false)
            onRefetch()
        } catch {
            toast.error("Failed to update lead")
        }
    }

    const handleLost = () => {
        if (!deal.pipelineId) {
            toast.error("Missing pipeline for this lead")
            return
        }
        dispatch(
            openMoveToLostDialog({
                dealId: deal.id,
                pipelineId: deal.pipelineId,
                targetStageId: null,
                targetProb: 0,
                sourceStageId: deal.stage,
                customerName: deal.customerName ?? null,
                moveContext: { kind: "detail" },
            }),
        )
    }

    const handleNext = async () => {
        if (!canAdvanceStage) {
            if (effectiveStageIndex < 0 && stages.length > 0) {
                toast.error("Could not determine the current pipeline stage")
            }
            return
        }
        const next = effectivePipelineTimeline[effectiveStageIndex + 1]
        if (!next || !deal.pipelineId) return

        if (isLostDestinationStageId(String(next.id), stages)) {
            handleLost()
            return
        }

        if (
            isEnteringDiscoverMeetingBookedStage(deal.stage, String(next.id), stages)
        ) {
            dispatch(
                openDiscoveryMeetingBookedDialog({
                    dealId: deal.id,
                    pipelineId: deal.pipelineId,
                    targetStageId: String(next.id),
                    targetProb: next.prob ?? 0,
                    sourceStageId: deal.stage,
                    customerName: deal.customerName ?? null,
                    moveContext: { kind: "detail" },
                }),
            )
            return
        }

        try {
            await moveLead({
                id: deal.id,
                stageId: String(next.id),
                prob: next.prob,
            })
            toast.success(`Moved to ${next.name}`)
            onRefetch()
        } catch {
            toast.error("Failed to move lead")
        }
    }

    return (
        <div className="flex h-full min-h-0 flex-col bg-transparent">
            {/* Slim header */}
            <header className="shrink-0 border-b border-gray-200/80 bg-transparent">
                <div className="flex items-center gap-2 border-b border-gray-100 px-3 py-2 sm:px-5">
                    <Button
                        variant="ghost"
                        size="icon"
                        onClick={onClose}
                        className="h-8 w-8 rounded-lg"
                    >
                        <ArrowLeft size={16} />
                    </Button>
                    <span className="text-[10px] font-bold uppercase tracking-[0.2em] text-gray-400">
                        Lead Detail
                    </span>
                </div>

                <div className="flex flex-col gap-3 px-3 py-3 sm:flex-row sm:items-center sm:justify-between sm:px-5">
                    <div className="min-w-0 flex-1">
                        <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-sm">
                            <span className="font-['Lexend'] text-base font-semibold text-gray-900 truncate max-w-[200px] sm:max-w-none">
                                {deal.customerName || "Unnamed Lead"}
                            </span>
                            {deal.leadId ? (
                                <>
                                    <span className="hidden h-4 w-px bg-gray-200 sm:block" />
                                    <span className="text-[12px] font-medium text-gray-400">
                                        ID: {deal.leadId}
                                    </span>
                                </>
                            ) : null}
                            <span className="hidden h-4 w-px bg-gray-200 sm:block" />
                            <span className="text-gray-500">{stageLabel}</span>
                            {deal.leadStatus ? (
                                <>
                                    <span className="hidden h-4 w-px bg-gray-200 sm:block" />
                                    <span className="text-gray-500">{deal.leadStatus}</span>
                                </>
                            ) : null}
                            <span className="hidden h-4 w-px bg-gray-200 sm:block" />
                            <span className="text-gray-500">
                                {teamDisplayName || formatTeamLabelForUi(deal.team) || "—"}
                            </span>
                        </div>
                        <div className="mt-1.5 flex flex-wrap items-center gap-2">
                            {isAlreadyCustomer ? (
                                <Badge className="rounded-full bg-emerald-100 text-emerald-700 hover:bg-emerald-100">
                                    Already a customer
                                </Badge>
                            ) : null}
                            {channelName ? (
                                <Badge variant="secondary" className="rounded-md text-[#6C63FF]">
                                    {channelName}
                                </Badge>
                            ) : null}
                            {deal.brand ? (
                                <Badge variant="outline" className="rounded-md">
                                    {deal.brand}
                                </Badge>
                            ) : null}
                            {resolveServiceName(deal) ? (
                                <Badge variant="outline" className="rounded-md">
                                    {resolveServiceName(deal)}
                                </Badge>
                            ) : null}
                        </div>
                    </div>

                    <div className="flex flex-wrap items-center gap-2">
                        <Button
                            variant="outline"
                            size="sm"
                            className="h-8 gap-1.5 rounded-lg text-xs"
                            onClick={() => setNotesOpen(true)}
                        >
                            <MessageSquare size={14} />
                            Notes ({noteCount})
                        </Button>
                        <Button
                            variant="outline"
                            size="sm"
                            className="h-8 gap-1.5 rounded-lg text-xs"
                            onClick={() => setRemindersOpen(true)}
                        >
                            <Bell size={14} />
                            Reminders ({reminderCount})
                        </Button>
                        {canViewUserActivity ? (
                            <Button
                                variant="outline"
                                size="sm"
                                className="h-8 gap-1.5 rounded-lg text-xs"
                                onClick={() =>
                                    router.push(`/leads/${deal.id}/user-deal-timeline`)
                                }
                            >
                                <Users size={14} />
                                User Activity
                            </Button>
                        ) : null}
                        <span className="mx-1 hidden h-4 w-px bg-gray-200 sm:block" />
                        <TooltipProvider delayDuration={300}>
                            <ButtonGroup aria-label="Lead actions">
                                <Tooltip>
                                    <TooltipTrigger asChild>
                                        <Button
                                            type="button"
                                            variant="outline"
                                            size="icon-sm"
                                            aria-label="Edit lead"
                                            onClick={handleEdit}
                                        >
                                            <Pencil className="size-3.5" aria-hidden />
                                        </Button>
                                    </TooltipTrigger>
                                    <TooltipContent>Edit</TooltipContent>
                                </Tooltip>
                                <Tooltip>
                                    <TooltipTrigger asChild>
                                        <Button
                                            type="button"
                                            variant="outline"
                                            size="icon-sm"
                                            aria-label="Mark as lost"
                                            className="text-red-600 hover:text-red-700 hover:bg-red-50"
                                            onClick={handleLost}
                                        >
                                            <Trash2 className="size-3.5" aria-hidden />
                                        </Button>
                                    </TooltipTrigger>
                                    <TooltipContent>Mark lost</TooltipContent>
                                </Tooltip>
                                <Tooltip>
                                    <TooltipTrigger asChild>
                                        <Button
                                            type="button"
                                            variant="default"
                                            size="icon-sm"
                                            aria-label="Move to next stage"
                                            className="bg-[#6C63FF] hover:bg-[#5a52d6] disabled:opacity-40"
                                            onClick={() => void handleNext()}
                                            disabled={isMoving || !canAdvanceStage}
                                        >
                                            <ArrowRight className="size-3.5" aria-hidden />
                                        </Button>
                                    </TooltipTrigger>
                                    <TooltipContent>
                                        {canAdvanceStage ? "Next stage" : "Last stage"}
                                    </TooltipContent>
                                </Tooltip>
                            </ButtonGroup>
                        </TooltipProvider>
                    </div>
                </div>
            </header>

            {/* Two-column body */}
            <div className="flex min-h-0 flex-1 overflow-hidden">
                {/* Left — scrollable main */}
                <div className="flex min-h-0 flex-1 flex-col overflow-y-auto scrollbar-themed lg:max-w-[62%]">
                    <div className="space-y-4 p-4 sm:p-5">
                        {isClosedLost ? (
                            <Alert className="rounded-xl border-red-200 bg-red-50">
                                <XCircle className="size-4 text-red-600" aria-hidden />
                                <AlertTitle className="text-red-900">Closed lost reason</AlertTitle>
                                <AlertDescription className="space-y-3 text-red-800">
                                    <p className="text-[13px] leading-relaxed whitespace-pre-wrap">
                                        {closedLostReason || "No reason recorded"}
                                    </p>
                                    {deal.closedLeadTags?.length ? (
                                        <div className="flex flex-wrap gap-1.5">
                                            {deal.closedLeadTags.map((tag) => (
                                                <Badge
                                                    key={tag.id}
                                                    variant="secondary"
                                                    className="bg-white/80 text-slate-700 hover:bg-white/80"
                                                >
                                                    {tag.name}
                                                </Badge>
                                            ))}
                                        </div>
                                    ) : null}
                                </AlertDescription>
                            </Alert>
                        ) : null}

                        {isDiscoverMeetingBooked && canCreateBusinessDeal ? (
                            <DiscoveryMeetingBookedAlert
                                deal={deal}
                                canCreateBusinessDeal={canCreateBusinessDeal}
                                onCreateBusinessDeal={
                                    onCreateBusinessDeal ?? (() => undefined)
                                }
                                permissionSource={permissionSource}
                                onAfterVerify={onRefetch}
                            />
                        ) : null}

                        <SectionCard title="Contact">
                            <div className="grid grid-cols-1 gap-x-6 sm:grid-cols-2">
                                <InfoCell label="Company" value={deal.customerName} icon={<Building2 size={12} />} />
                                <InfoCell label="Phone" value={deal.phone} icon={<Phone size={12} />} />
                                <InfoCell label="Home Phone" value={deal.homePhone} icon={<Phone size={12} />} />
                                <InfoCell label="Email" value={deal.email} icon={<Mail size={12} />} />
                                <InfoCell label="Address" value={deal.address} icon={<MapPin size={12} />} />
                                <InfoCell label="Postal Code" value={deal.postalCode} />
                            </div>
                        </SectionCard>

                        <SectionCard title="Team & Assignment">
                            <div className="grid grid-cols-1 gap-x-6 sm:grid-cols-2">
                                <InfoCell label="Lead Owner" value={deal.owner?.name} icon={<Users size={12} />} />
                                <InfoCell
                                    label="Team"
                                    value={teamDisplayName || formatTeamLabelForUi(deal.team)}
                                    icon={<Briefcase size={12} />}
                                />
                                <InfoCell
                                    label="Assign AE"
                                    value={assigneeAeNames.length ? assigneeAeNames.join(", ") : "—"}
                                    icon={<UserCheck size={12} />}
                                />
                                <InfoCell
                                    label="Assign BDR"
                                    value={assigneeBdrNames.length ? assigneeBdrNames.join(", ") : "—"}
                                    icon={<Users2 size={12} />}
                                />
                                <InfoCell
                                    label="Contributors"
                                    value={
                                        assigneeContributorNames.length
                                            ? assigneeContributorNames.join(", ")
                                            : "—"
                                    }
                                    icon={<UserPlus size={12} />}
                                />
                            </div>
                        </SectionCard>

                        <SectionCard title="Lead Information">
                            <div className="grid grid-cols-1 gap-x-6 sm:grid-cols-2">
                                <InfoCell label="Lead ID" value={deal.leadId} icon={<Hash size={12} />} />
                                <InfoCell label="Lead Status" value={deal.leadStatus} />
                                <InfoCell label="Channel" value={channelName} />
                                <InfoCell label="Brand" value={deal.brand} />
                                <InfoCell label="Service" value={resolveServiceName(deal)} />
                                <InfoCell label="Lead Type" value={resolveLeadTypeName(deal)} />
                                <InfoCell label="Project Type" value={resolveProjectTypeName(deal)} />
                                <InfoCell
                                    label="Stage Probability"
                                    value={
                                        currentStage?.prob != null
                                            ? `${currentStage.prob}%`
                                            : deal.probability != null
                                              ? `${deal.probability}%`
                                              : "—"
                                    }
                                />
                                <InfoCell
                                    label="Month / Year"
                                    value={`${deal.month || "—"} / ${deal.year || "—"}`}
                                    icon={<Calendar size={12} />}
                                />
                                <InfoCell
                                    label="Purchase Count"
                                    value={
                                        deal.purchaseCount != null
                                            ? String(deal.purchaseCount)
                                            : "—"
                                    }
                                />
                                <InfoCell
                                    label="Budget"
                                    value={formatDealBudget(deal.budget)}
                                    icon={<DollarSign size={12} />}
                                />
                                <InfoCell
                                    label="Expected Payment Date"
                                    value={formatDisplayDate(deal.expectedPaymentDate)}
                                    icon={<Calendar size={12} />}
                                />
                                <InfoCell label="Created By" value={deal.createdBy} />
                                <InfoCell
                                    label="Created At"
                                    value={formatDisplayDate(deal.createdDate)}
                                    icon={<Clock size={12} />}
                                />
                                <InfoTags
                                    label="Tags"
                                    items={deal.tags ?? []}
                                    badgeClassName="bg-primary/10 text-primary border-0"
                                />
                                <InfoCell
                                    label="Closed Reason"
                                    value={deal.lostReason || "—"}
                                />
                                <InfoTags
                                    label="Closed Lead Tags"
                                    items={
                                        deal.closedLeadTags?.map((t) => t.name) ?? []
                                    }
                                    badgeClassName="border-red-200 text-red-700 bg-red-50"
                                />
                            </div>
                        </SectionCard>

                        <SectionCard title="Metrics — Timeline">
                            {lastStageMove ? (
                                <p className="mb-3 text-[11px] text-gray-500">
                                    Last moved by{" "}
                                    <span className="font-semibold text-[#6C63FF]">
                                        {lastStageMove.addedByName || "System"}
                                    </span>{" "}
                                    on{" "}
                                    {new Date(lastStageMove.date).toLocaleDateString(undefined, {
                                        month: "short",
                                        day: "numeric",
                                        hour: "2-digit",
                                        minute: "2-digit",
                                    })}
                                </p>
                            ) : null}
                            <div className="overflow-x-auto pb-2">
                                <div className="flex min-w-max gap-2">
                                    {effectivePipelineTimeline.map((s, i) => {
                                        const done = effectiveStageIndex !== -1 && i < effectiveStageIndex
                                        const active = effectiveStageIndex !== -1 && i === effectiveStageIndex
                                        return (
                                            <div
                                                key={s.id}
                                                className="flex w-[88px] flex-col items-center gap-1.5"
                                            >
                                                <div
                                                    className={cn(
                                                        "flex h-7 w-7 items-center justify-center rounded-full border-2 transition-all",
                                                        done
                                                            ? "border-[#6C63FF] bg-[#6C63FF] text-white"
                                                            : active
                                                              ? "scale-110 border-[#6C63FF] bg-transparent text-[#6C63FF]"
                                                              : "border-gray-200 bg-transparent text-gray-300",
                                                    )}
                                                >
                                                    {done ? (
                                                        <CheckCircle2 size={14} />
                                                    ) : active ? (
                                                        <Sparkles size={14} />
                                                    ) : (
                                                        <Circle size={12} />
                                                    )}
                                                </div>
                                                <span
                                                    className={cn(
                                                        "line-clamp-2 text-center text-[9px] font-semibold uppercase leading-tight",
                                                        active ? "text-[#6C63FF]" : "text-gray-400",
                                                    )}
                                                >
                                                    {s.name}
                                                </span>
                                            </div>
                                        )
                                    })}
                                </div>
                            </div>
                        </SectionCard>

                        <SectionCard title="Description">
                            <p className="whitespace-pre-wrap text-[13px] leading-relaxed text-gray-600">
                                {deal.leadDetails?.trim() || "—"}
                            </p>
                        </SectionCard>

                        <SectionCard title="Tasks" className="flex min-h-[200px] flex-col">
                            {isScopingStage ? (
                                <div className="mb-3 flex justify-end">
                                    <Button size="sm" variant="outline" onClick={onAssignTask}>
                                        + Add Task
                                    </Button>
                                </div>
                            ) : null}
                            <DealTasksWidget
                                dealId={deal.id}
                                assignableUserIds={isScopingStage ? dealMemberUserIds : undefined}
                                taskModuleType="LEAD"
                                expandList
                            />
                        </SectionCard>
                    </div>
                </div>

                {/* Right — BANT fixed panel */}
                <aside className="hidden min-h-0 w-[38%] shrink-0 flex-col border-l border-gray-200/80 bg-transparent p-4 lg:flex">
                    <DealBantSidebar deal={deal} className="h-full min-h-0" />
                </aside>
            </div>

            {/* Mobile BANT below fold */}
            <div className="border-t border-gray-200/80 bg-transparent p-4 lg:hidden">
                <DealBantSidebar deal={deal} />
            </div>

            {/* Footer */}
            <footer className="shrink-0 border-t border-gray-200/80 bg-transparent px-4 py-3">
                <div className="flex flex-wrap items-center justify-center gap-4 text-[13px] font-semibold">
                    {canViewUserActivity ? (
                        <button
                            type="button"
                            className="text-gray-600 hover:text-[#6C63FF]"
                            onClick={() => router.push(`/leads/${deal.id}/user-deal-timeline`)}
                        >
                            User Activity
                        </button>
                    ) : null}
                    {canViewUserActivity && canCreateCustomer ? (
                        <span className="text-gray-200">|</span>
                    ) : null}
                    {canCreateCustomer && deal.stage === "closed_won" ? (
                        <button
                            type="button"
                            className="text-emerald-600 hover:text-emerald-700"
                            onClick={onMoveToCustomer}
                        >
                            {isAlreadyCustomer ? "View Customer" : "Convert to Customer"}
                        </button>
                    ) : null}
                    {(canViewUserActivity || canCreateCustomer) ? (
                        <span className="text-gray-200">|</span>
                    ) : null}
                    <button
                        type="button"
                        className="text-gray-500 hover:text-gray-800"
                        onClick={onClose}
                    >
                        Close
                    </button>
                </div>
            </footer>

            <LeadDetailNotesDialog
                open={notesOpen}
                onOpenChange={setNotesOpen}
                deal={deal}
                {...notesProps}
            />
            <LeadDetailRemindersDialog
                open={remindersOpen}
                onOpenChange={setRemindersOpen}
                deal={deal}
                {...remindersProps}
            />
            <EditDealModal
                deal={deal}
                stages={stages}
                teams={teams}
                isOpen={editOpen}
                onClose={() => setEditOpen(false)}
                onSave={handleSaveEdit}
            />
        </div>
    )
}
