// ============ INBOX TAB ============
// 2-column shared inbox: left list of customer threads, right transcript pane.
// "Take over" pauses the agent on a thread so you can reply as yourself.
// Threads are owned by app.jsx (so the dashboard can append a thread when
// a new agent is hired); we read + mutate them via the threads / setThreads
// props.

const IX_SERVER = () =>
  (typeof window !== "undefined" && window.CITRUS_CONFIG && window.CITRUS_CONFIG.SERVER_URL) ||
  "http://localhost:3001";

function InboxTab({ agents, threads, setThreads }) {
  const threadsState = threads || [];
  const byId = Object.fromEntries(agents.map(a => [a.id, a]));
  const [filter, setFilter]       = useState("all");
  const [openId, setOpenId]       = useState(threadsState[0] ? threadsState[0].id : null);
  const [takenOver, setTakenOver] = useState({});
  const [draft, setDraft]         = useState("");
  const [moreOpen, setMoreOpen]   = useState(false);
  const [nameMap, setNameMap]     = useState({});

  // Resolve raw customer IDs (tg:123, tgm:123, +1234567890) to known names.
  useEffect(() => {
    fetch(`${IX_SERVER()}/customers/memory`)
      .then(r => r.json())
      .then(data => {
        const map = {};
        for (const p of data.profiles || []) {
          if (p.name) map[p.from] = p.name;
        }
        setNameMap(map);
      })
      .catch(() => {});
  }, []);

  const resolvedName = (rawId) => nameMap[rawId] || null;
  // Teach state — which message index has the inline correction input open,
  // and the current draft. Lets you flag any agent reply that's wrong and
  // turn your one-line note into a durable agent learning.
  const [teachIdx, setTeachIdx]   = useState(null);
  const [teachNote, setTeachNote] = useState("");
  const [teachBusy, setTeachBusy] = useState(false);

  const submitTeach = (msgIdx) => {
    if (!teachNote.trim()) { window.toast && window.toast("Write what was wrong", "warn"); return; }
    if (!open || !openAgent) return;
    setTeachBusy(true);
    const tx = open.transcript || [];
    const start = Math.max(0, msgIdx - 2);
    const ctx = tx.slice(start, msgIdx + 1)
      .map((m) => `${m.from === "customer" ? "CUSTOMER" : m.from === "you" ? "YOU" : openAgent.name.toUpperCase()}: ${m.text || ""}`)
      .join("\n");
    fetch(`${IX_SERVER()}/agents/${openAgent.id}/teach`, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ note: teachNote, context: ctx }),
    })
      .then((r) => r.ok ? r.json() : r.json().then((j) => Promise.reject(j)))
      .then(() => {
        window.toast && window.toast(`${openAgent.name} just learned from that`, "good");
        setTeachIdx(null);
        setTeachNote("");
      })
      .catch((err) => window.toast && window.toast(err.error || "Couldn't save the correction", "warn"))
      .finally(() => setTeachBusy(false));
  };

  // Keep openId pointing at a thread that exists. When a new thread is
  // prepended (e.g., a new agent's seeded thread), surface it as the open
  // one so the user lands on it.
  useEffect(() => {
    if (threadsState.length === 0) { setOpenId(null); return; }
    if (!threadsState.some(t => t.id === openId)) setOpenId(threadsState[0].id);
  }, [threadsState.length, threadsState[0] && threadsState[0].id]);

  // Clear the unread dot when a thread is opened.
  const openThread = (id) => {
    setOpenId(id);
    setThreads((xs) => xs.map((x) => x.id === id ? { ...x, unread: false } : x));
  };

  const visibleThreads = filter === "all"
    ? threadsState
    : filter === "needs-you"
      ? threadsState.filter(t => t.status === "needs-you")
      : threadsState.filter(t => t.agent === filter);

  const open       = threadsState.find(t => t.id === openId) || visibleThreads[0];
  const openAgent  = open ? byId[open.agent] : null;
  const isTaken    = open && takenOver[open.id];

  const send = () => {
    if (!draft.trim() || !open) return;
    const now = new Date();
    const t = `${(now.getHours() % 12 || 12)}:${String(now.getMinutes()).padStart(2, "0")}`;
    const from = isTaken ? "you" : open.agent;
    setThreads((xs) => xs.map((x) =>
      x.id !== open.id ? x : {
        ...x,
        last: draft.trim(),
        time: "now",
        unread: false,
        status: x.status === "needs-you" ? "handled" : x.status,
        transcript: [...x.transcript, { from, text: draft.trim(), t }],
      }
    ));
    setDraft("");
  };
  const markUnread = () => {
    setThreads((xs) => xs.map((x) => x.id === open.id ? { ...x, unread: true } : x));
    setMoreOpen(false);
    window.toast("Marked unread", "info");
  };
  const archiveThread = () => {
    if (!window.confirm("Archive this conversation?")) return;
    const SERVER_URL = (window.CITRUS_CONFIG && window.CITRUS_CONFIG.SERVER_URL) || "http://localhost:3001";
    fetch(`${SERVER_URL}/conversations/${encodeURIComponent(open.id)}`, { method: "DELETE" })
      .catch(() => {}); // best-effort; remove locally regardless
    setThreads((xs) => xs.filter((x) => x.id !== open.id));
    setMoreOpen(false);
    window.toast("Conversation archived", "warn");
  };

  return (
    <div className="ix-page">
      <div className="ix-list">
        <div className="ix-filters">
          <button className={`ix-filter ${filter === "all" ? "is-on" : ""}`} onClick={() => setFilter("all")}>All</button>
          <button className={`ix-filter ${filter === "needs-you" ? "is-on" : ""}`} onClick={() => setFilter("needs-you")}>
            Needs you <span className="ix-filter-c">{threadsState.filter(t => t.status === "needs-you").length}</span>
          </button>
          {agents.filter(a => threadsState.some(t => t.agent === a.id)).map(a => (
            <button key={a.id} className={`ix-filter ${filter === a.id ? "is-on" : ""}`} onClick={() => setFilter(a.id)}>
              <span className="ix-filter-dot" style={{ background: a.palette.skin }} /> {a.name}
            </button>
          ))}
        </div>
        <div className="ix-threads">
          {visibleThreads.length === 0 ? (
            <div className="ix-empty" style={{ padding: "20px" }}>
              {threadsState.length === 0 ? "No threads yet." : "No conversations match this filter."}
            </div>
          ) : null}
          {visibleThreads.map(t => {
            const a = byId[t.agent];
            return (
              <button
                key={t.id}
                className={`ix-thread ${openId === t.id ? "is-open" : ""} ${t.unread ? "is-unread" : ""}`}
                onClick={() => openThread(t.id)}
              >
                <div className="ix-thread-side" style={{ background: a.palette.skin }} />
                <div className="ix-thread-body">
                  <div className="ix-thread-top">
                    <span className="ix-thread-name">{resolvedName(t.customer) || t.customer}</span>
                    <span className="ix-thread-time">{t.time}</span>
                  </div>
                  {resolvedName(t.customer) && (
                    <div className="ix-thread-id">{t.customer}</div>
                  )}
                  <div className="ix-thread-meta">
                    <span className="ix-thread-channel">{t.channel}</span>
                    <span className="ix-thread-sep">·</span>
                    <span className="ix-thread-agent">{a.name}</span>
                    {t.status === "needs-you" ? <span className="ix-thread-pip">needs you</span> : null}
                  </div>
                  <div className="ix-thread-last">{t.last}</div>
                  <div className="ix-thread-tag">{t.tag}</div>
                </div>
              </button>
            );
          })}
        </div>
      </div>

      <div className="ix-pane">
        {open ? (
          <>
            <div className="ix-pane-head">
              <div>
                <div className="ix-pane-name">{resolvedName(open.customer) || open.customer}</div>
                {resolvedName(open.customer) && (
                  <div className="ix-pane-id">{open.customer}</div>
                )}
                <div className="ix-pane-sub">
                  <span className="ix-mark" style={{ background: openAgent.palette.skin }}>{openAgent.name[0]}</span>
                  {openAgent.name} · {open.channel}
                  {isTaken ? <span className="ix-takeover-pill">you've taken over</span> : null}
                </div>
              </div>
              <div className="ix-pane-cta">
                {!isTaken ? (
                  <button className="btn btn-ghost btn-sm" onClick={() => setTakenOver({ ...takenOver, [open.id]: true })}>
                    Take over
                  </button>
                ) : (
                  <button className="btn btn-ghost btn-sm" onClick={() => setTakenOver({ ...takenOver, [open.id]: false })}>
                    Hand back to {openAgent.name}
                  </button>
                )}
                <div className="ix-more-wrap">
                  <button className="ix-pane-icon" title="More" onClick={() => setMoreOpen((v) => !v)}>⋯</button>
                  {moreOpen ? (
                    <div className="ix-more-menu" onMouseLeave={() => setMoreOpen(false)}>
                      <button className="ix-more-item" onClick={markUnread}>Mark unread</button>
                      <button className="ix-more-item ix-more-item-danger" onClick={archiveThread}>Archive thread</button>
                    </div>
                  ) : null}
                </div>
              </div>
            </div>
            <div className="ix-transcript">
              {open.transcript.map((m, i) => {
                const isCustomer = m.from === "customer";
                const isYou      = m.from === "you";
                const isAgent    = !isCustomer && !isYou;
                const bg = isCustomer ? null : (isYou ? "#1A120B" : openAgent.palette.skin);
                const label = isCustomer ? (resolvedName(open.customer) || open.customer) : (isYou ? "You" : openAgent.name);
                const isTeaching = teachIdx === i;
                return (
                  <div key={i} className={`ix-msg ix-msg-${isCustomer ? "in" : "out"}`}>
                    <div className="ix-msg-sender" style={{
                      fontSize: 11, fontWeight: 600, color: "var(--ink-soft, #888)",
                      marginBottom: 2, padding: "0 6px",
                    }}>
                      {label}
                    </div>
                    <div
                      className="ix-msg-bubble"
                      dir="auto"
                      style={!isCustomer ? { background: bg, color: "#fff" } : null}
                    >
                      {m.text}
                    </div>
                    <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "0 6px" }}>
                      <div className="ix-msg-time">{m.t}</div>
                      {isAgent && !isTeaching && (
                        <button
                          onClick={() => { setTeachIdx(i); setTeachNote(""); }}
                          title="Teach the agent what was wrong with this reply"
                          style={{
                            background: "transparent", border: "none", cursor: "pointer",
                            fontSize: 11, color: "var(--ink-soft, #888)", padding: 0,
                          }}
                        >👎 teach</button>
                      )}
                    </div>
                    {isTeaching && (
                      <div style={{ marginTop: 6, display: "flex", gap: 6, alignItems: "stretch" }}>
                        <input
                          autoFocus
                          type="text"
                          placeholder="What was wrong / what should it have done instead?"
                          value={teachNote}
                          onChange={(e) => setTeachNote(e.target.value)}
                          onKeyDown={(e) => {
                            if (e.key === "Enter") submitTeach(i);
                            if (e.key === "Escape") { setTeachIdx(null); setTeachNote(""); }
                          }}
                          style={{
                            flex: 1, padding: "6px 10px", fontSize: 12,
                            border: "1px solid var(--border, #c0c0c0)", borderRadius: 6,
                          }}
                        />
                        <button
                          onClick={() => submitTeach(i)}
                          disabled={teachBusy}
                          className="btn btn-primary btn-sm"
                          style={{ opacity: teachBusy ? 0.5 : 1 }}
                        >{teachBusy ? "…" : "Save"}</button>
                        <button
                          onClick={() => { setTeachIdx(null); setTeachNote(""); }}
                          className="btn btn-ghost btn-sm"
                        >Cancel</button>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
            <div className="ix-composer">
              <textarea
                className="ix-composer-input"
                placeholder={isTaken ? `Reply as you…` : `Reply as ${openAgent.name} (or take over)`}
                value={draft}
                onChange={(e) => setDraft(e.target.value)}
                onKeyDown={(e) => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); send(); } }}
                rows={2}
              />
              <div className="ix-composer-cta">
                <span className="ix-composer-hint">{isTaken ? "Sending as you" : `Sending as ${openAgent.name}`} · ⌘↵ to send</span>
                <button className="btn btn-primary btn-sm" onClick={send} disabled={!draft.trim()}>Send</button>
              </div>
            </div>
          </>
        ) : (
          <div className="ix-empty">
            {threadsState.length === 0
              ? "No conversations yet. Once you hire an agent and connect WhatsApp / Email, customer threads will land here."
              : "No conversations match."}
          </div>
        )}
      </div>
    </div>
  );
}

window.InboxTab = InboxTab;
