"use client";
import { useState, useRef, useEffect, useCallback } from "react";
import { useAppSelector } from "@/store/hooks";
import { useFormatPrice } from "@/hooks/useFormatPrice";
import { motion, AnimatePresence } from "framer-motion";
import {
  ArrowLeft,
  Phone,
  MoreVertical,
  Send,
  Tag,
  ShieldAlert,
  Ban,
  CheckCheck,
  Check,
  MapPin,
  Clock,
  ExternalLink,
  X,
  ChevronRight,
} from "lucide-react";
import { useMessaging } from "@/lib/MessagingContext";
import type { Message, Conversation } from "./types";
import Link from "next/link";

// ─── Helpers ─────────────────────────────────────────────────────────────────

function formatMsgTime(iso: string) {
  return new Date(iso).toLocaleTimeString("en-IN", {
    hour: "2-digit",
    minute: "2-digit",
    hour12: true,
  });
}


function formatDate(iso: string) {
  const d = new Date(iso);
  const today = new Date("2026-06-26");
  const yesterday = new Date("2026-06-25");
  if (d.toDateString() === today.toDateString()) return "Today";
  if (d.toDateString() === yesterday.toDateString()) return "Yesterday";
  return d.toLocaleDateString("en-IN", {
    day: "numeric",
    month: "long",
    year: "numeric",
  });
}

function getDateLabel(msgs: Message[], idx: number) {
  if (idx === 0) return formatDate(msgs[idx].timestamp);
  const prev = new Date(msgs[idx - 1].timestamp).toDateString();
  const cur = new Date(msgs[idx].timestamp).toDateString();
  if (prev !== cur) return formatDate(msgs[idx].timestamp);
  return null;
}

// ─── Offer Card ──────────────────────────────────────────────────────────────

function OfferCard({
  msg,
  conv,
  isMe,
}: {
  msg: Message;
  conv: Conversation;
  isMe: boolean;
}) {
  const { respondToOffer } = useMessaging();
  const formatPrice = useFormatPrice();
  const offer = msg.offer!;
  const discount = Math.round(
    ((offer.originalPrice - offer.amount) / offer.originalPrice) * 100,
  );
  const canRespond =
    !isMe && offer.status === "pending" && conv.myRole === "seller";

  const statusUI = {
    pending: {
      label: "Pending",
      bg: "bg-yellow-500/15",
      text: "text-yellow-400",
    },
    accepted: {
      label: "Accepted ✓",
      bg: "bg-green-500/15",
      text: "text-green-400",
    },
    rejected: { label: "Declined", bg: "bg-red-500/15", text: "text-red-400" },
    countered: {
      label: "Countered",
      bg: "bg-blue-500/15",
      text: "text-blue-400",
    },
  }[offer.status];

  return (
    <div
      className="rounded-2xl overflow-hidden border border-[var(--border)] min-w-[240px] max-w-[280px]"
      style={{ background: "var(--card)" }}
    >
      <div className="px-4 py-3 border-b border-[var(--border)]">
        <div className="flex items-center gap-2 mb-1">
          <Tag size={13} className="text-[var(--accent)]" />
          <span className="text-xs font-semibold text-[var(--accent)]">
            Price Offer
          </span>
        </div>
        <div className="text-xl font-bold text-[var(--text-primary)]">
          {formatPrice(offer.amount)}
        </div>
        <div className="flex items-center gap-2 mt-0.5">
          <span className="text-xs text-[var(--text-muted)] line-through">
            {formatPrice(offer.originalPrice)}
          </span>
          <span className="text-xs text-green-400 font-medium">
            -{discount}%
          </span>
        </div>
        {offer.message && (
          <p className="text-xs text-[var(--text-muted)] mt-2 italic">
            "{offer.message}"
          </p>
        )}
      </div>
      <div className="px-4 py-2 flex items-center justify-between">
        <span
          className={`text-xs font-semibold px-2 py-0.5 rounded-full ${statusUI.bg} ${statusUI.text}`}
        >
          {statusUI.label}
        </span>
        {canRespond && (
          <div className="flex gap-2">
            <button
              onClick={() => respondToOffer(conv.id, msg.id, "rejected")}
              className="text-xs px-3 py-1 rounded-full border border-red-500/40 text-red-400 hover:bg-red-500/10 transition-colors"
            >
              Decline
            </button>
            <button
              onClick={() => respondToOffer(conv.id, msg.id, "accepted")}
              className="text-xs px-3 py-1 rounded-full bg-[var(--accent)] text-white font-medium hover:opacity-90 transition-opacity"
            >
              Accept
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Typing Indicator ─────────────────────────────────────────────────────────

function TypingIndicator({ name }: { name: string }) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: 10 }}
      className="flex items-end gap-2 px-4 py-1"
    >
      <div
        className="flex items-center gap-1 px-4 py-3 rounded-2xl rounded-bl-sm"
        style={{ background: "var(--card)" }}
      >
        {[0, 1, 2].map((i) => (
          <motion.span
            key={i}
            className="w-1.5 h-1.5 rounded-full bg-[var(--text-muted)]"
            animate={{ y: [0, -4, 0] }}
            transition={{ duration: 0.8, repeat: Infinity, delay: i * 0.15 }}
          />
        ))}
      </div>
      <span className="text-[10px] text-[var(--text-muted)] mb-1">
        {name} is typing…
      </span>
    </motion.div>
  );
}

// ─── Make Offer Modal ─────────────────────────────────────────────────────────

function OfferModal({
  conv,
  onClose,
}: {
  conv: Conversation;
  onClose: () => void;
}) {
  const { sendMessage } = useMessaging();
  const formatPrice = useFormatPrice();
  const currencyCode = useAppSelector((s) => s.generalSetting.currencyCode);
  const [amount, setAmount] = useState(
    String(Math.round(conv.listingPrice * 0.9)),
  );
  const [note, setNote] = useState("");

  const submit = () => {
    const parsed = parseInt(amount.replace(/\D/g, ""), 10);
    if (!parsed || parsed <= 0) return;
    sendMessage(
      conv.id,
      `I'd like to offer ${formatPrice(parsed)} for ${conv.listingTitle}`,
      "offer",
      parsed,
    );
    onClose();
  };

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 z-[60] flex items-end sm:items-center justify-center p-0 sm:p-4"
      style={{ background: "rgba(0,0,0,0.6)" }}
      onClick={onClose}
    >
      <motion.div
        initial={{ y: "100%" }}
        animate={{ y: 0 }}
        exit={{ y: "100%" }}
        transition={{ type: "spring", stiffness: 300, damping: 30 }}
        className="w-full sm:max-w-md rounded-t-3xl sm:rounded-2xl overflow-hidden"
        style={{ background: "var(--card)" }}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between px-5 pt-5 pb-3 border-b border-[var(--border)]">
          <h3 className="font-bold text-[var(--text-primary)]">
            Make an Offer
          </h3>
          <button
            onClick={onClose}
            className="p-1 rounded-full hover:bg-[var(--bg)]"
          >
            <X size={16} className="text-[var(--text-muted)]" />
          </button>
        </div>

        <div className="p-5 space-y-4">
          {/* Product summary */}
          <div
            className="flex items-center gap-3 p-3 rounded-xl"
            style={{ background: "var(--bg)" }}
          >
            <img
              src={conv.listingImage}
              alt=""
              className="w-12 h-12 rounded-xl object-cover"
            />
            <div>
              <p className="text-sm font-medium text-[var(--text-primary)] line-clamp-1">
                {conv.listingTitle}
              </p>
              <p className="text-xs text-[var(--text-muted)]">
                Listed at {formatPrice(conv.listingPrice)}
              </p>
            </div>
          </div>

          {/* Amount input */}
          <div>
            <label className="text-xs text-[var(--text-muted)] font-medium mb-1.5 block">
              Your Offer ({currencyCode})
            </label>
            <div
              className="flex items-center rounded-xl px-4 py-3 gap-2"
              style={{
                background: "var(--bg)",
                border: "1.5px solid var(--accent)",
              }}
            >
              <span className="text-lg font-bold text-[var(--accent)]">{currencyCode}</span>
              <input
                value={amount}
                onChange={(e) => setAmount(e.target.value.replace(/\D/g, ""))}
                className="flex-1 bg-transparent outline-none text-xl font-bold text-[var(--text-primary)]"
                placeholder="0"
                inputMode="numeric"
              />
            </div>
            {parseInt(amount) > 0 && (
              <p className="text-xs text-[var(--text-muted)] mt-1">
                {Math.round(
                  ((conv.listingPrice - parseInt(amount)) / conv.listingPrice) *
                  100,
                )}
                % below asking price
              </p>
            )}
          </div>

          {/* Note */}
          <div>
            <label className="text-xs text-[var(--text-muted)] font-medium mb-1.5 block">
              Note to seller (optional)
            </label>
            <textarea
              value={note}
              onChange={(e) => setNote(e.target.value)}
              rows={2}
              placeholder="E.g. I can pick up today…"
              className="w-full rounded-xl px-4 py-3 text-sm outline-none resize-none text-[var(--text-primary)] placeholder:text-[var(--text-muted)]"
              style={{
                background: "var(--bg)",
                border: "1px solid var(--border)",
              }}
            />
          </div>

          <motion.button
            whileTap={{ scale: 0.97 }}
            onClick={submit}
            className="w-full py-3 rounded-xl text-white font-semibold text-sm"
            style={{ background: "var(--accent)" }}
          >
            Send Offer
          </motion.button>
        </div>
      </motion.div>
    </motion.div>
  );
}

// ─── Report Modal ─────────────────────────────────────────────────────────────

const REPORT_REASONS = [
  "Fake listing / scam",
  "Wrong price listed",
  "Abusive or harassing messages",
  "Spam",
  "Prohibited item",
  "Other",
];

function ReportModal({
  conv,
  onClose,
}: {
  conv: Conversation;
  onClose: () => void;
}) {
  const [selected, setSelected] = useState("");
  const [submitted, setSubmitted] = useState(false);

  const submit = () => {
    if (!selected) return;
    setSubmitted(true);
    setTimeout(onClose, 1500);
  };

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 z-50 flex items-end sm:items-center justify-center sm:p-4"
      style={{ background: "rgba(0,0,0,0.6)" }}
      onClick={onClose}
    >
      <motion.div
        initial={{ y: "100%" }}
        animate={{ y: 0 }}
        exit={{ y: "100%" }}
        transition={{ type: "spring", stiffness: 300, damping: 30 }}
        className="w-full sm:max-w-sm rounded-t-3xl sm:rounded-2xl overflow-hidden"
        style={{ background: "var(--card)" }}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between px-5 pt-5 pb-3 border-b border-[var(--border)]">
          <h3 className="font-bold text-[var(--text-primary)] flex items-center gap-2">
            <ShieldAlert size={16} className="text-red-400" /> Report User
          </h3>
          <button
            onClick={onClose}
            className="p-1 rounded-full hover:bg-[var(--bg)]"
          >
            <X size={16} className="text-[var(--text-muted)]" />
          </button>
        </div>

        {submitted ? (
          <div className="flex flex-col items-center py-10 gap-2">
            <span className="text-4xl">✅</span>
            <p className="font-semibold text-[var(--text-primary)]">
              Report Submitted
            </p>
            <p className="text-xs text-[var(--text-muted)]">
              We'll review it within 24 hours.
            </p>
          </div>
        ) : (
          <div className="p-4 space-y-2">
            <p className="text-xs text-[var(--text-muted)] mb-3">
              Why are you reporting {conv.otherUserName}?
            </p>
            {REPORT_REASONS.map((r) => (
              <button
                key={r}
                onClick={() => setSelected(r)}
                className="w-full flex items-center justify-between px-4 py-3 rounded-xl text-sm text-left transition-colors"
                style={{
                  background: selected === r ? "var(--accent)15" : "var(--bg)",
                  border: `1px solid ${selected === r ? "var(--accent)" : "var(--border)"}`,
                  color:
                    selected === r ? "var(--accent)" : "var(--text-primary)",
                }}
              >
                {r}
                {selected === r && <Check size={14} />}
              </button>
            ))}
            <motion.button
              whileTap={{ scale: 0.97 }}
              onClick={submit}
              disabled={!selected}
              className="w-full mt-2 py-3 rounded-xl text-white font-semibold text-sm disabled:opacity-40"
              style={{ background: "#ef4444" }}
            >
              Submit Report
            </motion.button>
          </div>
        )}
      </motion.div>
    </motion.div>
  );
}

// ─── Main ChatWindow ──────────────────────────────────────────────────────────

interface Props {
  onBack?: () => void;
}

export function ChatWindow({ onBack }: Props) {
  const {
    conversations,
    selectedConversationId,
    typingConversationId,
    sendMessage,
    blockUser,
  } = useMessaging();
  const conv = conversations.find((c) => c.id === selectedConversationId);

  const formatPrice = useFormatPrice();
  const [text, setText] = useState("");
  const [showOffer, setShowOffer] = useState(false);
  const [showReport, setShowReport] = useState(false);
  const [showMenu, setShowMenu] = useState(false);
  const [showBlockConfirm, setShowBlockConfirm] = useState(false);
  const bottomRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [conv?.messages.length, typingConversationId]);

  const handleSend = useCallback(() => {
    if (!conv || !text.trim()) return;
    sendMessage(conv.id, text.trim());
    setText("");
  }, [conv, text, sendMessage]);

  const handleKey = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  if (!conv) {
    return (
      <div className="flex flex-col items-center justify-center h-full gap-4 text-center px-8">
        <div className="text-6xl">💬</div>
        <h3 className="text-xl font-bold text-[var(--text-primary)]">
          Your Messages
        </h3>
        <p className="text-sm text-[var(--text-muted)] max-w-xs">
          Select a conversation to start chatting with buyers and sellers.
        </p>
      </div>
    );
  }

  const isTypingHere = typingConversationId === conv.id;

  return (
    <div className="flex flex-col h-full" style={{ background: "var(--bg)" }}>
      {/* ── Header ── */}
      <div
        className="flex items-center gap-3 px-4 py-3 border-b border-[var(--border)] shrink-0"
        style={{ background: "var(--card)" }}
      >
        {onBack && (
          <button
            onClick={onBack}
            className="p-1.5 rounded-full hover:bg-[var(--bg)]"
          >
            <ArrowLeft size={18} className="text-[var(--text-primary)]" />
          </button>
        )}

        {/* Avatar + status */}
        <div className="relative shrink-0">
          <img
            src={conv.otherUserAvatar}
            alt={conv.otherUserName}
            className="w-10 h-10 rounded-full object-cover"
          />
          {conv.otherUserIsOnline && (
            <span className="absolute bottom-0 right-0 w-2.5 h-2.5 rounded-full bg-green-500 border-2 border-[var(--card)]" />
          )}
        </div>

        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-1.5">
            <span className="font-semibold text-sm text-[var(--text-primary)] truncate">
              {conv.otherUserName}
            </span>
            {conv.otherUserVerified && (
              <span className="text-[9px] bg-[var(--accent)]/15 text-[var(--accent)] px-1 rounded font-medium">
                ✓
              </span>
            )}
          </div>
          <p className="text-[10px] text-[var(--text-muted)]">
            {isTypingHere
              ? "typing…"
              : conv.otherUserIsOnline
                ? "Online"
                : conv.otherUserLastSeen
                  ? `Last seen ${new Date(conv.otherUserLastSeen).toLocaleTimeString("en-IN", { hour: "2-digit", minute: "2-digit", hour12: true })}`
                  : "Offline"}
          </p>
        </div>

        <div className="flex items-center gap-1">
          <button className="p-2 rounded-full hover:bg-[var(--bg)]">
            <Phone size={16} className="text-[var(--text-muted)]" />
          </button>
          <div className="relative">
            <button
              onClick={() => setShowMenu(!showMenu)}
              className="p-2 rounded-full hover:bg-[var(--bg)]"
            >
              <MoreVertical size={16} className="text-[var(--text-muted)]" />
            </button>
            <AnimatePresence>
              {showMenu && (
                <motion.div
                  initial={{ opacity: 0, scale: 0.9, y: -4 }}
                  animate={{ opacity: 1, scale: 1, y: 0 }}
                  exit={{ opacity: 0, scale: 0.9, y: -4 }}
                  transition={{ duration: 0.12 }}
                  className="absolute right-0 top-10 z-30 rounded-xl overflow-hidden shadow-xl border border-[var(--border)] min-w-[180px]"
                  style={{ background: "var(--card)" }}
                >
                  <button
                    className="w-full flex items-center gap-2 px-4 py-2.5 text-sm text-[var(--text-primary)] hover:bg-[var(--bg)]"
                    onClick={() => {
                      setShowReport(true);
                      setShowMenu(false);
                    }}
                  >
                    <ShieldAlert size={14} className="text-red-400" /> Report
                    User
                  </button>
                  <button
                    className="w-full flex items-center gap-2 px-4 py-2.5 text-sm text-red-400 hover:bg-red-500/10"
                    onClick={() => {
                      setShowBlockConfirm(true);
                      setShowMenu(false);
                    }}
                  >
                    <Ban size={14} /> {conv.isBlocked ? "Unblock" : "Block"}{" "}
                    User
                  </button>
                </motion.div>
              )}
            </AnimatePresence>
          </div>
        </div>
      </div>

      {/* ── Product Card ── */}
      <div
        className="flex items-center gap-3 px-4 py-3 border-b border-[var(--border)] shrink-0"
        style={{ background: "var(--deep)" }}
      >
        <img
          src={conv.listingImage}
          alt=""
          className="w-12 h-12 rounded-xl object-cover shrink-0"
        />
        <div className="flex-1 min-w-0">
          <p className="text-sm font-semibold text-[var(--text-primary)] truncate">
            {conv.listingTitle}
          </p>
          <div className="flex items-center gap-3 mt-0.5">
            <span className="text-sm font-bold text-[var(--accent)]">
              {formatPrice(conv.listingPrice)}
            </span>
            <span className="text-[10px] text-[var(--text-muted)] flex items-center gap-1">
              <MapPin size={9} /> {conv.listingCity}
            </span>
            <span
              className={`text-[9px] px-1.5 py-0.5 rounded-full border font-medium ${conv.listingStatus === "sold"
                ? "bg-red-500/15 text-red-400 border-red-500/30"
                : conv.listingStatus === "reserved"
                  ? "bg-yellow-500/15 text-yellow-400 border-yellow-500/30"
                  : "bg-green-500/15 text-green-400 border-green-500/30"
                }`}
            >
              {conv.listingStatus}
            </span>
          </div>
        </div>
        <Link
          href={`/marketplace/listing/${conv.listingSlug}`}
          className="p-2 rounded-full hover:bg-[var(--card)] transition-colors"
        >
          <ExternalLink size={14} className="text-[var(--text-muted)]" />
        </Link>
      </div>

      {/* ── Messages ── */}
      <div className="flex-1 overflow-y-auto px-4 py-4 space-y-1">
        {conv.messages.map((msg, idx) => {
          const dateLabel = getDateLabel(conv.messages, idx);
          const isMe = msg.senderId === "me";
          const isSystem = msg.senderId === "system";

          return (
            <div key={msg.id}>
              {dateLabel && (
                <div className="flex items-center gap-3 my-4">
                  <div
                    className="flex-1 h-px"
                    style={{ background: "var(--border)" }}
                  />
                  <span className="text-[10px] text-[var(--text-muted)] px-2">
                    {dateLabel}
                  </span>
                  <div
                    className="flex-1 h-px"
                    style={{ background: "var(--border)" }}
                  />
                </div>
              )}

              {isSystem ? (
                <div className="flex justify-center my-3">
                  <span
                    className="text-[10px] px-4 py-1.5 rounded-full border border-[var(--border)] text-[var(--text-muted)] flex items-center gap-1.5"
                    style={{ background: "var(--card)" }}
                  >
                    <Clock size={9} />
                    {msg.content}
                  </span>
                </div>
              ) : (
                <motion.div
                  initial={{ opacity: 0, y: 6 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.2 }}
                  className={`flex ${isMe ? "justify-end" : "justify-start"} mb-1`}
                >
                  {/* Avatar for other user */}
                  {!isMe && (
                    <img
                      src={conv.otherUserAvatar}
                      alt=""
                      className="w-6 h-6 rounded-full object-cover shrink-0 mr-2 mt-auto mb-1"
                    />
                  )}

                  <div
                    className={`flex flex-col ${isMe ? "items-end" : "items-start"} max-w-[75%]`}
                  >
                    {msg.type === "offer" ? (
                      <OfferCard msg={msg} conv={conv} isMe={isMe} />
                    ) : (
                      <div
                        className="px-4 py-2.5 rounded-2xl text-sm"
                        style={{
                          background: isMe ? "var(--accent)" : "var(--card)",
                          color: isMe ? "#fff" : "var(--text-primary)",
                          borderRadius: isMe
                            ? "18px 18px 4px 18px"
                            : "18px 18px 18px 4px",
                        }}
                      >
                        {msg.content}
                      </div>
                    )}

                    {/* Time + read receipt */}
                    <div className="flex items-center gap-1 mt-0.5 px-1">
                      <span className="text-[9px] text-[var(--text-muted)]">
                        {formatMsgTime(msg.timestamp)}
                      </span>
                      {isMe &&
                        (msg.readAt ? (
                          <CheckCheck
                            size={11}
                            className="text-[var(--accent)]"
                          />
                        ) : (
                          <Check
                            size={11}
                            className="text-[var(--text-muted)]"
                          />
                        ))}
                    </div>
                  </div>
                </motion.div>
              )}
            </div>
          );
        })}

        {/* Typing indicator */}
        <AnimatePresence>
          {isTypingHere && <TypingIndicator name={conv.otherUserName} />}
        </AnimatePresence>

        <div ref={bottomRef} />
      </div>

      {/* ── Composer ── */}
      {conv.isBlocked ? (
        <div className="px-4 py-4 border-t border-[var(--border)] text-center">
          <p className="text-sm text-[var(--text-muted)]">
            You've blocked this user.{" "}
            <button
              onClick={() => blockUser(conv.id)}
              className="text-[var(--accent)] underline"
            >
              Unblock
            </button>
          </p>
        </div>
      ) : conv.listingStatus === "sold" ? (
        <div className="px-4 py-4 border-t border-[var(--border)] text-center">
          <p className="text-sm text-[var(--text-muted)]">
            This item has been sold. Messaging is disabled.
          </p>
        </div>
      ) : (
        <div
          className="flex items-end gap-2 px-3 py-3 border-t border-[var(--border)] shrink-0"
          style={{ background: "var(--card)" }}
        >
          {/* Make offer button */}
          {conv.myRole === "buyer" && conv.listingStatus === "available" && (
            <motion.button
              whileTap={{ scale: 0.92 }}
              onClick={() => setShowOffer(true)}
              className="flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold shrink-0 transition-colors"
              style={{
                background: "var(--accent)20",
                color: "var(--accent)",
                border: "1px solid var(--accent)40",
              }}
            >
              <Tag size={12} />
              Offer
            </motion.button>
          )}

          <div
            className="flex-1 flex items-end gap-2 rounded-2xl px-4 py-2"
            style={{
              background: "var(--bg)",
              border: "1px solid var(--border)",
            }}
          >
            <textarea
              value={text}
              onChange={(e) => setText(e.target.value)}
              onKeyDown={handleKey}
              rows={1}
              placeholder="Type a message…"
              className="flex-1 bg-transparent outline-none resize-none text-sm text-[var(--text-primary)] placeholder:text-[var(--text-muted)] leading-5 max-h-28"
              style={{ lineHeight: "1.4" }}
            />
          </div>

          <motion.button
            whileTap={{ scale: 0.88 }}
            onClick={handleSend}
            disabled={!text.trim()}
            className="w-9 h-9 rounded-full flex items-center justify-center shrink-0 disabled:opacity-30 transition-opacity"
            style={{ background: "var(--accent)" }}
          >
            <Send size={15} className="text-white translate-x-0.5" />
          </motion.button>
        </div>
      )}

      {/* ── Modals ── */}
      <AnimatePresence>
        {showOffer && (
          <OfferModal conv={conv} onClose={() => setShowOffer(false)} />
        )}
        {showReport && (
          <ReportModal conv={conv} onClose={() => setShowReport(false)} />
        )}
        {showBlockConfirm && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center p-4"
            style={{ background: "rgba(0,0,0,0.6)" }}
            onClick={() => setShowBlockConfirm(false)}
          >
            <motion.div
              initial={{ scale: 0.9 }}
              animate={{ scale: 1 }}
              exit={{ scale: 0.9 }}
              className="rounded-2xl overflow-hidden shadow-2xl p-6 max-w-xs w-full"
              style={{ background: "var(--card)" }}
              onClick={(e) => e.stopPropagation()}
            >
              <div className="flex flex-col items-center text-center gap-3">
                <div className="w-12 h-12 rounded-full bg-red-500/15 flex items-center justify-center">
                  <Ban size={22} className="text-red-400" />
                </div>
                <h3 className="font-bold text-[var(--text-primary)]">
                  {conv.isBlocked ? "Unblock" : "Block"} {conv.otherUserName}?
                </h3>
                <p className="text-xs text-[var(--text-muted)]">
                  {conv.isBlocked
                    ? "They will be able to message you again."
                    : "They won't be able to send you messages."}
                </p>
                <div className="flex gap-2 w-full mt-1">
                  <button
                    onClick={() => setShowBlockConfirm(false)}
                    className="flex-1 py-2.5 rounded-xl text-sm font-medium text-[var(--text-primary)] border border-[var(--border)]"
                  >
                    Cancel
                  </button>
                  <button
                    onClick={() => {
                      blockUser(conv.id);
                      setShowBlockConfirm(false);
                    }}
                    className="flex-1 py-2.5 rounded-xl text-sm font-medium text-white bg-red-500"
                  >
                    {conv.isBlocked ? "Unblock" : "Block"}
                  </button>
                </div>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
