/* ─────────────────────────────────────────────────────
   Equipment Balkans — Messages (inbox + chat thread)
   Mirrors apps/website/src/app/messages (conversation list + ChatRoom)
───────────────────────────────────────────────────── */
const { useState: useMsg, useEffect: useMsgEffect, useRef: useMsgRef } = React;

const SEED_CONVERSATIONS = [
  {
    id: "c-balkan",
    with: "Balkan Heavy Machinery",
    kind: "seller",
    avatar: "BH",
    color: "#1D4ED8",
    lot: "HAAS VF-4SS CNC Machining Center",
    lotId: "haas-vf4",
    online: true,
    messages: [
      { from: "them", text: "Hi — thanks for watching the HAAS VF-4SS. Happy to answer anything before the auction closes.", t: "-2h" },
      { from: "me", text: "Is an inspection possible before bidding? Want to check the spindle hours.", t: "-95m" },
      { from: "them", text: "Inspection available Tue–Fri before the HAAS auction closes. Spindle is at 4,200 hrs with full service folder.", t: "-25m" },
    ],
  },
  {
    id: "c-marko",
    with: "Marko Petrović",
    kind: "buyer",
    avatar: "M",
    color: "#2563EB",
    lot: "Caterpillar 320D L Excavator",
    lotId: "cat-320d",
    online: false,
    messages: [
      { from: "them", text: "Won the 320D — great machine. When can I arrange collection?", t: "-1d" },
      { from: "me", text: "Congratulations! Collection any weekday 8–4 from Belgrade, or I can quote managed transport.", t: "-1d" },
      { from: "them", text: "Transport quote please, delivering to Niš.", t: "-20h" },
    ],
  },
  {
    id: "c-adriatic",
    with: "Adriatic Tooling d.o.o.",
    kind: "seller",
    avatar: "AT",
    color: "#0EA5E9",
    lot: "Marketplace · CNC & metalworking",
    lotId: null,
    online: true,
    messages: [
      { from: "them", text: "We've listed three new lathes this week — let me know if you'd like first refusal.", t: "-3d" },
    ],
  },
];

const CANNED_REPLIES = [
  "Sounds good — I'll confirm the details and get back to you shortly.",
  "Noted. I'll prepare that and send it over within the hour.",
  "Thanks — happy to help. Anything else you'd like to know?",
];

function relMsgTime(t) {
  if (typeof t !== "string") return "";
  const m = t.match(/^-(\d+)([hmd])$/);
  if (!m) return t;
  const n = m[1], u = m[2];
  return u === "h" ? `${n}h ago` : u === "m" ? `${n}m ago` : `${n}d ago`;
}

function MessagesScreen({ user, onNav, openId }) {
  const [convos, setConvos] = useMsg(SEED_CONVERSATIONS);
  const [activeId, setActiveId] = useMsg(openId || (SEED_CONVERSATIONS[0] && SEED_CONVERSATIONS[0].id));
  const [draft, setDraft] = useMsg("");
  const threadRef = useMsgRef(null);
  const active = convos.find((c) => c.id === activeId) || null;

  useMsgEffect(() => {
    if (threadRef.current) threadRef.current.scrollTop = threadRef.current.scrollHeight;
  }, [activeId, active && active.messages.length]);

  const send = () => {
    const text = draft.trim();
    if (!text || !active) return;
    setConvos((prev) => prev.map((c) => (c.id === activeId ? { ...c, messages: [...c.messages, { from: "me", text, t: "now" }] } : c)));
    setDraft("");
    setTimeout(() => {
      setConvos((prev) => prev.map((c) => (c.id === activeId ? { ...c, messages: [...c.messages, { from: "them", text: CANNED_REPLIES[Math.floor(Math.random() * CANNED_REPLIES.length)], t: "now" }] } : c)));
    }, 1100);
  };

  return (
    <div style={{ maxWidth: 1180, margin: "0 auto", padding: "28px 24px 40px" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 18, flexWrap: "wrap", gap: 10 }}>
        <div>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 7, fontSize: 11, fontWeight: 800, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--cobalt)", marginBottom: 8 }}>
            <i data-lucide="message-circle" style={{ width: 14, height: 14 }}></i> Messages
          </span>
          <h1 style={{ fontFamily: "var(--ff-display)", fontSize: 34, fontWeight: 900, color: "var(--text)", textTransform: "uppercase", margin: 0, lineHeight: 1 }}>Your conversations</h1>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "320px 1fr", gap: 0, border: "1px solid var(--border)", borderRadius: 14, overflow: "hidden", height: 560, background: "var(--card-bg)" }} className="eb-msg-grid">
        {/* Conversation list */}
        <div style={{ borderRight: "1px solid var(--border)", overflowY: "auto", background: "var(--surface)" }} className="eb-msg-list">
          {convos.map((c) => {
            const last = c.messages[c.messages.length - 1];
            const on = c.id === activeId;
            return (
              <button key={c.id} onClick={() => setActiveId(c.id)} style={{ width: "100%", textAlign: "left", display: "flex", gap: 12, padding: "14px 16px", borderBottom: "1px solid var(--border)", background: on ? "var(--surface-2)" : "transparent", cursor: "pointer", position: "relative" }}>
                {on && <span style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 3, background: "var(--ignite)" }}></span>}
                <span style={{ position: "relative", flexShrink: 0 }}>
                  <span style={{ width: 42, height: 42, borderRadius: 9, background: c.color, color: "#fff", fontWeight: 800, fontSize: 15, display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--ff-display)" }}>{c.avatar}</span>
                  {c.online && <span style={{ position: "absolute", right: -2, bottom: -2, width: 12, height: 12, borderRadius: "50%", background: "#22C55E", border: "2px solid var(--surface)" }}></span>}
                </span>
                <span style={{ minWidth: 0, flex: 1 }}>
                  <span style={{ display: "flex", justifyContent: "space-between", gap: 8, alignItems: "baseline" }}>
                    <span style={{ fontWeight: 700, fontSize: 13.5, color: "var(--text)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.with}</span>
                    <span style={{ fontSize: 11, color: "var(--text-3)", flexShrink: 0 }}>{relMsgTime(last.t)}</span>
                  </span>
                  <span style={{ display: "block", fontSize: 11.5, color: "var(--text-3)", marginTop: 2, marginBottom: 3 }}>
                    <i data-lucide={c.kind === "seller" ? "store" : "user"} style={{ width: 11, height: 11, verticalAlign: "-1px", marginRight: 4 }}></i>{c.kind === "seller" ? "Seller" : "Buyer"} · {c.lot.length > 26 ? c.lot.slice(0, 26) + "…" : c.lot}
                  </span>
                  <span style={{ display: "block", fontSize: 12.5, color: "var(--text-2)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{last.from === "me" ? "You: " : ""}{last.text}</span>
                </span>
              </button>
            );
          })}
        </div>

        {/* Thread */}
        {active ? (
          <div style={{ display: "flex", flexDirection: "column", minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "13px 18px", borderBottom: "1px solid var(--border)", background: "var(--card-bg)" }}>
              <span style={{ width: 38, height: 38, borderRadius: 9, background: active.color, color: "#fff", fontWeight: 800, fontSize: 14, display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--ff-display)" }}>{active.avatar}</span>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ fontWeight: 700, fontSize: 14.5, color: "var(--text)" }}>{active.with}</div>
                <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>{active.online ? "Online now" : "Offline"} · {active.lot}</div>
              </div>
              {active.lotId && (
                <button onClick={() => onNav({ name: "detail", id: active.lotId })} style={{ ...ghostBtn, padding: "7px 13px", fontSize: 12.5 }}>
                  <i data-lucide="external-link" style={{ width: 14, height: 14 }}></i> View lot
                </button>
              )}
            </div>

            <div ref={threadRef} style={{ flex: 1, overflowY: "auto", padding: "20px 18px", display: "flex", flexDirection: "column", gap: 12, background: "var(--media-bg)" }}>
              {active.messages.map((m, i) => (
                <div key={i} style={{ alignSelf: m.from === "me" ? "flex-end" : "flex-start", maxWidth: "76%" }}>
                  <div style={{ background: m.from === "me" ? "var(--cobalt)" : "var(--surface-2)", color: m.from === "me" ? "#fff" : "var(--text)", padding: "10px 14px", borderRadius: m.from === "me" ? "12px 12px 4px 12px" : "12px 12px 12px 4px", fontSize: 13.5, lineHeight: 1.5 }}>{m.text}</div>
                  <div style={{ fontSize: 10.5, color: "var(--text-3)", marginTop: 4, textAlign: m.from === "me" ? "right" : "left" }}>{m.t === "now" ? "Just now" : relMsgTime(m.t)}</div>
                </div>
              ))}
            </div>

            <div style={{ display: "flex", gap: 10, padding: "13px 16px", borderTop: "1px solid var(--border)", background: "var(--card-bg)" }}>
              <input value={draft} onChange={(e) => setDraft(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") send(); }} placeholder="Write a message…" style={{ flex: 1, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 9, padding: "11px 14px", fontSize: 13.5, color: "var(--text)", outline: "none" }} />
              <button onClick={send} disabled={!draft.trim()} style={{ ...primaryBtn, opacity: draft.trim() ? 1 : 0.5, padding: "0 18px" }}>
                <i data-lucide="send" style={{ width: 16, height: 16 }}></i> Send
              </button>
            </div>
          </div>
        ) : (
          <div style={{ display: "flex", alignItems: "center", justifyContent: "center", color: "var(--text-3)", fontSize: 14 }}>Select a conversation</div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { MessagesScreen });
