"use client";

import Link from "next/link";
import { useEffect, useRef, useState, useTransition } from "react";

import { AIInboxAssistant } from "@/components/ai/AIInboxAssistant";

type Party = { type: "VISITOR" | "COMPANY"; id: string };

type ConversationItem = {
  id: string;
  partyA: Party;
  partyB: Party;
  contextEntityType: string | null;
  contextEntityId: string | null;
  contextTitle: string | null;
  contextPath: string | null;
  contextImageUrl: string | null;
  lastMessagePreview: string | null;
  lastMessageAt: string | null;
  unread: number;
  viewerIsA: boolean;
};

type Message = {
  id: string;
  author: Party;
  body: string;
  createdAt: string;
  readByAAt?: string | null;
  readByBAt?: string | null;
};

type RealtimeData = {
  presence: Record<string, "online" | "offline">;
  typing: Array<{ partyType: string; partyId: string }>;
  otherParty?: { type: "VISITOR" | "COMPANY"; id: string };
};

type Conversation = ConversationItem;

type Props = {
  /** Where this inbox lives — drives the URL of conversation links. */
  inboxBasePath: "/portal/poruke" | "/nalog/poruke";
  /** When deep-linked to a single thread, this is its id. Null = list view. */
  initialConversationId?: string | null;
};

function timeAgo(iso: string | null): string {
  if (!iso) return "";
  const ts = new Date(iso).getTime();
  if (!Number.isFinite(ts)) return "";
  const diff = Date.now() - ts;
  const m = Math.floor(diff / 60000);
  if (m < 1) return "upravo sada";
  if (m < 60) return `${m} min`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h`;
  const d = Math.floor(h / 24);
  if (d < 30) return `${d}d`;
  return new Date(iso).toLocaleDateString("sr-Latn-RS");
}

/**
 * Two-column inbox shell — conversation list on the left, active thread on
 * the right. Used by both `/nalog/poruke` (visitors) and `/portal/poruke`
 * (companies). Server-side decides which path to use; client logic is
 * identical.
 *
 * Polling-based real-time: conversation list refreshes every 15s, active
 * thread every 10s. Cheap enough that we don't need WebSockets for v1
 * and gracefully degrades on flaky connections.
 */
export function MessagingShell({ inboxBasePath, initialConversationId }: Props) {
  const [conversations, setConversations] = useState<ConversationItem[] | null>(null);
  const [activeId, setActiveId] = useState<string | null>(initialConversationId ?? null);
  const [activeThread, setActiveThread] = useState<{
    conversation: Conversation;
    messages: Message[];
    viewer: Party;
  } | null>(null);
  const [composer, setComposer] = useState("");
  const [sending, setSending] = useState(false);
  const [, startTransition] = useTransition();
  const threadEndRef = useRef<HTMLDivElement | null>(null);

  // Real-time state: presence + typing indicator
  const [realtime, setRealtime] = useState<RealtimeData>({ presence: {}, typing: [] });
  const lastTypingPostRef = useRef<number>(0);

  // Pro features: saved replies + lead pipeline stage
  type SavedReply = { id: string; label: string; body: string };
  const [savedReplies, setSavedReplies] = useState<SavedReply[]>([]);
  const [showSavedRepliesMenu, setShowSavedRepliesMenu] = useState(false);
  const [leadStage, setLeadStage] = useState<"NEW" | "HOT" | "WARM" | "CLOSED" | "LOST">("NEW");
  const [updatingLead, setUpdatingLead] = useState(false);

  // Load saved replies once (samo za COMPANY stranu).
  useEffect(() => {
    if (activeThread?.viewer.type !== "COMPANY") return;
    let cancelled = false;
    (async () => {
      try {
        const res = await fetch("/api/portal/messaging/saved-replies", {
          cache: "no-store",
        });
        if (!res.ok) return;
        const data = (await res.json()) as { items: SavedReply[] };
        if (!cancelled) setSavedReplies(data.items ?? []);
      } catch {
        /* noop */
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [activeThread?.viewer.type]);

  // Sync leadStage from activeThread
  useEffect(() => {
    const stage = (activeThread?.conversation as { leadStage?: string } | undefined)?.leadStage;
    if (stage === "HOT" || stage === "WARM" || stage === "CLOSED" || stage === "LOST" || stage === "NEW") {
      setLeadStage(stage);
    }
  }, [activeThread?.conversation]);

  async function updateLeadStage(next: typeof leadStage) {
    if (!activeId || activeThread?.viewer.type !== "COMPANY") return;
    setUpdatingLead(true);
    const prev = leadStage;
    setLeadStage(next); // optimistic
    try {
      const res = await fetch(`/api/messages/conversations/${activeId}/lead`, {
        method: "PATCH",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ stage: next }),
      });
      if (!res.ok) throw new Error("update failed");
    } catch {
      setLeadStage(prev); // revert
    } finally {
      setUpdatingLead(false);
    }
  }

  // Initial + periodic load of conversation list.
  useEffect(() => {
    let cancelled = false;
    async function load() {
      if (document.hidden) return; // pauza dok tab nije vidljiv → manje poziva
      try {
        const res = await fetch("/api/messages/conversations", { cache: "no-store" });
        if (!res.ok) return;
        const data = (await res.json()) as { items: ConversationItem[] };
        if (cancelled) return;
        setConversations(data.items);
        // If we have a deep-linked thread but no active selection, pick first.
        if (!activeId && data.items.length > 0) {
          setActiveId(data.items[0].id);
        }
      } catch {
        /* network blip */
      }
    }
    void load();
    const id = setInterval(load, 15_000);
    // Čim se tab vrati u fokus, odmah osveži listu razgovora.
    const onVisible = () => {
      if (!document.hidden) void load();
    };
    document.addEventListener("visibilitychange", onVisible);
    return () => {
      cancelled = true;
      clearInterval(id);
      document.removeEventListener("visibilitychange", onVisible);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Initial + periodic load of active thread.
  useEffect(() => {
    if (!activeId) return;
    let cancelled = false;

    async function load() {
      try {
        const res = await fetch(`/api/messages/conversations/${activeId}`, {
          cache: "no-store",
        });
        if (!res.ok) return;
        const data = (await res.json()) as {
          conversation: Conversation;
          messages: Message[];
          viewer: Party;
        };
        if (cancelled) return;
        setActiveThread(data);
      } catch {
        /* noop */
      }
    }
    void load();
    const t = setInterval(load, 10_000);
    return () => {
      cancelled = true;
      clearInterval(t);
    };
  }, [activeId]);

  // Auto-scroll to bottom on new messages.
  useEffect(() => {
    threadEndRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });
  }, [activeThread?.messages.length]);

  // Real-time poll — presence + typing every 3s for the active conversation.
  useEffect(() => {
    if (!activeId) {
      setRealtime({ presence: {}, typing: [] });
      return;
    }
    let cancelled = false;
    let timer: ReturnType<typeof setTimeout>;

    async function poll() {
      try {
        const res = await fetch(
          `/api/messages/realtime?conversationId=${activeId}`,
          { cache: "no-store" },
        );
        if (!res.ok) return;
        const data = (await res.json()) as RealtimeData;
        if (cancelled) return;
        setRealtime(data);
      } catch {
        /* noop */
      }
    }
    void poll();
    function schedule() {
      timer = setTimeout(async () => {
        if (cancelled) return;
        await poll();
        schedule();
      }, 3_000);
    }
    schedule();

    return () => {
      cancelled = true;
      if (timer) clearTimeout(timer);
    };
  }, [activeId]);

  // Notify server when user is typing (throttled — at most once per 2s).
  function onComposerChange(value: string) {
    setComposer(value);
    if (!activeId) return;
    const now = Date.now();
    if (now - lastTypingPostRef.current < 2_000) return;
    lastTypingPostRef.current = now;
    void fetch("/api/messages/typing", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ conversationId: activeId }),
    }).catch(() => null);
  }

  // Is the other party currently typing?
  const otherIsTyping =
    realtime.typing.length > 0 && realtime.otherParty
      ? realtime.typing.some(
          (t) =>
            t.partyType === realtime.otherParty!.type &&
            t.partyId === realtime.otherParty!.id,
        )
      : false;

  // Is the other party online?
  const otherIsOnline =
    realtime.otherParty
      ? realtime.presence[`${realtime.otherParty.type}:${realtime.otherParty.id}`] === "online"
      : false;

  async function send() {
    const body = composer.trim();
    if (!body || !activeId) return;
    setSending(true);
    try {
      const res = await fetch(`/api/messages/conversations/${activeId}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ body }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data?.error || "Slanje nije uspelo.");
      }
      setComposer("");
      // Optimistic refresh.
      startTransition(() => {
        void (async () => {
          const r = await fetch(`/api/messages/conversations/${activeId}`, {
            cache: "no-store",
          });
          if (r.ok) setActiveThread(await r.json());
        })();
      });
    } catch (err) {
      alert(err instanceof Error ? err.message : "Slanje nije uspelo.");
    } finally {
      setSending(false);
    }
  }

  function partyLabel(p: Party): string {
    if (p.type === "COMPANY") return "Kompanija";
    return "Korisnik";
  }

  if (conversations === null) {
    return (
      <div className="grid gap-3 lg:grid-cols-[320px_minmax(0,1fr)]">
        <div className="space-y-2">
          {[0, 1, 2, 3].map((i) => (
            <div key={i} className="skeleton h-20 rounded-2xl" />
          ))}
        </div>
        <div className="skeleton h-[60vh] rounded-2xl" />
      </div>
    );
  }

  if (conversations.length === 0) {
    return (
      <div className="rounded-2xl border border-dashed border-[#ede8e3] bg-white p-12 text-center">
        <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-[#fff4f0]">
          <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#c2410c" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
          </svg>
        </div>
        <h2 className="mt-5 font-display text-xl font-bold text-[#0c1828]">
          Inbox je još prazan
        </h2>
        <p className="mx-auto mt-2 max-w-md text-sm leading-7 text-[#6b7280]">
          Kada nekome pošaljete poruku ili neko vama, razgovor će se pojaviti ovde.
          Otvorite profil firme ili oglas i kliknite{" "}
          <strong className="text-[#0c1828]">Pošalji poruku</strong>.
        </p>
        <div className="mt-6 flex flex-wrap items-center justify-center gap-2">
          <Link
            href="/kompanije"
            className="inline-flex items-center gap-1.5 rounded-full border border-[#ede8e3] bg-white px-4 py-2 text-xs font-bold text-[#0c1828] transition hover:border-[#c2410c]/30 hover:bg-[#fff4f0] hover:text-[#c2410c]"
          >
            Pretraži kompanije
          </Link>
          <Link
            href="/nekretnine"
            className="inline-flex items-center gap-1.5 rounded-full border border-[#ede8e3] bg-white px-4 py-2 text-xs font-bold text-[#0c1828] transition hover:border-[#c2410c]/30 hover:bg-[#fff4f0] hover:text-[#c2410c]"
          >
            Pretraži nekretnine
          </Link>
        </div>
      </div>
    );
  }

  const activeConv = conversations.find((c) => c.id === activeId) ?? activeThread?.conversation;

  return (
    <div className="grid gap-3 lg:grid-cols-[340px_minmax(0,1fr)]">
      {/* Conversation list */}
      <aside className="space-y-2">
        {conversations.map((c) => {
          const isActive = c.id === activeId;
          const otherParty = c.viewerIsA ? c.partyB : c.partyA;
          return (
            <Link
              key={c.id}
              href={`${inboxBasePath}/${c.id}`}
              prefetch={false}
              onClick={(e) => {
                e.preventDefault();
                setActiveId(c.id);
                window.history.replaceState({}, "", `${inboxBasePath}/${c.id}`);
              }}
              className={`group block rounded-2xl border p-4 transition ${
                isActive
                  ? "border-[#c2410c]/60 bg-gradient-to-r from-[#fff4ee] to-[#fff8f4] shadow-[0_10px_28px_-8px_rgba(194,65,12,0.22)]"
                  : "border-[#ede8e3] bg-white hover:-translate-y-0.5 hover:border-[#c2410c]/30 hover:shadow-[0_8px_22px_-10px_rgba(10,18,35,0.14)]"
              }`}
            >
              <div className="flex items-center gap-3">
                <div className="relative h-9 w-9 shrink-0 overflow-hidden rounded-xl bg-[#0c1828]">
                  {c.contextImageUrl ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img src={c.contextImageUrl} alt="" className="h-full w-full object-cover" />
                  ) : (
                    <span className="flex h-full w-full items-center justify-center text-xs font-bold text-white">
                      {otherParty.type === "COMPANY" ? "🏢" : "👤"}
                    </span>
                  )}
                  {c.unread > 0 && (
                    <span className="absolute -right-1 -top-1 inline-flex h-5 min-w-[20px] items-center justify-center rounded-full bg-[#c2410c] px-1 text-[10px] font-black text-white">
                      {c.unread > 9 ? "9+" : c.unread}
                    </span>
                  )}
                </div>
                <div className="min-w-0 flex-1">
                  <div className="flex items-baseline justify-between gap-2">
                    <p className="truncate text-sm font-bold text-[#0c1828]">
                      {c.contextTitle || partyLabel(otherParty)}
                    </p>
                    <span className="shrink-0 text-[0.65rem] font-semibold text-[#9ca3af]">
                      {timeAgo(c.lastMessageAt)}
                    </span>
                  </div>
                  <p className={`mt-0.5 line-clamp-1 text-xs ${c.unread > 0 ? "font-bold text-[#0c1828]" : "text-[#6b7280]"}`}>
                    {c.lastMessagePreview || "Razgovor počet"}
                  </p>
                </div>
              </div>
            </Link>
          );
        })}
      </aside>

      {/* Active thread */}
      <section className="flex min-h-[60vh] flex-col overflow-hidden rounded-2xl border border-[#ede8e3] bg-white shadow-[inset_0_1px_0_rgba(255,255,255,0.9),0_18px_44px_-20px_rgba(10,18,35,0.18)]">
        {activeConv ? (
          <>
            {/* Context header — premium gradient sa avatarom i online statusom */}
            {activeConv.contextTitle && activeConv.contextPath && (
              <div className="flex items-center gap-3 border-b border-[#ede8e3] bg-gradient-to-r from-white via-[#fffaf6] to-[#fff4ee] px-5 py-4">
                {activeConv.contextImageUrl ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={activeConv.contextImageUrl}
                    alt=""
                    className="h-11 w-11 shrink-0 rounded-xl object-cover ring-1 ring-black/5 shadow-sm"
                  />
                ) : (
                  <div className="inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-[#f97552] to-[#c2410c] text-base font-bold text-white shadow-sm">
                    {activeConv.contextTitle.slice(0, 1).toUpperCase()}
                  </div>
                )}
                <div className="min-w-0 flex-1">
                  <p className="text-[0.6rem] font-bold uppercase tracking-[0.16em] text-[#c2410c]">
                    Razgovor o
                  </p>
                  <Link
                    href={activeConv.contextPath}
                    className="mt-0.5 inline-block line-clamp-1 text-[0.95rem] font-bold leading-tight text-[#0a1223] hover:text-[#c2410c] transition"
                  >
                    {activeConv.contextTitle} ↗
                  </Link>
                </div>
                {/* Online status dot */}
                {otherIsOnline && (
                  <span
                    title="Trenutno online"
                    className="inline-flex items-center gap-1.5 rounded-full border border-emerald-200 bg-emerald-50 px-2.5 py-1 text-[0.62rem] font-bold text-emerald-700"
                  >
                    <span className="relative flex h-2 w-2">
                      <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-500 opacity-75" />
                      <span className="relative inline-flex h-2 w-2 rounded-full bg-emerald-500" />
                    </span>
                    Online
                  </span>
                )}
              </div>
            )}

            {/* Lead pipeline chips — vidi ih SAMO vlasnik firme */}
            {activeThread?.viewer.type === "COMPANY" && (
              <div className="flex flex-wrap items-center gap-1.5 border-b border-[#ede8e3] bg-white px-5 py-2.5">
                <span className="mr-1 text-[0.62rem] font-bold uppercase tracking-[0.14em] text-[#9ca3af]">
                  Lead status:
                </span>
                {(
                  [
                    { value: "NEW", label: "Nov", tone: "zinc" },
                    { value: "HOT", label: "🔥 Hot", tone: "rose" },
                    { value: "WARM", label: "♨️ Warm", tone: "amber" },
                    { value: "CLOSED", label: "✓ Zatvoren", tone: "emerald" },
                    { value: "LOST", label: "Izgubljen", tone: "zinc" },
                  ] as const
                ).map((opt) => {
                  const active = leadStage === opt.value;
                  const toneCls = active
                    ? opt.tone === "rose"
                      ? "border-rose-500 bg-rose-500 text-white"
                      : opt.tone === "amber"
                        ? "border-amber-500 bg-amber-500 text-white"
                        : opt.tone === "emerald"
                          ? "border-emerald-500 bg-emerald-500 text-white"
                          : "border-zinc-700 bg-zinc-800 text-white"
                    : "border-[#ede8e3] bg-white text-[#0c1828] hover:border-[#c2410c]/30";
                  return (
                    <button
                      key={opt.value}
                      type="button"
                      disabled={updatingLead}
                      onClick={() => updateLeadStage(opt.value)}
                      className={`inline-flex items-center rounded-full border px-2.5 py-1 text-[0.7rem] font-bold transition disabled:opacity-50 ${toneCls}`}
                    >
                      {opt.label}
                    </button>
                  );
                })}
              </div>
            )}

            {/* Messages */}
            <div
              className="flex-1 space-y-3 overflow-y-auto p-5"
              style={{
                background:
                  "radial-gradient(circle at top right, rgba(194,65,12,0.04) 0%, transparent 40%), linear-gradient(180deg, #fafafa 0%, #ffffff 100%)",
              }}
            >
              {activeThread?.messages.length === 0 ? (
                <p className="py-8 text-center text-sm text-[#9ca3af]">Razgovor je tek počet.</p>
              ) : (
                activeThread?.messages.map((m) => {
                  const isMe =
                    activeThread.viewer.type === m.author.type &&
                    activeThread.viewer.id === m.author.id;
                  // Read receipt: poruka koju sam JA poslao i druga strana je već pročitala.
                  const viewerIsA = activeConv && activeThread.viewer.type === activeConv.partyA.type && activeThread.viewer.id === activeConv.partyA.id;
                  const readByOther = isMe
                    ? viewerIsA
                      ? Boolean(m.readByBAt)
                      : Boolean(m.readByAAt)
                    : false;
                  return (
                    <div
                      key={m.id}
                      className={`flex ${isMe ? "justify-end" : "justify-start"}`}
                    >
                      <div
                        className={`max-w-[78%] rounded-2xl px-4 py-2.5 text-sm leading-6 ${
                          isMe
                            ? "rounded-br-md bg-gradient-to-br from-[#f97552] to-[#c2410c] text-white shadow-[0_8px_18px_-6px_rgba(194,65,12,0.45)]"
                            : "rounded-bl-md border border-[#ede8e3] bg-white text-[#0c1828] shadow-[0_2px_8px_rgba(10,18,35,0.04)]"
                        }`}
                      >
                        <p className="whitespace-pre-wrap">{m.body}</p>
                        <p className={`mt-1 inline-flex items-center gap-1 text-[0.6rem] ${isMe ? "text-white/70" : "text-[#9ca3af]"}`}>
                          {timeAgo(m.createdAt)}
                          {isMe && (
                            <span aria-hidden="true" title={readByOther ? "Pročitano" : "Poslato"}>
                              {readByOther ? (
                                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
                                  <polyline points="3 12 7 16 13 10" />
                                  <polyline points="11 12 15 16 21 10" />
                                </svg>
                              ) : (
                                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
                                  <polyline points="6 12 10 16 18 8" />
                                </svg>
                              )}
                            </span>
                          )}
                        </p>
                      </div>
                    </div>
                  );
                })
              )}
              {/* Typing indicator */}
              {otherIsTyping && (
                <div className="flex justify-start">
                  <div className="rounded-2xl rounded-bl-md border border-[#ede8e3] bg-[#faf9f7] px-4 py-2.5 shadow-sm">
                    <span className="inline-flex items-center gap-1">
                      <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-[#9ca3af] [animation-delay:0ms]" />
                      <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-[#9ca3af] [animation-delay:200ms]" />
                      <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-[#9ca3af] [animation-delay:400ms]" />
                    </span>
                  </div>
                </div>
              )}
              <div ref={threadEndRef} />
            </div>

            {/* Composer + AI assistant */}
            <div className="space-y-3 border-t border-[#ede8e3] bg-white p-4">
              {activeId && (
                <AIInboxAssistant
                  conversationId={activeId}
                  enoughForSummary={(activeThread?.messages.length ?? 0) >= 4}
                  onApplyDraft={(draft) => setComposer(draft)}
                />
              )}

              {/* Saved replies — samo za COMPANY stranu i kada postoje */}
              {activeThread?.viewer.type === "COMPANY" && savedReplies.length > 0 && (
                <div className="relative">
                  <button
                    type="button"
                    onClick={() => setShowSavedRepliesMenu((v) => !v)}
                    className="inline-flex items-center gap-1.5 rounded-lg border border-[#ede8e3] bg-white px-3 py-1.5 text-xs font-bold text-[#0c1828] transition hover:border-[#c2410c]/40 hover:text-[#c2410c]"
                  >
                    💬 Sačuvani odgovori
                    <span className="rounded-full bg-[#c2410c]/10 px-1.5 text-[0.6rem] text-[#c2410c]">
                      {savedReplies.length}
                    </span>
                  </button>
                  {showSavedRepliesMenu && (
                    <div className="absolute bottom-full left-0 z-30 mb-2 w-80 max-h-72 overflow-y-auto rounded-xl border border-[#ede8e3] bg-white shadow-[0_18px_44px_rgba(12,24,40,0.18)]">
                      <ul className="py-1">
                        {savedReplies.map((r) => (
                          <li key={r.id}>
                            <button
                              type="button"
                              onClick={() => {
                                setComposer((c) => (c ? `${c}\n${r.body}` : r.body));
                                setShowSavedRepliesMenu(false);
                              }}
                              className="block w-full px-3 py-2 text-left transition hover:bg-[#faf9f7]"
                            >
                              <p className="text-sm font-bold text-[#0c1828]">{r.label}</p>
                              <p className="mt-0.5 line-clamp-2 text-xs text-[#6b7280]">{r.body}</p>
                            </button>
                          </li>
                        ))}
                      </ul>
                      <div className="border-t border-[#ede8e3] bg-[#faf9f7] px-3 py-2 text-center">
                        <Link
                          href="/portal/poruke-podesavanja"
                          className="text-xs font-bold text-[#c2410c] hover:underline"
                        >
                          Uredi sačuvane odgovore →
                        </Link>
                      </div>
                    </div>
                  )}
                </div>
              )}

              <div className="flex items-end gap-2">
                <textarea
                  rows={2}
                  value={composer}
                  onChange={(e) => onComposerChange(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
                      e.preventDefault();
                      void send();
                    }
                  }}
                  placeholder="Napišite poruku… (Cmd+Enter za slanje)"
                  className="flex-1 resize-none rounded-xl border border-[#ede8e3] bg-[#faf9f7] px-3.5 py-2.5 text-sm text-[#0c1828] placeholder:text-[#9ca3af] outline-none transition focus:border-[#c2410c]/40 focus:bg-white focus:ring-2 focus:ring-[#c2410c]/15"
                />
                <button
                  type="button"
                  onClick={send}
                  disabled={sending || !composer.trim()}
                  className="inline-flex h-11 items-center gap-1.5 rounded-xl bg-[#c2410c] px-4 text-sm font-bold text-white transition hover:bg-[#d94e22] active:scale-[0.97] disabled:opacity-60"
                >
                  {sending ? "Šaljem..." : "Pošalji"}
                </button>
              </div>
            </div>
          </>
        ) : (
          <div className="flex flex-1 items-center justify-center p-12 text-center text-sm text-[#9ca3af]">
            Izaberite razgovor sa leve strane.
          </div>
        )}
      </section>
    </div>
  );
}
