// Inbox page — persisted conversation workflow

function InboxPage() {
  const hub = window.useClearCast();
  const [folder, setFolder] = React.useState("all");
  const [activeId, setActiveId] = React.useState(null);
  const [reply, setReply] = React.useState("");
  const [query, setQuery] = React.useState("");
  const [replyState, setReplyState] = React.useState("");

  const labels = [
    { id: "sales", label: "Sales lead", color: "var(--accent)" },
    { id: "support", label: "Support", color: "#3b82f6" },
    { id: "press", label: "Press", color: "#a78bfa" },
    { id: "ugc", label: "UGC", color: "#ec4899" },
  ];

  const messages = (hub.data.inbox || []).map((message) => ({
    ...message,
    type: message.type || (message.platform === "instagram" || message.platform === "facebook" ? "comments" : "dms"),
    status: message.status || "open",
    assignee: message.assignee || "Unassigned",
    archived: Boolean(message.archived),
    vip: Boolean(message.vip),
    draft: message.draft || "",
    replies: message.replies || []
  }));

  const filtered = messages
    .filter((message) => {
      if (folder === "archive") return message.archived;
      if (folder === "vip") return message.vip && !message.archived;
      if (["comments", "dms", "mentions", "reviews"].includes(folder)) return message.type === folder && !message.archived;
      return !message.archived;
    })
    .filter((message) => {
      const text = `${message.from} ${message.handle} ${message.text} ${message.label}`.toLowerCase();
      return !query.trim() || text.includes(query.trim().toLowerCase());
    });

  const counts = {
    all: messages.filter((message) => !message.archived).length,
    comments: messages.filter((message) => message.type === "comments" && !message.archived).length,
    dms: messages.filter((message) => message.type === "dms" && !message.archived).length,
    mentions: messages.filter((message) => message.type === "mentions" && !message.archived).length,
    reviews: messages.filter((message) => message.type === "reviews" && !message.archived).length,
    vip: messages.filter((message) => message.vip && !message.archived).length,
    archive: messages.filter((message) => message.archived).length
  };

  const folders = [
    { id: "all", label: "All", count: counts.all, ico: "Inbox" },
    { id: "comments", label: "Comments", count: counts.comments, ico: "Message" },
    { id: "dms", label: "Direct Messages", count: counts.dms, ico: "Mail" },
    { id: "mentions", label: "Mentions", count: counts.mentions, ico: "AtSign" },
    { id: "reviews", label: "Reviews", count: counts.reviews, ico: "Star" },
    { id: "vip", label: "VIP", count: counts.vip, ico: "Star" },
    { id: "archive", label: "Archived", count: counts.archive, ico: "Archive" },
  ];

  const cur = filtered.find((message) => message.id === activeId) || filtered[0] || messages[0];

  React.useEffect(() => {
    if (cur && activeId !== cur.id) {
      setActiveId(cur.id);
      setReply(cur.draft || "");
    }
  }, [cur?.id]);

  const updateConversation = async (payload, toast) => {
    if (!cur) return;
    await hub.actions.updateInbox(cur.id, payload, toast);
  };

  const sendReply = async () => {
    if (!cur) return;
    if (replyState) return;
    const text = (reply.trim() || (cur.draft || "").trim());
    if (!text) {
      hub.toast("Write a reply first");
      return;
    }
    setReplyState("send");
    try {
      await hub.actions.reply(cur.id, text);
      setReply("");
    } finally {
      setReplyState("");
    }
  };

  const saveDraft = async () => {
    if (replyState) return;
    setReplyState("draft");
    try {
      await updateConversation({ draft: reply }, "Reply draft saved");
    } finally {
      setReplyState("");
    }
  };

  const labelFor = (id) => labels.find((label) => label.id === id);
  const initials = (name = "") => name.split(" ").map((word) => word[0]).join("").slice(0, 2) || "CC";

  return (
    <div className="page mobile-inbox-page" style={{ padding: 0 }}>
      <div style={{ display: "grid", gridTemplateColumns: "220px 380px minmax(0, 1fr)", height: "calc(100vh - 72px)" }}>
        <div style={{ borderRight: "1px solid var(--border)", padding: "20px 12px", overflowY: "auto" }}>
          <div className="nav-section-label">Folders</div>
          {folders.map(f => {
            const Ico = Icon[f.ico];
            const active = folder === f.id;
            return (
              <button key={f.id} className={`nav-item ${active ? "active" : ""}`} onClick={() => setFolder(f.id)} style={{ marginBottom: 2 }}>
                <Ico className="ico" />
                <span>{f.label}</span>
                {f.count > 0 && <span className="nav-badge" style={{ background: active ? "var(--accent)" : "var(--elev)", color: active ? "#06120d" : "var(--text-2)" }}>{f.count}</span>}
              </button>
            );
          })}

          <div className="nav-section-label">Labels</div>
          {labels.map(l => (
            <button key={l.id} className="nav-item" onClick={() => setQuery(l.id)}>
              <span style={{ width: 10, height: 10, borderRadius: 3, background: l.color, marginLeft: 4 }}/>
              <span>{l.label}</span>
            </button>
          ))}

          <div className="nav-section-label">Channels</div>
          {["instagram", "facebook", "x", "tiktok", "linkedin", "youtube", "pinterest"].map(p => (
            <button key={p} className="nav-item" style={{ gap: 10 }} onClick={() => setQuery(p)}>
              <PlatformIcon id={p} size={18} />
              <span>{Platforms[p].name}</span>
            </button>
          ))}
        </div>

        <div style={{ borderRight: "1px solid var(--border)", display: "flex", flexDirection: "column" }}>
          <div style={{ padding: "16px 16px 10px", borderBottom: "1px solid var(--border)" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
              <div style={{ fontSize: 14, fontWeight: 600 }}>{folders.find(f => f.id === folder)?.label}</div>
              <div style={{ display: "flex", gap: 4 }}>
                <button className="btn btn-ghost" style={{ padding: 6 }} title="Filter" onClick={() => hub.toast("Type in the search box above to filter conversations")}><Icon.Filter width="14" height="14" /></button>
                <button className="btn btn-ghost" style={{ padding: 6 }} title="Refresh" onClick={hub.actions.refresh}><Icon.Refresh width="14" height="14" /></button>
              </div>
            </div>
            <div style={{ position: "relative" }}>
              <Icon.Search width="14" height="14" style={{ position: "absolute", left: 10, top: "50%", transform: "translateY(-50%)", color: "var(--text-3)" }}/>
              <input className="input" value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Search conversations" style={{ paddingLeft: 32, fontSize: 12.5 }}/>
            </div>
          </div>
          <div style={{ flex: 1, overflowY: "auto" }}>
            {filtered.map((th) => {
              const isActive = th.id === cur?.id;
              const lbl = labelFor(th.label);
              return (
                <button key={th.id} onClick={() => { setActiveId(th.id); setReply(th.draft || ""); if (th.unread) hub.actions.updateInbox(th.id, { unread: false }, "Marked as read"); }} style={{
                  width: "100%", textAlign: "left",
                  padding: "12px 16px",
                  borderBottom: "1px solid var(--border)",
                  background: isActive ? "var(--card-2)" : "transparent",
                  position: "relative",
                  display: "block",
                  borderLeft: isActive ? "2px solid var(--accent)" : "2px solid transparent",
                }}>
                  {th.unread && <div style={{ position: "absolute", left: 6, top: 18, width: 6, height: 6, borderRadius: 999, background: "var(--accent)" }}/>}
                  <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
                    <div style={{ position: "relative" }}>
                      <div className="avatar sz-36" style={{ background: "linear-gradient(135deg, #ffc8a3, #8c5a3a)", color: "white" }}>{initials(th.from)}</div>
                      <div style={{ position: "absolute", bottom: -2, right: -2, background: "var(--bg-2)", borderRadius: 6, padding: 1 }}>
                        <PlatformIcon id={th.platform} size={14} />
                      </div>
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 8 }}>
                        <div style={{ fontSize: 13, fontWeight: th.unread ? 600 : 500 }}>{th.from} {th.vip && <span style={{ color: "var(--warn)" }}>★</span>}</div>
                        <div style={{ fontSize: 11, color: "var(--text-3)", flexShrink: 0 }}>{th.status}</div>
                      </div>
                      <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>{th.handle} · {th.assignee}</div>
                      <div style={{ fontSize: 12.5, color: th.unread ? "var(--text)" : "var(--text-2)", marginTop: 4, overflow: "hidden", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical" }}>
                        {th.draft ? `Draft: ${th.draft}` : th.text}
                      </div>
                      {lbl && (
                        <div style={{ display: "inline-flex", alignItems: "center", gap: 5, marginTop: 6, padding: "2px 8px", borderRadius: 999, fontSize: 10.5, fontWeight: 600, background: `${lbl.color}22`, color: lbl.color }}>
                          <span style={{ width: 6, height: 6, borderRadius: 999, background: lbl.color }}/>
                          {lbl.label}
                        </div>
                      )}
                    </div>
                  </div>
                </button>
              );
            })}
            {!filtered.length && <div className="empty-note" style={{ margin: 16 }}>No conversations match this view.</div>}
          </div>
        </div>

        {cur ? (
          <div style={{ display: "flex", flexDirection: "column" }}>
            <div style={{ padding: "16px 24px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 12 }}>
              <div style={{ position: "relative" }}>
                <div className="avatar sz-40" style={{ background: "linear-gradient(135deg, #ffc8a3, #8c5a3a)", color: "white" }}>{initials(cur.from)}</div>
                <div style={{ position: "absolute", bottom: -2, right: -2, background: "var(--bg)", borderRadius: 6, padding: 1 }}>
                  <PlatformIcon id={cur.platform} size={14} />
                </div>
              </div>
              <div style={{ flex: 1, lineHeight: 1.2 }}>
                <div style={{ fontWeight: 600, fontSize: 14 }}>{cur.from}</div>
                <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>{cur.handle} · assigned to {cur.assignee}</div>
              </div>
              <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                <select className="input" value={cur.assignee} onChange={(event) => updateConversation({ assignee: event.target.value }, "Conversation assigned")} style={{ width: 130 }}>
                  <option>Unassigned</option>
                  <option>Emma</option>
                  <option>Maya</option>
                  <option>Jordan</option>
                  <option>Diego</option>
                </select>
                <select className="input" value={cur.status} onChange={(event) => updateConversation({ status: event.target.value }, "Status updated")} style={{ width: 120 }}>
                  <option value="open">Open</option>
                  <option value="pending">Pending</option>
                  <option value="replied">Replied</option>
                  <option value="closed">Closed</option>
                </select>
                <button className={`btn btn-sm ${cur.vip ? "btn-primary" : ""}`} onClick={() => updateConversation({ vip: !cur.vip }, cur.vip ? "Conversation removed from VIP" : "Conversation marked VIP")}><Icon.Star width="12" height="12" /> VIP</button>
                <button className="btn btn-sm" onClick={() => updateConversation({ archived: !cur.archived }, cur.archived ? "Conversation restored" : "Conversation archived")}><Icon.Archive width="12" height="12" /> {cur.archived ? "Restore" : "Archive"}</button>
              </div>
            </div>

            <div style={{ padding: "12px 24px", background: "var(--bg-2)", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 10 }}>
              <div style={{ width: 40, height: 40, borderRadius: 6, background: "linear-gradient(135deg, #d4b8a0, #846050)", flexShrink: 0 }}/>
              <div style={{ flex: 1, lineHeight: 1.25 }}>
                <div style={{ fontSize: 12, color: "var(--text-3)" }}>Replying on {Platforms[cur.platform]?.name || cur.platform}</div>
                <div style={{ fontSize: 12.5 }}>"{cur.text.slice(0, 72)}{cur.text.length > 72 ? "..." : ""}"</div>
              </div>
              <button className="btn btn-sm" onClick={() => hub.toast("Opening on the platform becomes available once that channel is connected")}><Icon.External width="12" height="12" /> Open</button>
            </div>

            <div style={{ flex: 1, overflowY: "auto", padding: "24px", display: "flex", flexDirection: "column", gap: 16 }}>
              <div style={{ textAlign: "center", fontSize: 11, color: "var(--text-3)" }}>{cur.status} · {cur.label || "unlabeled"}</div>
              <div style={{ display: "flex", gap: 10, alignItems: "flex-end" }}>
                <div className="avatar sz-28" style={{ background: "linear-gradient(135deg, #ffc8a3, #8c5a3a)", color: "white", fontSize: 10 }}>{initials(cur.from)}</div>
                <div style={{ background: "var(--card-2)", padding: "10px 14px", borderRadius: "14px 14px 14px 4px", maxWidth: 480, fontSize: 13, lineHeight: 1.5 }}>
                  {cur.text}
                </div>
              </div>
              {(cur.replies || []).map((item) => (
                <div key={item.id} style={{ display: "flex", justifyContent: "flex-end" }}>
                  <div style={{ background: "var(--accent-soft)", color: "var(--accent-2)", padding: "10px 14px", borderRadius: "14px 14px 4px 14px", maxWidth: 480, fontSize: 13, lineHeight: 1.5 }}>
                    {item.text}
                  </div>
                </div>
              ))}

              <div style={{ marginTop: 12, padding: 14, background: "var(--card)", border: "1px solid var(--border)", borderRadius: 12 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 10, fontSize: 12, color: "var(--accent-2)", fontWeight: 600 }}>
                  <Icon.Sparkles width="14" height="14" /> Suggested replies
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {[
                    "Thanks for reaching out. Happy to help.",
                    "Thanks for the note. We are checking on this and will follow up shortly.",
                    "Appreciate you sharing this. I will pass it to the team and come back with the next step.",
                  ].map((s, i) => (
                    <button key={i} onClick={() => setReply(s)} style={{ textAlign: "left", padding: "10px 12px", background: "var(--bg-2)", border: "1px solid var(--border)", borderRadius: 10, fontSize: 12.5, color: "var(--text-2)" }}>
                      {s}
                    </button>
                  ))}
                </div>
              </div>
            </div>

            <div className="inbox-reply-shell" style={{ padding: 16, borderTop: "1px solid var(--border)" }}>
              <div className="inbox-saved-replies">
                {(hub.data.savedReplies || []).map((r) => (
                  <button key={r.id} className="tb-chip" title={r.text} onClick={() => setReply(reply.trim() ? `${reply.trim()} ${r.text}` : r.text)}>{r.title}</button>
                ))}
                {reply.trim() && <button className="tb-chip" style={{ color: "var(--accent-2)" }} onClick={() => hub.actions.saveSavedReply({ text: reply.trim() })}>+ Save reply</button>}
              </div>
              <div style={{ background: "var(--bg-2)", border: "1px solid var(--border)", borderRadius: 12, padding: 12 }}>
                <textarea value={reply} onChange={(e) => setReply(e.target.value)} placeholder={`Reply to ${cur.from}...`} className="textarea" style={{ background: "transparent", border: "none", padding: 0, minHeight: 40, resize: "none" }}/>
                <div className="inbox-reply-actions" style={{ display: "flex", alignItems: "center", marginTop: 6 }}>
                  <div style={{ display: "flex", gap: 14, color: "var(--text-3)" }}>
                    <Icon.Smile width="16" height="16" />
                    <Icon.Image width="16" height="16" />
                    <Icon.Link width="16" height="16" />
                    <Icon.Sparkles width="16" height="16" style={{ color: "var(--accent-2)" }}/>
                  </div>
                  <div className="inbox-reply-buttons" style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
                    <button className="btn btn-sm" disabled={!!replyState} onClick={saveDraft}>{replyState === "draft" ? "Saving..." : "Save draft"}</button>
                    <button onClick={sendReply} disabled={!!replyState || !(reply.trim() || (cur?.draft || "").trim())} className="btn btn-primary btn-sm" style={{ padding: "6px 14px" }}>{replyState === "send" ? "Sending..." : "Send"} <Icon.Share width="12" height="12" /></button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        ) : (
          <div className="empty-note" style={{ margin: 24 }}>No conversation selected.</div>
        )}
      </div>
    </div>
  );
}

window.InboxPage = InboxPage;
