﻿// 用户端动态页面
var _a = React.useState, _b = React.useEffect;
var useState = _a, useEffect = _b;

var h = React.createElement;

// ===== 时间格式化 =====
function formatTime(dateStr) {
  if (!dateStr) return "-";
  var now = Date.now();
  var dt = new Date(dateStr).getTime();
  if (isNaN(dt)) return "-";
  var diff = Math.floor((now - dt) / 1000);
  if (diff < 60) return "刚刚";
  if (diff < 3600) return Math.floor(diff / 60) + "分钟前";
  if (diff < 86400) return Math.floor(diff / 3600) + "小时前";
  var d = new Date(dateStr);
  return ("0" + (d.getMonth() + 1)).slice(-2) + "-" + ("0" + d.getDate()).slice(-2);
}

// ===== 等级标签 =====
var LEVEL_LABELS = { 0: "不限", 1: "黑铁", 2: "青铜", 3: "白银", 4: "黄金", 5: "铂金", 6: "钻石", 7: "王者" };
var LEVEL_COLORS = { 1: "#8b7355", 2: "#cd7f32", 3: "#c0c0c0", 4: "#ffd700", 5: "#e5e4e2", 6: "#b9f2ff", 7: "#ff6b6b" };
var TYPE_LABELS = { naikuai: "奶块打手", delta: "三角洲打手" };
var GENDER_LABELS = { 1: "男", 2: "女" };

// ===== 图标组件 =====
var iconAttrs = { width: 20, height: 20, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.75, strokeLinecap: "round", strokeLinejoin: "round" };

function HeartIcon(col, filled) {
  if (filled) {
    return h("svg", { width: 20, height: 20, viewBox: "0 0 24 24", fill: col || "#ff4d4f", stroke: col || "#ff4d4f", strokeWidth: 1.75, strokeLinecap: "round", strokeLinejoin: "round" },
      h("path", { d: "M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" })
    );
  }
  return h("svg", Object.assign({}, iconAttrs, { stroke: col || "#999" }),
    h("path", { d: "M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" })
  );
}

function CommentIcon() {
  return h("svg", iconAttrs,
    h("path", { d: "M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" })
  );
}

function SendIcon() {
  return h("svg", { width: 18, height: 18, viewBox: "0 0 24 24", fill: "none", stroke: "#fff", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round" },
    h("line", { x1: 22, y1: 2, x2: 11, y2: 13 }),
    h("polygon", { points: "22 2 15 22 11 13 2 9 22 2" })
  );
}

function ChevronRight() {
  return h("svg", { width: 16, height: 16, viewBox: "0 0 24 24", fill: "none", stroke: "#bbb", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round" },
    h("path", { d: "m9 18 6-6-6-6" })
  );
}

// ===== 图片网格 =====
function renderImages(images) {
  if (!images || !Array.isArray(images) || images.length === 0) return null;
  var displayImages = images.slice(0, 9);
  var count = displayImages.length;
  var gridStyle = { display: "grid", gap: 4, marginTop: 10, borderRadius: 8, overflow: "hidden" };
  if (count === 1) {
    gridStyle.gridTemplateColumns = "1fr";
    return h("div", { style: gridStyle },
      h("img", { src: displayImages[0], style: { width: "100%", height: 180, objectFit: "cover", borderRadius: 8, cursor: "pointer" }, onClick: function() { window.open(displayImages[0]); }, onError: function(e) { e.target.style.display = "none"; } })
    );
  }
  if (count === 2) { gridStyle.gridTemplateColumns = "1fr 1fr"; }
  else if (count === 4) { gridStyle.gridTemplateColumns = "1fr 1fr"; }
  else { gridStyle.gridTemplateColumns = "1fr 1fr 1fr"; }
  return h("div", { style: gridStyle },
    displayImages.map(function(url, i) {
      return h("div", { key: i, style: { position: "relative", paddingTop: count === 1 ? "50%" : "100%", overflow: "hidden", borderRadius: 4, cursor: "pointer" } },
        h("img", { src: url, style: { position: "absolute", top: 0, left: 0, width: "100%", height: "100%", objectFit: "cover" }, onClick: function() { window.open(url); }, onError: function(e) { e.target.style.display = "none"; } })
      );
    })
  );
}

// ===== 主组件 =====
function DynamicsPage() {
  var _list = useState([]); var list = _list[0], setList = _list[1];
  var _loading = useState(true); var loading = _loading[0], setLoading = _loading[1];
  var _error = useState(""); var error = _error[0], setError = _error[1];
  // Comment state per dynamic: { [dynamicId]: { comments: [], visible: bool, loading: bool, inputVal: string, replyTarget: {commentId, userId, userName} | null } }
  var _commentStates = useState({}); var commentStates = _commentStates[0], setCommentStates = _commentStates[1];
  var _n = useState([]); var notices = _n[0], setNotices = _n[1];

  function loadData() {
    setLoading(true);
    setError("");
    NK.Api.Booster.publicDynamics()
      .then(function(res) {
        if (res && res.code === 0) {
          var newList = Array.isArray(res.data && res.data.list) ? res.data.list : [];
        setList(newList);
        // Auto-load comments for all dynamics
        newList.forEach(function(dyn) {
          loadComments(dyn.id);
        });
        } else {
          setError((res && res.message) || "动态加载失败");
        }
        setLoading(false);
      })
      .catch(function(e) {
        console.error("Dynamics load error:", e);
        setError("动态加载失败");
        setLoading(false);
      });
  }

  useEffect(function() { loadData(); }, []);

  // === Like toggle ===
  function handleLike(dynId, index) {
    var token = NK.Api.getToken();
    if (!token) { alert("请先登录"); return; }
    NK.Api.Booster.toggleDynamicLike(dynId).then(function(res) {
      if (res && res.code === 0) {
        setList(function(prev) {
          return prev.map(function(item, i) {
            if (i !== index) return item;
            return Object.assign({}, item, { likedByMe: res.data.liked, likeCount: res.data.likeCount });
          });
        });
      } else {
        alert((res && res.message) || "操作失败");
      }
    }).catch(function(e) { alert(e.message || "操作失败"); });
  }

  // === Toggle comment section ===
  // === Focus comment input (comments are always visible) ===
  function toggleComments(dynId) {
    // Focus the comment input for this dynamic
    var el = document.querySelector('.comment-input-' + dynId);
    if (el) { el.focus(); }
  }

  // === Load comments ===
  function loadComments(dynId) {
    setCommentStates(function(prev) {
      var current = prev[dynId] || { comments: [], visible: true, loading: true, inputVal: "", replyTarget: null };
      return Object.assign({}, prev, { [dynId]: Object.assign({}, current, { loading: true }) });
    });
    NK.Api.Booster.dynamicComments(dynId).then(function(res) {
      setCommentStates(function(prev) {
        var current = prev[dynId] || { comments: [], visible: true, loading: false, inputVal: "", replyTarget: null };
        if (res && res.code === 0) {
          return Object.assign({}, prev, { [dynId]: Object.assign({}, current, { comments: res.data.list || [], loading: false, loaded: true }) });
        }
        return Object.assign({}, prev, { [dynId]: Object.assign({}, current, { loading: false, loaded: true }) });
      });
    }).catch(function() {
      setCommentStates(function(prev) {
        var current = prev[dynId] || { comments: [], visible: true, loading: false, inputVal: "", replyTarget: null };
        return Object.assign({}, prev, { [dynId]: Object.assign({}, current, { loading: false, loaded: true }) });
      });
    });
  }

  // === Submit comment ===
  function submitComment(dynId, index) {
    var token = NK.Api.getToken();
    if (!token) { alert("请先登录"); return; }
    var state = commentStates[dynId] || { inputVal: "", replyTarget: null };
    var content = state.inputVal.trim();
    if (!content) { alert("请输入评论内容"); return; }
    if (content.length > 500) { alert("评论内容最多500字"); return; }
    var data = { content: content };
    if (state.replyTarget) {
      data.parentId = state.replyTarget.commentId;
      data.replyToUserId = state.replyTarget.userId;
    }
    NK.Api.Booster.createDynamicComment(dynId, data).then(function(res) {
      if (res && res.code === 0) {
        var newComment = res.data;
        setCommentStates(function(prev) {
          var current = prev[dynId] || { comments: [], visible: true, loading: false, inputVal: "", replyTarget: null };
          return Object.assign({}, prev, { [dynId]: Object.assign({}, current, { comments: current.comments.concat([newComment]), inputVal: "", replyTarget: null }) });
        });
        // Update comment count on the card
        setList(function(prev) {
          return prev.map(function(item, i) {
            if (i !== index) return item;
            return Object.assign({}, item, { commentCount: (item.commentCount || 0) + 1 });
          });
        });
      } else {
        alert((res && res.message) || "评论失败");
      }
    }).catch(function(e) { alert(e.message || "评论失败"); });
  }

  // === Set reply target ===
  function setReplyTarget(dynId, commentId, userId, userName) {
    setCommentStates(function(prev) {
      var current = prev[dynId] || { comments: [], visible: true, loading: false, inputVal: "", replyTarget: null };
      return Object.assign({}, prev, { [dynId]: Object.assign({}, current, { replyTarget: { commentId: commentId, userId: userId, userName: userName } }) });
    });
  }

  // === Cancel reply ===
  function cancelReply(dynId) {
    setCommentStates(function(prev) {
      var current = prev[dynId] || { comments: [], visible: true, loading: false, inputVal: "", replyTarget: null };
      return Object.assign({}, prev, { [dynId]: Object.assign({}, current, { replyTarget: null, inputVal: "" }) });
    });
  }

  // === Update input value ===
  function updateInputVal(dynId, val) {
    setCommentStates(function(prev) {
      var current = prev[dynId] || { comments: [], visible: true, loading: false, inputVal: "", replyTarget: null };
      return Object.assign({}, prev, { [dynId]: Object.assign({}, current, { inputVal: val }) });
    });
  }

  // ===== Render Dynamic Card =====
  function renderDynamicCard(item, index) {
    var name = item.boosterName || "-";
    var avatar = item.boosterAvatar || "";
    var gender = item.boosterGender;
    var level = item.boosterLevel || 0;
    var type = item.boosterType || "";
    var time = formatTime(item.createdAt);
    var text = item.content || item.title || "";
    if (!text) text = "这个打手还没有填写动态内容";
    var images = item.images || [];
    var likeCount = item.likeCount || 0;
    var commentCount = item.commentCount || 0;
    var likedByMe = item.likedByMe || false;
    var dynId = item.id;
    var cs = commentStates[dynId] || { comments: [], visible: true, loading: false, inputVal: "", replyTarget: null };

    var avatarContent;
    if (avatar) {
      avatarContent = h("img", { src: avatar, style: { width: 44, height: 44, borderRadius: "50%", objectFit: "cover", flexShrink: 0 }, onError: function(e) { e.target.style.display = "none"; } });
    } else {
      avatarContent = h("div", { style: { width: 44, height: 44, borderRadius: "50%", background: "#1677ff", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 16, color: "#fff", fontWeight: 600, flexShrink: 0 } }, name.charAt(0) || "?");
    }

    return h("div", { key: dynId, style: { background: "#fff", borderRadius: 12, padding: 16, marginBottom: 10, boxShadow: "0 1px 3px rgba(0,0,0,0.04)" } },
      // Header (clickable - navigates to public profile)
      h("div", { style: { display: "flex", alignItems: "flex-start", gap: 10, cursor: "pointer" }, onClick: function() { if (NK.Store.openNativePage && NK.Store.openNativePage("pages/booster/public-profile", { source: "dynamic", boosterUserId: item.boosterUserId, boosterProfileId: item.boosterProfileId })) return; NK.Store.navigate("boosterPublicProfile", { boosterUserId: item.boosterUserId, boosterProfileId: item.boosterProfileId }); } },
        avatarContent,
        h("div", { style: { flex: 1, minWidth: 0 } },
          h("div", { style: { display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" } },
            h("span", { style: { fontSize: 15, fontWeight: 600, color: "#1a1a2e" } }, name),
            gender ? h("span", { style: { fontSize: 11, color: gender === 1 ? "#1677ff" : "#ff4d8f", background: gender === 1 ? "#e6f4ff" : "#fff0f6", padding: "1px 6px", borderRadius: 4 } }, GENDER_LABELS[gender] || "") : null,
            type ? h("span", { style: { fontSize: 11, color: "#fa8c16", background: "#fff7e6", padding: "1px 6px", borderRadius: 4 } }, TYPE_LABELS[type] || type) : null,
            level > 0 ? h("span", { style: { fontSize: 11, color: LEVEL_COLORS[level] || "#666", background: (LEVEL_COLORS[level] || "#f0f0f0") + "22", padding: "1px 6px", borderRadius: 4, border: "1px solid " + (LEVEL_COLORS[level] || "#ddd") + "44" } }, LEVEL_LABELS[level] || "") : null
          ),
          h("div", { style: { fontSize: 12, color: "#999", marginTop: 2 } }, time)
        )
      ),
      // Content
      h("div", { style: { marginTop: 12, fontSize: 14, color: "#333", lineHeight: 1.6, whiteSpace: "pre-wrap", wordBreak: "break-word" } }, text),
      // Images
      renderImages(images),
      // Actions
      h("div", { style: { display: "flex", alignItems: "center", gap: 24, marginTop: 14, paddingTop: 10, borderTop: "1px solid #f5f5f5" } },
        // Like button
        h("div", { style: { display: "flex", alignItems: "center", gap: 4, cursor: "pointer", color: likedByMe ? "#ff4d4f" : "#999", fontSize: 13 }, onClick: function() { handleLike(dynId, index); } },
          HeartIcon(likedByMe ? "#ff4d4f" : "#999", likedByMe),
          h("span", null, likeCount > 0 ? likeCount : "点赞")
        ),
        // Comment button
        h("div", { style: { display: "flex", alignItems: "center", gap: 4, cursor: "pointer", color: "#999", fontSize: 13 }, onClick: function() { toggleComments(dynId); } },
          CommentIcon(),
          h("span", null, commentCount > 0 ? commentCount : "评论")
        )
      ),
      // Comments section
      cs.visible ? h("div", { style: { marginTop: 12, paddingTop: 10, borderTop: "1px solid #f0f0f0" } },
        // Loading
        cs.loading ? h("div", { style: { textAlign: "center", padding: "12px 0", color: "#999", fontSize: 12 } }, "加载评论中...") :
        // Comment list
        cs.comments.length === 0 ? h("div", { style: { textAlign: "center", padding: "12px 0", color: "#999", fontSize: 12 } }, "暂无评论") :
        h("div", { style: { marginBottom: 8 } },
          cs.comments.map(function(c) {
            var isReply = !!c.parentId;
            return h("div", { key: c.id, style: { padding: "6px 0", fontSize: 13, lineHeight: 1.5, cursor: "pointer" }, onClick: function() { setReplyTarget(dynId, c.id, c.userId, c.userName || "用户"); } },
              h("span", { style: { color: "#1677ff", fontWeight: 500, marginRight: 4 } }, c.userName || "用户"),
              isReply ? h("span", { style: { color: "#999", marginRight: 4 } }, "回复") : null,
              isReply ? h("span", { style: { color: "#1677ff", fontWeight: 500, marginRight: 4 } }, c.replyToUserName || "用户") : null,
              isReply ? h("span", { style: { color: "#999", marginRight: 4 } }, ":") : h("span", { style: { color: "#999", marginRight: 4 } }, ":"),
              h("span", { style: { color: "#333" } }, c.content || "")
            );
          })
        ),
        // Reply indicator
        cs.replyTarget ? h("div", { style: { display: "flex", alignItems: "center", marginBottom: 6, fontSize: 12 } },
          h("span", { style: { color: "#1677ff", marginRight: 4 } }, "正在回复 " + (cs.replyTarget.userName || "用户")),
          h("span", { style: { color: "#999", cursor: "pointer", marginLeft: 8 }, onClick: function(e) { e.stopPropagation(); cancelReply(dynId); } }, "取消")
        ) : null,
        // Comment input
        h("div", { style: { display: "flex", gap: 8, alignItems: "center" } },
          h("input", {
            className: "comment-input-" + dynId,
            value: cs.inputVal || "",
            placeholder: cs.replyTarget ? ("回复 " + (cs.replyTarget.userName || "用户") + "...") : "说点什么吧...",
            onInput: function(e) { updateInputVal(dynId, e.target.value); },
            maxLength: 500,
            style: { flex: 1, padding: "8px 12px", border: "1px solid #e8e8e8", borderRadius: 18, fontSize: 13, outline: "none", background: "#f9f9f9" }
          }),
          h("button", {
            onClick: function() { submitComment(dynId, index); },
            style: { width: 36, height: 36, borderRadius: "50%", border: "none", background: "#1677ff", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", flexShrink: 0 }
          }, SendIcon())
        )
      ) : null
    );
  }


  // ===== 置顶公告数据 =====
  useEffect(function() {
    NK.Api.Dynamic.notices().then(function(res) {
      if (res && res.code === 0 && Array.isArray(res.data)) {
        setNotices(res.data);
      }
    }).catch(function(err) {
      console.log("[DynamicsPage] notices fetch error", err);
    });
  }, []);

  return h("div", { className: "dynamics-page", style: { background: "#f5f6f8", minHeight: "100vh", paddingBottom: 20 } },
    // Header
    h("div", { style: { position: "sticky", top: 0, zIndex: 50, background: "#fff", padding: "12px 16px", borderBottom: "1px solid #f0f0f0", display: "flex", alignItems: "center", justifyContent: "center" } },
      h("div", { style: { fontSize: 17, fontWeight: 600, color: "#1a1a2e" } }, "动态")
    ),
    // Banner
    h("div", { style: { margin: "12px 16px", borderRadius: 14, overflow: "hidden", height: 88, background: "linear-gradient(135deg, #10b981 0%, #3b82f6 100%)", padding: "16px 20px", display: "flex", flexDirection: "column", justifyContent: "center" } },
      h("div", { style: { fontSize: 18, fontWeight: 700, color: "#fff", marginBottom: 4 } }, "方块号仓动态圈"),
      h("div", { style: { fontSize: 12, color: "rgba(255,255,255,0.85)" } }, "分享打手服务、订单故事和游戏日常"),
      h("div", { style: { display: "flex", gap: 6, marginTop: 8 } },
        h("div", { style: { width: 6, height: 6, borderRadius: "50%", background: "#fff" } }),
        h("div", { style: { width: 6, height: 6, borderRadius: "50%", background: "rgba(255,255,255,0.5)" } })
      )
    ),
    // Notices
    notices.length > 0 ? h("div", { style: { margin: "0 16px 12px", background: "#fff", borderRadius: 12, overflow: "hidden" } },
      notices.map(function(n, i) {
        return h("div", { key: n.id || i, style: { display: "flex", alignItems: "center", padding: "14px 16px", borderBottom: i < notices.length - 1 ? "1px solid #f5f5f5" : "none", cursor: "pointer" }, onClick: function() { NK.Store.navigate("dynamicNoticeDetail", { noticeId: n.id }); } },
          h("span", { style: { background: "#f3f0ff", color: "#7c3aed", fontSize: 11, fontWeight: 600, padding: "2px 8px", borderRadius: 4, marginRight: 10, flexShrink: 0 } }, "置顶"),
          h("span", { style: { flex: 1, fontSize: 14, color: n.titleColor || "#333", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, n.title),
          ChevronRight()
        );
      })
    ) : null,
    // Loading state
    loading ? h("div", { style: { textAlign: "center", padding: "40px 0", color: "#999", fontSize: 14 } }, "动态加载中...") :
    // Error state
    error ? h("div", { style: { textAlign: "center", padding: "40px 16px" } },
      h("div", { style: { fontSize: 14, color: "#999", marginBottom: 12 } }, error),
      h("button", { onClick: loadData, style: { padding: "8px 24px", background: "#1677ff", color: "#fff", border: "none", borderRadius: 6, fontSize: 13, cursor: "pointer" } }, "重新加载")
    ) :
    // Empty state
    list.length === 0 ? h("div", { style: { textAlign: "center", padding: "40px 0", color: "#999", fontSize: 14 } }, "暂无动态") :
    // Dynamic list
    h("div", { style: { margin: "0 16px" } },
      list.map(function(item, i) { return renderDynamicCard(item, i); })
    ),
  );
}

window.NK = window.NK || {};
NK.DynamicsPage = DynamicsPage;
