// ============================================================================
// public/screens/inbox.jsx — Unified Inbox (Phase 6B)
// ============================================================================

function InboxScreen() {
  const [threads, setThreads]   = React.useState(null);
  const [pagination, setPag]    = React.useState({});
  const [stats, setStats]       = React.useState(null);
  const [channel, setChannel]   = React.useState("all");
  const [status, setStatus]     = React.useState("open");
  const [search, setSearch]     = React.useState("");
  const [activeThread, setActiveThread] = React.useState(null);
  const [messages, setMessages] = React.useState([]);
  const [reply, setReply]       = React.useState("");

  const load = React.useCallback(async (page = 1) => {
    const p = new URLSearchParams({ page, limit: 25, channel, status });
    if (search) p.set("search", search);
    const r = await VoaisAPI.get("/api/inbox?" + p.toString());
    if (r.ok && r.data?.ok) { setThreads(r.data.threads); setPag(r.data.pagination); }
  }, [channel, status, search]);

  const loadStats = React.useCallback(async () => {
    const r = await VoaisAPI.get("/api/inbox/stats");
    if (r.ok && r.data?.ok) setStats(r.data);
  }, []);

  React.useEffect(() => { load(); loadStats(); }, [load, loadStats]);

  const openThread = async (id) => {
    const r = await VoaisAPI.get("/api/inbox/" + id);
    if (r.ok && r.data?.ok) { setActiveThread(r.data.thread); setMessages(r.data.messages); loadStats(); }
  };

  const sendReply = async () => {
    if (!reply.trim() || !activeThread) return;
    await VoaisAPI.post("/api/inbox/" + activeThread.id + "/reply", { content: reply });
    setReply(""); openThread(activeThread.id);
  };

  const updateThread = async (id, fields) => {
    await VoaisAPI.patch("/api/inbox/" + id, fields);
    if (activeThread?.id === id) openThread(id);
    load();
  };

  if (threads === null) return <DashboardSkeleton/>;

  const channelIcon = { call: I.phone, whatsapp: I.whatsapp, email: I.email, sms: I.message, web: I.globe };

  return (
    <div style={{ display: "flex", gap: 0, height: "calc(100vh - 140px)" }}>

      {/* Left: thread list */}
      <div style={{ width: 380, borderRight: "1px solid var(--line)", display: "flex", flexDirection: "column", flexShrink: 0 }}>
        {/* Channel tabs */}
        <div style={{ display: "flex", gap: 4, padding: "8px 12px", borderBottom: "1px solid var(--line)", flexWrap: "wrap" }}>
          {["all", "call", "whatsapp", "email"].map(ch => (
            <button key={ch} className={`btn btn-ghost sm ${channel === ch ? "active" : ""}`}
              style={{ fontSize: 12, background: channel === ch ? "var(--accent-soft)" : "transparent" }}
              onClick={() => setChannel(ch)}>
              {ch === "all" ? "All" : ch.charAt(0).toUpperCase() + ch.slice(1)}
              {stats && ch !== "all" && (() => {
                const s = stats.byChannel?.find(b => b.channel === ch);
                return s?.unread > 0 ? <span style={{ marginLeft: 4, color: "var(--accent)", fontWeight: 600 }}>{s.unread}</span> : null;
              })()}
              {stats && ch === "all" && stats.all?.unread > 0 && <span style={{ marginLeft: 4, color: "var(--accent)", fontWeight: 600 }}>{stats.all.unread}</span>}
            </button>
          ))}
        </div>

        {/* Search */}
        <div style={{ padding: "8px 12px" }}>
          <div style={{ position: "relative" }}>
            <I.search size={14} style={{ position: "absolute", left: 10, top: "50%", transform: "translateY(-50%)", color: "var(--ink-3)" }}/>
            <input className="input" placeholder="Search conversations..." value={search}
              onChange={e => setSearch(e.target.value)} onKeyDown={e => { if (e.key === "Enter") load(); }}
              style={{ paddingLeft: 32, fontSize: 12 }}/>
          </div>
        </div>

        {/* Thread list */}
        <div style={{ flex: 1, overflowY: "auto" }}>
          {threads.map(t => {
            const ChIcon = channelIcon[t.channel] || I.message;
            const isActive = activeThread?.id === t.id;
            return (
              <div key={t.id} onClick={() => openThread(t.id)} style={{
                padding: "12px 14px", cursor: "pointer", borderBottom: "1px solid var(--line)",
                background: isActive ? "var(--accent-soft)" : t.unread_count > 0 ? "var(--surface-2)" : "transparent",
              }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <ChIcon size={14} style={{ color: "var(--ink-3)", flexShrink: 0 }}/>
                  <span style={{ fontSize: 13, fontWeight: t.unread_count > 0 ? 600 : 400, flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {t.display_name || t.phone || t.email || "Unknown"}
                  </span>
                  {t.unread_count > 0 && <span style={{ minWidth: 18, height: 18, borderRadius: 9, background: "var(--accent)", color: "#fff", fontSize: 10, fontWeight: 600, display: "grid", placeItems: "center" }}>{t.unread_count}</span>}
                  {t.pinned ? <I.pin size={12} style={{ color: "var(--accent)" }}/> : null}
                </div>
                <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                  {t.last_message_preview || "No messages"}
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 4 }}>
                  {t.intent && t.intent !== "unset" && <Badge tone={t.intent === "hot" ? "red" : t.intent === "warm" ? "yellow" : "gray"}>{t.intent}</Badge>}
                  <span style={{ fontSize: 10, color: "var(--ink-3)", flex: 1, textAlign: "right" }}>
                    {t.last_message_at ? timeAgoShort(t.last_message_at) : ""}
                  </span>
                </div>
              </div>
            );
          })}
          {threads.length === 0 && <div style={{ padding: 32, textAlign: "center", color: "var(--ink-3)", fontSize: 13 }}>No conversations found.</div>}
        </div>
      </div>

      {/* Right: thread detail / empty state */}
      <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
        {!activeThread ? (
          <div style={{ flex: 1, display: "grid", placeItems: "center" }}>
            <div style={{ textAlign: "center", color: "var(--ink-3)" }}>
              <I.inbox size={40} style={{ opacity: 0.3, marginBottom: 12 }}/>
              <div style={{ fontSize: 15, fontWeight: 600 }}>Select a conversation</div>
              <div style={{ fontSize: 13, marginTop: 4 }}>Pick a thread from the left to view messages.</div>
            </div>
          </div>
        ) : (
          <>
            {/* Thread header */}
            <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 10 }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 15, fontWeight: 600 }}>{activeThread.display_name || activeThread.phone || "Unknown"}</div>
                <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{activeThread.phone || ""} · {activeThread.channel}</div>
              </div>
              <Btn kind="ghost" size="sm" onClick={() => updateThread(activeThread.id, { pinned: activeThread.pinned ? 0 : 1 })}>
                <I.pin size={13}/> {activeThread.pinned ? "Unpin" : "Pin"}
              </Btn>
              <Btn kind="ghost" size="sm" onClick={() => updateThread(activeThread.id, { status: "closed" })}>
                <I.check size={13}/> Close
              </Btn>
            </div>

            {/* Messages */}
            <div style={{ flex: 1, overflowY: "auto", padding: 16, display: "flex", flexDirection: "column", gap: 6 }}>
              {messages.map((m, i) => (
                <div key={i} style={{
                  padding: "8px 12px", borderRadius: 10, fontSize: 13, lineHeight: 1.6, maxWidth: "75%",
                  background: m.direction === "outbound" ? "var(--accent-soft)" : "var(--surface-2)",
                  alignSelf: m.direction === "outbound" ? "flex-end" : "flex-start",
                }}>
                  <div style={{ fontSize: 11, fontWeight: 600, color: "var(--ink-3)", marginBottom: 2 }}>
                    {m.from_role === "contact" || m.from_role === "caller" ? (activeThread.display_name || "Contact") : m.from_role === "ai" ? "AI" : "You"}
                  </div>
                  {m.content}
                  <div style={{ fontSize: 10, color: "var(--ink-3)", marginTop: 2, textAlign: "right" }}>
                    {m.created_at ? new Date(m.created_at).toLocaleTimeString("en-IN", { hour: "2-digit", minute: "2-digit" }) : ""}
                    {m.status && m.direction === "outbound" && <span style={{ marginLeft: 6 }}>{m.status === "read" ? "✓✓" : m.status === "delivered" ? "✓✓" : m.status === "sent" ? "✓" : ""}</span>}
                  </div>
                </div>
              ))}
              {messages.length === 0 && <div style={{ textAlign: "center", color: "var(--ink-3)", padding: 32, fontSize: 13 }}>No messages in this thread.</div>}
            </div>

            {/* Reply box */}
            <div style={{ padding: "12px 16px", borderTop: "1px solid var(--line)", display: "flex", gap: 8 }}>
              <input className="input" style={{ flex: 1 }} placeholder="Type a message..." value={reply}
                onChange={e => setReply(e.target.value)} onKeyDown={e => { if (e.key === "Enter") sendReply(); }}/>
              <Btn kind="primary" icon={<I.send size={14}/>} onClick={sendReply} disabled={!reply.trim()}>Send</Btn>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function timeAgoShort(d) { const s = Math.floor((Date.now()-new Date(d).getTime())/1000); if(s<60) return "now"; if(s<3600) return Math.floor(s/60)+"m"; if(s<86400) return Math.floor(s/3600)+"h"; return Math.floor(s/86400)+"d"; }

window.InboxScreen = InboxScreen;
