﻿// 用户端 - 打手公开主页
var _a = React.useState, _b = React.useEffect;
var useState = _a, useEffect = _b;
var h = React.createElement;

var LEVEL_NAMES = ["", "黑铁", "青铜", "白银", "黄金", "铂金", "钻石", "王者"];
var LEVEL_COLORS = { 1: "#8b7355", 2: "#cd7f32", 3: "#c0c0c0", 4: "#ffd700", 5: "#e5e4e2", 6: "#b9f2ff", 7: "#ff6b6b" };
var TYPE_LABELS = { naikuai: "奶块打手", delta: "三角洲打手" };

// ===== Format time =====
function formatDynamicTime(d) {
  if (!d) return "-";
  var now = Date.now(), dt = new Date(d).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 td = new Date(d);
  return ("0" + (td.getMonth() + 1)).slice(-2) + "-" + ("0" + td.getDate()).slice(-2);
}

// ===== Image grid =====
function renderImageGrid(imgs) {
  if (!imgs || !Array.isArray(imgs) || imgs.length === 0) return null;
  var display = imgs.slice(0, 9), cnt = display.length;
  var gs = { display: "grid", gap: 3, marginTop: 8, borderRadius: 8, overflow: "hidden" };
  if (cnt === 1) { gs.gridTemplateColumns = "1fr"; return h("div", { style: gs }, h("img", { src: display[0], style: { width: "100%", height: 160, objectFit: "cover", borderRadius: 8 } })); }
  if (cnt === 2) gs.gridTemplateColumns = "1fr 1fr"; else if (cnt === 4) gs.gridTemplateColumns = "1fr 1fr"; else gs.gridTemplateColumns = "1fr 1fr 1fr";
  return h("div", { style: gs }, display.map(function(u, i) { return h("div", { key: "pi-" + i, style: { position: "relative", paddingTop: "100%", overflow: "hidden", borderRadius: 4 } }, h("img", { src: u, style: { position: "absolute", top: 0, left: 0, width: "100%", height: "100%", objectFit: "cover" } })); }));
}

function BoosterPublicProfilePage() {
  var pageParams = NK.Store.get("pageParams") || {};
  var boosterUserId = pageParams.boosterUserId;
  var profileSource = String(pageParams.source || "").toLowerCase();
  var _loading = useState(true), loading = _loading[0], setLoading = _loading[1];
  var _error = useState(""), error = _error[0], setError = _error[1];
  var _profile = useState(null), profile = _profile[0], setProfile = _profile[1];
  var _services = useState([]), services = _services[0], setServices = _services[1];
  var _dynamics = useState([]), dynamics = _dynamics[0], setDynamics = _dynamics[1];
  var _reviewStats = useState(null), reviewStats = _reviewStats[0], setReviewStats = _reviewStats[1];
  var _reviews = useState([]), reviews = _reviews[0], setReviews = _reviews[1];
  var _activeTab = useState("services"), activeTab = _activeTab[0], setActiveTab = _activeTab[1];
  // Order modal
    //
  // Spec selection modal
  var _showSpecModal = useState(false), showSpecModal = _showSpecModal[0], setShowSpecModal = _showSpecModal[1];
  var _specTarget = useState(null), specTarget = _specTarget[0], setSpecTarget = _specTarget[1];
  var _selectedSpecIdx = useState(0), selectedSpecIdx = _selectedSpecIdx[0], setSelectedSpecIdx = _selectedSpecIdx[1];
  var _previewImage = useState(null), previewImage = _previewImage[0], setPreviewImage = _previewImage[1];
  var _ratingFilter = useState("all"), ratingFilter = _ratingFilter[0], setRatingFilter = _ratingFilter[1];
  var _onlyWithImage = useState(false), onlyWithImage = _onlyWithImage[0], setOnlyWithImage = _onlyWithImage[1];
  var _showRatingMenu = useState(false), showRatingMenu = _showRatingMenu[0], setShowRatingMenu = _showRatingMenu[1];
  // Comment states per dynamic
  var _commentStates = useState({}), commentStates = _commentStates[0], setCommentStates = _commentStates[1];
  var _privateMsgLoading = useState(false), privateMsgLoading = _privateMsgLoading[0], setPrivateMsgLoading = _privateMsgLoading[1];

  function loadData() {
    setLoading(true); setError("");
    NK.Api.Booster.publicProfile({ boosterUserId: boosterUserId }).then(function(res) {
      if (res && res.code === 0) {
        var d = res.data;
        setProfile(d.profile || null);
        setServices(d.services || []);
        setDynamics(d.dynamics || []);
        setReviewStats(d.reviewStats || { total: 0, good: 0, middle: 0, bad: 0, goodRate: 0 });
        setReviews(d.reviews || []);
        // Auto-load comments for dynamics
        (d.dynamics || []).forEach(function(dyn) { loadDynComments(dyn.id); });
      } else { setError((res && res.message) || "加载失败"); }
      setLoading(false);
    }).catch(function() { setError("加载失败"); setLoading(false); });
  }

  useEffect(function() { if (boosterUserId) loadData(); }, []);

  // === Comment functions ===
  function loadDynComments(dynId) {
    setCommentStates(function(prev) {
      var cur = prev[dynId] || { comments: [], loading: true, inputVal: "", replyTarget: null };
      return Object.assign({}, prev, { [dynId]: Object.assign({}, cur, { loading: true }) });
    });
    NK.Api.Booster.dynamicComments(dynId).then(function(res) {
      setCommentStates(function(prev) {
        var cur = prev[dynId] || { comments: [], loading: false, inputVal: "", replyTarget: null };
        var list = (res && res.code === 0) ? (res.data.list || []) : [];
        return Object.assign({}, prev, { [dynId]: Object.assign({}, cur, { comments: list, loading: false, loaded: true }) });
      });
    }).catch(function() {
      setCommentStates(function(prev) {
        var cur = prev[dynId] || { comments: [], loading: false, inputVal: "", replyTarget: null };
        return Object.assign({}, prev, { [dynId]: Object.assign({}, cur, { loading: false, loaded: true }) });
      });
    });
  }

  function handleDynLike(dynId, index) {
    var token = NK.Api.getToken();
    if (!token) { alert("请先登录"); return; }
    NK.Api.Booster.toggleDynamicLike(dynId).then(function(res) {
      if (res && res.code === 0) {
        setDynamics(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 || "操作失败"); });
  }

  function submitDynComment(dynId, index) {
    var token = NK.Api.getToken();
    if (!token) { alert("请先登录"); return; }
    var state = commentStates[dynId] || { inputVal: "", replyTarget: null };
    var ct = state.inputVal.trim();
    if (!ct) { alert("请输入评论内容"); return; }
    if (ct.length > 500) { alert("评论内容最多500字"); return; }
    var data = { content: ct };
    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) {
        setCommentStates(function(prev) {
          var cur = prev[dynId] || { comments: [], inputVal: "", replyTarget: null };
          return Object.assign({}, prev, { [dynId]: Object.assign({}, cur, { comments: cur.comments.concat([res.data]), inputVal: "", replyTarget: null }) });
        });
        setDynamics(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 || "评论失败"); });
  }

  function updateDynInput(dynId, val) {
    setCommentStates(function(prev) {
      var cur = prev[dynId] || { comments: [], inputVal: "", replyTarget: null };
      return Object.assign({}, prev, { [dynId]: Object.assign({}, cur, { inputVal: val }) });
    });
  }
  function setDynReply(dynId, commentId, userId, userName) {
    setCommentStates(function(prev) {
      var cur = prev[dynId] || { comments: [], inputVal: "", replyTarget: null };
      return Object.assign({}, prev, { [dynId]: Object.assign({}, cur, { replyTarget: { commentId: commentId, userId: userId, userName: userName } }) });
    });
  }
  function cancelDynReply(dynId) {
    setCommentStates(function(prev) {
      var cur = prev[dynId] || { comments: [], inputVal: "", replyTarget: null };
      return Object.assign({}, prev, { [dynId]: Object.assign({}, cur, { replyTarget: null, inputVal: "" }) });
    });
  }

  // === Designated order: navigate to EscortPayPage ===
  function startDesignatedOrder(svc, specIdx) {
    var token = NK.Api.getToken();
    if (!token) { alert("请先登录"); return; }
    var specs = svc.specs || [{ specId: null, specName: svc.title, price: svc.price }];
    var spec = specs[specIdx] || specs[0];
    NK.Store.navigate("escortPay", {
      serviceId: svc.serviceId,
      title: svc.title,
      coverImage: svc.coverImage || "",
      bizType: svc.bizType || "naikuai",
      category: svc.category || "",
      specId: spec.specId || null,
      specName: spec.specName || svc.title,
      price: spec.price || svc.price,
      designatedBoosterUserId: profile.boosterUserId,
      designatedBoosterProfileId: profile.boosterProfileId,
      designatedBoosterName: profile.name,
      designatedBoosterAvatar: profile.avatar || "",
      designatedBoosterLevel: profile.level || 1
    });
  }
  function handleSpecifiedOrder(svc) {
    var token = NK.Api.getToken();
    if (!token) { alert("请先登录"); return; }
    var specs = svc.specs || [];
    if (specs.length <= 1) { startDesignatedOrder(svc, 0); return; }
    setSpecTarget(svc);
    setSelectedSpecIdx(0);
    setShowSpecModal(true);
  }

  function handlePrivateMessage() {
    if (privateMsgLoading) return;
    var token = NK.Api.getToken();
    if (!token) { NK.Store.navigate("login"); return; }
    var bid = (profile && (profile.boosterUserId || profile.userId)) || boosterUserId;
    if (!bid) { alert("打手ID缺失"); return; }
    setPrivateMsgLoading(true);
    NK.Api.Escort.buyerBoosterConversation({ boosterUserId: bid }).then(function(r) {
      setPrivateMsgLoading(false);
      if (r && r.code === 0 && r.data) {
        var nextConversationId = Number(r.data.conversation_id || r.data.id);
        if (!nextConversationId || isNaN(nextConversationId)) { alert("会话参数无效，请稍后重试"); return; }
        var latestOrder = r.data.latestOrder || null;
        var chatParams = {
          conversationId: nextConversationId,
          boosterUserId: bid,
          role: "buyer",
          source: "boosterProfile",
          latestOrder: latestOrder
        };
        var latestOrderId = Number(latestOrder && latestOrder.orderId);
        if (latestOrderId && !isNaN(latestOrderId)) chatParams.orderId = latestOrderId;
        NK.Store.navigate("escortOrderChat", chatParams);
      } else {
        alert((r && r.message) || "创建会话失败");
      }
    }).catch(function() {
      setPrivateMsgLoading(false);
      alert("网络错误，请稍后重试");
    });
  }

  function handleServiceChat(svc) {
    if (privateMsgLoading) return;
    var token = NK.Api.getToken();
    if (!token) { NK.Store.navigate("login"); return; }
    var serviceId = Number(svc && (svc.serviceId || svc.id));
    var bid = Number((profile && (profile.boosterUserId || profile.userId)) || boosterUserId);
    if (!serviceId || !bid) { alert("服务或打手信息缺失"); return; }
    setPrivateMsgLoading(true);
    NK.Api.Im.escortServiceConversation({
      service_id: serviceId,
      assignment_mode: profileSource === "ranking" || profileSource === "rank" || profileSource === "top" ? "featured" : "specified",
      booster_user_id: bid
    }).then(function(r) {
      setPrivateMsgLoading(false);
      if (!r || r.code !== 0 || !r.data) { alert((r && r.message) || "创建服务会话失败"); return; }
      var conversationId = Number(r.data.conversation_id || 0);
      if (!conversationId) { alert("服务会话信息异常"); return; }
      NK.Store.navigate("supportChat", { conversationId: conversationId, conversationData: r.data });
    }).catch(function() {
      setPrivateMsgLoading(false);
      alert("网络错误，请稍后重试");
    });
  }

  function renderProfileActionIcon(type) {
    if (type === "gift") {
      return h("span", { "aria-hidden": true, style: { position: "relative", width: 18, height: 18, display: "inline-block", flexShrink: 0, color: "currentColor" } },
        h("span", { style: { position: "absolute", left: 2, top: 7, width: 14, height: 9, border: "2px solid currentColor", borderRadius: 2, boxSizing: "border-box" } }),
        h("span", { style: { position: "absolute", left: 1, top: 5, width: 16, height: 5, border: "2px solid currentColor", borderRadius: 2, boxSizing: "border-box", background: "inherit" } }),
        h("span", { style: { position: "absolute", left: 8, top: 5, width: 2, height: 11, background: "currentColor" } }),
        h("span", { style: { position: "absolute", left: 3, top: 1, width: 6, height: 5, border: "2px solid currentColor", borderRadius: "6px 6px 0 6px", boxSizing: "border-box" } }),
        h("span", { style: { position: "absolute", right: 3, top: 1, width: 6, height: 5, border: "2px solid currentColor", borderRadius: "6px 6px 6px 0", boxSizing: "border-box" } })
      );
    }
    return h("span", { "aria-hidden": true, style: { position: "relative", width: 18, height: 18, display: "inline-block", flexShrink: 0, color: "currentColor" } },
      h("span", { style: { position: "absolute", left: 1, top: 2, width: 16, height: 12, border: "2px solid currentColor", borderRadius: 5, boxSizing: "border-box" } }),
      h("span", { style: { position: "absolute", left: 4, bottom: 1, width: 5, height: 5, borderLeft: "2px solid currentColor", borderBottom: "2px solid currentColor", transform: "skew(-20deg)", boxSizing: "border-box" } })
    );
  }

  // ===== RENDER =====
  if (loading) return h("div", { style: { padding: 60, textAlign: "center", color: "#999" } }, "加载中...");
  if (error || !profile) return h("div", { style: { padding: 60, textAlign: "center" } }, h("div", { style: { color: "#999", marginBottom: 12 } }, error || "打手不存在"), h("button", { onClick: function() { NK.Store.back ? NK.Store.back() : NK.Store.navigate("dynamics"); }, style: { padding: "6px 20px", background: "#1677ff", color: "#fff", border: "none", borderRadius: 6 } }, "返回"));

  var coverBg = profile.cover ? "url(" + profile.cover + ") center/cover no-repeat" : "linear-gradient(135deg, #1677ff 0%, #0958d9 40%, #003eb3 100%)";
  var tabs = [{ key: "services", label: "陪玩" }, { key: "dynamics", label: "动态" }, { key: "reviews", label: "评价" }];

  return h("div", { style: { flex: 1, display: "flex", flexDirection: "column", overflowY: "auto", background: "#f5f6f8", minHeight: "100vh" } },
    // === Cover header (new) ===
    h("div", { style: { position: "relative", height: 260, background: coverBg, flexShrink: 0, zIndex: 1, overflow: "hidden" } },
      // Overlay
      h("div", { style: { position: "absolute", inset: 0, background: "rgba(0,0,0,0.32)", zIndex: 1 } }),
      // Nav bar: back + title + placeholder
      h("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", height: 44, padding: "0 12px", position: "absolute", top: 0, left: 0, right: 0, zIndex: 10 } },
        h("div", { onClick: function() { NK.Store.back ? NK.Store.back() : NK.Store.navigate("dynamics"); }, style: { width: 36, height: 36, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" } },
          h("svg", { width: 20, height: 20, viewBox: "0 0 24 24", fill: "none", stroke: "#fff", strokeWidth: 2.5, strokeLinecap: "round", strokeLinejoin: "round" }, h("path", { d: "m15 18-6-6 6-6" }))
        ),
        h("div", { style: { fontSize: 17, fontWeight: 600, color: "#fff", textShadow: "0 1px 2px rgba(0,0,0,0.4)" } }, "个人主页"),
        h("div", { style: { width: 36 } })
      ),
      // Profile info inside cover (left avatar + right meta)
      (function() {
        var gameRaw = profile.gameType || profile.bizType || profile.game || "";
        var rawLower = String(gameRaw || "").toLowerCase();
        var isDelta = rawLower.indexOf("三角洲") >= 0 || rawLower.indexOf("delta") >= 0;
        var gameText = isDelta ? "三角洲打手" : "奶块打手";
        var levelText = profile.levelName || (profile.level > 0 ? LEVEL_NAMES[profile.level] : "") || "";
        var uid = profile.boosterUserId || profile.userId || profile.id || "";
        var parts = [];
        if (gameText) parts.push(gameText);
        if (levelText) parts.push(levelText);
        if (uid) parts.push("ID " + uid);
        var identityLine = parts.join(" · ");
        var isOnline = profile.isOnline === true || profile.isOnline === 1 || profile.isAccepting === true || profile.isAccepting === 1;
        return h("div", { style: { position: "absolute", left: 16, right: 16, bottom: 20, zIndex: 5, display: "flex", alignItems: "center" } },
          // Left: avatar
          profile.avatar
            ? h("img", { src: profile.avatar, style: { width: 80, height: 80, borderRadius: "50%", objectFit: "cover", border: "4px solid #fff", flexShrink: 0, boxShadow: "0 6px 18px rgba(0,0,0,0.22)", background: "#e8e8e8" } })
            : h("div", { style: { width: 80, height: 80, borderRadius: "50%", border: "4px solid #fff", flexShrink: 0, boxShadow: "0 6px 18px rgba(0,0,0,0.22)", background: "#e8e8e8", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 30, fontWeight: 700, color: "#8a8f99" } }, (profile.name || "?").charAt(0)),
          // Right: meta
          h("div", { style: { marginLeft: 14, flex: 1, minWidth: 0 } },
            // Row 1: name + online/offline status
            h("div", { style: { display: "flex", alignItems: "center", gap: 8 } },
              h("div", { style: { fontSize: 20, fontWeight: 700, color: "#fff", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flexShrink: 1, minWidth: 0, textShadow: "0 1px 3px rgba(0,0,0,0.35)" } }, profile.name || "打手"),
              h("span", { style: { flexShrink: 0, padding: "2px 10px", borderRadius: 999, fontSize: 12, background: isOnline ? "#22c55e" : "rgba(255,255,255,0.25)", color: "#fff" } }, isOnline ? "在线" : "下线")
            ),
            // Row 2: identity (game · level · ID)
            identityLine ? h("div", { style: { marginTop: 6, fontSize: 13, color: "rgba(255,255,255,0.88)", textShadow: "0 1px 2px rgba(0,0,0,0.3)" } }, identityLine) : null,
            // Row 3: bio
            h("div", { style: { marginTop: 4, fontSize: 13, color: "rgba(255,255,255,0.78)", lineHeight: "18px", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden", textOverflow: "ellipsis", textShadow: "0 1px 2px rgba(0,0,0,0.3)" } }, profile.bio || profile.description || profile.signature || "暂无简介")
          )
        );
      })()
    ),
    // === Main panel (new unified white panel) ===
    h("div", { style: { background: "#fff", borderRadius: "18px 18px 0 0", overflow: "hidden", boxShadow: "0 -4px 16px rgba(15,23,42,0.06)", margin: 0, position: "relative", zIndex: 20 } },
      // Tabs row
      h("div", { style: { display: "flex", padding: "6px 14px", borderBottom: "1px solid #f1f2f4" } },
        tabs.map(function(tab) {
          var isActive = activeTab === tab.key;
          return h("div", { key: tab.key, onClick: function() { setActiveTab(tab.key); }, style: { flex: 1, textAlign: "center", padding: "10px 0", borderRadius: 12, cursor: "pointer", fontSize: 15, color: isActive ? "#fff" : "#8a8f99", fontWeight: isActive ? 700 : 500, background: isActive ? "#F59E0B" : "transparent" } }, tab.label);
        })
      ),
      // Tab content area
      h("div", { style: { padding: "12px 8px" } },
        // Services tab
        activeTab === "services" ? (
          services.length === 0 ? h("div", { style: { textAlign: "center", padding: 20, color: "#999", fontSize: 13 } }, "该打手暂未开启服务") :
          h("div", { style: { display: "flex", flexDirection: "column", gap: 10 } },
            services.map(function(svc) {
              return h("div", { key: "svc-" + svc.serviceId, style: { display: "flex", gap: 10, padding: 10, background: "#fafafa", borderRadius: 10 } },
                svc.coverImage ? h("img", { src: svc.coverImage, style: { width: 56, height: 56, borderRadius: 8, objectFit: "cover", flexShrink: 0 } }) :
                h("div", { style: { width: 56, height: 56, borderRadius: 8, background: "#e8e8e8", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 } }, h("svg", { width: 24, height: 24, viewBox: "0 0 24 24", fill: "none", stroke: "#bbb", strokeWidth: 1.5 }, h("rect", { x: 3, y: 3, width: 18, height: 18, rx: 2 }), h("circle", { cx: 8.5, cy: 8.5, r: 1.5 }), h("path", { d: "m21 15-5-5L5 21" }))),
                h("div", { style: { flex: 1, minWidth: 0 } },
                  h("div", { style: { fontSize: 14, fontWeight: 600, color: "#1a1a2e" } }, svc.title),
                  h("div", { style: { fontSize: 11, color: "#8c8c8c", marginTop: 2 } }, (TYPE_LABELS[svc.bizType] || svc.bizType) + "  " + (svc.serverName || "")),
                  h("div", { style: { fontSize: 14, fontWeight: 600, color: "#f59e0b", marginTop: 4 } }, "💎" + Number(svc.price).toFixed(2))
                ),
                h("div", { style: { display: "flex", flexDirection: "column", gap: 6, flexShrink: 0, alignSelf: "center" } },
                  h("button", { onClick: function() { handleServiceChat(svc); }, disabled: privateMsgLoading, style: { padding: "6px 14px", background: "#ecfdf5", color: "#0f766e", border: "1px solid #0f766e", borderRadius: 14, fontSize: 12, fontWeight: 600, cursor: privateMsgLoading ? "not-allowed" : "pointer" } }, privateMsgLoading ? "连接中" : "服务私聊"),
                  h("button", { onClick: function() { handleSpecifiedOrder(svc); }, style: { padding: "6px 14px", background: "#1677ff", color: "#fff", border: "none", borderRadius: 14, fontSize: 12, fontWeight: 500, cursor: "pointer" } }, "指定下单")
                )
              );
            })
          )
        ) :
        // Dynamics tab
        activeTab === "dynamics" ? (
          dynamics.length === 0 ? h("div", { style: { textAlign: "center", padding: 20, color: "#999", fontSize: 13 } }, "暂无动态") :
          h("div", { style: { display: "flex", flexDirection: "column", gap: 10 } },
            dynamics.map(function(dyn, di) {
              var name = dyn.boosterName || profile.name || "-";
              var avatar = dyn.boosterAvatar || profile.avatar || "";
              var level = dyn.boosterLevel || 0, type = dyn.boosterType || "";
              var text = dyn.content || dyn.title || "";
              if (!text) text = "这个打手还没有填写动态内容";
              var imgs = dyn.images || [];
              var lc = dyn.likeCount || 0, cc = dyn.commentCount || 0;
              var liked = dyn.likedByMe || false;
              var cs = commentStates[dyn.id] || { comments: [], loading: false, inputVal: "", replyTarget: null };
              return h("div", { key: "pdyn-" + dyn.id, style: { padding: 10, background: "#fafafa", borderRadius: 10 } },
                h("div", { style: { display: "flex", alignItems: "flex-start", gap: 8 } },
                  avatar ? h("img", { src: avatar, style: { width: 36, height: 36, borderRadius: "50%", objectFit: "cover", flexShrink: 0 } }) : h("div", { style: { width: 36, height: 36, borderRadius: "50%", background: "#1677ff", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14, color: "#fff", fontWeight: 600, flexShrink: 0 } }, name.charAt(0) || "?"),
                  h("div", { style: { flex: 1 } },
                    h("div", { style: { display: "flex", alignItems: "center", gap: 4, flexWrap: "wrap" } },
                      h("span", { style: { fontSize: 13, fontWeight: 600, color: "#1a1a2e" } }, name),
                      type ? h("span", { style: { fontSize: 10, color: "#fa8c16", background: "#fff7e6", padding: "1px 5px", borderRadius: 3 } }, TYPE_LABELS[type] || type) : null,
                      level > 0 ? h("span", { style: { fontSize: 10, color: LEVEL_COLORS[level] || "#666", background: (LEVEL_COLORS[level] || "#f0f0f0") + "22", padding: "1px 5px", borderRadius: 3 } }, LEVEL_NAMES[level] || "") : null
                    ),
                    h("div", { style: { fontSize: 11, color: "#999", marginTop: 1 } }, formatDynamicTime(dyn.createdAt))
                  )
                ),
                h("div", { style: { marginTop: 6, fontSize: 13, color: "#333", lineHeight: 1.5, whiteSpace: "pre-wrap", wordBreak: "break-word" } }, text),
                renderImageGrid(imgs),
                h("div", { style: { display: "flex", alignItems: "center", gap: 20, marginTop: 8, paddingTop: 6, borderTop: "1px solid #f0f0f0" } },
                  h("span", { onClick: function() { handleDynLike(dyn.id, di); }, style: { display: "flex", alignItems: "center", gap: 3, cursor: "pointer", fontSize: 12, color: liked ? "#ff4d4f" : "#999" } },
                    h("svg", { width: 15, height: 15, viewBox: "0 0 24 24", fill: liked ? "#ff4d4f" : "none", stroke: liked ? "#ff4d4f" : "#999", 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" })), lc > 0 ? lc : "点赞"
                  ),
                  h("span", { style: { display: "flex", alignItems: "center", gap: 3, fontSize: 12, color: "#999" } },
                    h("svg", { width: 15, height: 15, viewBox: "0 0 24 24", fill: "none", stroke: "#999", strokeWidth: 1.75, strokeLinecap: "round", strokeLinejoin: "round" }, 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" })), cc > 0 ? cc : "评论"
                  )
                ),
                // Comments
                cs.loading ? h("div", { style: { marginTop: 6, color: "#999", fontSize: 11, textAlign: "center" } }, "评论加载中...") :
                cs.comments.length === 0 ? h("div", { style: { marginTop: 6, color: "#999", fontSize: 11, textAlign: "center" } }, "暂无评论") :
                h("div", { style: { marginTop: 6, paddingTop: 4, borderTop: "1px solid #f5f5f5" } },
                  cs.comments.map(function(c) {
                    var isReply = !!c.parentId;
                    return h("div", { key: "pc-" + c.id, onClick: function() { setDynReply(dyn.id, c.id, c.userId, c.userName || "用户"); }, style: { padding: "2px 0", fontSize: 11, lineHeight: 1.5, cursor: "pointer" } },
                      h("span", { style: { color: "#1677ff", fontWeight: 500, marginRight: 3 } }, c.userName || "用户"),
                      isReply ? h("span", { style: { color: "#999", marginRight: 3 } }, "回复") : null,
                      isReply ? h("span", { style: { color: "#1677ff", fontWeight: 500, marginRight: 3 } }, c.replyToUserName || "用户") : null,
                      isReply ? h("span", { style: { color: "#999", marginRight: 3 } }, ":") : h("span", { style: { color: "#999", marginRight: 3 } }, ":"),
                      h("span", { style: { color: "#333" } }, c.content || "")
                    );
                  })
                ),
                cs.replyTarget ? h("div", { style: { display: "flex", alignItems: "center", marginTop: 4, fontSize: 11 } },
                  h("span", { style: { color: "#1677ff" } }, "正在回复 " + (cs.replyTarget.userName || "用户")),
                  h("span", { onClick: function(e) { e.stopPropagation(); cancelDynReply(dyn.id); }, style: { color: "#999", cursor: "pointer", marginLeft: 6 } }, "取消")
                ) : null,
                h("div", { style: { display: "flex", gap: 4, alignItems: "center", marginTop: 4 } },
                  h("input", { value: cs.inputVal || "", placeholder: cs.replyTarget ? ("回复 " + (cs.replyTarget.userName || "用户") + "...") : "说点什么吧...", onInput: function(e) { updateDynInput(dyn.id, e.target.value); }, maxLength: 500, style: { flex: 1, padding: "5px 8px", border: "1px solid #e8e8e8", borderRadius: 12, fontSize: 11, outline: "none", background: "#f9f9f9" } }),
                  h("button", { onClick: function() { submitDynComment(dyn.id, di); }, style: { width: 26, height: 26, borderRadius: "50%", border: "none", background: "#1677ff", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", flexShrink: 0 } },
                    h("svg", { width: 12, height: 12, viewBox: "0 0 24 24", fill: "none", stroke: "#fff", strokeWidth: 2.5, 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" }))
                  )
                )
              );
            })
          )
        ) :

        // Reviews tab
        h("div", null,
          h("div", { style: { display: "flex", marginBottom: 8 } },
            [{ label: "总评价", val: reviewStats.total || 0 }, { label: "好评", val: reviewStats.good || 0, color: "#16a34a" }, { label: "中评", val: reviewStats.middle || 0, color: "#f59e0b" }, { label: "差评", val: reviewStats.bad || 0, color: "#ef4444" }].map(function(r, ri) { return h("div", { key: "rv-" + ri, style: { flex: 1, textAlign: "center", padding: "8px 4px" } }, h("div", { style: { fontSize: 16, fontWeight: 700, color: r.color || "#1677ff" } }, String(r.val)), h("div", { style: { fontSize: 10, color: "#8c8c8c" } }, r.label)); })
          ),
          // Filter bar
          h("div", { style: { display: "flex", gap: 8, marginBottom: 10, position: "relative" } },
            // Rating filter dropdown
            h("div", { style: { position: "relative" } },
              h("button", {
                onClick: function() { setShowRatingMenu(!showRatingMenu); },
                style: { padding: "5px 12px", borderRadius: 6, border: "1px solid #e0e0e0", background: "#fff", fontSize: 12, color: "#333", cursor: "pointer", display: "flex", alignItems: "center", gap: 4, whiteSpace: "nowrap" }
              }, ratingFilter === "all" ? "全部" : ratingFilter === "good" ? "好评" : ratingFilter === "middle" ? "中评" : "差评",
                h("span", { style: { fontSize: 10, marginLeft: 2 } }, "▼")
              ),
              showRatingMenu ? h("div", {
                style: { position: "absolute", top: "100%", left: 0, marginTop: 4, background: "#fff", borderRadius: 8, boxShadow: "0 4px 16px rgba(0,0,0,0.12)", zIndex: 50, overflow: "hidden", minWidth: 100 },
                onClick: function(e) { e.stopPropagation(); }
              },
                [{ key: "all", label: "全部" }, { key: "good", label: "好评" }, { key: "middle", label: "中评" }, { key: "bad", label: "差评" }].map(function(opt) {
                  var sel = ratingFilter === opt.key;
                  return h("div", { key: opt.key,
                    onClick: function() { setRatingFilter(opt.key); setShowRatingMenu(false); },
                    style: { padding: "8px 14px", fontSize: 12, cursor: "pointer", color: sel ? "#1677ff" : "#333", fontWeight: sel ? 600 : 400, background: sel ? "#f0f5ff" : "#fff", borderBottom: "1px solid #f5f5f5" }
                  }, opt.label);
                })
              ) : null
            ),
            // Only with image toggle
            h("button", {
              onClick: function() { setOnlyWithImage(!onlyWithImage); },
              style: { padding: "5px 12px", borderRadius: 6, border: onlyWithImage ? "1px solid #1677ff" : "1px solid #e0e0e0", background: onlyWithImage ? "#f0f5ff" : "#fff", fontSize: 12, color: onlyWithImage ? "#1677ff" : "#666", fontWeight: onlyWithImage ? 600 : 400, cursor: "pointer", whiteSpace: "nowrap" }
            }, "带图评价")
          ),
          // Filtered reviews logic
          (function() {
            var filtered = reviews;
            if (ratingFilter !== "all") {
              filtered = filtered.filter(function(rv) { return rv.rating === ratingFilter; });
            }
            if (onlyWithImage) {
              filtered = filtered.filter(function(rv) {
                var imgs = Array.isArray(rv.images) ? rv.images : [];
                return imgs.length > 0;
              });
            }
            if (filtered.length === 0) {
              return h("div", { style: { textAlign: "center", fontSize: 13, color: "#8c8c8c", padding: "20px 0", minHeight: "120px", display: "flex", alignItems: "center", justifyContent: "center" } }, "暂无符合条件的评价");
            }
            return h("div", { style: { display: "flex", flexDirection: "column", gap: 0 } },
              filtered.map(function(rv, rvi) {
                var ratingTag = rv.rating === "good" ? "好评" : rv.rating === "middle" ? "中评" : "差评";
                var ratingTagColor = rv.rating === "good" ? "#f59e0b" : rv.rating === "middle" ? "#d97706" : "#ef4444";
                var bottomLabel = rv.rating === "good" ? "服务不错" : rv.rating === "middle" ? "体验一般" : "体验较差";
                var bottomIcon = rv.rating === "good" ? "✅" : rv.rating === "middle" ? "⚠️" : "❌";
                var ratingColor = rv.rating === "good" ? "#f59e0b" : rv.rating === "middle" ? "#d97706" : "#ef4444";
                var imgs = Array.isArray(rv.images) ? rv.images : [];
                return h("div", { key: "review-" + (rv.orderId || rvi),
                  style: { padding: "12px 0", borderBottom: rvi < filtered.length - 1 ? "1px solid #f0f0f0" : "none" }
                },
                  h("div", { style: { display: "flex", alignItems: "flex-start", gap: 10 } },
                    h("div", { style: { width: 36, height: 36, borderRadius: "50%", overflow: "hidden", flexShrink: 0, background: "#e5e7eb" } },
                      rv.buyerAvatar
                        ? h("img", { src: rv.buyerAvatar, alt: "", style: { width: "100%", height: "100%", objectFit: "cover" },
                            onError: function(e) { e.target.style.display = "none"; }
                          })
                        : h("div", { style: { width: "100%", height: "100%", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14, color: "#9ca3af" } }, "🙂")
                    ),
                    h("div", { style: { flex: 1, minWidth: 0 } },
                      h("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 4 } },
                        h("span", { style: { fontSize: 14, fontWeight: 600, color: "#1f2937" } }, rv.buyerNickname || "匿名用户"),
                        h("span", { style: { display: "inline-block", fontSize: 11, fontWeight: 600, padding: "1px 6px", borderRadius: 4, background: ratingTagColor + "18", color: ratingTagColor, flexShrink: 0 } }, ratingTag)
                      ),
                      h("span", { style: { display: "inline-flex", alignItems: "center", gap: 4, fontSize: 11, padding: "2px 8px", borderRadius: 4, background: "#f5f5f5", color: "#6b7280", marginBottom: 6 } }, h("span", { style: { fontSize: 12 } }, bottomIcon), bottomLabel),
                      rv.comment ? h("div", { style: { fontSize: 13, color: "#374151", lineHeight: "20px", wordBreak: "break-word" } }, rv.comment) : null,
                      imgs.length > 0 ? h("div", { style: { display: "flex", flexWrap: "wrap", gap: 6, marginTop: 6 } },
                        imgs.map(function(img, ii) {
                          return h("img", { key: "img-" + ii, src: img, alt: "",
                            style: { width: 64, height: 64, borderRadius: 6, objectFit: "cover", cursor: "pointer" },
                            onError: function(e) { e.target.style.display = "none"; },
                            onClick: function(e) { e.stopPropagation(); setPreviewImage(img); }
                          });
                        })
                      ) : null,
                      h("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 6 } },
                        h("span", { style: { fontSize: 11, color: "#9ca3af" } }, rv.createdAt ? formatDynamicTime(rv.createdAt) : ""),
                        (function() { var currentUser = NK.Store.get("user"); var currentId = currentUser ? (currentUser.id || currentUser.userId) : null; if (currentId != null && String(currentId) === String(rv.buyerUserId || 0)) { return h("button", { onClick: function(e) { e.stopPropagation(); if (confirm("确认删除该评价内容？")) { NK.Api.Booster.deleteReviewContent(rv.orderId).then(function(res) { if (res && res.code === 0) { alert("删除成功"); loadData(); } else { alert((res && res.message) || "删除失败"); } }).catch(function() { alert("删除失败，请稍后重试"); }); } }, style: { padding: 4, borderRadius: 4, border: "none", background: "transparent", cursor: "pointer", width: 32, height: 32, display: "flex", alignItems: "center", justifyContent: "center" } }, h("svg", { width: 23, height: 23, viewBox: "0 0 48 48", fill: "none" }, h("path", { d: "M9 10V44H39V10H9Z", fill: "#ffffff", stroke: "#333", strokeWidth: "4", strokeLinejoin: "round" }), h("path", { d: "M20 20V33", stroke: "#333", strokeWidth: "4", strokeLinecap: "round", strokeLinejoin: "round" }), h("path", { d: "M28 20V33", stroke: "#333", strokeWidth: "4", strokeLinecap: "round", strokeLinejoin: "round" }), h("path", { d: "M4 10H44", stroke: "#333", strokeWidth: "4", strokeLinecap: "round", strokeLinejoin: "round" }), h("path", { d: "M16 10L19.289 4H28.7771L32 10H16Z", fill: "#ffffff", stroke: "#333", strokeWidth: "4", strokeLinejoin: "round" }))); } return null; })()
                      ),
                    )
                  )
                );
              })
            );
          })()
        )
      )
    ),
    h("div", { style: { position: "sticky", bottom: 0, zIndex: 120, display: "flex", gap: 10, padding: "10px 12px calc(10px + env(safe-area-inset-bottom, 0px))", background: "#fff", borderTop: "1px solid #e5e7eb", boxShadow: "0 -4px 14px rgba(15,23,42,0.06)" } },
      h("button", { onClick: function() { alert("打赏礼物功能开发中"); }, style: { flex: 1, minWidth: 0, height: 46, borderRadius: 10, border: "1px solid #b9ded9", background: "#eff8f7", color: "#0f766e", display: "flex", alignItems: "center", justifyContent: "center", gap: 8, fontSize: 14, fontWeight: 600, cursor: "pointer" } }, renderProfileActionIcon("gift"), "打赏礼物"),
      h("button", { onClick: handlePrivateMessage, disabled: privateMsgLoading, style: { flex: 1, minWidth: 0, height: 46, borderRadius: 10, border: "1px solid #0f8f87", background: privateMsgLoading ? "#7cc5c0" : "#0f8f87", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", gap: 8, fontSize: 14, fontWeight: 700, cursor: privateMsgLoading ? "not-allowed" : "pointer" } }, renderProfileActionIcon("chat"), privateMsgLoading ? "正在连接" : "私信打手")
    ),
    // Spec selection modal
    showSpecModal && specTarget ? h("div", { style: { position: "fixed", top: 0, left: 0, right: 0, bottom: 0, background: "rgba(0,0,0,0.5)", zIndex: 200, display: "flex", alignItems: "center", justifyContent: "center" }, onClick: function() { setShowSpecModal(false); } },
      h("div", { style: { background: "#fff", borderRadius: 14, padding: 20, width: "90%", maxWidth: 380, maxHeight: "80vh", overflow: "auto" }, onClick: function(e) { e.stopPropagation(); } },
        h("div", { style: { fontSize: 17, fontWeight: 600, marginBottom: 14 } }, "选择服务规格"),
        h("div", { style: { display: "flex", flexDirection: "column", gap: 8, marginBottom: 16 } },
          (specTarget.specs || []).map(function(spec, si) {
            var isSel = si === selectedSpecIdx;
            return h("div", { key: "spec-" + si, onClick: function() { setSelectedSpecIdx(si); }, style: { padding: "10px 12px", borderRadius: 8, border: isSel ? "2px solid #1677ff" : "1px solid #e0e0e0", background: isSel ? "#f0f5ff" : "#fafafa", cursor: "pointer", display: "flex", justifyContent: "space-between", alignItems: "center" } },
              h("span", { style: { fontSize: 14, fontWeight: isSel ? 600 : 400, color: "#1a1a2e" } }, spec.specName || ("规格" + (si + 1))),
              h("span", { style: { fontSize: 14, fontWeight: 600, color: "#f59e0b" } }, "\u{1f48e}" + Number(spec.price || 0).toFixed(2))
            );
          })
        ),
        h("div", { style: { display: "flex", justifyContent: "flex-end", gap: 10 } },
          h("button", { onClick: function() { setShowSpecModal(false); }, style: { padding: "8px 20px", background: "#f0f0f0", color: "#666", border: "none", borderRadius: 6, fontSize: 13, cursor: "pointer" } }, "取消"),
          h("button", { onClick: function() { setShowSpecModal(false); startDesignatedOrder(specTarget, selectedSpecIdx); }, style: { padding: "8px 20px", background: "#1677ff", color: "#fff", border: "none", borderRadius: 6, fontSize: 13, cursor: "pointer" } }, "确认")
        )
      )
    ) : null,

    // Image preview overlay
    previewImage ? h("div", {
      style: { position: "fixed", top: 0, left: 0, right: 0, bottom: 0, background: "rgba(0,0,0,0.65)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 9999, padding: 20 },
      onClick: function() { setPreviewImage(null); }
    },
      h("img", {
        src: previewImage, alt: "",
        onClick: function(e) { e.stopPropagation(); setPreviewImage(null); },
        style: { maxWidth: "90%", maxHeight: "80vh", borderRadius: 8, objectFit: "contain", cursor: "pointer", boxShadow: "0 4px 24px rgba(0,0,0,0.3)" }
      })
    ) : null,
  );
}

window.NK = window.NK || {};
NK.BoosterPublicProfilePage = BoosterPublicProfilePage;
