/* COMMS INBOX — lead list + threaded conversation + pinned draft. window.SCREENS.Inbox */
(function () {
  const { useState, useRef, useEffect } = React;
  const I = window.ICONS;
  const { Avatar, LoanMeta, ChannelChip, Pill, Btn } = window.UI;
  const { leadById, threads, drafts } = window.DATA;

  // lead ids that actually have conversation threads (from the live data)
  const THREAD_ORDER = Object.keys(threads || {});

  function lastMsg(id) {
    const t = threads[id] || [];
    return t[t.length - 1];
  }
  function draftFor(id, pool) { return pool.find(d => d.leadId === id); }

  // Sanitize email/borrower HTML before rendering (XSS protection via DOMPurify).
  if (window.DOMPurify && !window.__ccPurifyHook) {
    window.__ccPurifyHook = true;
    window.DOMPurify.addHook("afterSanitizeAttributes", function (node) {
      if (node.tagName === "A") { node.setAttribute("target", "_blank"); node.setAttribute("rel", "noopener noreferrer"); }
      if (node.tagName === "IMG") { node.setAttribute("loading", "lazy"); }
    });
  }
  function renderEmail(html) {
    if (window.DOMPurify) return window.DOMPurify.sanitize(html || "", { ADD_ATTR: ["target"] });
    const d = document.createElement("div"); d.textContent = html || ""; return d.innerHTML; // fallback: escape to text
  }
  function stripTags(s) {
    return (s || "").replace(/<style[\s\S]*?<\/style>/gi, " ").replace(/<[^>]+>/g, " ").replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/\s+/g, " ").trim();
  }

  // Render an SMS body: plain text, with URLs linkified and trusted (Bonzo) image URLs shown inline.
  // Builds React nodes (auto-escaped); only http(s) URLs become href/src, so no javascript: injection.
  function renderSmsBody(text) {
    const urlRe = /(https?:\/\/\S+)/gi;
    const isImg = (u) => /\.(?:jpg|jpeg|png|gif|heic|webp)(?:\?|$)/i.test(u);
    const trusted = (u) => { try { return /(?:^|\.)getbonzo\.com$|amazonaws\.com$/i.test(new URL(u).host); } catch { return false; } };
    return (text || "").split(urlRe).map((p, i) => {
      if (!/^https?:\/\//i.test(p)) return p;
      const clean = p.replace(/[)\].,]+$/, "");
      if (isImg(clean) && trusted(clean)) {
        return <a key={i} href={clean} target="_blank" rel="noopener noreferrer"><img src={clean} alt="attachment" loading="lazy" style={{ maxWidth: "100%", maxHeight: 320, marginTop: 6, display: "block" }} /></a>;
      }
      return <a key={i} href={clean} target="_blank" rel="noopener noreferrer" style={{ color: "inherit", textDecoration: "underline", wordBreak: "break-all" }}>{clean}</a>;
    });
  }

  function EmailMsg({ m }) {
    const me = m.from === "me";
    return (
      <div style={{ display: "flex", justifyContent: me ? "flex-end" : "flex-start" }}>
        <div style={{ width: "100%", maxWidth: 640 }}>
          <div className="eyebrow" style={{ marginBottom: 5, color: "var(--gold)", textAlign: me ? "right" : "left" }}>✉ Email{me ? " · sent" : " · received"}</div>
          <div className="email-body" dangerouslySetInnerHTML={{ __html: renderEmail(m.text) }} />
          <div className="mono" style={{ fontSize: 9.5, color: "var(--ink-faint)", marginTop: 4, textAlign: me ? "right" : "left" }}>{m.time}{me && m.status === "sent" ? " · Sent" : ""}</div>
        </div>
      </div>
    );
  }

  function Bubble({ m }) {
    const me = m.from === "me";
    return (
      <div style={{ display: "flex", justifyContent: me ? "flex-end" : "flex-start" }}>
        <div style={{ maxWidth: "72%" }}>
          <div style={{
            padding: "10px 14px", fontSize: 14.5, lineHeight: 1.5, whiteSpace: "pre-wrap",
            background: me ? "var(--green)" : "var(--bg-2)",
            color: me ? "var(--ink)" : "var(--ink)",
            border: me ? "1px solid var(--green)" : "1px solid var(--line)",
            borderRadius: me ? "16px 16px 4px 16px" : "16px 16px 16px 4px",
          }}>{renderSmsBody(m.text)}</div>
          <div className="mono" style={{ fontSize: 9.5, color: "var(--ink-faint)", marginTop: 4, textAlign: me ? "right" : "left", letterSpacing: "0.08em" }}>
            {m.time}{me && m.status === "sent" ? " · Sent" : ""}
          </div>
        </div>
      </div>
    );
  }

  function Inbox({ pool, onApprove, onReject, sentExtra }) {
    const [sel, setSel] = useState(THREAD_ORDER[0] || null);
    const [manualText, setManualText] = useState("");
    const [localSent, setLocalSent] = useState([]);
    const [hint, setHint] = useState("");
    const bodyRef = useRef(null);

    const lead = leadById[sel];
    const thread = threads[sel] || [];
    const extra = sentExtra[sel] || [];
    const d = draftFor(sel, pool);

    useEffect(() => { if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight; }, [sel, extra.length, localSent.length]);
    useEffect(() => { setManualText(""); setLocalSent([]); setHint(""); }, [sel]);

    if (!THREAD_ORDER.length || !lead) {
      return (
        <div className="page">
          <div className="panel empty">
            <div className="empty-mark"><I.inbox width={24} height={24} /></div>
            <div className="display" style={{ fontSize: 32 }}>Inbox empty</div>
            <div style={{ color: "var(--ink-soft)", maxWidth: 340 }}>No client conversations are loaded right now.</div>
          </div>
        </div>
      );
    }

    return (
      <div style={{ display: "grid", gridTemplateColumns: "300px minmax(0,1fr)", height: "100%", minHeight: 0 }}>
        {/* LEFT: lead list */}
        <div style={{ borderRight: "1px solid var(--line)", display: "flex", flexDirection: "column", minHeight: 0 }}>
          <div style={{ padding: "13px 16px", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <span className="eyebrow">Conversations</span>
            <Pill kind="sent">{THREAD_ORDER.filter(id => { const lm = lastMsg(id); return lm && lm.unread; }).length} unread</Pill>
          </div>
          <div className="hide-scroll" style={{ overflowY: "auto", flex: 1 }}>
            {THREAD_ORDER.map(id => {
              const l = leadById[id], lm = lastMsg(id);
              if (!l) return null;
              const ex = sentExtra[id] || [];
              const preview = ex.length ? ex[ex.length - 1].text : (lm ? (lm.html ? stripTags(lm.text) : lm.text) : "");
              const unread = lm && lm.unread && !ex.length;
              return (
                <div key={id} onClick={() => { setSel(id); setEditing(false); }}
                  style={{ display: "flex", gap: 12, padding: "13px 16px", cursor: "pointer", borderBottom: "1px solid var(--line)",
                    background: sel === id ? "var(--bg-2)" : "transparent", position: "relative" }}>
                  {sel === id && <span style={{ position: "absolute", left: 0, top: 10, bottom: 10, width: 2, background: "var(--green-lift)" }}></span>}
                  <Avatar init={l.init} size={36} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
                      <span style={{ fontSize: 13.5, fontWeight: unread ? 600 : 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{l.name}</span>
                      <span className="mono" style={{ fontSize: 9.5, color: "var(--ink-faint)", flexShrink: 0 }}>{lm ? lm.time : ""}</span>
                    </div>
                    <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 3 }}>
                      <span style={{ flex: 1, minWidth: 0, fontSize: 12.5, color: unread ? "var(--ink)" : "var(--ink-faint)",
                        whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{preview}</span>
                      {unread && <span className="unread-dot"></span>}
                    </div>
                    <div className="mono" style={{ fontSize: 9, color: "var(--ink-ghost)", marginTop: 4, letterSpacing: "0.06em", textTransform: "uppercase" }}>{l.loan} · {l.stage}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* RIGHT: conversation */}
        <div style={{ display: "flex", flexDirection: "column", minHeight: 0, minWidth: 0 }}>
          {/* context header */}
          <div style={{ padding: "13px 20px", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 13 }}>
            <Avatar init={lead.init} size={38} gold />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 15.5, fontWeight: 600 }}>{lead.name}</div>
              <LoanMeta lead={lead} />
            </div>
            <Pill kind={lead.days >= 7 ? "reject" : lead.days === 0 ? "sent" : "plain"}>
              {lead.days === 0 ? "Active today" : `${lead.days}d since contact`}
            </Pill>
            <button className="icon-btn" title="Call"><I.phone /></button>
          </div>

          {/* thread body */}
          <div ref={bodyRef} className="hide-scroll" style={{ flex: 1, overflowY: "auto", padding: "20px 22px", display: "flex", flexDirection: "column", gap: 12 }}>
            <div className="eyebrow" style={{ textAlign: "center", color: "var(--ink-ghost)", margin: "0 0 4px" }}>— SMS thread · {lead.phone} —</div>
            {thread.map((m, i) => m.html ? <EmailMsg key={i} m={m} /> : <Bubble key={i} m={m} />)}
            {extra.map((m, i) => <Bubble key={"x" + i} m={m} />)}
            {localSent.map((m, i) => <Bubble key={"l" + i} m={m} />)}
          </div>

          {/* compose — type your reply, or have AI draft one into the box to edit/send/regenerate */}
          <div style={{ borderTop: "1px solid var(--line)", background: "var(--bg-1)", padding: "14px 20px" }}>
            <textarea className="field" rows={3} placeholder="Type your reply… or let AI draft one for you" value={manualText} onChange={e => { setManualText(e.target.value); if (hint) setHint(""); }} style={{ marginBottom: 10 }} />
            <div style={{ display: "flex", gap: 9, justifyContent: "space-between", alignItems: "center" }}>
              <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
                <Btn sm kind="ghost-gold" icon={I.bolt} onClick={() => { if (d) { setManualText(d.draft); setHint(""); } else { setHint("On-demand AI drafting connects in Phase 2 — no queued draft for this lead yet."); } }}>{manualText ? "Draft again" : "Draft with AI"}</Btn>
                {manualText && <button onClick={() => setManualText("")} className="mono" style={{ background: "none", border: "none", color: "var(--ink-faint)", fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", cursor: "pointer" }}>Clear</button>}
              </div>
              <Btn sm kind="primary" icon={I.send} disabled={!manualText.trim()} onClick={() => { const t = manualText.trim(); if (!t) return; setLocalSent(p => [...p, { from: "me", text: t, time: "Now", status: "sent" }]); setManualText(""); }}>Send</Btn>
            </div>
            {hint && <div className="mono" style={{ fontSize: 10.5, color: "var(--ink-faint)", marginTop: 8 }}>{hint}</div>}
          </div>
        </div>
      </div>
    );
  }

  window.SCREENS = window.SCREENS || {};
  window.SCREENS.Inbox = Inbox;
})();
