"use client"

import * as React from "react"
import { Deal, DealReminder, Stage } from "./types"
import { Button } from "@/components/ui/button"
import Image from "next/image"
import { cn } from "@/lib/utils"
import {
    Building2, Phone, Mail, MapPin, Users, UserPlus,
    CheckCircle2, Circle, Sparkles, UserCheck, Loader2,
    MessageSquare, Bell, User as UserIcon, Users2, Send, Trash2, Plus, ListChecks, Pencil,
    FileText, Upload, ExternalLink, Layout, X, ImagePlus, Clock, Info,
    ClipboardList, DollarSign,
    Activity,
    Briefcase,
} from "lucide-react"
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"
import { DeleteConfirmationAlert } from "@/components/ui/delete-confirmation-alert"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Textarea } from "@/components/ui/textarea"
import { Input } from "@/components/ui/input"
import { MultiSelect } from "@/components/ui/multi-select"
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from "@/components/ui/popover"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Badge } from "@/components/ui/badge"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import dynamic from "next/dynamic"

const PdfViewerDialog = dynamic(
    () => import("@/components/ui/pdf-viewer-dialog").then((mod) => mod.PdfViewerDialog),
    {
        ssr: false,
        loading: () => <Loader2 className="h-4 w-4 animate-spin text-[#6C63FF]" />,
    }
);
import { useAuthToken } from "@/hooks/use-auth-token"
import { apiBaseUrl } from "@/api/client"
import {
    useGetDealQuery,
    useConvertDealToCustomerMutation,
    useUploadDealNoteImageMutation,
    useAddDealNoteMutation,
    useUpdateDealNoteMutation,
    useDeleteDealNoteMutation,
    useCreateDealReminderMutation,
    useDeleteDealReminderMutation,
    useGetDealProposalsQuery,
    useUploadDealProposalMutation,
    useDeleteDealProposalMutation,
    useUpdateDealMutation,
} from "@/api/rtk/deals-api"
import { DealNoteComposer, getEditableTextFromNote, getNoteImageUrls, mergeEditedNoteTextWithImages, NoteContent } from "./deal-note-composer"
import { useGetProfileQuery } from "@/api/rtk/auth-api"
import { useGetTeamsQuery, useGetAllUsersQuery } from "@/api/rtk/teams-api"
import {
    formatTeamLabelForUi,
    listAssignedUserNames,
    resolveTeamDisplayName,
} from "@/lib/deal-display"
import { DetailItemAssigneeChips } from "@/components/deals/deal-detail-assignee-chips"
import { UserAvatar } from "@/components/ui/user-avatar"
import { DateTimePicker } from "@/components/ui/date-time-picker"
import { DealTasksWidget } from "@/components/tasks/deal-tasks-widget"
import { TaskFormModal } from "@/components/tasks/task-form-modal"
import { getDealMemberUserIds } from "@/lib/deal-team-members"
import { isDiscoverMeetingBookedStage } from "@/lib/deal-stage-labels"
import { DiscoveryMeetingBookedAlert } from "@/components/deals/discovery-meeting-booked-alert"
import { useAppDispatch } from "@/store/hooks"
import { openBusinessDealDialog } from "@/store/slices/business-deal-dialog-slice"
import { canViewDealUserActivity, hasPermission, isAdminUser } from "@/lib/permissions"
import { useSession } from "next-auth/react"

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)
}

/** Main stages in array order, each followed by its substages — full path for the timeline scroller. */
function buildPipelineTimelineStages(stages: Stage[]): Stage[] {
    const mains = stages.filter((s) => !s.isSubStage)
    const byId = new Map(stages.map((s) => [s.id, s]))
    const out: Stage[] = []

    for (const m of mains) {
        out.push(m)
        if (m.subStages && m.subStages.length > 0) {
            const sorted = [...m.subStages].sort((a, b) => a.sortOrder - b.sortOrder)
            for (const sub of sorted) {
                const full = byId.get(sub.id)
                out.push(
                    full ?? {
                        id: sub.id,
                        name: sub.name,
                        color: sub.color ?? m.color,
                        prob: typeof sub.prob === "number" ? sub.prob : m.prob,
                        isSubStage: true,
                        parentStageId: m.id,
                        parentStageName: m.name,
                    },
                )
            }
        } else {
            out.push(...stages.filter((s) => s.isSubStage && s.parentStageId === m.id))
        }
    }

    return out
}

import { DealDetailModalProps } from "@/types/deals"

function DetailItem({ label, value, icon, className }: { label: string; value: string | number | undefined | null; icon?: React.ReactNode; className?: string }) {
    const display = value !== undefined && value !== null && value !== "" ? String(value) : "—"

    // Split by comma if it's a phone field
    const isPhone = label.toLowerCase().includes("phone")
    const parts = isPhone && value !== undefined && value !== null && String(value).trim() !== ""
        ? String(value).split(",").map(p => p.trim()).filter(Boolean)
        : null

    return (
        <div className={cn("min-w-0 p-4 rounded-2xl bg-gray-50/50 border border-gray-100/80 transition-all hover:bg-white hover:border-[#6C63FF]/20 group", className)}>
            <div className="flex items-center gap-2 mb-1.5 min-w-0">
                {icon && <span className="text-gray-400 group-hover:text-[#6C63FF] transition-colors shrink-0">{icon}</span>}
                <span className="text-[10px] font-medium text-gray-400 uppercase tracking-widest font-['Lexend_Deca'] truncate">{label}</span>
            </div>
            {parts ? (
                <div className="flex flex-wrap gap-1.5 mt-0.5">
                    {parts.map((p, i) => (
                        <Badge
                            key={i}
                            variant="secondary"
                            className="bg-[#6C63FF]/5 text-[#6C63FF] border-[#6C63FF]/20 hover:bg-[#6C63FF]/10 transition-colors h-auto py-0.5 px-2 text-[13px] font-semibold rounded-md"
                        >
                            {p}
                        </Badge>
                    ))}
                </div>
            ) : (
                <p className="text-[15px] font-medium text-gray-800 font-['Lexend'] break-words [overflow-wrap:anywhere] whitespace-pre-line">{display}</p>
            )}
        </div>
    )
}

function SectionHeading({ icon, children }: { icon: React.ReactNode; children: React.ReactNode }) {
    return (
        <div className="flex items-center gap-2">
            <span className="text-[#6C63FF]/60">{icon}</span>
            <h3 className="text-[11px] font-semibold text-gray-400 uppercase tracking-widest">{children}</h3>
            <div className="flex-1 h-px bg-gray-100 ml-1" />
        </div>
    )
}

function FieldLabel({ children }: { children: React.ReactNode }) {
    return (
        <label className="block text-[10px] font-medium text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5 select-none">
            {children}
        </label>
    )
}

export function DealDetailModal({ dealId, stages = [], convertedDealIds = new Set(), isOpen, onClose, defaultTab }: DealDetailModalProps) {
    const { data: deal, isLoading, isError, isFetching, refetch } = useGetDealQuery(dealId ?? "", {
        skip: !isOpen || !dealId,
    })
    const router = useRouter()
    const dispatch = useAppDispatch()
    const [convertToCustomer, { isLoading: isConverting }] = useConvertDealToCustomerMutation()

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

    const leadTypeDisplay =
        typeof (deal as any)?.leadType === "object" && (deal as any)?.leadType !== null
            ? ((deal as any).leadType as { name?: string }).name
            : (deal as any)?.leadTypeName || (deal as any)?.leadType

    // Deletion states
    const [deleteNoteId, setDeleteNoteId] = React.useState<string | null>(null)
    const [deleteReminderId, setDeleteReminderId] = React.useState<string | null>(null)
    const [deleteProposalId, setDeleteProposalId] = React.useState<string | null>(null)
    const [viewerOpen, setViewerOpen] = React.useState(false);
    const [viewerUrl, setViewerUrl] = React.useState<string | null>(null);
    const [viewerFileName, setViewerFileName] = React.useState("");

    // Notes state
    const [uploadNoteImage] = useUploadDealNoteImageMutation()
    const [addNoteMutation] = useAddDealNoteMutation()
    const [updateNoteMutation] = useUpdateDealNoteMutation()
    const [deleteNoteMutation, { isLoading: isDeletingNote }] =
        useDeleteDealNoteMutation()
    const [editingNoteId, setEditingNoteId] = React.useState<string | null>(null)
    const [editingNoteText, setEditingNoteText] = React.useState("")
    const [editingNoteRemainingImageUrls, setEditingNoteRemainingImageUrls] = React.useState<string[] | null>(null)
    const notesEndRef = React.useRef<HTMLDivElement>(null)

    // Reminders state
    const [createReminder] = useCreateDealReminderMutation()
    const [deleteReminder, { isLoading: isDeletingReminder }] =
        useDeleteDealReminderMutation()
    const [reminderText, setReminderText] = React.useState("")
    const [reminderDate, setReminderDate] = React.useState("")
    const [reminderTarget, setReminderTarget] = React.useState<"SELF" | "USERS">("SELF")
    const [selectedUserIds, setSelectedUserIds] = React.useState<string[]>([])
    const [reminderErrors, setReminderErrors] = React.useState<{ text?: string; date?: string; users?: string }>({})

    // Proposals state
    const [uploadProposal, { isLoading: isUploadingProposal }] = useUploadDealProposalMutation()
    const [deleteProposal, { isLoading: isDeletingProposal }] =
        useDeleteDealProposalMutation()
    const { data: proposals = [], isLoading: proposalsLoading } =
        useGetDealProposalsQuery(deal?.id ?? "", {
            skip: !deal?.id || !isOpen,
        })

    const { token: accessToken } = useAuthToken()
    const { data: session } = useSession()
    const { data: allUsers = [] } = useGetAllUsersQuery(undefined, { skip: !accessToken })
    const reminderUserOptions = React.useMemo(
        () =>
            allUsers.map((user) => ({
                value: user.id,
                label: `${user.name} (${user.email})`,
            })),
        [allUsers],
    )
    const { data: fullTeams = [] } = useGetTeamsQuery(undefined, { skip: !accessToken || !isOpen })
    const { data: userProfile } = useGetProfileQuery(undefined, { skip: !accessToken })

    const teamDisplayName = React.useMemo(
        () => resolveTeamDisplayName(deal?.team, fullTeams),
        [deal?.team, fullTeams],
    )
    const assigneeAeNames = React.useMemo(
        () => (deal ? listAssignedUserNames(deal.aes, deal.aeIds, allUsers) : []),
        [deal, allUsers],
    )
    const assigneeBdrNames = React.useMemo(
        () => (deal ? listAssignedUserNames(deal.bdrs, deal.bdrIds, allUsers) : []),
        [deal, allUsers],
    )
    const assigneeContributorNames = React.useMemo(
        () => (deal ? listAssignedUserNames(deal.contributors, deal.contributorIds, allUsers) : []),
        [deal, allUsers],
    )
    const permissionSource = (session as { backendUser?: unknown } | null)?.backendUser ?? userProfile
    const isAdmin = isAdminUser(permissionSource)
    const canViewUserActivity = canViewDealUserActivity(permissionSource)
    const canCreateCustomer = hasPermission(permissionSource, ["CREATE", "UPDATE"], "CUSTOMER")
    const canUpdateDeal = hasPermission(permissionSource, "UPDATE", "DEAL")
    const currentUserId = (permissionSource as { id?: string } | null | undefined)?.id
    const canEditNotes = React.useMemo(() => {
        if (!deal) return false
        if (typeof deal.canEdit === "boolean") return deal.canEdit
        return (
            canUpdateDeal ||
            isAdmin ||
            (Boolean(currentUserId) && deal.ownerId === currentUserId)
        )
    }, [deal, canUpdateDeal, isAdmin, currentUserId])

    const [assignTaskOpen, setAssignTaskOpen] = React.useState(false)
    const activeStageRef = React.useRef<HTMLDivElement>(null)

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

    React.useEffect(() => {
        if (!isOpen) setAssignTaskOpen(false)
    }, [isOpen])

    // React.useEffect(() => {
    //     if (!isOpen) return
    //     const timer = setTimeout(() => {
    //         activeStageRef.current?.scrollIntoView({ behavior: "smooth", block: "nearest" })
    //     }, 300)
    //     return () => clearTimeout(timer)
    // }, [isOpen, deal?.stage, pipelineTimeline.length])

    const dealMemberUserIds = React.useMemo(() => {
        if (!deal) return [] as string[]
        const d = deal as { team?: string; ownerId?: string; contributorIds?: string[] }
        return getDealMemberUserIds(d.team, d.ownerId, fullTeams, d.contributorIds)
    }, [deal, fullTeams])

    const lastStageMove = React.useMemo(() => {
        const timeline = Array.isArray(deal?.timeline) ? (deal.timeline as any[]) : []
        const sorted = [...timeline].sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
        return sorted.find(entry => entry.title && entry.title.startsWith("Moved to"))
    }, [deal?.timeline])

    // Notes handlers
    const handleAddNote = async (content: string) => {
        if (!deal || !content.trim()) return
        try {
            await addNoteMutation({ dealId: deal.id, text: content }).unwrap()
            toast.success("Note added successfully")
            setTimeout(() => notesEndRef.current?.scrollIntoView({ behavior: "smooth" }), 100)
        } catch (err) {
            console.error("Failed to add note:", err)
            toast.error("Failed to add note")
        }
    }

    const handleUpdateNote = async (noteId: string, text: string) => {
        if (!text.trim()) return
        try {
            await updateNoteMutation({ dealId: deal!.id, noteId, text }).unwrap()
            toast.success("Note updated successfully")
            setEditingNoteId(null)
            setEditingNoteText("")
            setEditingNoteRemainingImageUrls(null)
        } catch (err) {
            console.error("Failed to update note:", err)
            toast.error("Failed to update note")
        }
    }

    const [editingNoteUploadingImage, setEditingNoteUploadingImage] = React.useState(false)
    const editNoteFileInputRef = React.useRef<HTMLInputElement>(null)

    const handleEditNoteAddImage = async (file: File) => {
        if (!canEditNotes) return
        if (!file.type.startsWith("image/")) {
            toast.error("Please select an image file")
            return
        }
        setEditingNoteUploadingImage(true)
        try {
            const res = await uploadNoteImage({ dealId: deal!.id, file }).unwrap()
            const displayUrl = res.url.startsWith("http") ? res.url : `${apiBaseUrl.replace(/\/$/, "")}${res.url.startsWith("/") ? res.url : `/${res.url}`}`
            setEditingNoteRemainingImageUrls((prev) => [...(prev ?? []), displayUrl])
        } catch (err) {
            console.error("Failed to upload image:", err)
            const msg =
                err && typeof err === "object" && "data" in err
                    ? (() => {
                        const d = (err as { data?: { message?: unknown } }).data?.message
                        return typeof d === "string" ? d : Array.isArray(d) && typeof d[0] === "string" ? d[0] : ""
                    })()
                    : ""
            toast.error(msg.trim() || "Failed to upload image")
        } finally {
            setEditingNoteUploadingImage(false)
        }
    }

    const handleDeleteNote = async (noteId: string) => {
        try {
            await deleteNoteMutation({ dealId: deal!.id, noteId }).unwrap()
            toast.success("Note deleted successfully")
            setDeleteNoteId(null)
        } catch (err) {
            console.error("Failed to delete note:", err)
            toast.error("Failed to delete note")
            throw err
        }
    }

    // Reminders handlers
    const handleAddReminder = async () => {
        setReminderErrors({})
        const errors: { text?: string; date?: string; users?: string } = {}
        if (!reminderText.trim()) errors.text = "Reminder text is required"
        if (!reminderDate) errors.date = "Date & time is required"
        if (reminderTarget === "USERS" && selectedUserIds.length === 0) errors.users = "Please select at least one user"
        if (Object.keys(errors).length > 0) {
            setReminderErrors(errors)
            toast.error("Please fill required fields")
            return
        }
        if (!deal) return

        try {
            await createReminder({
                dealId: deal.id,
                text: reminderText.trim(),
                remindAt: reminderDate,
                targetType: reminderTarget,
                targetUserIds: reminderTarget === "USERS" ? selectedUserIds : undefined,
            }).unwrap()

            toast.success("Reminder scheduled successfully")
            setReminderText("")
            setReminderDate("")
            setSelectedUserIds([])
            setReminderErrors({})
        } catch (err) {
            console.error("Failed to add reminder:", err)
            toast.error("Failed to add reminder")
        }
    }

    const handleDeleteReminder = (reminderId: string) => {
        setDeleteReminderId(reminderId)
    }

    const confirmDeleteReminder = async () => {
        if (!deal || !deleteReminderId) return
        try {
            await deleteReminder({ dealId: deal.id, reminderId: deleteReminderId }).unwrap()
            toast.success("Reminder removed")
            setDeleteReminderId(null)
        } catch (err) {
            console.error("Failed to delete reminder:", err)
            toast.error("Failed to delete reminder")
            throw err
        }
    }

    // Proposals handlers
    const handleUploadProposal = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0]
        if (!file || !deal) return
        const fileName = file.name?.toLowerCase() ?? ""
        const isAllowed = fileName.endsWith(".pdf") || fileName.endsWith(".docx")
        if (!isAllowed) {
            toast.error("Only PDF and DOCX files are allowed")
            e.target.value = ""
            return
        }
        try {
            await uploadProposal({ dealId: deal.id, file }).unwrap()
            toast.success("Document uploaded successfully")
            e.target.value = ""
        } catch (err) {
            console.error("Upload failed:", err)
            toast.error("Failed to upload document")
        }
    }

    const handleDeleteProposal = (documentId: string) => {
        setDeleteProposalId(documentId)
    }

    const confirmDeleteProposal = async () => {
        if (!deal || !deleteProposalId) return
        try {
            await deleteProposal({ dealId: deal.id, documentId: deleteProposalId }).unwrap()
            toast.success("Document removed")
            setDeleteProposalId(null)
        } catch (err) {
            console.error("Delete failed:", err)
            toast.error("Failed to remove document")
            throw err
        }
    }

    const getDownloadUrl = (fileUrl: string) => {
        const base = apiBaseUrl.replace(/\/$/, "")
        const raw = (fileUrl || "").trim()
        if (!raw) return base

        // If backend already returned an absolute URL, normalize to backend host.
        if (/^https?:\/\//i.test(raw)) {
            try {
                const u = new URL(raw)
                return `${base}${u.pathname}${u.search}${u.hash}`
            } catch {
                return raw
            }
        }

        const path = raw.startsWith("/") ? raw : `/${raw}`
        return `${base}${path}`
    }

    if (!isOpen || !dealId) return null

    const si = deal ? pipelineTimeline.findIndex((s) => s.id === deal.stage) : -1
    const currentStage =
        si !== -1
            ? pipelineTimeline[si]
            : deal
                ? stages.find((s) => s.id === deal.stage)
                : undefined
    const isProposalStage = Boolean(
        currentStage &&
        (String(currentStage.id).toLowerCase().includes("proposal") ||
            String(currentStage.name || "").toLowerCase().includes("proposal"))
    )

    const isScopingStage = Boolean(
        currentStage &&
        (String(currentStage.id).toLowerCase().includes("scoping") ||
            String(currentStage.name || "").toLowerCase().includes("scoping"))
    )

    const isAlreadyCustomer = deal ? convertedDealIds.has(deal.id) : false

    const resolvedDefaultTab = defaultTab === "timeline" ? "details" : (defaultTab ?? "details")
    const initialTab = resolvedDefaultTab

    const isDiscoverMeetingBooked = Boolean(deal && isDiscoverMeetingBookedStage(deal, currentStage))
    const canCreateBusinessDeal = hasPermission(permissionSource, ["CREATE", "UPDATE"], "DEAL")

    const handleCreateBusinessDeal = () => {
        if (!deal) return
        const toDateInput = (iso?: string | null) => {
            if (!iso) return ""
            const d = new Date(iso)
            if (Number.isNaN(d.getTime())) return ""
            return d.toISOString().slice(0, 10)
        }
        const leadTypeName =
            typeof deal.leadType === "object" && deal.leadType?.name
                ? deal.leadType.name
                : ""
        const projectTypeName =
            typeof deal.projectType === "object" && deal.projectType?.name
                ? deal.projectType.name
                : ""
        dispatch(
            openBusinessDealDialog({
                prefill: {
                    linkKind: "lead",
                    leadId: deal.id,
                    leadDisplayName:
                        deal.customerName?.trim() ||
                        deal.leadId ||
                        "",
                    pipelineId: deal.pipelineId,
                    title:
                        deal.customerName?.trim() ||
                        deal.leadId ||
                        "New business deal",
                    dealType: leadTypeName || projectTypeName || "",
                    region: "",
                    expectedCloseDate: toDateInput(deal.expectedPaymentDate),
                    dealValue:
                        deal.budget != null && Number.isFinite(Number(deal.budget))
                            ? String(deal.budget)
                            : "",
                    probability:
                        currentStage?.prob != null
                            ? String(currentStage.prob)
                            : "",
                    brand: deal.brand ?? "",
                    notes: deal.leadDetails ?? "",
                    ownerId: deal.ownerId,
                },
            }),
        )
        onClose()
    }

    const handleMoveToCustomer = async () => {
        if (!deal) return
        if (isAlreadyCustomer) {
            toast.info("Customer already moved. Opening customers…")
            onClose()
            router.push("/customers")
            return
        }
        try {
            await convertToCustomer(deal.id).unwrap()
            toast.success("Moved to Customers. Opening customer module…")
            onClose()
            router.push("/customers")
        } catch (error: unknown) {
            const err = error as { data?: { message?: string } }
            const msg = err?.data?.message ?? ""
            if (msg.includes("already been converted") || msg.includes("already converted")) {
                toast.info("Customer already moved. Opening customers…")
                onClose()
                router.push("/customers")
                return
            }
            toast.error(msg || "Failed to move to customer")
        }
    }

    return (
        <>
            <Dialog open={isOpen} onOpenChange={onClose}>
                <DialogContent className="max-sm:inset-x-0 overflow-hidden max-sm:top-0 max-sm:left-1/2 max-sm:translate-x-[-50%] max-sm:translate-y-0 max-sm:h-[100dvh] max-sm:max-h-[100dvh] max-sm:w-full max-sm:max-w-full max-sm:rounded-none sm:max-w-[1100px] w-[96vw] max-h-[95vh] min-w-0 p-0 overflow-y-auto scrollbar-themed animate-in zoom-in-95 duration-200">
                    {isLoading ? (
                        <div className="flex min-h-[400px] items-center justify-center p-6 sm:p-10">
                            <DialogTitle className="sr-only">Loading deal details</DialogTitle>
                            <Alert variant="info" className="max-w-md rounded-2xl border shadow-sm">
                                <Info className="size-4 shrink-0" aria-hidden />
                                <AlertTitle>Loading deal</AlertTitle>
                                <AlertDescription>
                                    Fetching this deal&apos;s details from the server. This usually takes a moment.
                                </AlertDescription>
                            </Alert>
                        </div>
                    ) : (isError || !deal) ? (
                        <div className="flex flex-col items-center justify-center min-h-[300px] gap-5 p-8 text-center">
                            <DialogTitle className="sr-only">Deal details unavailable</DialogTitle>
                            <div className="size-16 rounded-full bg-red-50 flex items-center justify-center">
                                <X className="size-8 text-red-500" />
                            </div>
                            <div>
                                <h3 className="text-lg font-semibold text-gray-900">Could not load deal info</h3>
                                <p className="text-sm text-gray-500 mt-1 max-w-[280px]">We encountered an error while retrieving this record. Please try again or contact support.</p>
                            </div>
                            <Button variant="outline" size="relaxed" onClick={onClose}>
                                Close View
                            </Button>
                        </div>
                    ) : (
                        <>
                            <DialogTitle className="sr-only">{deal.customerName || "Deal"} details</DialogTitle>
                            {/* HEADER */}
                            <div className="relative  pt-6 pb-8 px-4 sm:pt-8 sm:pb-10 sm:px-8">
                                <div className="pointer-events-none absolute inset-0 bg-[#6C63FF] opacity-[0.03]" aria-hidden />
                                <div className="pointer-events-none absolute top-0 right-0 h-96 w-96 bg-[#6C63FF] opacity-[0.05] blur-[120px] -translate-y-1/2 translate-x-1/4" aria-hidden />

                                <div className="relative flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between">
                                    <div className="flex items-start gap-4 min-w-0 sm:gap-6">
                                        <div className="h-14 w-14 shrink-0 rounded-2xl bg-[#6C63FF]/10 border border-[#6C63FF]/20 flex items-center justify-center shadow-inner sm:h-16 sm:w-16">
                                            <Building2 className="size-7 text-[#6C63FF] sm:size-8" />
                                        </div>
                                        <div className="min-w-0 flex-1">
                                            <h2 className="text-xl font-semibold text-gray-900 font-['Lexend'] leading-tight tracking-tight sm:text-[28px] break-words">
                                                {deal.customerName || "Unnamed Lead"}
                                            </h2>
                                            {deal.leadId && (
                                                <p className="text-[12px] font-medium text-gray-400 font-['Lexend_Deca'] mt-0.5">Lead ID: {deal.leadId}</p>
                                            )}
                                            <div className="flex items-center gap-3 mt-1.5 flex-wrap">
                                                {isAlreadyCustomer && (
                                                    <span className="text-[11px] font-medium px-2.5 py-0.5 rounded-full bg-emerald-100 text-emerald-700">Already a customer</span>
                                                )}
                                                {deal.leadStatus && <span className="text-[14px] font-medium text-gray-500">{deal.leadStatus}</span>}
                                                {(teamDisplayName || deal.team) && (
                                                    <>
                                                        <span className="text-gray-300">/</span>
                                                        <span className="text-[14px] font-medium text-gray-600">{teamDisplayName || formatTeamLabelForUi(deal.team)}</span>
                                                    </>
                                                )}
                                            </div>
                                        </div>
                                    </div>

                                    <div className="flex flex-wrap items-stretch gap-4 sm:gap-4 lg:flex-nowrap lg:items-center lg:justify-end lg:shrink-0">
                                        {deal.leadChannel && (
                                            <div className="min-w-0 text-left sm:text-right">
                                                <p className="text-[11px] font-medium text-gray-400 uppercase tracking-widest mb-1.5">Channel</p>
                                                <p className="text-lg font-semibold text-[#6C63FF] font-['Lexend'] leading-tight tracking-tight sm:text-[20px] sm:leading-none break-words">
                                                    {channelName || "—"}
                                                </p>
                                            </div>
                                        )}
                                        {deal.brand && (
                                            <>
                                                <div className="hidden h-12 w-px bg-gray-100 lg:block" aria-hidden />
                                                <div className="min-w-0 text-left sm:text-right">
                                                    <p className="text-[11px] font-medium text-gray-400 uppercase tracking-widest mb-1.5">Brand</p>
                                                    <p className="text-lg font-semibold text-gray-900 font-['Lexend'] leading-tight sm:text-[20px] sm:leading-none break-words">{deal.brand}</p>
                                                </div>
                                            </>
                                        )}
                                        {Boolean((typeof deal.service === 'object' ? deal.service?.name : deal.service) || deal.serviceName) && (
                                            <>
                                                <div className="hidden h-12 w-px bg-gray-100 lg:block" aria-hidden />
                                                <div className="min-w-0 text-left sm:text-right">
                                                    <p className="text-[11px] font-medium text-gray-400 uppercase tracking-widest mb-1.5">Service</p>
                                                    <p className="text-lg font-semibold text-gray-900 font-['Lexend'] leading-tight sm:text-[20px] sm:leading-none break-words">
                                                        {(typeof deal.service === 'object' ? deal.service?.name : deal.service) || deal.serviceName || "—"}
                                                    </p>
                                                </div>
                                            </>
                                        )}
                                    </div>
                                </div>

                                {isDiscoverMeetingBooked && (
                                    <DiscoveryMeetingBookedAlert
                                        className="relative mt-6"
                                        deal={deal}
                                        canCreateBusinessDeal={canCreateBusinessDeal}
                                        onCreateBusinessDeal={handleCreateBusinessDeal}
                                        permissionSource={permissionSource}
                                        onAfterVerify={() => void refetch()}
                                    />
                                )}

                                {/* STAGE PROGRESS */}
                                <div className="mt-8 sm:mt-12">
                                    <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between mb-4">
                                        <SectionHeading icon={<Activity size={14} className="text-secondary" />}>
                                            Pipeline Stages
                                        </SectionHeading>
                                        {lastStageMove && (
                                            <div className="flex items-start gap-2 px-3 py-1.5 rounded-lg bg-gray-50/50 border border-gray-100 text-[11px] font-medium text-gray-500 animate-in fade-in slide-in-from-top-2 duration-500 sm:items-center sm:text-right max-w-full">
                                                <Clock size={12} className="text-gray-400 shrink-0 mt-0.5 sm:mt-0" />
                                                <span className="break-words">Last moved by <span className="text-accent font-bold">{lastStageMove?.addedByName || "System"}</span> on {new Date(lastStageMove.date).toLocaleDateString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}</span>
                                            </div>
                                        )}
                                    </div>
                                </div>
                                <div
                                    className="mt-2  max-w-[54vw] mx-auto overflow-x-scroll  pb-6 pt-1  px-4 sm:-mx-8 sm:px-8"
                                    role="region"
                                    aria-label="Pipeline stages"
                                >
                                    <div className="flex  gap-x-2 gap-y-5 sm:gap-x-3 sm:gap-y-6">
                                        {pipelineTimeline.map((s, i) => {
                                            const done = si !== -1 && i < si
                                            const active = si !== -1 && i === si
                                            return (
                                                <div
                                                    key={s.id}
                                                    // ref={active ? activeStageRef : null}
                                                    className="flex min-h-[5.5rem] min-w-[100px]  min-w-0 flex-col items-center gap-2"
                                                >
                                                    <div
                                                        className={cn(
                                                            "z-10 h-8 w-8 shrink-0 rounded-full border-2 flex items-center justify-center transition-all duration-300",
                                                            done
                                                                ? "bg-[#6C63FF] border-[#6C63FF] text-white shadow-lg shadow-[#6C63FF]/30"
                                                                : active
                                                                    ? "bg-white border-[#6C63FF] text-[#6C63FF] scale-110 shadow-xl"
                                                                    : "bg-white border-gray-200 text-gray-300"
                                                        )}
                                                    >
                                                        {done ? (
                                                            <CheckCircle2 size={16} />
                                                        ) : active ? (
                                                            <Sparkles size={16} className="animate-pulse" />
                                                        ) : (
                                                            <Circle size={14} />
                                                        )}
                                                    </div>
                                                    <span
                                                        className={cn(
                                                            "min-h-[2.75rem] w-full text-center text-[9px] font-semibold uppercase leading-tight tracking-wide font-['Lexend_Deca'] break-words hyphens-auto line-clamp-3 sm:text-[11px] sm:tracking-widest sm:line-clamp-4",
                                                            active ? "text-[#6C63FF]" : "text-gray-400"
                                                        )}
                                                    >
                                                        {s.name}
                                                    </span>
                                                </div>
                                            )
                                        })}
                                    </div>
                                </div>
                                {isScopingStage && (
                                    <div className="mt-5 flex justify-end">
                                        <Button
                                            type="button"
                                            variant="accentSoftOutline"
                                            onClick={() => setAssignTaskOpen(true)}
                                        >
                                            <ClipboardList size={16} />
                                            Assign task
                                        </Button>
                                    </div>
                                )}
                            </div>

                            {/* CONTENT */}
                            <div className="px-4 pb-6 sm:px-8 sm:pb-8">
                                <Tabs key={`${deal.id}-${initialTab}`} defaultValue={initialTab} className="w-full min-w-0">
                                    <div className="sticky top-0 z-20 bg-white/95 backdrop-blur-md border-b border-gray-100 py-3 -mx-4 px-4 sm:mx-0 sm:px-0">
                                        <div className="overflow-x-auto overflow-y-hidden -mx-1 px-1 pb-0.5 [scrollbar-width:thin]">
                                            <TabsList className="inline-flex h-auto min-h-10 w-max max-w-none flex-nowrap rounded-[14px] p-[3px]">
                                                {[
                                                    { value: "details", label: "Deal Details", icon: <Layout size={14} /> },
                                                    { value: "notes", label: "Notes", icon: <MessageSquare size={14} /> },
                                                    { value: "reminders", label: "Reminders", icon: <Bell size={14} /> },
                                                    { value: "proposals", label: "Proposals", icon: <FileText size={14} /> },
                                                    { value: "tasks", label: "Tasks", icon: <ClipboardList size={14} /> },
                                                ].map(tab => (
                                                    <TabsTrigger
                                                        key={tab.value}
                                                        value={tab.value}
                                                        className="shrink-0 flex-none gap-1.5 px-3 py-2 text-xs font-semibold sm:gap-2 sm:px-4 sm:text-[13px] data-[state=active]:text-[#6C63FF]"
                                                    >
                                                        <span className="shrink-0">{tab.icon}</span>
                                                        <span className="whitespace-nowrap">{tab.label}</span>
                                                    </TabsTrigger>
                                                ))}
                                            </TabsList>
                                        </div>
                                    </div>

                                    <TabsContent value="details" className="mt-6 outline-none">
                                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
                                            <DetailItem label="Phone" value={deal.phone || "—"} icon={<Phone size={14} />} />
                                            <DetailItem label="Home Phone" value={deal.homePhone || "—"} icon={<Phone size={14} />} />
                                            <DetailItem label="Email" value={deal.email || "—"} icon={<Mail size={14} />} />
                                            <DetailItem label="Address" value={deal.address || "—"} icon={<MapPin size={14} />} />
                                            <DetailItem label="Postal Code" value={deal.postalCode || "—"} />
                                            <DetailItem label="Lead Owner" value={deal.owner?.name || "—"} icon={<Users size={14} />} />
                                            <DetailItem label="Team" value={teamDisplayName || formatTeamLabelForUi(deal.team) || "—"} icon={<Briefcase size={14} />} />
                                            <DetailItemAssigneeChips label="Assign AE" names={assigneeAeNames} icon={<UserCheck size={14} />} />
                                            <DetailItemAssigneeChips label="Assign BDR" names={assigneeBdrNames} icon={<Users2 size={14} />} />
                                            <DetailItemAssigneeChips label="Contributors" names={assigneeContributorNames} icon={<UserPlus size={14} />} />
                                            <DetailItem label="Created By" value={deal.createdBy || "—"} />
                                            <DetailItem
                                                label="Created At"
                                                value={deal?.createdDate ? new Date(deal?.createdDate)?.toLocaleDateString() : "—"}
                                                icon={<Clock size={14} />}
                                            />
                                            <div className={cn("p-4 rounded-2xl bg-gray-50/50 border border-gray-100/80 transition-all hover:bg-white hover:border-[#6C63FF]/20 group")}>
                                                <div className="flex items-center gap-2 mb-1.5">
                                                    <span className="text-[10px] font-medium text-gray-400 uppercase tracking-widest font-['Lexend_Deca']">Tags</span>
                                                </div>
                                                <div className="flex flex-wrap gap-2">
                                                    {deal.tags?.length ? (
                                                        deal.tags.map((tag) => (
                                                            <Badge
                                                                key={tag}
                                                                variant="secondary"
                                                                className="rounded-md px-2.5 py-1 text-[12px] font-medium bg-primary/10 text-primary border-0"
                                                            >
                                                                {tag}
                                                            </Badge>
                                                        ))
                                                    ) : (
                                                        <span className="text-[15px] font-medium text-gray-400">—</span>
                                                    )}
                                                </div>
                                            </div>
                                            <div className={cn("p-4 rounded-2xl bg-gray-50/50 border border-gray-100/80 transition-all hover:bg-white hover:border-[#6C63FF]/20 group")}>
                                                <div className="flex items-center gap-2 mb-1.5">
                                                    <span className="text-[10px] font-medium text-gray-400 uppercase tracking-widest font-['Lexend_Deca']">Closed lead tags</span>
                                                </div>
                                                <div className="flex flex-wrap gap-2">
                                                    {deal.closedLeadTags?.length ? (
                                                        deal.closedLeadTags.map((tag) => (
                                                            <Badge
                                                                key={tag.id}
                                                                variant="outline"
                                                                className="rounded-md px-2.5 py-1 text-[12px] font-medium border-red-200 text-red-700 bg-red-50"
                                                            >
                                                                {tag.name}
                                                            </Badge>
                                                        ))
                                                    ) : (
                                                        <span className="text-[15px] font-medium text-gray-400">—</span>
                                                    )}
                                                </div>
                                            </div>

                                            <DetailItem label="Month / Year" value={`${deal.month || "—"} / ${deal.year || "—"}`} />
                                            <DetailItem label="Purchase Count" value={deal.purchaseCount ?? "—"} />
                                            <DetailItem
                                                label="Budget"
                                                value={formatDealBudget(deal.budget)}
                                                icon={<DollarSign size={14} />}
                                            />
                                            <DetailItem
                                                label="Expected Payment Date"
                                                value={deal.expectedPaymentDate ? new Date(deal.expectedPaymentDate).toLocaleDateString() : "—"}
                                            />
                                        </div>

                                        <div className="mt-6">
                                            <div className="flex items-center gap-2 mb-3">
                                                <span className="text-[#6C63FF]/60"><ListChecks size={14} /></span>
                                                <h3 className="text-[11px] font-extrabold text-gray-400 uppercase tracking-widest">BANT Qualification</h3>
                                                <div className="flex-1 h-px bg-gray-100 ml-1" />
                                            </div>
                                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5">
                                                <DetailItem label="BANT Score" value={deal.bantScore?.name ?? "—"} />
                                                <DetailItem label="BANT Budget" value={deal.bantBudget?.name ?? "—"} />
                                                <DetailItem label="BANT Authority" value={deal.bantAuthority?.name ?? "—"} />
                                                <DetailItem label="BANT Need" value={deal.bantNeed?.name ?? "—"} />
                                                <DetailItem label="BANT Timeline" value={deal.bantTimeline?.name ?? "—"} />
                                            </div>
                                        </div>

                                        {deal.leadDetails && (
                                            <div className="mt-6 p-6 rounded-3xl bg-[#6C63FF]/2 border border-border/50">
                                                <h4 className="text-[11px] font-semibold text-gray-400 uppercase tracking-widest mb-4 font-['Lexend_Deca']">Lead Details</h4>
                                                <p className="text-[13px] text-gray-600 leading-relaxed font-['Lexend']">{deal.leadDetails}</p>
                                            </div>
                                        )}

                                    </TabsContent>

                                    <TabsContent value="notes" className="mt-0 outline-none">
                                        <div className="flex flex-col" style={{ height: "calc(95vh - 400px)", minHeight: 400 }}>
                                            {isFetching && !isLoading ? (
                                                <div
                                                    className="mb-2 flex shrink-0 items-center gap-2 rounded-lg border border-[#6C63FF]/20 bg-[#6C63FF]/10 px-3 py-2 text-[11px] font-medium tracking-wide text-[#5a52d6] animate-in fade-in duration-300"
                                                    role="status"
                                                    aria-live="polite"
                                                >
                                                    <span className="relative flex h-2 w-2">
                                                        <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-[#6C63FF] opacity-40" />
                                                        <span className="relative inline-flex h-2 w-2 rounded-full bg-[#6C63FF]" />
                                                    </span>
                                                    Syncing latest notes…
                                                </div>
                                            ) : null}
                                            <div className="flex-1 overflow-y-auto px-0 py-5 space-y-6 scrollbar-themed">
                                                {deal.dealNotes?.length ? deal.dealNotes.map((note) => (
                                                    <div key={note.id} className="flex gap-4 animate-in fade-in slide-in-from-bottom-2 group">
                                                        <UserAvatar
                                                            avatar={note.author?.profile?.avatar}
                                                            name={note.author?.name}
                                                            size="md"
                                                            className="shadow-lg shadow-[#6C63FF]/20"
                                                        />
                                                        <div className="flex-1 min-w-0">
                                                            <div className="bg-gray-50 rounded-2xl p-4 border border-gray-100 shadow-sm">
                                                                <div className="flex items-center justify-between gap-3 mb-2">
                                                                    <span className="text-[14px] font-semibold text-gray-900">{note.author?.name}</span>
                                                                    <span className="text-[11px] font-medium text-gray-400">{new Date(note.createdAt).toLocaleString()}</span>
                                                                </div>
                                                                {editingNoteId === note.id ? (
                                                                    <div className="space-y-3">
                                                                        <Textarea
                                                                            className="min-h-[60px] text-[13px] bg-white border-gray-200 rounded-xl"
                                                                            value={editingNoteText}
                                                                            onChange={(e) => setEditingNoteText(e.target.value)}
                                                                            autoFocus
                                                                        />
                                                                        <div className="space-y-1.5">
                                                                            <p className="text-[11px] font-medium text-gray-500">Attached images — click × to remove, or add below</p>
                                                                            {(editingNoteRemainingImageUrls ?? []).length > 0 ? (
                                                                                <div className="flex flex-wrap gap-2">
                                                                                    {(editingNoteRemainingImageUrls ?? []).map((src, i) => (
                                                                                        <div key={`${src}-${i}`} className="relative w-16 h-16 rounded-lg overflow-hidden border-2 border-gray-200 shadow-sm bg-gray-100 shrink-0 group">
                                                                                            <Image
                                                                                                src={src}
                                                                                                alt=""
                                                                                                fill
                                                                                                loading="lazy"
                                                                                                sizes="(max-width: 768px) 100px, 100px"
                                                                                                className="w-full h-full object-cover"
                                                                                            />
                                                                                            <button
                                                                                                type="button"
                                                                                                onClick={() => setEditingNoteRemainingImageUrls((prev) => (prev ? prev.filter((u) => u !== src) : []))}
                                                                                                className="absolute top-0.5 right-0.5 h-5 w-5 rounded-full bg-red-500 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 hover:bg-red-600 transition-opacity"
                                                                                                aria-label="Remove image"
                                                                                            >
                                                                                                <X className="h-3 w-3" />
                                                                                            </button>
                                                                                        </div>
                                                                                    ))}
                                                                                </div>
                                                                            ) : null}
                                                                            <input
                                                                                ref={editNoteFileInputRef}
                                                                                type="file"
                                                                                accept="image/*"
                                                                                className="hidden"
                                                                                onChange={(e) => {
                                                                                    const f = e.target.files?.[0]
                                                                                    if (f) handleEditNoteAddImage(f)
                                                                                    e.target.value = ""
                                                                                }}
                                                                            />
                                                                            <div
                                                                                className={cn(
                                                                                    "flex items-center gap-2 rounded-xl border-2 border-dashed border-gray-200 bg-gray-50/80 px-3 py-2 min-h-[44px]",
                                                                                    "focus-within:border-[#6C63FF]/50"
                                                                                )}
                                                                                onPaste={(e) => {
                                                                                    const item = Array.from(e.clipboardData?.items ?? []).find((i) => i.type.startsWith("image/"))
                                                                                    const file = item?.getAsFile()
                                                                                    if (file) {
                                                                                        e.preventDefault()
                                                                                        handleEditNoteAddImage(file)
                                                                                    }
                                                                                }}
                                                                                onDrop={(e) => {
                                                                                    e.preventDefault()
                                                                                    const file = e.dataTransfer.files?.[0]
                                                                                    if (file?.type.startsWith("image/")) handleEditNoteAddImage(file)
                                                                                }}
                                                                                onDragOver={(e) => e.preventDefault()}
                                                                            >
                                                                                <Button
                                                                                    type="button"
                                                                                    variant="outlineNoteAttach"
                                                                                    disabled={editingNoteUploadingImage || !canEditNotes}
                                                                                    onClick={() => editNoteFileInputRef.current?.click()}
                                                                                >
                                                                                    {editingNoteUploadingImage ? (
                                                                                        <Loader2 className="h-3.5 w-3.5 animate-spin" />
                                                                                    ) : (
                                                                                        <ImagePlus className="h-3.5 w-3.5" />
                                                                                    )}
                                                                                    {editingNoteUploadingImage ? "Uploading…" : "Add image"}
                                                                                </Button>
                                                                                <span className="text-[11px] text-gray-500">or paste / drop image here</span>
                                                                            </div>
                                                                        </div>
                                                                        <div className="flex gap-2">
                                                                            <Button
                                                                                variant="accentNoteSave"
                                                                                onClick={() => handleUpdateNote(note.id, mergeEditedNoteTextWithImages(editingNoteText, editingNoteRemainingImageUrls ?? [], apiBaseUrl))}
                                                                            >
                                                                                Save
                                                                            </Button>
                                                                            <Button
                                                                                variant="ghostNoteCancel"
                                                                                onClick={() => {
                                                                                    setEditingNoteId(null)
                                                                                    setEditingNoteText("")
                                                                                    setEditingNoteRemainingImageUrls(null)
                                                                                }}
                                                                            >
                                                                                Cancel
                                                                            </Button>
                                                                        </div>
                                                                    </div>
                                                                ) : (
                                                                    <NoteContent text={note.text} apiBaseUrl={apiBaseUrl} />
                                                                )}
                                                            </div>
                                                            {editingNoteId !== note.id && canEditNotes ? (
                                                                <div className="flex items-center gap-4 mt-2 ml-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                                                    <button
                                                                        onClick={() => {
                                                                            setEditingNoteId(note.id)
                                                                            setEditingNoteText(getEditableTextFromNote(note.text))
                                                                            setEditingNoteRemainingImageUrls(getNoteImageUrls(note.text, apiBaseUrl))
                                                                        }}
                                                                        className="text-[12px] font-semibold text-gray-500 hover:text-[#6C63FF] transition-colors"
                                                                    >
                                                                        Edit
                                                                    </button>
                                                                    <button
                                                                        onClick={() => setDeleteNoteId(note.id)}
                                                                        className="text-[12px] font-semibold text-gray-500 hover:text-red-600 transition-colors"
                                                                    >
                                                                        Delete
                                                                    </button>
                                                                </div>
                                                            ) : null}
                                                        </div>
                                                    </div>
                                                )) : (
                                                    <div className="flex flex-col items-center justify-center py-20 opacity-30">
                                                        <MessageSquare size={48} className="mb-4 text-gray-400" />
                                                        <p className="text-[13px] font-semibold uppercase tracking-widest text-gray-400">No notes yet</p>
                                                        <p className="text-[11px] text-gray-400 mt-1">Add your first note below</p>
                                                    </div>
                                                )}
                                                <div ref={notesEndRef} />
                                            </div>
                                            <div className="shrink-0 border-t border-gray-100 bg-white px-0 py-4">
                                                <DealNoteComposer
                                                    dealId={deal.id}
                                                    apiBaseUrl={apiBaseUrl}
                                                    disabled={!canEditNotes}
                                                    placeholder="Add an internal note... (paste image to attach)"
                                                    onSend={handleAddNote}
                                                    uploadImage={async (did, file) => {
                                                        const res = await uploadNoteImage({ dealId: did, file }).unwrap()
                                                        return res
                                                    }}
                                                />
                                            </div>
                                        </div>
                                    </TabsContent>

                                    <TabsContent value="reminders" className="mt-0 outline-none">
                                        <div className="px-0 py-6 space-y-6">
                                            <section>
                                                <SectionHeading icon={<Bell size={14} />}>Add Reminder</SectionHeading>
                                                <p className="text-[12px] text-gray-500 mt-1 mb-4">
                                                    Set a reminder for yourself or notify all deal owners.
                                                </p>
                                                <div className="space-y-4">
                                                    <div>
                                                        <FieldLabel>Reminder text</FieldLabel>
                                                        <Textarea
                                                            className={cn(
                                                                "min-h-[80px] text-[13px] bg-gray-50 rounded-xl",
                                                                reminderErrors.text ? "border-red-400 focus-visible:ring-red-400" : "border-gray-200"
                                                            )}
                                                            placeholder="e.g. Follow up with client..."
                                                            value={reminderText}
                                                            onChange={(e) => {
                                                                setReminderText(e.target.value)
                                                                if (reminderErrors.text) setReminderErrors((prev) => ({ ...prev, text: undefined }))
                                                            }}
                                                        />
                                                        {reminderErrors.text && (
                                                            <p className="text-xs text-red-500 mt-1">{reminderErrors.text}</p>
                                                        )}
                                                    </div>
                                                    <div className="flex flex-wrap gap-4 items-end">
                                                        <div>
                                                            <FieldLabel>Date & time</FieldLabel>
                                                            <DateTimePicker
                                                                value={reminderDate}
                                                                onChange={(date) => {
                                                                    setReminderDate(date || "")
                                                                    if (reminderErrors.date) setReminderErrors((prev) => ({ ...prev, date: undefined }))
                                                                }}
                                                                placeholder="Set date & time"
                                                            />
                                                            {reminderErrors.date && (
                                                                <p className="text-xs text-red-500 mt-1">{reminderErrors.date}</p>
                                                            )}
                                                        </div>
                                                        <div className="flex gap-2">
                                                            <button
                                                                type="button"
                                                                onClick={() => {
                                                                    setReminderTarget("SELF")
                                                                    setSelectedUserIds([])
                                                                }}
                                                                className={cn(
                                                                    "flex items-center gap-1.5 px-4 py-2 rounded-xl text-[12px] font-medium transition-all h-10",
                                                                    reminderTarget === "SELF"
                                                                        ? "bg-[#6C63FF] text-white"
                                                                        : "bg-gray-100 text-gray-600 hover:bg-gray-200"
                                                                )}
                                                            >
                                                                <UserIcon size={14} />
                                                                For me
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() => setReminderTarget("USERS")}
                                                                className={cn(
                                                                    "flex items-center gap-1.5 px-4 py-2 rounded-xl text-[12px] font-medium transition-all h-10",
                                                                    reminderTarget === "USERS"
                                                                        ? "bg-[#6C63FF] text-white"
                                                                        : "bg-gray-100 text-gray-600 hover:bg-gray-200"
                                                                )}
                                                            >
                                                                <Users2 size={14} />
                                                                For users
                                                            </button>
                                                        </div>
                                                        {reminderTarget === "USERS" && (
                                                            <div className="w-full">
                                                                <FieldLabel>Select Users</FieldLabel>
                                                                <MultiSelect
                                                                    options={reminderUserOptions}
                                                                    value={selectedUserIds}
                                                                    onValueChange={(ids) => {
                                                                        setSelectedUserIds(ids)
                                                                        if (reminderErrors.users) {
                                                                            setReminderErrors((prev) => ({
                                                                                ...prev,
                                                                                users: undefined,
                                                                            }))
                                                                        }
                                                                    }}
                                                                    placeholder="Select users..."
                                                                    className={cn(
                                                                        reminderErrors.users && "border-red-400",
                                                                    )}
                                                                />
                                                                {reminderErrors.users && (
                                                                    <p className="text-xs text-red-500 mt-1">{reminderErrors.users}</p>
                                                                )}
                                                            </div>
                                                        )}
                                                        <Button
                                                            variant="accentReminderBar"
                                                            onClick={handleAddReminder}
                                                            disabled={!reminderText.trim() || !reminderDate || (reminderTarget === "USERS" && selectedUserIds.length === 0)}
                                                        >
                                                            Add Reminder
                                                        </Button>
                                                    </div>
                                                </div>
                                            </section>
                                            <section>
                                                <SectionHeading icon={<Bell size={14} />}>Scheduled Reminders</SectionHeading>
                                                <div className="mt-4 space-y-2">
                                                    {(deal.dealReminders?.length ?? 0) > 0 ? (
                                                        deal.dealReminders!.map((r: DealReminder) => {
                                                            const targetUserNames = r.targetType === "USERS" && r.targetUserIds?.length
                                                                ? r.targetUserIds.map(id => allUsers.find(u => u.id === id)?.name).filter(Boolean).join(", ")
                                                                : null

                                                            return (
                                                                <div
                                                                    key={r.id}
                                                                    className="flex items-center justify-between gap-3 p-4 rounded-xl bg-gray-50 border border-gray-100 hover:border-[#6C63FF]/20 transition-all group"
                                                                >
                                                                    <div className="min-w-0 flex-1 pr-2">
                                                                        <div className="flex flex-wrap items-center gap-2">
                                                                            <p className="text-[14px] font-semibold text-gray-800">{r.text}</p>
                                                                            {r.targetType === "USERS" ? (
                                                                                <Badge
                                                                                    variant="secondary"
                                                                                    className="shrink-0 gap-1 border border-[#6C63FF]/25 bg-[#6C63FF]/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-[#5a52d6]"
                                                                                >
                                                                                    <Users2 className="size-3 text-[#6C63FF]" aria-hidden />
                                                                                    Group
                                                                                </Badge>
                                                                            ) : null}
                                                                            {r.isSent ? (
                                                                                <Badge
                                                                                    variant="secondary"
                                                                                    className="shrink-0 gap-1 border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-emerald-800"
                                                                                >
                                                                                    <CheckCircle2 className="size-3 text-emerald-600" aria-hidden />
                                                                                    Send success
                                                                                </Badge>
                                                                            ) : null}
                                                                        </div>
                                                                        <div className="flex flex-wrap items-center gap-2 mt-1 text-[11px] text-gray-500">
                                                                            <span>{new Date(r.remindAt).toLocaleString()}</span>
                                                                            <span className={r.targetType === "USERS" ? "text-[#6C63FF] font-medium" : "text-gray-400"}>
                                                                                {r.targetType === "USERS"
                                                                                    ? `→ ${targetUserNames || `${r.targetUserIds?.length || 0} user(s)`}`
                                                                                    : "→ Me only"}
                                                                            </span>
                                                                            {r.createdBy && <span>by {r.createdBy.name}</span>}
                                                                        </div>
                                                                    </div>
                                                                    <Button
                                                                        variant="toolbarDangerReveal"
                                                                        className="shrink-0"
                                                                        onClick={() => handleDeleteReminder(r.id)}
                                                                    >
                                                                        <Trash2 size={14} />
                                                                    </Button>
                                                                </div>
                                                            )
                                                        })
                                                    ) : (
                                                        <div className="p-8 rounded-xl bg-gray-50/50 border-2 border-dashed border-gray-100 text-center">
                                                            <Bell size={32} className="mx-auto text-gray-300 mb-2" />
                                                            <p className="text-[13px] font-medium text-gray-400">No reminders yet</p>
                                                        </div>
                                                    )}
                                                </div>
                                            </section>
                                        </div>
                                    </TabsContent>

                                    <TabsContent value="proposals" className="mt-0 outline-none">
                                        <div className="px-0 py-6 space-y-6">
                                            {isProposalStage && !proposalsLoading && proposals.length === 0 && (
                                                <div className="rounded-xl bg-amber-50 border border-amber-200 px-4 py-3 flex items-center gap-3">
                                                    <FileText size={20} className="text-amber-600 shrink-0" />
                                                    <div>
                                                        <p className="text-[13px] font-medium text-amber-800">This deal is in Proposal stage</p>
                                                        <p className="text-[12px] text-amber-700 mt-0.5">Please upload a proposal document for this deal.</p>
                                                    </div>
                                                </div>
                                            )}
                                            <section>
                                                <SectionHeading icon={<FileText size={14} />}>
                                                    Proposal Documents
                                                </SectionHeading>
                                                <p className="text-[12px] text-gray-500 mt-1 mb-4">
                                                    Upload proposal documents (PDFs, docs, etc.) to attach to this deal.
                                                </p>

                                                <label className="inline-flex items-center gap-2 h-10 px-4 rounded-xl bg-[#6C63FF]/10 border border-[#6C63FF]/20 text-[#6C63FF] font-semibold text-[13px] cursor-pointer hover:bg-[#6C63FF]/15 transition-colors disabled:cursor-not-allowed disabled:opacity-60">
                                                    {isUploadingProposal ? (
                                                        <span className="flex items-center gap-2 text-[12px]">
                                                            <Loader2 className="h-4 w-4 animate-spin" />
                                                            Uploading...
                                                        </span>
                                                    ) : (
                                                        <>
                                                            <Upload size={16} />
                                                            Upload document
                                                        </>
                                                    )}
                                                    <input
                                                        type="file"
                                                        className="hidden"
                                                        accept=".pdf,.docx,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                                                        disabled={isUploadingProposal}
                                                        onChange={handleUploadProposal}
                                                    />
                                                </label>

                                                <div className="mt-6 space-y-3">
                                                    {proposalsLoading ? (
                                                        <div className="flex items-center justify-center py-12 text-gray-400 text-[13px]">
                                                            Loading documents...
                                                        </div>
                                                    ) : proposals.length === 0 ? (
                                                        <div className="flex flex-col items-center justify-center py-12 rounded-2xl bg-gray-50/80 border border-dashed border-gray-200">
                                                            <FileText size={40} className="mb-3 text-gray-300" />
                                                            <p className="text-[13px] font-semibold text-gray-400">No documents uploaded yet</p>
                                                            <p className="text-[11px] text-gray-400 mt-0.5">Upload a proposal document to get started</p>
                                                        </div>
                                                    ) : (
                                                        proposals.map((doc) => (
                                                            <div
                                                                key={doc.id}
                                                                className="flex items-center justify-between gap-4 p-4 rounded-xl bg-gray-50 border border-gray-100 hover:border-gray-200 transition-colors"
                                                            >
                                                                <div className="flex items-center gap-3 min-w-0">
                                                                    <div className="h-10 w-10 rounded-xl bg-[#6C63FF]/10 flex items-center justify-center shrink-0">
                                                                        <FileText size={18} className="text-[#6C63FF]" />
                                                                    </div>
                                                                    <div className="min-w-0">
                                                                        <p className="text-[13px] font-semibold text-gray-900 truncate">
                                                                            {doc.fileName}
                                                                        </p>
                                                                        <p className="text-[11px] text-gray-400">
                                                                            {doc.size ? `${(doc.size / 1024).toFixed(1)} KB` : ""}
                                                                            {doc.size && doc.createdAt ? " · " : ""}
                                                                            {doc.createdAt
                                                                                ? new Date(doc.createdAt).toLocaleDateString()
                                                                                : ""}
                                                                        </p>
                                                                    </div>
                                                                </div>
                                                                <div className="flex items-center gap-2 shrink-0">
                                                                    <button
                                                                        onClick={() => {
                                                                            setViewerUrl(getDownloadUrl(doc.fileUrl));
                                                                            setViewerFileName(doc.fileName);
                                                                            setViewerOpen(true);
                                                                        }}
                                                                        className="h-9 w-9 rounded-lg bg-gray-200/80 flex items-center justify-center text-gray-600 hover:bg-gray-300 transition-colors"
                                                                        title="View"
                                                                    >
                                                                        <FileText size={14} />
                                                                    </button>
                                                                    <button
                                                                        type="button"
                                                                        onClick={() => handleDeleteProposal(doc.id)}
                                                                        className="h-9 w-9 rounded-lg bg-rose-50 flex items-center justify-center text-rose-600 hover:bg-rose-100 transition-colors"
                                                                        title="Remove"
                                                                    >
                                                                        <Trash2 size={14} />
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        ))
                                                    )}
                                                </div>
                                            </section>
                                        </div>
                                    </TabsContent>

                                    <TabsContent value="tasks" className="mt-6 outline-none">
                                        <p className="text-[13px] text-gray-500 mb-4 max-w-xl">
                                            {isScopingStage
                                                ? "Tasks for this deal. While the deal is in Scoping, you can only assign work to people on this deal’s CRM team (owner and members from the Team record)."
                                                : "Tasks linked to this deal. Open the Tasks page to see them with the rest of the team’s work."}
                                        </p>
                                        <DealTasksWidget
                                            dealId={deal.id}
                                            assignableUserIds={isScopingStage ? dealMemberUserIds : undefined}
                                            taskModuleType={deal.isBusinessDeal ? "DEAL" : "LEAD"}
                                        />
                                    </TabsContent>
                                </Tabs>
                            </div>

                            <div className="bg-gray-50 px-4 py-4 border-t border-gray-100 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between sm:px-8 sm:py-5">
                                <div className="flex flex-wrap items-center gap-2 sm:gap-3">
                                    <Button
                                        variant="outlineAccent"
                                        size="responsiveFooter"
                                        onClick={() => {
                                            // onClose()
                                            const base = deal.isBusinessDeal ? "/sales-deals" : "/leads"
                                            router.push(`${base}/${deal.id}/tracker`)
                                        }}
                                    >
                                        <Clock size={14} />
                                        View History
                                    </Button>
                                    {canViewUserActivity && (
                                        <Button
                                            variant="outlineSuccess"
                                            size="responsiveFooter"
                                            onClick={() => {
                                                // onClose()
                                                const base = deal.isBusinessDeal ? "/sales-deals" : "/leads"
                                                router.push(`${base}/${deal.id}/user-deal-timeline`)
                                            }}
                                        >
                                            <Users size={14} />
                                            User Timeline
                                        </Button>
                                    )}
                                </div>


                                <div className="flex flex-wrap items-stretch justify-end gap-2 sm:items-center sm:gap-3 w-full sm:w-auto">
                                    {canCreateCustomer && deal.stage === "closed_won" && (
                                        <Button
                                            variant={isAlreadyCustomer ? "secondary" : "success"}
                                            size="responsiveFooterWide"
                                            onClick={handleMoveToCustomer}
                                            disabled={isConverting}
                                        >
                                            {isConverting ? <Loader2 className="h-4 w-4 animate-spin" /> : <UserCheck className="h-4 w-4" />}
                                            {isAlreadyCustomer ? "View customer" : "Move to customer"}
                                        </Button>
                                    )}
                                    <Button
                                        variant="ghostMuted"
                                        size="responsiveFooter"
                                        onClick={onClose}
                                    >
                                        Close View
                                    </Button>
                                </div>
                            </div>
                        </>
                    )}
                </DialogContent>

                <DeleteConfirmationAlert
                    open={!!deleteNoteId}
                    onOpenChange={(open) => !open && setDeleteNoteId(null)}
                    onConfirm={async () => {
                        if (!deleteNoteId) return
                        await handleDeleteNote(deleteNoteId)
                    }}
                    title="Delete Note"
                    description="Permanently remove this note and its attachments. This cannot be undone."
                    confirmText="Delete Note"
                    isLoading={isDeletingNote}
                />

                {/* Delete Reminder Confirmation Dialog */}
                <DeleteConfirmationAlert
                    open={!!deleteReminderId}
                    onOpenChange={(open) => !open && setDeleteReminderId(null)}
                    onConfirm={confirmDeleteReminder}
                    title="Delete Reminder"
                    description="Cancel this reminder for all targeted users."
                    confirmText="Remove"
                    isLoading={isDeletingReminder}
                />

                {/* Delete Proposal Confirmation Dialog */}
                <DeleteConfirmationAlert
                    open={!!deleteProposalId}
                    onOpenChange={(open) => !open && setDeleteProposalId(null)}
                    onConfirm={confirmDeleteProposal}
                    title="Remove Document"
                    description="Detach this proposal document from the deal record permanently."
                    confirmText="Remove"
                    isLoading={isDeletingProposal}
                />

                <PdfViewerDialog
                    open={viewerOpen}
                    onOpenChange={setViewerOpen}
                    url={viewerUrl}
                    fileName={viewerFileName}
                    canDownload={true}
                    token={accessToken}
                />
            </Dialog>

            {/* Task dialog must be outside the deal Dialog — nested Radix dialogs break form submit / focus */}
            {isOpen && dealId && !isLoading && deal && (
                <TaskFormModal
                    open={assignTaskOpen}
                    onClose={() => setAssignTaskOpen(false)}
                    dealId={deal.id}
                    assignableUserIds={dealMemberUserIds}
                    title="Assign task"
                    defaultModuleType={deal.isBusinessDeal ? "DEAL" : "LEAD"}
                />
            )}
        </>
    )
}
