"use client";

import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";

type Status = "OPEN" | "WAITING" | "RESPONDED" | "CLOSED";

type SessionListItem = {
  id: string;
  visitorName: string | null;
  visitorEmail: string | null;
  visitorPhone: string | null;
  topic: string | null;
  pageUrl: string | null;
  status: Status;
  unreadByAdmin: number;
  lastMessageAt: string;
  lastMessagePreview: string | null;
  lastFromVisitor: boolean | null;
  assignedToName: string | null;
  createdAt: string;
};

type Message = {
  id: string;
  fromVisitor: boolean;
  body: string;
  createdAt: string;
};

type SessionDetail = {
  session: {
    id: string;
    visitorName: string | null;
    visitorEmail: string | null;
    visitorPhone: string | null;
    visitorAccountId: string | null;
    topic: string | null;
    pageUrl: string | null;
    status: Status;
    assignedToName: string | null;
    lastMessageAt: string;
    createdAt: string;
  };
  messages: Message[];
};

const STATUS_LABEL: Record<Status, string> = {
  OPEN: "Otvoreno",
  WAITING: "Čeka odgovor",
  RESPONDED: "Odgovoreno",
  CLOSED: "Zatvoreno",
};

const STATUS_TONE: Record<Status, string> = {
  OPEN: "border-sky-200 bg-sky-50 text-sky-700",
  WAITING: "border-amber-200 bg-amber-50 text-amber-700",
  RESPONDED: "border-emerald-200 bg-emerald-50 text-emerald-700",
  CLOSED: "border-zinc-200 bg-zinc-100 text-zinc-600",
};

const STATUS_DOT: Record<Status, string> = {
  OPEN: "bg-sky-500",
  WAITING: "bg-amber-500",
  RESPONDED: "bg-emerald-500",
  CLOSED: "bg-zinc-400",
};

const STATUS_RING: Record<Status, string> = {
  OPEN: "ring-sky-200",
  WAITING: "ring-amber-200",
  RESPONDED: "ring-emerald-200",
  CLOSED: "ring-zinc-200",
};

const QUICK_REPLIES = [
  "Pozdrav! Kako mogu da pomognem?",
  "Hvala na javljanju — odmah proveravam.",
  "Možete li poslati još malo detalja?",
  "Sve je rešeno, javite ako treba još nešto.",
];

/* ── Ikone ───────────────────────────────────────────────────────────── */
function Svg({ children, size = 18 }: { children: ReactNode; size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth={1.8}
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      {children}
    </svg>
  );
}
const IcChat = (
  <Svg>
    <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" />
  </Svg>
);
const IcCheckCircle = (
  <Svg>
    <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
    <path d="m22 4-10 10.01-3-3" />
  </Svg>
);
const IcTag = (
  <Svg size={13}>
    <path d="M20.59 13.41 13.42 20.59a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z" />
    <line x1="7" y1="7" x2="7.01" y2="7" />
  </Svg>
);
const IcMail = (
  <Svg size={13}>
    <rect x="3" y="5" width="18" height="14" rx="2" />
    <path d="m3 7 9 6 9-6" />
  </Svg>
);
const IcPhone = (
  <Svg size={13}>
    <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z" />
  </Svg>
);
const IcLink = (
  <Svg size={12}>
    <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />
    <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />
  </Svg>
);
const IcCheckSmall = (
  <Svg size={12}>
    <polyline points="20 6 9 17 4 12" />
  </Svg>
);
const IcSend = (
  <Svg size={16}>
    <line x1="22" y1="2" x2="11" y2="13" />
    <polygon points="22 2 15 22 11 13 2 9 22 2" />
  </Svg>
);
const IcSmile = (
  <Svg size={18}>
    <circle cx="12" cy="12" r="10" />
    <path d="M8 14s1.5 2 4 2 4-2 4-2" />
    <line x1="9" y1="9" x2="9.01" y2="9" />
    <line x1="15" y1="9" x2="15.01" y2="9" />
  </Svg>
);
const IcBell = (
  <Svg size={13}>
    <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9" />
    <path d="M13.73 21a2 2 0 0 1-3.46 0" />
  </Svg>
);
const IcBellOff = (
  <Svg size={13}>
    <path d="M13.73 21a2 2 0 0 1-3.46 0" />
    <path d="M18.63 13A17.89 17.89 0 0 1 18 8" />
    <path d="M6.26 6.26A5.86 5.86 0 0 0 6 8c0 7-3 9-3 9h14" />
    <path d="M18 8a6 6 0 0 0-9.33-5" />
    <line x1="1" y1="1" x2="23" y2="23" />
  </Svg>
);

const EMOJI_GROUPS: { label: string; emojis: string[] }[] = [
  {
    label: "Smajli",
    emojis: ["😀", "😄", "😊", "🙂", "😉", "😍", "😎", "🤩", "😅", "😂", "🤗", "🤔", "😴", "😮", "🥳", "😇"],
  },
  {
    label: "Gestovi",
    emojis: ["👍", "👏", "🙏", "💪", "🤝", "👋", "🙌", "👌", "✌️", "🤞", "👇", "☝️"],
  },
  {
    label: "Simboli",
    emojis: ["✅", "✔️", "❌", "⚠️", "ℹ️", "⭐", "🔥", "💯", "❤️", "🧡", "💛", "✨", "🎉", "🎯", "🚀", "💡"],
  },
  {
    label: "Posao",
    emojis: ["📞", "✉️", "💬", "📅", "⏰", "📌", "📎", "💰", "🏆", "🛠️", "🔧", "📈"],
  },
];

function urlBase64ToUint8Array(base64String: string): Uint8Array {
  const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
  const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
  const raw = atob(base64);
  const out = new Uint8Array(raw.length);
  for (let i = 0; i < raw.length; i += 1) out[i] = raw.charCodeAt(i);
  return out;
}

/**
 * Nivo 2 — pravi Web Push: registruje push service worker (scope /admin/ da ne
 * dira root kill-switch), kreira pretplatu i čuva je na topic „admin_livechat".
 * Tako admin dobija OS notifikaciju i kada je panel POTPUNO zatvoren.
 * Best-effort — ako VAPID ključ nije postavljen ili browser ne podržava, tiho
 * preskoči (Nivo 1: zvuk + tab notifikacija i dalje rade).
 */
async function subscribeAdminWebPush(): Promise<void> {
  try {
    if (!("serviceWorker" in navigator) || !("PushManager" in window)) return;
    const key = process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY || "";
    if (!key) return;
    const reg = await navigator.serviceWorker.register("/sw-push.js", {
      scope: "/admin/",
    });
    await navigator.serviceWorker.ready;
    let sub = await reg.pushManager.getSubscription();
    if (!sub) {
      sub = await reg.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array(key).buffer as ArrayBuffer,
      });
    }
    const json = sub.toJSON();
    await fetch("/api/admin/live-chat/push-subscribe", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ endpoint: json.endpoint, keys: json.keys }),
    });
  } catch {
    /* best-effort */
  }
}

function initials(name: string) {
  const parts = name.trim().split(/\s+/).filter(Boolean);
  const letters = (parts[0]?.[0] ?? "") + (parts[1]?.[0] ?? "");
  return (letters || name.slice(0, 2)).toUpperCase() || "?";
}

function timeAgo(iso: string) {
  const diff = Date.now() - new Date(iso).getTime();
  const m = Math.floor(diff / 60000);
  if (m < 1) return "upravo";
  if (m < 60) return `pre ${m} min`;
  const h = Math.floor(m / 60);
  if (h < 24) return `pre ${h}h`;
  const d = Math.floor(h / 24);
  return `pre ${d} dana`;
}

function Avatar({
  name,
  status,
  size = 40,
}: {
  name: string;
  status: Status;
  size?: number;
}) {
  return (
    <span className="relative inline-flex shrink-0">
      <span
        className={`inline-flex items-center justify-center rounded-full bg-gradient-to-br from-[#c2410c] to-[#f59e6b] font-bold text-white ring-2 ${STATUS_RING[status]}`}
        style={{ width: size, height: size, fontSize: size * 0.36 }}
      >
        {initials(name)}
      </span>
      <span
        className={`absolute -bottom-0.5 -right-0.5 h-3 w-3 rounded-full border-2 border-white ${STATUS_DOT[status]}`}
      />
    </span>
  );
}

export function LiveChatInbox() {
  const [sessions, setSessions] = useState<SessionListItem[]>([]);
  const [statusFilter, setStatusFilter] = useState<Status | "ALL">("WAITING");
  const [loading, setLoading] = useState(true);
  const [activeId, setActiveId] = useState<string | null>(null);
  const [detail, setDetail] = useState<SessionDetail | null>(null);
  const [composer, setComposer] = useState("");
  const [sending, setSending] = useState(false);
  const [emojiOpen, setEmojiOpen] = useState(false);
  const [notifState, setNotifState] = useState<
    "unsupported" | "default" | "granted" | "denied"
  >("default");
  const messagesEndRef = useRef<HTMLDivElement | null>(null);
  const composerRef = useRef<HTMLTextAreaElement | null>(null);
  const emojiRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (typeof Notification === "undefined") {
      setNotifState("unsupported");
      return;
    }
    setNotifState(Notification.permission as "default" | "granted" | "denied");
  }, []);

  function testChime() {
    try {
      const Ctx =
        window.AudioContext ||
        (window as unknown as { webkitAudioContext?: typeof AudioContext })
          .webkitAudioContext;
      if (!Ctx) return;
      const ctx = new Ctx();
      const now = ctx.currentTime;
      for (const [i, freq] of [880, 1175].entries()) {
        const osc = ctx.createOscillator();
        const gain = ctx.createGain();
        osc.type = "sine";
        osc.frequency.value = freq;
        const t = now + i * 0.16;
        gain.gain.setValueAtTime(0, t);
        gain.gain.linearRampToValueAtTime(0.18, t + 0.02);
        gain.gain.exponentialRampToValueAtTime(0.0001, t + 0.22);
        osc.connect(gain).connect(ctx.destination);
        osc.start(t);
        osc.stop(t + 0.24);
      }
    } catch {
      /* no-op */
    }
  }

  async function enableNotifications() {
    testChime(); // klik = user gest → otključava zvuk za kasnije alarme
    if (typeof Notification === "undefined") {
      setNotifState("unsupported");
      return;
    }
    if (Notification.permission === "granted") {
      setNotifState("granted");
      void subscribeAdminWebPush();
      new Notification("Obaveštenja su uključena", {
        body: "Javićemo ti zvukom i push porukom — čak i kada je panel zatvoren.",
        tag: "bp-livechat-test",
        icon: "/icons/app-icon.png",
      });
      return;
    }
    try {
      const p = await Notification.requestPermission();
      setNotifState(p as "default" | "granted" | "denied");
      if (p === "granted") {
        void subscribeAdminWebPush();
        new Notification("Obaveštenja su uključena", {
          body: "Javićemo ti zvukom i push porukom — čak i kada je panel zatvoren.",
          tag: "bp-livechat-test",
          icon: "/icons/app-icon.png",
        });
      }
    } catch {
      /* no-op */
    }
  }

  // Zatvori emoji panel klikom van njega
  useEffect(() => {
    function onClick(e: MouseEvent) {
      if (!emojiRef.current?.contains(e.target as Node)) setEmojiOpen(false);
    }
    if (emojiOpen) document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, [emojiOpen]);

  function insertEmoji(emoji: string) {
    const ta = composerRef.current;
    if (!ta) {
      setComposer((c) => c + emoji);
      return;
    }
    const start = ta.selectionStart ?? ta.value.length;
    const end = ta.selectionEnd ?? ta.value.length;
    const next = ta.value.slice(0, start) + emoji + ta.value.slice(end);
    setComposer(next);
    requestAnimationFrame(() => {
      ta.focus();
      const pos = start + emoji.length;
      ta.setSelectionRange(pos, pos);
    });
  }

  async function loadSessions() {
    setLoading(true);
    try {
      const url =
        statusFilter === "ALL"
          ? "/api/admin/live-chat"
          : `/api/admin/live-chat?status=${statusFilter}`;
      const res = await fetch(url, { cache: "no-store" });
      if (!res.ok) return;
      const data = await res.json();
      setSessions(data.items ?? []);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void loadSessions();
    const interval = window.setInterval(loadSessions, 10_000);
    return () => window.clearInterval(interval);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [statusFilter]);

  useEffect(() => {
    if (!activeId) {
      setDetail(null);
      return;
    }
    let cancelled = false;
    async function loadDetail() {
      try {
        const res = await fetch(`/api/admin/live-chat/${activeId}/messages`, {
          cache: "no-store",
        });
        if (!res.ok) return;
        const data = (await res.json()) as SessionDetail;
        if (!cancelled) setDetail(data);
      } catch {
        /* noop */
      }
    }
    void loadDetail();
    const interval = window.setInterval(loadDetail, 4000);
    return () => {
      cancelled = true;
      window.clearInterval(interval);
    };
  }, [activeId]);

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

  async function send(closeAfter = false) {
    if (!activeId || composer.trim().length < 1) return;
    setSending(true);
    const body = composer.trim();
    setComposer("");
    try {
      await fetch(`/api/admin/live-chat/${activeId}/send`, {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ message: body, closeAfter }),
      });
      const res = await fetch(`/api/admin/live-chat/${activeId}/messages`);
      if (res.ok) {
        const data = await res.json();
        setDetail(data);
      }
      await loadSessions();
    } finally {
      setSending(false);
    }
  }

  const waitingCount = sessions.filter((s) => s.status === "WAITING").length;
  const headerName = useMemo(() => {
    if (!detail) return "";
    return (
      detail.session.visitorName || detail.session.visitorEmail || "Anonimni posetilac"
    );
  }, [detail]);

  return (
    <div className="grid h-[calc(100vh-220px)] min-h-[520px] grid-cols-1 gap-4 md:grid-cols-[340px_1fr]">
      {/* Sidebar — list */}
      <aside className="flex flex-col overflow-hidden rounded-3xl border border-border bg-white shadow-[0_18px_50px_rgba(12,24,40,0.06)]">
        <div className="border-b border-border bg-gradient-to-b from-[#fff7f3] to-white p-3">
          <div className="mb-2.5 flex items-center justify-between gap-2 px-1">
            <p className="text-[0.65rem] font-extrabold uppercase tracking-[0.18em] text-muted-foreground">
              Razgovori
            </p>
            <div className="flex items-center gap-2">
              {notifState !== "unsupported" &&
                (notifState === "granted" ? (
                  <span
                    className="inline-flex items-center gap-1 rounded-full border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-[0.58rem] font-bold uppercase tracking-[0.1em] text-emerald-600"
                    title="Desktop obaveštenja i zvuk su uključeni"
                  >
                    {IcBell}
                    Obaveštenja
                  </span>
                ) : notifState === "denied" ? (
                  <span
                    className="inline-flex items-center gap-1 rounded-full border border-zinc-200 bg-zinc-100 px-2 py-0.5 text-[0.58rem] font-bold uppercase tracking-[0.1em] text-zinc-500"
                    title="Obaveštenja su blokirana u pretraživaču. Otključaj ih u podešavanjima sajta (ikona pored adrese)."
                  >
                    {IcBellOff}
                    Blokirano
                  </span>
                ) : (
                  <button
                    type="button"
                    onClick={enableNotifications}
                    className="inline-flex items-center gap-1 rounded-full border border-primary/30 bg-[#fff4ef] px-2 py-0.5 text-[0.58rem] font-bold uppercase tracking-[0.1em] text-primary transition hover:bg-[#ffe9e0]"
                    title="Uključi zvuk i desktop obaveštenja za nove poruke"
                  >
                    {IcBell}
                    Uključi
                  </button>
                ))}
              <span className="inline-flex items-center gap-1.5 text-[0.6rem] font-bold uppercase tracking-[0.12em] text-emerald-600">
                <span className="relative flex h-2 w-2">
                  <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-75" />
                  <span className="relative inline-flex h-2 w-2 rounded-full bg-emerald-500" />
                </span>
                Uživo
              </span>
            </div>
          </div>
          <div className="flex gap-1.5 overflow-x-auto pb-0.5 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
            {(["WAITING", "RESPONDED", "CLOSED", "ALL"] as const).map((s) => {
              const tabLabel =
                s === "ALL" ? "Sve" : s === "WAITING" ? "Čeka" : STATUS_LABEL[s];
              const active = statusFilter === s;
              return (
                <button
                  key={s}
                  type="button"
                  onClick={() => setStatusFilter(s)}
                  className={`flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full px-3.5 py-1.5 text-[0.72rem] font-bold transition ${
                    active
                      ? "bg-gradient-to-br from-[#c2410c] to-[#e2632f] text-white shadow-sm"
                      : "bg-white text-muted-foreground ring-1 ring-border hover:bg-zinc-50"
                  }`}
                >
                  {tabLabel}
                  {s === "WAITING" && waitingCount > 0 ? (
                    <span
                      className={`inline-flex min-w-[1.1rem] items-center justify-center rounded-full px-1 text-[0.62rem] font-extrabold ${
                        active ? "bg-white/25 text-white" : "bg-rose-500 text-white"
                      }`}
                    >
                      {waitingCount}
                    </span>
                  ) : null}
                </button>
              );
            })}
          </div>
        </div>
        <div className="flex-1 overflow-y-auto">
          {loading && sessions.length === 0 ? (
            <div className="space-y-2 p-3">
              {[0, 1, 2].map((i) => (
                <div key={i} className="flex items-center gap-3 rounded-2xl border border-border p-3">
                  <div className="h-10 w-10 shrink-0 animate-pulse rounded-full bg-zinc-100" />
                  <div className="flex-1 space-y-1.5">
                    <div className="h-3 w-2/3 animate-pulse rounded bg-zinc-100" />
                    <div className="h-2.5 w-full animate-pulse rounded bg-zinc-100" />
                  </div>
                </div>
              ))}
            </div>
          ) : sessions.length === 0 ? (
            <div className="flex h-full flex-col items-center justify-center px-8 py-12 text-center">
              <span
                className={`flex h-16 w-16 items-center justify-center rounded-2xl ${
                  statusFilter === "WAITING"
                    ? "bg-emerald-50 text-emerald-500"
                    : "bg-[#fff4ef] text-primary"
                }`}
              >
                {statusFilter === "WAITING" ? IcCheckCircle : IcChat}
              </span>
              <p className="mt-4 text-sm font-bold text-foreground">
                {statusFilter === "WAITING"
                  ? "Nema poruka koje čekaju"
                  : statusFilter === "ALL"
                    ? "Još nema nijednog razgovora"
                    : "Nema sesija u ovom statusu"}
              </p>
              {statusFilter === "WAITING" ? (
                <p className="mt-1.5 max-w-[15rem] text-xs leading-5 text-muted-foreground">
                  Sve je odgovoreno. Javićemo ti (badge + email) čim stigne nova poruka.
                </p>
              ) : null}
            </div>
          ) : (
            <ul className="space-y-1.5 p-2.5">
              {sessions.map((s) => {
                const name =
                  s.visitorName || s.visitorEmail || "Anonimni posetilac";
                const isActive = activeId === s.id;
                return (
                  <li key={s.id}>
                    <button
                      type="button"
                      onClick={() => setActiveId(s.id)}
                      className={`flex w-full items-start gap-3 rounded-2xl border p-3 text-left transition ${
                        isActive
                          ? "border-primary/30 bg-[#fff7f3] shadow-[0_8px_24px_rgba(194,65,12,0.08)]"
                          : "border-transparent hover:border-border hover:bg-zinc-50"
                      }`}
                    >
                      <Avatar name={name} status={s.status} />
                      <span className="min-w-0 flex-1">
                        <span className="flex items-center justify-between gap-2">
                          <span className="truncate text-sm font-bold text-foreground">
                            {name}
                          </span>
                          <span className="shrink-0 text-[0.62rem] font-semibold text-muted-foreground">
                            {timeAgo(s.lastMessageAt)}
                          </span>
                        </span>
                        {s.topic && (
                          <span className="mt-0.5 flex items-center gap-1 text-[0.7rem] text-muted-foreground">
                            <span className="text-muted-foreground/70">{IcTag}</span>
                            <span className="truncate">{s.topic}</span>
                          </span>
                        )}
                        {s.lastMessagePreview && (
                          <span className="mt-0.5 flex items-center gap-1 text-xs text-muted-foreground">
                            {!s.lastFromVisitor && (
                              <span className="text-emerald-500">{IcCheckSmall}</span>
                            )}
                            <span className="line-clamp-1">{s.lastMessagePreview}</span>
                          </span>
                        )}
                        <span className="mt-1.5 flex items-center justify-between gap-2">
                          <span
                            className={`inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 text-[0.62rem] font-bold ${STATUS_TONE[s.status]}`}
                          >
                            <span className={`h-1.5 w-1.5 rounded-full ${STATUS_DOT[s.status]}`} />
                            {STATUS_LABEL[s.status]}
                          </span>
                          {s.unreadByAdmin > 0 && (
                            <span className="inline-flex min-w-[1.15rem] items-center justify-center rounded-full bg-rose-500 px-1 text-[0.62rem] font-extrabold text-white">
                              {s.unreadByAdmin}
                            </span>
                          )}
                        </span>
                      </span>
                    </button>
                  </li>
                );
              })}
            </ul>
          )}
        </div>
      </aside>

      {/* Thread */}
      <section className="flex flex-col overflow-hidden rounded-3xl border border-border bg-white shadow-[0_18px_50px_rgba(12,24,40,0.06)]">
        {!detail ? (
          <div className="flex flex-1 items-center justify-center p-8 text-center">
            <div className="max-w-xs">
              <span className="mx-auto flex h-20 w-20 items-center justify-center rounded-3xl bg-[#fff4ef] text-primary">
                <Svg size={34}>
                  <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" />
                </Svg>
              </span>
              <p className="mt-4 text-base font-bold text-foreground">
                Izaberi razgovor
              </p>
              <p className="mt-1.5 text-sm leading-6 text-muted-foreground">
                Odaberi sesiju iz liste levo da vidiš celu prepisku i odgovoriš posetiocu u realnom vremenu.
              </p>
            </div>
          </div>
        ) : (
          <>
            {/* Header */}
            <div className="flex items-start justify-between gap-3 border-b border-border bg-gradient-to-b from-[#fff7f3] to-white p-4">
              <div className="flex min-w-0 items-center gap-3">
                <Avatar name={headerName} status={detail.session.status} size={46} />
                <div className="min-w-0">
                  <p className="truncate font-display text-lg font-bold text-foreground">
                    {headerName}
                  </p>
                  <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
                    {detail.session.visitorEmail && (
                      <a
                        href={`mailto:${detail.session.visitorEmail}`}
                        className="inline-flex items-center gap-1 text-primary hover:underline"
                      >
                        {IcMail}
                        {detail.session.visitorEmail}
                      </a>
                    )}
                    {detail.session.visitorPhone && (
                      <a
                        href={`tel:${detail.session.visitorPhone}`}
                        className="inline-flex items-center gap-1 text-primary hover:underline"
                      >
                        {IcPhone}
                        {detail.session.visitorPhone}
                      </a>
                    )}
                    {detail.session.topic && (
                      <span className="inline-flex items-center gap-1">
                        {IcTag}
                        {detail.session.topic}
                      </span>
                    )}
                  </div>
                  {detail.session.pageUrl && (
                    <a
                      href={detail.session.pageUrl}
                      target="_blank"
                      rel="noreferrer"
                      className="mt-1 inline-flex max-w-full items-center gap-1 truncate text-[0.65rem] text-muted-foreground hover:underline"
                    >
                      {IcLink}
                      <span className="truncate">{detail.session.pageUrl}</span>
                    </a>
                  )}
                </div>
              </div>
              <span
                className={`inline-flex shrink-0 items-center gap-1 rounded-full border px-2.5 py-1 text-[0.65rem] font-bold ${STATUS_TONE[detail.session.status]}`}
              >
                <span className={`h-1.5 w-1.5 rounded-full ${STATUS_DOT[detail.session.status]}`} />
                {STATUS_LABEL[detail.session.status]}
              </span>
            </div>

            {/* Messages */}
            <div className="flex-1 space-y-3 overflow-y-auto bg-[#faf9f7] p-4">
              {detail.messages.map((m) => (
                <div
                  key={m.id}
                  className={`flex items-end gap-2 ${m.fromVisitor ? "justify-start" : "justify-end"}`}
                >
                  {m.fromVisitor && (
                    <Avatar name={headerName} status={detail.session.status} size={26} />
                  )}
                  <div
                    className={`max-w-[76%] px-3.5 py-2.5 text-sm leading-5 shadow-sm ${
                      m.fromVisitor
                        ? "rounded-2xl rounded-bl-md border border-border bg-white text-foreground"
                        : "rounded-2xl rounded-br-md bg-gradient-to-br from-[#c2410c] to-[#e2632f] text-white"
                    }`}
                  >
                    <p className="whitespace-pre-wrap">{m.body}</p>
                    <p
                      className={`mt-1 flex items-center justify-end gap-1 text-[0.6rem] ${
                        m.fromVisitor ? "text-muted-foreground" : "text-white/75"
                      }`}
                    >
                      {timeAgo(m.createdAt)}
                      {!m.fromVisitor && IcCheckSmall}
                    </p>
                  </div>
                </div>
              ))}
              <div ref={messagesEndRef} />
            </div>

            {/* Composer */}
            {detail.session.status !== "CLOSED" ? (
              <div className="border-t border-border bg-white p-3">
                <div className="mb-2 flex gap-1.5 overflow-x-auto pb-0.5 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
                  {QUICK_REPLIES.map((q) => (
                    <button
                      key={q}
                      type="button"
                      onClick={() => {
                        setComposer(q);
                        composerRef.current?.focus();
                      }}
                      className="shrink-0 whitespace-nowrap rounded-full border border-border bg-zinc-50 px-3 py-1 text-[0.7rem] font-semibold text-muted-foreground transition hover:border-primary/40 hover:bg-[#fff4ef] hover:text-primary"
                    >
                      {q}
                    </button>
                  ))}
                </div>
                <div className="rounded-2xl border border-border bg-zinc-50 p-2 transition focus-within:border-primary/40 focus-within:bg-white focus-within:shadow-[0_0_0_4px_rgba(194,65,12,0.08)]">
                  <textarea
                    ref={composerRef}
                    rows={2}
                    value={composer}
                    onChange={(e) => setComposer(e.target.value)}
                    onKeyDown={(e) => {
                      if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
                        e.preventDefault();
                        void send();
                      }
                    }}
                    placeholder="Napiši odgovor posetiocu…  (Cmd/Ctrl + Enter za slanje)"
                    className="w-full resize-none bg-transparent px-2 py-1 text-sm text-foreground placeholder:text-muted-foreground/60 focus:outline-none"
                  />
                  <div className="flex items-center justify-between gap-2 px-1 pt-1">
                    <div className="flex items-center gap-2">
                      <div ref={emojiRef} className="relative">
                        <button
                          type="button"
                          onClick={() => setEmojiOpen((v) => !v)}
                          aria-label="Dodaj emotikon"
                          aria-expanded={emojiOpen}
                          className={`flex h-8 w-8 items-center justify-center rounded-full transition ${
                            emojiOpen
                              ? "bg-[#fff4ef] text-primary"
                              : "text-muted-foreground hover:bg-zinc-100 hover:text-primary"
                          }`}
                        >
                          {IcSmile}
                        </button>
                        {emojiOpen && (
                          <div className="absolute bottom-full left-0 z-50 mb-2 w-72 overflow-hidden rounded-2xl border border-border bg-white shadow-[0_24px_60px_rgba(12,24,40,0.18)]">
                            <div className="max-h-64 overflow-y-auto p-3">
                              {EMOJI_GROUPS.map((group) => (
                                <div key={group.label} className="mb-2 last:mb-0">
                                  <p className="mb-1 px-0.5 text-[0.6rem] font-extrabold uppercase tracking-[0.16em] text-muted-foreground">
                                    {group.label}
                                  </p>
                                  <div className="grid grid-cols-8 gap-0.5">
                                    {group.emojis.map((emoji) => (
                                      <button
                                        key={emoji}
                                        type="button"
                                        onClick={() => insertEmoji(emoji)}
                                        className="flex h-8 w-8 items-center justify-center rounded-lg text-lg leading-none transition hover:bg-zinc-100"
                                      >
                                        {emoji}
                                      </button>
                                    ))}
                                  </div>
                                </div>
                              ))}
                            </div>
                          </div>
                        )}
                      </div>
                      <button
                        type="button"
                        onClick={() => send(true)}
                        disabled={sending || composer.trim().length < 1}
                        className="text-xs font-bold text-muted-foreground transition hover:text-rose-600 disabled:opacity-40"
                      >
                        Pošalji i zatvori
                      </button>
                    </div>
                    <button
                      type="button"
                      onClick={() => send(false)}
                      disabled={sending || composer.trim().length < 1}
                      className="inline-flex items-center gap-2 rounded-xl bg-gradient-to-br from-[#c2410c] to-[#e2632f] px-5 py-2 text-sm font-bold text-white shadow-sm transition hover:brightness-105 disabled:opacity-40"
                    >
                      {IcSend}
                      {sending ? "Šaljem…" : "Pošalji"}
                    </button>
                  </div>
                </div>
              </div>
            ) : (
              <div className="flex items-center justify-center gap-2 border-t border-border bg-zinc-50 p-3 text-center text-xs font-semibold text-muted-foreground">
                <span className="text-zinc-400">{IcCheckSmall}</span>
                Sesija je zatvorena.
              </div>
            )}
          </>
        )}
      </section>
    </div>
  );
}
