"use client"

import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react"
import { ArrowDown, Copy, Flag, ImagePlus, Lock, Pencil, Reply, SendHorizontal, Trash2, X } from "lucide-react"

import AppBarBackButton from "@/components/common/appbar-back-button.component"
import ErrorBox from "@/components/common/error-box.component"
import Loading from "@/components/common/loading.component"
import Link from "@/components/common/versioned-link"
import CoachAvatar from "@/components/catalogue/coach-avatar.component"
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from "@/components/ui/drawer"
import { Button } from "@/components/ui/button"
import { toast } from "@/components/ui/use-toast"

import { CHATS_CHANGED_EVENT } from "@/hooks/use-chat-unread"
import { useNumberQueryParam } from "@/hooks/useNumberQueryParam"
import { ChatHeaderDto, ChatMessageDto, ChatMessagesDto } from "@/lib/dto/chat.dto"
import { chatDayKey, chatDayLabel, chatTime } from "@/lib/helpers/chat.helper"
import { faNumber } from "@/lib/helpers/format.helper"
import { ApiEndpoint } from "@/lib/services/api.service"
import { getApiErrorMessage, useApi } from "@/lib/services/axios.service"
import { cn } from "@/lib/utils"

/** New messages are checked this often while the thread is on screen (and slower in the background). */
const POLL_MS = 4_000
const POLL_HIDDEN_MS = 15_000
/** Every so often the newest page is re-read, so edits, deletions and moderation show up too. */
const FULL_REFRESH_EVERY = 8
const MAX_BODY = 2000

/** The conversation screen: `/chats/view?id=` (technical-plan 4.11). */
export default function ChatThreadView() {
  const id = useNumberQueryParam("id")

  // Hooks live in ChatThread, so none runs after this return (rules of hooks).
  if (!id) return null

  return <ChatThread key={id} id={id} />
}

/** Upsert by id, oldest first. */
function merge(current: ChatMessageDto[], incoming: ChatMessageDto[]): ChatMessageDto[] {
  const byId = new Map(current.map((m) => [m.id, m]))
  incoming.forEach((m) => byId.set(m.id, m))
  return Array.from(byId.values()).sort((a, b) => a.id - b.id)
}

function ChatThread({ id }: { id: number }) {
  const [header, setHeader] = useState<ChatHeaderDto | null>(null)
  const [messages, setMessages] = useState<ChatMessageDto[]>([])
  const [hasMore, setHasMore] = useState(false)
  const [otherRead, setOtherRead] = useState(0)
  const [readOnly, setReadOnly] = useState(false)
  const [loadError, setLoadError] = useState<string | null>(null)
  const [loaded, setLoaded] = useState(false)

  const [body, setBody] = useState("")
  const [image, setImage] = useState<File | null>(null)
  const [preview, setPreview] = useState<string | null>(null)
  const [replyTo, setReplyTo] = useState<ChatMessageDto | null>(null)
  const [editing, setEditing] = useState<ChatMessageDto | null>(null)
  const [sending, setSending] = useState(false)

  const [actionFor, setActionFor] = useState<ChatMessageDto | null>(null)
  const [reportFor, setReportFor] = useState<ChatMessageDto | null>(null)
  const [reportReason, setReportReason] = useState("")
  const [viewing, setViewing] = useState<string | null>(null)
  const [newBelow, setNewBelow] = useState(false)
  const [coursesOpen, setCoursesOpen] = useState(false)

  const listRef = useRef<HTMLDivElement | null>(null)
  const fileRef = useRef<HTMLInputElement | null>(null)
  const inputRef = useRef<HTMLTextAreaElement | null>(null)
  const lastId = useRef(0)
  const pollCount = useRef(0)
  const lastReadSent = useRef(0)

  const [, fetchHeader] = useApi<ChatHeaderDto>({ url: ApiEndpoint("chat", "show", { id }), method: "GET" })
  const [, fetchMessages] = useApi<ChatMessagesDto>({ url: ApiEndpoint("chat", "messages", { id }), method: "GET" })
  const [, postMessage] = useApi<ChatMessageDto>({ url: ApiEndpoint("chat", "messages", { id }), method: "POST" })
  const [, postRead] = useApi({ url: ApiEndpoint("chat", "read", { id }), method: "POST" })
  const [, callMessage] = useApi<ChatMessageDto>({ method: "PATCH" })

  const nearBottom = useCallback(() => {
    const el = listRef.current
    return !el || el.scrollHeight - el.scrollTop - el.clientHeight < 120
  }, [])

  const scrollToBottom = useCallback((smooth = false) => {
    const el = listRef.current
    if (el) el.scrollTo({ top: el.scrollHeight, behavior: smooth ? "smooth" : "auto" })
    setNewBelow(false)
  }, [])

  /** Tell the server what's been read (the coach's ✓✓, the unread badges). */
  const markRead = useCallback((upTo: number) => {
    if (upTo <= lastReadSent.current || document.visibilityState !== "visible") return
    lastReadSent.current = upTo
    postRead({ data: { message_id: upTo } }).then(() => window.dispatchEvent(new CustomEvent(CHATS_CHANGED_EVENT)), () => { lastReadSent.current = 0 })
  }, [postRead])

  const apply = useCallback((data: ChatMessagesDto | undefined, mode: "replace" | "merge") => {
    if (!data) return
    setMessages((current) => (mode === "replace" ? data.messages : merge(current, data.messages)))
    setOtherRead(data.other_last_read_id)
    setReadOnly(data.read_only)
    const newest = data.messages[data.messages.length - 1]
    if (newest && newest.id > lastId.current) lastId.current = newest.id
  }, [])

  // First load: the header and the newest page.
  useEffect(() => {
    Promise.all([fetchHeader(), fetchMessages()]).then(
      ([h, m]) => {
        setHeader(h?.body?.data ?? null)
        const data = m?.body?.data
        apply(data, "replace")
        setHasMore(!!data?.has_more)
        setLoadError(null)
        setLoaded(true)
        requestAnimationFrame(() => scrollToBottom())
        if (lastId.current) markRead(lastId.current)
      },
      (err: unknown) => {
        setLoadError(getApiErrorMessage(err))
        setLoaded(true)
      },
    )
  }, [fetchHeader, fetchMessages, apply, scrollToBottom, markRead])

  // Polling: what's new since the last id; now and then the whole newest page.
  useEffect(() => {
    if (!loaded || loadError) return
    let timer: ReturnType<typeof setTimeout>
    let stopped = false

    const tick = () => {
      pollCount.current += 1
      const full = pollCount.current % FULL_REFRESH_EVERY === 0
      const wasNearBottom = nearBottom()
      fetchMessages({ params: full ? {} : { after: lastId.current } }).then(
        (response) => {
          const data = response?.body?.data
          const before = lastId.current
          apply(data, "merge")
          const fresh = (data?.messages ?? []).filter((m) => m.id > before && !m.mine)
          if (fresh.length) {
            if (wasNearBottom) requestAnimationFrame(() => scrollToBottom(true))
            else setNewBelow(true)
            markRead(lastId.current)
          }
        },
        () => { /* offline for a moment: the next tick tries again */ },
      ).finally(() => {
        if (!stopped) timer = setTimeout(tick, document.visibilityState === "visible" ? POLL_MS : POLL_HIDDEN_MS)
      })
    }

    timer = setTimeout(tick, POLL_MS)
    const onVisible = () => {
      if (document.visibilityState === "visible" && lastId.current) markRead(lastId.current)
    }
    document.addEventListener("visibilitychange", onVisible)
    return () => {
      stopped = true
      clearTimeout(timer)
      document.removeEventListener("visibilitychange", onVisible)
    }
  }, [loaded, loadError, fetchMessages, apply, nearBottom, scrollToBottom, markRead])

  function loadOlder() {
    const el = listRef.current
    const oldest = messages[0]?.id
    if (!oldest) return
    const fromBottom = el ? el.scrollHeight - el.scrollTop : 0
    fetchMessages({ params: { before: oldest } }).then(
      (response) => {
        const data = response?.body?.data
        if (!data) return
        setMessages((current) => merge(current, data.messages))
        setHasMore(data.has_more)
        // Keep what was on screen in place while older messages appear above it.
        requestAnimationFrame(() => {
          if (el) el.scrollTop = el.scrollHeight - fromBottom
        })
      },
      (err: unknown) => toast({ title: "پیام‌های قبلی نیامد", description: getApiErrorMessage(err), variant: "error" }),
    )
  }

  function pickImage(file: File | undefined) {
    if (!file) return
    if (!/^image\/(jpeg|png|webp)$/.test(file.type)) {
      toast({ title: "فقط عکس JPG، PNG یا WebP", variant: "error" })
      return
    }
    if (file.size > 10 * 1024 * 1024) {
      toast({ title: "حجم عکس حداکثر ۱۰ مگابایت است", variant: "error" })
      return
    }
    if (preview) URL.revokeObjectURL(preview)
    setImage(file)
    setPreview(URL.createObjectURL(file))
  }

  function clearImage() {
    if (preview) URL.revokeObjectURL(preview)
    setImage(null)
    setPreview(null)
    if (fileRef.current) fileRef.current.value = ""
  }

  function startEdit(message: ChatMessageDto) {
    setEditing(message)
    setReplyTo(null)
    clearImage()
    setBody(message.body ?? "")
    requestAnimationFrame(() => inputRef.current?.focus())
  }

  function cancelCompose() {
    setEditing(null)
    setReplyTo(null)
    setBody("")
  }

  function send() {
    const text = body.trim()
    if (sending || (!text && !image)) return
    setSending(true)

    const request = editing
      ? callMessage({ url: ApiEndpoint("chat", "message", { id, message: editing.id }), method: "PATCH", data: { body: text } })
      : (() => {
          const form = new FormData()
          if (text) form.append("body", text)
          if (image) form.append("image", image)
          if (replyTo) form.append("reply_to_id", String(replyTo.id))
          return postMessage({ data: form })
        })()

    request.then(
      (response) => {
        const message = response?.body?.data
        if (message) {
          setMessages((current) => merge(current, [message]))
          if (message.id > lastId.current) lastId.current = message.id
          lastReadSent.current = Math.max(lastReadSent.current, message.id)
        }
        setBody("")
        setReplyTo(null)
        setEditing(null)
        clearImage()
        requestAnimationFrame(() => scrollToBottom(true))
        window.dispatchEvent(new CustomEvent(CHATS_CHANGED_EVENT))
      },
      (err: unknown) => toast({ title: editing ? "ویرایش نشد" : "پیام فرستاده نشد", description: getApiErrorMessage(err), variant: "error" }),
    ).finally(() => setSending(false))
  }

  function remove(message: ChatMessageDto) {
    setActionFor(null)
    callMessage({ url: ApiEndpoint("chat", "message", { id, message: message.id }), method: "DELETE" }).then(
      (response) => {
        const updated = response?.body?.data
        if (updated) setMessages((current) => merge(current, [updated]))
      },
      (err: unknown) => toast({ title: "حذف نشد", description: getApiErrorMessage(err), variant: "error" }),
    )
  }

  function report() {
    const target = reportFor
    if (!target || reportReason.trim().length < 3) return
    callMessage({ url: ApiEndpoint("chat", "report", { id, message: target.id }), method: "POST", data: { reason: reportReason.trim() } }).then(
      () => {
        toast({ title: "گزارش ثبت شد", description: "رنگوک آن را بررسی می‌کند.", variant: "success" })
        setReportFor(null)
        setReportReason("")
      },
      (err: unknown) => toast({ title: "گزارش ثبت نشد", description: getApiErrorMessage(err), variant: "error" }),
    )
  }

  async function copy(message: ChatMessageDto) {
    setActionFor(null)
    try {
      await navigator.clipboard.writeText(message.body ?? "")
      toast({ title: "کپی شد", variant: "success" })
    } catch {
      toast({ title: "کپی انجام نشد", variant: "error" })
    }
  }

  const courses = header?.courses ?? []
  const shownCourses = courses.slice(0, 2)
  const moreCourses = courses.length - shownCourses.length
  const canWrite = !readOnly && !header?.locked
  const canSend = (body.trim().length > 0 || !!image) && !sending

  // Day separators between messages of different days.
  const rows = useMemo(() => messages.map((m, i) => ({
    message: m,
    day: i === 0 || chatDayKey(messages[i - 1].created_at) !== chatDayKey(m.created_at) ? chatDayLabel(m.created_at) : null,
  })), [messages])

  return (
    <div className="relative flex flex-col flex-1 min-h-0 bg-background">
      {/* Header: back, the coach, their courses you have. */}
      <header className="sticky top-0 z-40 bg-canvas border-b border-line">
        <div className="flex items-center gap-2 h-14 px-2">
          <AppBarBackButton />
          {header && (
            <Link href={header.coach.slug ? `/coach/view?slug=${encodeURIComponent(header.coach.slug)}` : "#"} className="flex items-center gap-2.5 min-w-0 flex-1">
              <CoachAvatar src={header.coach.avatar} name={header.coach.name} className="w-9 h-9 text-body" />
              <span className="min-w-0">
                <span className="block font-bold text-body truncate">{header.coach.name ?? "مربی"}</span>
                <span className="block text-micro text-ink-soft truncate">مربی</span>
              </span>
            </Link>
          )}
        </div>
        {courses.length > 0 && (
          <div className="flex items-center gap-1.5 px-4 pb-2 overflow-hidden">
            {shownCourses.map((c) => (
              <Link key={c.id} href={`/course/detail?id=${c.id}`} className="max-w-[45%] truncate text-micro font-semibold px-2.5 py-1 rounded-full bg-sienna-soft text-sienna-dark">
                {c.title}
              </Link>
            ))}
            {moreCourses > 0 && (
              <button type="button" onClick={() => setCoursesOpen(true)} className="shrink-0 text-micro font-semibold px-2.5 py-1 rounded-full bg-paper-2 text-ink-soft">
                +{faNumber(moreCourses)} دوره‌ی دیگر
              </button>
            )}
          </div>
        )}
      </header>

      <Loading loading={!loaded}>
        <ErrorBox active={!!loadError} title="گفتگو باز نشد" description={loadError} showRetry onRetry={() => window.location.reload()}>
          <div ref={listRef} className="relative flex-1 min-h-0 overflow-y-auto px-3 py-3 flex flex-col gap-1.5" aria-live="polite">
            {hasMore && (
              <button type="button" onClick={loadOlder} className="self-center my-1 text-micro font-semibold px-3 py-1.5 rounded-full border border-line bg-canvas text-ink-soft">
                پیام‌های قبلی
              </button>
            )}

            {messages.length === 0 && (
              <div className="m-auto text-center px-8 py-10">
                <p className="font-bold text-body">سؤالت را از {header?.coach.name ?? "مربی"} بپرس</p>
                <p className="text-body-sm text-ink-soft mt-1">مثلاً درباره‌ی یکی از جلسه‌ها، یا عکسی از کارت بفرست و نظرش را بپرس.</p>
              </div>
            )}

            {rows.map(({ message: m, day }) => (
              <Fragment key={m.id}>
                {day && (
                  <div className="self-center my-2 text-micro px-3 py-0.5 rounded-full bg-paper-2 text-ink-soft">{day}</div>
                )}
                <Bubble
                  message={m}
                  read={m.mine && m.id <= otherRead}
                  onOpen={() => m.state === "normal" && setActionFor(m)}
                  onImage={setViewing}
                />
              </Fragment>
            ))}
          </div>

          {newBelow && (
            <button type="button" onClick={() => scrollToBottom(true)}
                    className="absolute bottom-24 left-1/2 -translate-x-1/2 z-30 flex items-center gap-1 text-micro font-bold px-3 py-1.5 rounded-full bg-sienna text-canvas shadow-raised">
              <ArrowDown className="w-3.5 h-3.5" aria-hidden="true" />
              پیام تازه
            </button>
          )}

          {/* Composer, or why you can't write. */}
          {header && !canWrite ? (
            <div className="border-t border-line bg-canvas px-4 py-3 pb-[max(12px,env(safe-area-inset-bottom))] flex items-center gap-2 text-body-sm text-ink-soft">
              <Lock className="w-4 h-4 shrink-0" aria-hidden="true" />
              {header.locked ? "رنگوک این گفتگو را بسته است." : "این گفتگو فقط خواندنی است؛ دوره‌ای از این مربی نداری."}
            </div>
          ) : (
            <div className="border-t border-line bg-canvas px-3 pt-2 pb-[max(8px,env(safe-area-inset-bottom))]">
              {(replyTo || editing) && (
                <div className="flex items-center gap-2 mb-2 px-3 py-1.5 rounded-xl bg-paper-2 border-r-4 border-sienna">
                  {editing ? <Pencil className="w-4 h-4 text-sienna shrink-0" /> : <Reply className="w-4 h-4 text-sienna shrink-0" />}
                  <span className="flex-1 min-w-0 text-micro">
                    <b className="block">{editing ? "ویرایش پیام" : `پاسخ به ${replyTo?.sender_name}`}</b>
                    <span className="block truncate text-ink-soft">{(editing ?? replyTo)?.body ?? "تصویر"}</span>
                  </span>
                  <button type="button" onClick={cancelCompose} aria-label="لغو" className="p-1"><X className="w-4 h-4" /></button>
                </div>
              )}
              {preview && (
                <div className="relative inline-block mb-2">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img src={preview} alt="عکس انتخاب‌شده" className="h-20 rounded-xl object-cover border border-line" />
                  <button type="button" onClick={clearImage} aria-label="حذف عکس" className="absolute -top-2 -left-2 w-6 h-6 rounded-full bg-ink text-canvas grid place-items-center">
                    <X className="w-3.5 h-3.5" />
                  </button>
                </div>
              )}
              <div className="flex items-end gap-2">
                {!editing && (
                  <>
                    <button type="button" onClick={() => fileRef.current?.click()} aria-label="افزودن عکس"
                            className="w-11 h-11 shrink-0 rounded-2xl grid place-items-center text-ink-soft hover:bg-paper-2">
                      <ImagePlus className="w-5 h-5" />
                    </button>
                    <input ref={fileRef} type="file" accept="image/jpeg,image/png,image/webp" hidden onChange={(e) => pickImage(e.target.files?.[0])} />
                  </>
                )}
                <textarea
                  ref={inputRef}
                  value={body}
                  onChange={(e) => setBody(e.target.value.slice(0, MAX_BODY))}
                  rows={1}
                  placeholder="پیام…"
                  aria-label="متن پیام"
                  className="flex-1 min-h-11 max-h-32 resize-none rounded-2xl border border-line bg-background px-3.5 py-2.5 text-body leading-6 outline-none focus:border-sienna [field-sizing:content]"
                />
                <button type="button" onClick={send} disabled={!canSend} aria-label={editing ? "ذخیره‌ی ویرایش" : "ارسال"}
                        className="w-11 h-11 shrink-0 rounded-2xl grid place-items-center bg-sienna text-canvas disabled:opacity-40 transition-opacity">
                  <SendHorizontal className="w-5 h-5 -scale-x-100" />
                </button>
              </div>
            </div>
          )}
        </ErrorBox>
      </Loading>

      {/* A message's actions. */}
      <Drawer open={!!actionFor} onOpenChange={(open) => !open && setActionFor(null)}>
        <DrawerContent className="mx-auto w-full max-w-[480px]">
          <DrawerHeader className="text-right">
            <DrawerTitle className="text-body font-bold truncate">{actionFor?.body ?? "تصویر"}</DrawerTitle>
            <DrawerDescription className="sr-only">کارهای این پیام</DrawerDescription>
          </DrawerHeader>
          <div className="px-2 pb-[max(16px,env(safe-area-inset-bottom))] flex flex-col">
            {actionFor && canWrite && (
              <SheetButton icon={<Reply className="w-5 h-5" />} label="پاسخ" onClick={() => { setReplyTo(actionFor); setEditing(null); setActionFor(null); requestAnimationFrame(() => inputRef.current?.focus()) }} />
            )}
            {actionFor?.body && <SheetButton icon={<Copy className="w-5 h-5" />} label="کپی متن" onClick={() => copy(actionFor)} />}
            {actionFor?.editable && actionFor.body && (
              <SheetButton icon={<Pencil className="w-5 h-5" />} label="ویرایش" onClick={() => { const m = actionFor; setActionFor(null); startEdit(m) }} />
            )}
            {actionFor?.editable && (
              <SheetButton icon={<Trash2 className="w-5 h-5" />} label="حذف" danger onClick={() => remove(actionFor)} />
            )}
            {actionFor && !actionFor.mine && (
              <SheetButton icon={<Flag className="w-5 h-5" />} label="گزارش به رنگوک" danger onClick={() => { setReportFor(actionFor); setActionFor(null) }} />
            )}
          </div>
        </DrawerContent>
      </Drawer>

      {/* Report a message. */}
      <Drawer open={!!reportFor} onOpenChange={(open) => !open && setReportFor(null)}>
        <DrawerContent className="mx-auto w-full max-w-[480px]">
          <DrawerHeader className="text-right">
            <DrawerTitle className="text-title-3 font-extrabold">گزارش پیام</DrawerTitle>
            <DrawerDescription>رنگوک گزارش را می‌خواند؛ مربی نمی‌فهمد چه کسی گزارش داده است.</DrawerDescription>
          </DrawerHeader>
          <div className="px-4 pb-[max(16px,env(safe-area-inset-bottom))] flex flex-col gap-3">
            <textarea value={reportReason} onChange={(e) => setReportReason(e.target.value.slice(0, 500))} rows={3}
                      placeholder="چه مشکلی دارد؟" aria-label="دلیل گزارش"
                      className="rounded-2xl border border-line bg-background px-3.5 py-2.5 text-body outline-none focus:border-sienna" />
            <Button size="lg" className="h-12 rounded-2xl" disabled={reportReason.trim().length < 3} onClick={report}>ثبت گزارش</Button>
          </div>
        </DrawerContent>
      </Drawer>

      {/* All the courses you have from this coach. */}
      <Drawer open={coursesOpen} onOpenChange={setCoursesOpen}>
        <DrawerContent className="mx-auto w-full max-w-[480px]">
          <DrawerHeader className="text-right">
            <DrawerTitle className="text-title-3 font-extrabold">{faNumber(courses.length)} دوره از {header?.coach.name ?? "این مربی"}</DrawerTitle>
            <DrawerDescription className="sr-only">دوره‌هایی که از این مربی داری</DrawerDescription>
          </DrawerHeader>
          <div className="px-2 pb-[max(16px,env(safe-area-inset-bottom))] flex flex-col max-h-[50vh] overflow-y-auto">
            {courses.map((c) => (
              <Link key={c.id} href={`/course/detail?id=${c.id}`} className="px-3 py-3 rounded-xl text-body hover:bg-paper-2">{c.title}</Link>
            ))}
          </div>
        </DrawerContent>
      </Drawer>

      {/* An image, large. */}
      <Dialog open={!!viewing} onOpenChange={(open) => !open && setViewing(null)}>
        <DialogContent className="p-2 max-w-[440px]">
          <DialogTitle className="sr-only">تصویر پیام</DialogTitle>
          {/* eslint-disable-next-line @next/next/no-img-element */}
          {viewing && <img src={viewing} alt="تصویر پیام" className="w-full max-h-[75vh] object-contain rounded-xl" />}
        </DialogContent>
      </Dialog>
    </div>
  )
}

function SheetButton({ icon, label, onClick, danger }: { icon: React.ReactNode; label: string; onClick: () => void; danger?: boolean }) {
  return (
    <button type="button" onClick={onClick} className={cn("flex items-center gap-3 h-12 px-3 rounded-xl text-body font-semibold hover:bg-paper-2", danger && "text-rose")}>
      {icon}
      {label}
    </button>
  )
}

function Bubble({ message: m, read, onOpen, onImage }: { message: ChatMessageDto; read: boolean; onOpen: () => void; onImage: (url: string) => void }) {
  const admin = m.role === "admin"
  const gone = m.state !== "normal"

  return (
    <div className={cn("flex", admin ? "justify-center" : m.mine ? "justify-start" : "justify-end")}>
      <div
        role="button"
        tabIndex={0}
        onClick={onOpen}
        onKeyDown={(e) => (e.key === "Enter" || e.key === " ") && onOpen()}
        className={cn(
          "max-w-[80%] rounded-2xl px-3 py-2 text-right shadow-card outline-none focus-visible:ring-2 focus-visible:ring-ultra",
          admin && "max-w-[90%] bg-ochre-soft border border-ochre/40",
          !admin && m.mine && "bg-sienna-soft rounded-tr-md",
          !admin && !m.mine && "bg-canvas border border-line rounded-tl-md",
          gone && "opacity-70",
        )}
      >
        {admin && <span className="block text-micro font-bold text-ochre-ink mb-0.5">رنگوک</span>}

        {m.reply_to && !gone && (
          <span className="block mb-1 px-2 py-1 rounded-lg bg-ink/5 border-r-2 border-sienna text-micro">
            <b className="block">{m.reply_to.sender_name}</b>
            <span className="block truncate text-ink-soft">{m.reply_to.preview}</span>
          </span>
        )}

        {gone ? (
          <span className="block text-body-sm italic text-ink-soft">{m.placeholder}</span>
        ) : (
          <>
            {m.image && (
              <button type="button" onClick={(e) => { e.stopPropagation(); onImage(m.image!) }} className="block mb-1">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={m.image} alt="تصویر پیام" loading="lazy" className="max-h-64 rounded-xl object-cover" />
              </button>
            )}
            {m.body && <span className="block text-body leading-7 whitespace-pre-wrap break-words">{m.body}</span>}
          </>
        )}

        <span className="flex items-center justify-end gap-1 mt-0.5 text-micro text-ink-soft">
          {m.edited && !gone && <span>ویرایش‌شده</span>}
          <span className="tabular-nums">{chatTime(m.created_at)}</span>
          {m.mine && !admin && (
            <span className={cn("tracking-[-0.2em]", read ? "text-sienna" : "")} aria-label={read ? "خوانده شد" : "فرستاده شد"}>
              {read ? "✓✓" : "✓"}
            </span>
          )}
        </span>
      </div>
    </div>
  )
}
