// 打手中心 - 基础工作台 v2 (real data)
const { useState, useEffect } = React;

function BoosterCenterPage() {
  var h = React.createElement;

  var _loading = useState(true); var loading = _loading[0], setLoading = _loading[1];
  var _approved = useState(false); var approved = _approved[0], setApproved = _approved[1];
var _connectionError = useState(false); var connectionError = _connectionError[0], setConnectionError = _connectionError[1];
  var _online = useState(true); var online = _online[0], setOnline = _online[1];
  var _tags = useState([]); var tags = _tags[0], setTags = _tags[1];
  var _levelName = useState("黑铁"); var levelName = _levelName[0], setLevelName = _levelName[1];
  var _todayAccepted = useState(0); var todayAccepted = _todayAccepted[0], setTodayAccepted = _todayAccepted[1];
  var _servingCount = useState(0); var servingCount = _servingCount[0], setServingCount = _servingCount[1];
  var _currentTab = useState("hall"), currentTab = _currentTab[0], setCurrentTab = _currentTab[1];
  var _profileData = useState(null), profileData = _profileData[0], setProfileData = _profileData[1];
  var _profileLoading = useState(false), profileLoading = _profileLoading[0], setProfileLoading = _profileLoading[1];
  var _profileError = useState(""), profileError = _profileError[0], setProfileError = _profileError[1];
  var _subView = useState(null), subView = _subView[0], setSubView = _subView[1];
  var _ordersLoading = useState(false), ordersLoading = _ordersLoading[0], setOrdersLoading = _ordersLoading[1];
  var _ordersError = useState(""), ordersError = _ordersError[0], setOrdersError = _ordersError[1];
  var _orderList = useState([]), orderList = _orderList[0], setOrderList = _orderList[1];
  var _orderFilter = useState("all"), orderFilter = _orderFilter[0], setOrderFilter = _orderFilter[1];
  var _messagesLoading = useState(false), messagesLoading = _messagesLoading[0], setMessagesLoading = _messagesLoading[1];
  var _messagesError = useState(""), messagesError = _messagesError[0], setMessagesError = _messagesError[1];
  var _messageList = useState([]), messageList = _messageList[0], setMessageList = _messageList[1];
  var boosterMessagePollRef = React.useRef(null);
  var boosterMessageRefreshTimerRef = React.useRef(null);
  var boosterMessageSocketCleanupRef = React.useRef(null);
  var boosterMessageRefreshInFlightRef = React.useRef(false);
  var boosterOrderRefreshTimerRef = React.useRef(null);
  var boosterOrderSocketCleanupRef = React.useRef(null);
  var boosterOrderRefreshInFlightRef = React.useRef(false);
  var _pubTitle = useState(""), pubTitle = _pubTitle[0], setPubTitle = _pubTitle[1];
  var _pubContent = useState(""), pubContent = _pubContent[0], setPubContent = _pubContent[1];
  var _pubImages = useState([]), pubImages = _pubImages[0], setPubImages = _pubImages[1];
  var _pubSubmitting = useState(false), pubSubmitting = _pubSubmitting[0], setPubSubmitting = _pubSubmitting[1];
  var _dynamicsList = useState([]), dynamicsList = _dynamicsList[0], setDynamicsList = _dynamicsList[1];
  var _dynamicsLoading = useState(false), dynamicsLoading = _dynamicsLoading[0], setDynamicsLoading = _dynamicsLoading[1];
  var _dynamicsError = useState(""), dynamicsError = _dynamicsError[0], setDynamicsError = _dynamicsError[1];
  var _profileCommentStates = useState({}), profileCommentStates = _profileCommentStates[0], setProfileCommentStates = _profileCommentStates[1];
  var _dynMsgList = useState([]), dynMsgList = _dynMsgList[0], setDynMsgList = _dynMsgList[1];
  var _dynMsgLoading = useState(false), dynMsgLoading = _dynMsgLoading[0], setDynMsgLoading = _dynMsgLoading[1];
  var _dynMsgError = useState(""), dynMsgError = _dynMsgError[0], setDynMsgError = _dynMsgError[1];
  var _replyModal = useState({ show: false, dynamicId: 0, commentId: 0, userId: 0, userName: "", commentContent: "" }), replyModal = _replyModal[0], setReplyModal = _replyModal[1];
  var _replyContent = useState(""), replyContent = _replyContent[0], setReplyContent = _replyContent[1];
  var _replySubmitting = useState(false), replySubmitting = _replySubmitting[0], setReplySubmitting = _replySubmitting[1];
  var _dynReplyInputs = useState({}), dynReplyInputs = _dynReplyInputs[0], setDynReplyInputs = _dynReplyInputs[1];
  var _dynReplySendingId = useState(null), dynReplySendingId = _dynReplySendingId[0], setDynReplySendingId = _dynReplySendingId[1];
  var _rankType = useState("spender"), rankType = _rankType[0], setRankType = _rankType[1];
  var _rankPeriod = useState("week"), rankPeriod = _rankPeriod[0], setRankPeriod = _rankPeriod[1];
  var _rankList = useState([]), rankList = _rankList[0], setRankList = _rankList[1];
  var _rankLoading = useState(false), rankLoading = _rankLoading[0], setRankLoading = _rankLoading[1];
  var _rankError = useState(""), rankError = _rankError[0], setRankError = _rankError[1];
  var _profileTab = useState("accompany"), profileTab = _profileTab[0], setProfileTab = _profileTab[1];
  var _scopeLoading = useState(false), scopeLoading = _scopeLoading[0], setScopeLoading = _scopeLoading[1];
  var _scopeError = useState(""), scopeError = _scopeError[0], setScopeError = _scopeError[1];
  var _scopeList = useState([]), scopeList = _scopeList[0], setScopeList = _scopeList[1];
  var _toggleLoading = useState({}), toggleLoading = _toggleLoading[0], setToggleLoading = _toggleLoading[1];
  var _editName = useState(""), editName = _editName[0], setEditName = _editName[1];
  var _editBio = useState(""), editBio = _editBio[0], setEditBio = _editBio[1];
  var _editAvatar = useState(""), editAvatar = _editAvatar[0], setEditAvatar = _editAvatar[1];
  var _editCover = useState(""), editCover = _editCover[0], setEditCover = _editCover[1];
  var _reviewsList = useState([]), reviewsList = _reviewsList[0], setReviewsList = _reviewsList[1];
  var _reviewsLoading = useState(false), reviewsLoading = _reviewsLoading[0], setReviewsLoading = _reviewsLoading[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];
  var _editSaving = useState(false), editSaving = _editSaving[0], setEditSaving = _editSaving[1];
  var _editDetailLoaded = useState(false), editDetailLoaded = _editDetailLoaded[0], setEditDetailLoaded = _editDetailLoaded[1];
  var _showServiceModal = useState(false), showServiceModal = _showServiceModal[0], setShowServiceModal = _showServiceModal[1];
  var _hallOrders = useState([]), hallOrders = _hallOrders[0], setHallOrders = _hallOrders[1];
  var _hallLoading = useState(false), hallLoading = _hallLoading[0], setHallLoading = _hallLoading[1];
  var _accepting = useState(null), accepting = _accepting[0], setAccepting = _accepting[1];
  var _diamondData = useState(null), diamondData = _diamondData[0], setDiamondData = _diamondData[1];
  var _diamondLoading = useState(false), diamondLoading = _diamondLoading[0], setDiamondLoading = _diamondLoading[1];
  var _fundDetailTab = useState("deposit"), fundDetailTab = _fundDetailTab[0], setFundDetailTab = _fundDetailTab[1];
  var _convertSubmitting = useState(false), convertSubmitting = _convertSubmitting[0], setConvertSubmitting = _convertSubmitting[1];
  var _showDepositModal = useState(false), showDepositModal = _showDepositModal[0], setShowDepositModal = _showDepositModal[1];
  var _depositAmount = useState(""), depositAmount = _depositAmount[0], setDepositAmount = _depositAmount[1];
  var _depositSubmitting = useState(false), depositSubmitting = _depositSubmitting[0], setDepositSubmitting = _depositSubmitting[1];



  // Fetch booster info on mount
  useEffect(function() {
    var isLogin = NK.Store.isLoggedIn();
    if (!isLogin) { setLoading(false); return; }
    NK.Api.Booster.me().then(function(res) {
      if (res.code === 0 && res.data && res.data.isBooster) {
        setApproved(true);
        setTags(res.data.tags || []);
        setLevelName(res.data.levelName || "黑铁");
        setTodayAccepted(res.data.todayAcceptedCount || 0);
        setServingCount(res.data.servingCount || 0);
      }
      setLoading(false);
    }).catch(function() {
      setLoading(false);
    });
  }, []);

  // Fetch profile summary when switching to "我的" tab
  // Tab data loading (only when approved and no connection error)
  useEffect(function() {
    if (!approved || connectionError) return;
    if (currentTab === "messages") { fetchBoosterImConversations(false); fetchDynamicMessages(); return; }
    if (currentTab === "publish") { fetchDynamics(); return; }
    if (currentTab === "profile") {
      fetchDiamonds();
      if (!profileData) { setProfileLoading(true);
      setProfileError("");
      NK.Api.Booster.centerSummary().then(function(res) {
        if (res && res.code === 0 && res.data) {
          setProfileData(res.data);
          setProfileLoading(false);
        } else {
          setProfileError((res && res.message) || "\u6253\u624B\u6570\u636E\u52A0\u8F7D\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
          setProfileLoading(false);
        }
      }).catch(function(err) {
        setProfileError("\u6253\u624B\u6570\u636E\u52A0\u8F7D\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
        setProfileLoading(false);
      });
      }
    }
  }, [currentTab, approved, connectionError]);

  // Unified IM refresh for the booster messages tab. Keep the global socket alive.
  useEffect(function() {
    if (!approved || connectionError || currentTab !== "messages") return;
    var disposed = false;

    function scheduleRefresh() {
      if (disposed) return;
      if (boosterMessageRefreshTimerRef.current) clearTimeout(boosterMessageRefreshTimerRef.current);
      boosterMessageRefreshTimerRef.current = setTimeout(function() {
        boosterMessageRefreshTimerRef.current = null;
        if (!disposed) fetchBoosterImConversations(true);
      }, 100);
    }

    var offHandlers = [];
    var token = NK.Api && NK.Api.getToken ? NK.Api.getToken() : "";
    if (token && typeof NK.UserImSocket !== "undefined") {
      NK.UserImSocket.connect(token);
      offHandlers.push(NK.UserImSocket.on("im:new_message", scheduleRefresh));
      offHandlers.push(NK.UserImSocket.on("im:conversation_updated", scheduleRefresh));
      offHandlers.push(NK.UserImSocket.on("im:unread_updated", scheduleRefresh));
    }

    boosterMessageSocketCleanupRef.current = function() {
      offHandlers.forEach(function(off) { if (typeof off === "function") off(); });
    };
    boosterMessagePollRef.current = setInterval(function() {
      if (!disposed) fetchBoosterImConversations(true);
    }, 30000);

    return function() {
      disposed = true;
      if (boosterMessageRefreshTimerRef.current) {
        clearTimeout(boosterMessageRefreshTimerRef.current);
        boosterMessageRefreshTimerRef.current = null;
      }
      if (boosterMessagePollRef.current) {
        clearInterval(boosterMessagePollRef.current);
        boosterMessagePollRef.current = null;
      }
      if (boosterMessageSocketCleanupRef.current) {
        boosterMessageSocketCleanupRef.current();
        boosterMessageSocketCleanupRef.current = null;
      }
    };
  }, [currentTab, approved, connectionError]);

  useEffect(function() {
    if (!approved || connectionError || subView !== "orders") return;
    var disposed = false;
    function scheduleOrderRefresh() {
      if (disposed) return;
      if (boosterOrderRefreshTimerRef.current) clearTimeout(boosterOrderRefreshTimerRef.current);
      boosterOrderRefreshTimerRef.current = setTimeout(function() {
        boosterOrderRefreshTimerRef.current = null;
        if (!disposed) fetchOrderRecords(true);
      }, 180);
    }
    var offHandlers = [];
    if (typeof NK.UserImSocket !== "undefined") {
      offHandlers.push(NK.UserImSocket.on("im:conversation_updated", scheduleOrderRefresh));
      offHandlers.push(NK.UserImSocket.on("escort:order_updated", scheduleOrderRefresh));
    }
    boosterOrderSocketCleanupRef.current = function() {
      offHandlers.forEach(function(off) { if (typeof off === "function") off(); });
    };
    return function() {
      disposed = true;
      if (boosterOrderRefreshTimerRef.current) {
        clearTimeout(boosterOrderRefreshTimerRef.current);
        boosterOrderRefreshTimerRef.current = null;
      }
      if (boosterOrderSocketCleanupRef.current) {
        boosterOrderSocketCleanupRef.current();
        boosterOrderSocketCleanupRef.current = null;
      }
    };
  }, [subView, approved, connectionError]);

  // Load rankings when entering rankings subView
  useEffect(function() {
    if (!approved || connectionError) return;
    if (subView !== "rankings") return;
    setRankLoading(true);
    setRankError("");
    NK.Api.Booster.rankings({ type: rankType, period: rankPeriod }).then(function(res) {
      if (res && res.code === 0) {
        setRankList((res.data && res.data.list) || []);
      } else {
        setRankError((res && res.message) || "排行榜加载失败");
      }
      setRankLoading(false);
    }).catch(function() {
      setRankError("排行榜加载失败，请稍后重试");
      setRankLoading(false);
    });
  }, [subView, rankType, rankPeriod, approved, connectionError]);

  // Auto-load service scope when entering profileHome
  useEffect(function() {
    if (!approved || connectionError) return;
    if (subView === "profileHome") { fetchScope(); }
  }, [subView, approved]);
  // Load hall orders when switching to hall tab
  useEffect(function() {
    if (!approved) return;
    if (currentTab !== "hall") return;
    if (!hallLoading) { loadHallOrders(); }
  }, [currentTab, approved]);

  // Load reviews when switching to reviews tab
  useEffect(function() {
    if (profileTab === "reviews" && reviewsList.length === 0 && !reviewsLoading) {
      loadProfileReviews();
    }
  }, [profileTab]);
  function goBack() { NK.Store.navigate("mine"); }
  function toggleOnline() { setOnline(!online); }
  function placeholderClick(label) { alert(label + " 功能开发中"); }

  // === Inline SVG Icons (line style, 20px, strokeWidth 1.8, round) ===
  function IconHome(color) { return h("svg",{width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:color||"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round"},h("path",{d:"m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"})); }
  function IconPencil(color) { return h("svg",{width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:color||"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round"},h("path",{d:"M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"}),h("path",{d:"m15 5 4 4"})); }
  function IconMessage(color) { return h("svg",{width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:color||"currentColor",strokeWidth:1.8,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"})); }
  function IconUser(color) { return h("svg",{width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:color||"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round"},h("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),h("circle",{cx:12,cy:7,r:4})); }
  function IconTrophy(color) { return h("svg",{width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:color||"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round"},h("path",{d:"M6 9H4.5a2.5 2.5 0 0 1 0-5H6"}),h("path",{d:"M18 9h1.5a2.5 2.5 0 0 0 0-5H18"}),h("path",{d:"M4 22h16"}),h("path",{d:"M10 14.66V22"}),h("path",{d:"M14 14.66V22"}),h("path",{d:"M7 22V9a5 5 0 0 1 10 0v13"})); }
  function IconHeadset(color) { return h("svg",{width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:color||"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round"},h("path",{d:"M3 11v3a4 4 0 0 0 4 4h1"}),h("path",{d:"M21 11v3a4 4 0 0 1-4 4h-1"}),h("path",{d:"M3 11a9 9 0 0 1 18 0"})); }
  function IconChart(color) { return h("svg",{width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:color||"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round"},h("path",{d:"M3 3v18h18"}),h("path",{d:"m19 9-5 5-4-4-3 3"})); }
  function IconClipboard(color) { return h("svg",{width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:color||"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round"},h("rect",{x:8,y:2,width:8,height:4,rx:1}),h("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"})); }
  function IconChevronRight(color) { return h("svg",{width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:color||"#bfbfbf",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round"},h("path",{d:"m9 18 6-6-6-6"})); }


  // ---- Loading ----
  if (loading) {
    return h("div", { className: "detail-page", style: { display: "flex", alignItems: "center", justifyContent: "center", minHeight: "100vh" } },
      h("div", { style: { color: "#999", fontSize: 14 } }, "加载中...")
    );
  }

  // ---- Connection Error ----
  if (connectionError) {
    return h("div", { className: "detail-page" },
      h("div", { className: "app-page-header" },
        h("div", { className: "back-btn", onClick: goBack },
          h("svg", { width: 22, height: 22, viewBox: "0 0 24 24", fill: "none", stroke: "#111827", strokeWidth: 1.875, strokeLinecap: "round", strokeLinejoin: "round" },
            h("path", { d: "m15 18-6-6 6-6" })
          )
        ),
        h("span", { className: "app-page-title" }, "打手中心")
      ),
      h("div", { style: { padding: "40px 20px", textAlign: "center" } },
        h("svg", { width:48, height:48, viewBox:"0 0 24 24", fill:"none", stroke:"#ff9800", strokeWidth:1.5, strokeLinecap:"round", strokeLinejoin:"round", style: { marginBottom:16 } }, h("circle", { cx:"12", cy:"12", r:"10"}), h("line", { x1:"12", y1:"8", x2:"12", y2:"12"}), h("line", { x1:"12", y1:"16", x2:"12.01", y2:"16"})),
        h("div", { style: { fontSize: 18, fontWeight: 700, color: "#333", marginBottom: 8 } }, "服务连接异常，请稍后重试"),
        h("div", { style: { fontSize: 14, color: "#999", marginBottom: 24 } }, "网络连接失败，请检查网络后重新加载"),
        h("button", {
          onClick: function() { setConnectionError(false); setLoading(true); setTimeout(function() { window.location.reload(); }, 100); },
          style: { padding: "10px 32px", background: "#1677ff", color: "#fff", border: "none", borderRadius: 8, fontSize: 15, fontWeight: 600, cursor: "pointer" }
        }, "重新加载")
      )
    );
  }

  // ---- Not Approved ----
  if (!approved) {
    return h("div", { className: "detail-page" },
      h("div", { className: "app-page-header" },
        h("div", { className: "back-btn", onClick: goBack },
          h("svg", { width: 22, height: 22, viewBox: "0 0 24 24", fill: "none", stroke: "#111827", strokeWidth: 1.875, strokeLinecap: "round", strokeLinejoin: "round" },
            h("path", { d: "m15 18-6-6 6-6" })
          )
        ),
        h("span", { className: "app-page-title" }, "打手中心"),
        h("span", { style: { color:"red", fontSize:10, marginLeft:8, fontWeight:700 } }, "DEBUG: real_booster_center_loaded")
      ),
      h("div", { style: { padding: "40px 20px", textAlign: "center" } },
        h("svg", { width:48, height:48, viewBox:"0 0 24 24", fill:"none", stroke:"#bbb", strokeWidth:1.5, strokeLinecap:"round", strokeLinejoin:"round", style: { marginBottom:16 } }, h("path", { d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"}), h("path", { d:"M12 8v4"}), h("path", { d:"M12 16h.01"})),
        h("div", { style: { fontSize: 18, fontWeight: 700, color: "#333", marginBottom: 8 } }, "你还不是认证打手"),
        h("div", { style: { fontSize: 14, color: "#999", marginBottom: 24 } }, "请先申请入驻，审核通过后即可使用打手中心"),
        h("button", {
          onClick: function() { NK.Store.navigate("dashouJoin"); },
          style: { padding: "10px 32px", background: "#1677ff", color: "#fff", border: "none", borderRadius: 8, fontSize: 15, fontWeight: 600, cursor: "pointer" }
        }, "去申请入驻")
      )
    );
  }


  // === TAB: Hall - existing booster workbench ===

  var TAG_LABELS = { naikuai: "奶块", delta: "三角洲", dungeon: "副本", accompany: "陪玩", enchant: "附魔", labor: "苦力", escort: "护航" };

  function tagLabel(code) { return TAG_LABELS[code] || code; }

  function loadHallOrders() {
    if (connectionError) return;
    setHallLoading(true);
    NK.Api.Booster.hall({ filter: "all" }).then(function(res) {
      if (res.code === 0) setHallOrders(res.data || []);
      setHallLoading(false);
    }).catch(function() { setHallLoading(false); setConnectionError(true); });
  }

  // ---- ASYNC handleAcceptOrder ----
  async function handleAcceptOrder(order) {
    if (!order || accepting) return;
    setAccepting(order.id);
    try {
      var sourceType = order.sourceType || order.source_type;
      var sourceId = order.sourceId || order.source_id;
      if (sourceType !== "escort_service" || !sourceId) {
        throw new Error("订单来源异常，无法接取护航服务订单");
      }
      var acceptRes = await NK.Api.Escort.acceptOrder(sourceId);
      if (!acceptRes || acceptRes.code !== 0) {
        throw new Error((acceptRes && acceptRes.message) || "接单失败");
      }
      loadHallOrders();
      NK.Api.Booster.me().then(function(meRes) {
        if (meRes.code === 0 && meRes.data) {
          setTodayAccepted(meRes.data.todayAcceptedCount || 0);
          setServingCount(meRes.data.servingCount || 0);
        }
      });
    } catch (err) {
      console.error("[accept] failed:", err);
      alert(err.message || "接单失败，请稍后重试");
      loadHallOrders();
    } finally {
      setAccepting(null);
    }
  }

  function renderHallContent() {
    return h("div", { style: { paddingBottom: 24 } },
      // Status card
      h("div", { className: "pf-card" },
        h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center" } },
          h("div", null,
            h("div", { style: { fontSize: 12, color: "#999", marginBottom: 2 } }, "打手身份"),
            h("div", { style: { fontSize: 16, fontWeight: 700, color: "#1677ff" } }, "已认证打手"),
            h("div", { style: { fontSize: 13, color: "#fa8c16", marginTop: 4, fontWeight: 600 } }, "打手等级：" + levelName)
          ),
          h("div", {
            onClick: toggleOnline,
            style: { display: "flex", alignItems: "center", gap: 8, cursor: "pointer" }
          },
            h("div", { style: { width: 44, height: 24, borderRadius: 12, position: "relative", background: online ? "#1677ff" : "#d9d9d9", transition: "background 0.2s" } },
              h("div", { style: { width: 20, height: 20, borderRadius: "50%", background: "#fff", position: "absolute", top: 2, left: online ? 22 : 2, boxShadow: "0 1px 3px rgba(0,0,0,0.2)", transition: "left 0.2s" } })
            ),
            h("span", { style: { fontSize: 12, fontWeight: 600, color: online ? "#1677ff" : "#999" } }, online ? "接单中" : "已下线")
          )
        ),
      ),

      // Order list
      hallLoading
        ? h("div", { style: { padding: "40px 20px", textAlign: "center" } }, h("span", { style: { color: "#999", fontSize: 14 } }, "加载中..."))
        : hallOrders.length === 0
          ? h("div", { style: { padding: "60px 20px", textAlign: "center" } },
              h("div", { style: { fontSize: 15, fontWeight: 600, color: "#8c8c8c", marginBottom: 6 } }, "暂无可接订单"),
              h("div", { style: { fontSize: 13, color: "#bfbfbf" } }, "请切换分类或稍后再来看看")
            )
          : h("div", { style: { padding: "0 0 12px" } },
              hallOrders.map(function(order) {
                var isThisAccepting = accepting === order.id;
                return h("div", { key: order.id, style: { background: "#fff", borderRadius: 14, padding: "14px 16px", marginBottom: 10, boxShadow: "0 1px 3px rgba(0,0,0,0.04)" } },
                  h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 } },
                    h("div", { style: { display: "flex", gap: 6, alignItems: "center" } },
                      h("span", { style: { padding: "2px 8px", borderRadius: 4, fontSize: 10, fontWeight: 600,
                        background: order.gameTag === "naikuai" ? "#edf3ff" : "#fff0e6",
                        color: order.gameTag === "naikuai" ? "#1677ff" : "#d46b08" } }, tagLabel(order.gameTag)),
                      h("span", { style: { padding: "2px 8px", borderRadius: 4, fontSize: 10, fontWeight: 500, background: "#f5f5f5", color: "#8c8c8c" } }, tagLabel(order.serviceTag)),
                    (order.assignMode === "specified" || order.assign_mode === "specified") ? h("span", { style: { padding: "2px 8px", borderRadius: 4, fontSize: 10, fontWeight: 600, background: "#fff7e6", color: "#d46b08" } }, "指定") : null
                    ),
                    h("span", { style: { fontSize: 18, fontWeight: 700, color: "#ff4d4f" } }, "¥" + Number(order.amount).toFixed(2))
                  ),
                  h("div", { style: { fontSize: 15, fontWeight: 600, color: "#1a1a2e", marginBottom: 4, lineHeight: 1.4 } }, order.title),
                  h("div", { style: { fontSize: 10, color: "#bfbfbf", marginBottom: 6 } }, "ESC:" + (order.escortOrderNo || order.orderNo || "-")),
                  h("div", { style: { fontSize: 13, color: "#8c8c8c", marginBottom: 10, lineHeight: 1.5, overflow: "hidden", textOverflow: "ellipsis", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical" } }, order.description || ""),
                  h("div", { style: { fontSize: 12, color: "#595959", marginBottom: 4 } }, (order.buyerServer || "未填写")),
                  order.buyerRemark ? h("div", { style: { fontSize: 12, color: "#8c8c8c", marginBottom: 8 } }, "买家备注：" + order.buyerRemark) : null,
                  h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center" } },
                    h("div", { style: { display: "flex", gap: 12, fontSize: 12, color: "#bfbfbf" } },
                      h("span", null, order.estimatedTime || ""),
                      h("span", null, order.createdAt ? (function() {
                        var d = new Date(order.createdAt);
                        var diff = Math.floor((Date.now() - d.getTime()) / 60000);
                        return diff < 1 ? "刚刚" : diff < 60 ? diff + "分钟前" : Math.floor(diff / 60) + "小时前";
                      })() : "")
                    ),
                    h("button", { onClick: function() { handleAcceptOrder(order); }, disabled: isThisAccepting,
                      style: { padding: "6px 18px", borderRadius: 16, fontSize: 13, fontWeight: 600,
                        background: isThisAccepting ? "#91caff" : "#1677ff", color: "#fff", border: "none",
                        cursor: isThisAccepting ? "wait" : "pointer", opacity: isThisAccepting ? 0.7 : 1 }
                    }, isThisAccepting ? "接单中..." : "接单")
                  )
                );
              })
            ),

      // Reply modal
      replyModal.show ? 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() { setReplyModal({ show: false }); } },
        h("div", { style: { background: "#fff", borderRadius: 14, padding: 20, width: "90%", maxWidth: 380, maxHeight: "70vh", overflow: "auto" }, onClick: function(e) { e.stopPropagation(); } },
          h("div", { style: { fontSize: 16, fontWeight: 600, marginBottom: 12 } }, "回复评论"),
          h("div", { style: { background: "#f9f9f9", borderRadius: 8, padding: 10, marginBottom: 12, fontSize: 13 } },
            h("span", { style: { color: "#1677ff", fontWeight: 500 } }, replyModal.userName || "用户"),
            h("span", { style: { color: "#999", margin: "0 4px" } }, ":"),
            h("span", { style: { color: "#333" } }, replyModal.commentContent)
          ),
          h("textarea", { value: replyContent, onInput: function(e) { setReplyContent(e.target.value); }, placeholder: "输入回复内容...", maxLength: 500, style: { width: "100%", height: 80, padding: "8px 12px", border: "1px solid #e8e8e8", borderRadius: 8, fontSize: 13, resize: "none", outline: "none", boxSizing: "border-box" } }),
          h("div", { style: { display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 12 } },
            h("button", { onClick: function() { setReplyModal({ show: false }); setReplyContent(""); }, style: { padding: "8px 20px", background: "#f0f0f0", color: "#666", border: "none", borderRadius: 6, fontSize: 13, cursor: "pointer" } }, "取消"),
            h("button", { onClick: submitReply, disabled: replySubmitting, style: { padding: "8px 20px", background: "#1677ff", color: "#fff", border: "none", borderRadius: 6, fontSize: 13, cursor: "pointer" } }, replySubmitting ? "发送中..." : "发送回复")
          )
        )
      ) : null
    );
  }


  
  function handlePayDeposit() {
    setDepositSubmitting(true);
    NK.Api.Booster.payDepositWithDiamonds({ payFull: true }).then(function(res) {
      setDepositSubmitting(false);
      if (res && res.code === 0) {
        alert("保证金缴纳成功！");
        setShowDepositModal(false);
        fetchDiamonds();
      } else {
        alert((res && res.message) || "缴纳失败");
        if ((res && res.message) && res.message.indexOf("不足") >= 0) { /* keep modal open */ } else { setShowDepositModal(false); }
      }
    }).catch(function() { setDepositSubmitting(false); alert("缴纳失败，请稍后重试"); });
  }

  function fetchDiamonds() {
    setDiamondLoading(true);
    NK.Api.Booster.diamondSummary().then(function(res) {
      if (res && res.code === 0) { console.log("[BoosterCenter] diamondSummary response", res.data); setDiamondData(res.data || res); }
      setDiamondLoading(false);
    }).catch(function() { setDiamondLoading(false); });
  }

  function handleConvertDiamonds() {
    var amt = diamondData ? (diamondData.diamondBalance || 0) : 0;
    if (!amt || amt <= 0) { alert("暂无可兑换钻石"); return; }
    setConvertSubmitting(true);
    NK.Api.Booster.convertDiamonds({ convertAll: true }).then(function(res) {
      setConvertSubmitting(false);
      if (res && res.code === 0) {
        alert("转换成功！¥" + (res.data.walletAmount || 0).toFixed(2) + "已到账");

        fetchDiamonds();
        setProfileData(null);
      } else {
        alert((res && res.message) || "转换失败");
      }
    }).catch(function() {
      setConvertSubmitting(false);
      alert("转换失败，请稍后重试");
    });
  }

  // === Fetch service scope ===
  function fetchScope() {
    setScopeLoading(true); setScopeError("");
    NK.Api.Booster.serviceScope().then(function(res) {
      if (res && res.code === 0) setScopeList((res.data && res.data.services) || []);
      else setScopeError((res && res.message) || "服务项目加载失败，请稍后重试");
      setScopeLoading(false);
    }).catch(function() { setScopeError("服务项目加载失败，请稍后重试"); setScopeLoading(false); });
  }

  function toggleScope(serviceId, enable) {
    var key = String(serviceId);
    setToggleLoading(Object.assign({}, toggleLoading, {[key]: true}));
    NK.Api.Booster.toggleServiceScope(serviceId, enable).then(function(res) {
      if (res && res.code === 0) {
        setScopeList(scopeList.map(function(s) { return s.id === serviceId ? Object.assign({}, s, {enabledByBooster: enable}) : s; }));
      }
      var t = Object.assign({}, toggleLoading); delete t[key]; setToggleLoading(t);
    }).catch(function() { var t = Object.assign({}, toggleLoading); delete t[key]; setToggleLoading(t); });
  }
  // Unified service enabled check (handles bool, number, string)
  function isServiceEnabled(srv) {
    if (!srv) return false;
    if (srv.enabledByBooster === true) return true;
    if (srv.enabledByBooster === false) return false;
    if (srv.enabledByBooster === 1) return true;
    if (srv.enabledByBooster === 0) return false;
    if (srv.enabledByBooster === "1") return true;
    if (srv.enabledByBooster === "0") return false;
    if (srv.enabled === true) return true;
    if (srv.enabled === false) return false;
    return false;
  }



  // === Fetch edit profile detail ===
  function fetchEditDetail() {
    NK.Api.Booster.profileDetail().then(function(res) {
      if (res && res.code === 0) {
        var d = res.data || {};
        setEditName(d.name || "");
        setEditBio(d.bio || "");
        setEditAvatar(d.avatar || "");
        setEditCover(d.cover || "");
        setEditDetailLoaded(true);
      }
    }).catch(function() { setEditDetailLoaded(true); });
  }

  function handleUploadEditImage(file, callback) {
    NK.Api.Upload.image(file).then(function(res) {
      if (res && res.code === 0 && res.data && res.data.url) callback(res.data.url);
      else alert("上传失败");
    }).catch(function() { alert("上传失败"); });
  }

  function handleSaveProfile() {
    var name = editName.trim();
    if (!name) { alert("请输入打手名称"); return; }
    if (name.length < 2 || name.length > 12) { alert("名称需要2-12个字"); return; }
    if (editBio.length > 100) { alert("简介最多100字"); return; }
    setEditSaving(true);
    NK.Api.Booster.updateProfile({
      name: name, bio: editBio.trim(),
      avatar: editAvatar, cover: editCover
    }).then(function(res) {
      setEditSaving(false);
      if (res && res.code === 0) {
        alert("资料保存成功");
        setSubView("profileHome");
        NK.Api.Booster.centerSummary().then(function(sumRes) {
          if (sumRes && sumRes.code === 0) { setProfileData(sumRes.data || sumRes); setProfileError(""); }
        }).catch(function(){});
      } else {
        alert((res && res.message) || "保存失败");
      }
    }).catch(function() { setEditSaving(false); alert("保存失败，请稍后重试"); });
  }

  // === Fetch my dynamics ===
  function loadProfileReviews() {
    setReviewsLoading(true);
    var p = profileData ? (profileData.profile || {}) : {};
    NK.Api.Booster.publicProfile({ boosterUserId: p.userId }).then(function(res) {
      if (res && res.code === 0 && res.data) {
        setReviewsList(res.data.reviews || []);
      }
      setReviewsLoading(false);
    }).catch(function() { setReviewsLoading(false); });
  }

  function fetchDynamics() {
    setDynamicsLoading(true);
    setDynamicsError("");
    NK.Api.Booster.myDynamics().then(function(res) {
      if (res && res.code === 0) {
        var newList = (res.data && res.data.list) || [];
        setDynamicsList(newList);
        newList.forEach(function(d) { loadProfileComments(d.id); });
      } else {
        setDynamicsError((res && res.message) || "动态加载失败，请稍后重试");
      }
      setDynamicsLoading(false);
    }).catch(function() {
      setDynamicsError("动态加载失败，请稍后重试");
      setDynamicsLoading(false);
    });
  }

  // === Profile dynamic: like toggle ===
  function handleProfileLike(dynId) {
    NK.Api.Booster.toggleDynamicLike(dynId).then(function(res) {
      if (res && res.code === 0) {
        setDynamicsList(function(prev) {
          return prev.map(function(item) {
            if (item.id !== dynId) 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 || "操作失败"); });
  }

  // === Profile dynamic: load comments ===
  function loadProfileComments(dynId) {
    setProfileCommentStates(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) {
      setProfileCommentStates(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() {
      setProfileCommentStates(function(prev) {
        var cur = prev[dynId] || { comments: [], loading: false, inputVal: "", replyTarget: null };
        return Object.assign({}, prev, { [dynId]: Object.assign({}, cur, { loading: false, loaded: true }) });
      });
    });
  }

  // === Profile dynamic: submit comment ===
  function submitProfileComment(dynId) {
    var state = profileCommentStates[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) {
        setProfileCommentStates(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 }) });
        });
        setDynamicsList(function(prev) {
          return prev.map(function(item) {
            if (item.id !== dynId) return item;
            return Object.assign({}, item, { commentCount: (item.commentCount || 0) + 1 });
          });
        });
      } else { alert((res && res.message) || "评论失败"); }
    }).catch(function(e) { alert(e.message || "评论失败"); });
  }

  // === Profile dynamic: update input ===
  function updateProfileInputVal(dynId, val) {
    setProfileCommentStates(function(prev) {
      var cur = prev[dynId] || { comments: [], inputVal: "", replyTarget: null };
      return Object.assign({}, prev, { [dynId]: Object.assign({}, cur, { inputVal: val }) });
    });
  }

  // === Profile dynamic: set reply target ===
  function setProfileReplyTarget(dynId, commentId, userId, userName) {
    setProfileCommentStates(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 } }) });
    });
  }

  // === Profile dynamic: cancel reply ===
  function cancelProfileReply(dynId) {
    setProfileCommentStates(function(prev) {
      var cur = prev[dynId] || { comments: [], inputVal: "", replyTarget: null };
      return Object.assign({}, prev, { [dynId]: Object.assign({}, cur, { replyTarget: null, inputVal: "" }) });
    });
  }

  // === TAB: Publish (static shell) ===
  function renderPublish() {
    var cardStyle = { background:"#fff", borderRadius:14, padding:16, marginBottom:12, boxShadow:"0 1px 4px rgba(0,0,0,0.04)" };
    var sectionTitleStyle = { fontSize:13, fontWeight:600, color:"#8c8c8c", marginBottom:12, letterSpacing:0.5 };
    var inputStyle = { width:"100%", padding:"10px 12px", borderRadius:8, border:"1px solid #e8e8e8", fontSize:14, outline:"none", boxSizing:"border-box", background:"#fafafa", transition:"border-color 0.2s" };

    // Upload single image
    function uploadImage(file) {
      return NK.Api.Upload.image(file).then(function(res) {
        if (res && res.code === 0 && res.data && res.data.url) return res.data.url;
        throw new Error("上传失败");
      });
    }

    // Handle file select
    function handleFileSelect(e) {
      var files = Array.from(e.target.files || []);
      if (pubImages.length + files.length > 9) { alert("图片过大（单张限10MB），请压缩后再上传"); return; }
      var promises = files.map(function(f) { return uploadImage(f).catch(function() { return null; }); });
      Promise.all(promises).then(function(urls) {
        var valid = urls.filter(function(u) { return !!u; });
        if (valid.length === 0 && files.length > 0) { alert('上传失败，请稍后重试'); return; }
        if (valid.length < files.length) { alert('部分图片上传失败，请重试'); }
        if (valid.length > 0) setPubImages(pubImages.concat(valid));
      });
    }

    function removeImage(idx) {
      var arr = pubImages.slice();
      arr.splice(idx, 1);
      setPubImages(arr);
    }

    function handlePublish() {
      var title = pubTitle.trim();
      var content = pubContent.trim();
      if (!title) { alert("请填写动态标题"); return; }
      if (title.length > 30) { alert("标题最多30字"); return; }
      if (!content) { alert("请填写动态内容"); return; }
      if (content.length > 500) { alert("内容最多500字"); return; }

      setPubSubmitting(true);
      NK.Api.Booster.createDynamic({ title: title, content: content, images: pubImages }).then(function(res) {
        if (res && res.code === 0) {
          alert("动态发布成功");
          setPubTitle("");
          setPubContent("");
          setPubImages([]);
          fetchDynamics();
        } else {
          alert((res && res.message) || "发布失败");
        }
        setPubSubmitting(false);
      }).catch(function() {
        alert("发布失败，请稍后重试");
        setPubSubmitting(false);
      });
    }

    function handleDelete(dynId) {
      if (!confirm("确定删除这条动态吗？")) return;
      NK.Api.Booster.deleteDynamic(dynId).then(function(res) {
        if (res && res.code === 0) {
          alert("动态已删除");
          fetchDynamics();
        } else {
          alert((res && res.message) || "删除失败");
        }
      }).catch(function() {
        alert("删除失败，请稍后重试");
      });
    }

    function formatTime(d) {
      if (!d) return "";
      var t = new Date(d);
      var mm = String(t.getMonth() + 1).padStart(2, "0");
      var dd = String(t.getDate()).padStart(2, "0");
      var hh = String(t.getHours()).padStart(2, "0");
      var min = String(t.getMinutes()).padStart(2, "0");
      return mm + "/" + dd + " " + hh + ":" + min;
    }

    return h("div", { style: { padding:"16px 16px 24px", overflowY:"auto", flex:1 } },

      // ═══ Publish card ═══
      h("div", { style: cardStyle },
        h("div", { style: sectionTitleStyle }, "发布动态"),
        // Title
        h("div", { style: { marginBottom:12 } },
          h("input", { placeholder:"请输入动态标题", value: pubTitle, onInput: function(e) { setPubTitle(e.target.value); }, maxLength:30, style: inputStyle })
        ),
        // Content
        h("div", { style: { marginBottom:12 } },
          h("textarea", { placeholder:"分享你的服务经验、接单状态或游戏心得...", value: pubContent, onInput: function(e) { setPubContent(e.target.value); }, maxLength:500, rows:4,
            style: { ...inputStyle, resize:"vertical", minHeight:80, fontFamily:"inherit" } })
        ),
        // Images
        h("div", { style: { marginBottom:12 } },
          h("div", { style: { display:"flex", flexWrap:"wrap", gap:8 } },
            pubImages.map(function(url, i) {
              return h("div", { key:"img-"+i, style: { position:"relative", width:72, height:72, borderRadius:8, overflow:"hidden", flexShrink:0 } },
                h("img", { src: url, style: { width:"100%", height:"100%", objectFit:"cover" } }),
                h("div", { onClick: function() { removeImage(i); },
                  style: { position:"absolute", top:2, right:2, width:20, height:20, borderRadius:"50%", background:"rgba(0,0,0,0.5)", display:"flex", alignItems:"center", justifyContent:"center", cursor:"pointer" }
                },
                  h("svg", { width:12, height:12, viewBox:"0 0 24 24", fill:"none", stroke:"#fff", strokeWidth:2.5, strokeLinecap:"round" },
                    h("path", { d:"M18 6 6 18" }), h("path", { d:"m6 6 12 12" })
                  )
                )
              );
            }),
            pubImages.length < 9 ? h("label", { key:"add-btn", style: { width:72, height:72, borderRadius:8, border:"1px dashed #d9d9d9", display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", cursor:"pointer", background:"#fafafa" } },
              h("svg", { width:22, height:22, viewBox:"0 0 24 24", fill:"none", stroke:"#bfbfbf", strokeWidth:1.8, strokeLinecap:"round", strokeLinejoin:"round" },
                h("path", { d:"M12 5v14" }), h("path", { d:"M5 12h14" })
              ),
              h("span", { style: { fontSize:10, color:"#bfbfbf", marginTop:2 } }, "添加图片"),
              h("input", { type:"file", accept:"image/jpeg,image/png,image/webp,image/gif", multiple:true, onChange: handleFileSelect, style: { display:"none" } })
            ) : null
          )
        ),
        // Submit button
        h("button", { onClick: handlePublish, disabled: pubSubmitting,
          style: { width:"100%", padding:"10px 0", background: pubSubmitting ? "#91caff" : "#1677ff", color:"#fff", border:"none", borderRadius:8, fontSize:14, fontWeight:600, cursor: pubSubmitting ? "default" : "pointer", transition:"background 0.2s" }
        }, pubSubmitting ? "发布中..." : "发布动态")
      ),

    );
  }


  // === Fetch messages (order service list) ===
  // === Fetch dynamic messages ===
  function fetchDynamicMessages() {
    setDynMsgLoading(true);
    setDynMsgError("");
    NK.Api.Booster.dynamicMessages().then(function(res) {
      if (res && res.code === 0) {
        setDynMsgList((res.data && res.data.list) || []);
      } else {
        setDynMsgError((res && res.message) || "动态消息加载失败");
      }
      setDynMsgLoading(false);
    }).catch(function() {
      setDynMsgError("动态消息加载失败");
      setDynMsgLoading(false);
    });
  }

  // === Submit reply from message modal ===
  function submitReply() {
    var content = replyContent.trim();
    if (!content) { alert("请输入回复内容"); return; }
    if (content.length > 500) { alert("回复内容最多500字"); return; }
    setReplySubmitting(true);
    NK.Api.Booster.createDynamicComment(replyModal.dynamicId, {
      content: content,
      parentId: replyModal.commentId,
      replyToUserId: replyModal.userId
    }).then(function(res) {
      setReplySubmitting(false);
      if (res && res.code === 0) {
        alert("回复成功");
        setReplyModal({ show: false, dynamicId: 0, commentId: 0, userId: 0, userName: "", commentContent: "" });
        setReplyContent("");
        fetchDynamicMessages();
      } else {
        alert((res && res.message) || "回复失败");
      }
    }).catch(function(e) {
      setReplySubmitting(false);
      alert(e.message || "回复失败");
    });
  }

  function fetchBoosterImConversations(silent) {
    if (boosterMessageRefreshInFlightRef.current) return Promise.resolve();
    if (!NK.Api || !NK.Api.Im || !NK.Api.Im.conversations) {
      if (!silent) setMessagesError("统一消息服务暂不可用，请稍后重试");
      return Promise.resolve();
    }
    boosterMessageRefreshInFlightRef.current = true;
    if (!silent) {
      setMessagesLoading(true);
      setMessagesError("");
    }
    return NK.Api.Im.conversations({ type: "buyer_booster" }).then(function(res) {
      if (!res || res.code !== 0) {
        if (!silent) setMessagesError((res && res.message) || "消息加载失败，请稍后重试");
        return;
      }
      var raw = Array.isArray(res.data) ? res.data : [];
      var buyerMap = {};
      raw.filter(function(c) {
        return c && c.type === "buyer_booster" && c.current_member_role === "booster";
      }).forEach(function(c) {
        var peerId = Number(c.peer_user_id || c.peerUserId || c.buyerUserId || 0);
        var convId = Number(c.conversation_id || c.id || 0);
        if (!peerId || !convId) return;
        var key = String(peerId);
        var previous = buyerMap[key];
        var currentTime = new Date(c.last_message_at || c.updated_at || 0).getTime() || 0;
        var previousTime = previous ? (new Date(previous.last_message_at || previous.updated_at || 0).getTime() || 0) : -1;
        if (!previous || currentTime >= previousTime) buyerMap[key] = c;
      });
      var deduped = Object.keys(buyerMap).map(function(key) { return buyerMap[key]; });
      deduped.sort(function(a, b) {
        return (new Date(b.last_message_at || b.updated_at || 0).getTime() || 0) - (new Date(a.last_message_at || a.updated_at || 0).getTime() || 0);
      });
      setMessageList(deduped);
      setMessagesError("");
    }).catch(function() {
      if (!silent) setMessagesError("消息加载失败，请稍后重试");
    }).finally(function() {
      boosterMessageRefreshInFlightRef.current = false;
      if (!silent) setMessagesLoading(false);
    });
  }

  // === TAB: Messages (unified buyer-booster IM) ===
  function renderMessages() {
    var sectionTitleStyle = { fontSize:13, fontWeight:700, color:"#475569", margin:"16px 2px 10px", letterSpacing:0.3 };

    function formatTime(value) {
      if (!value) return "";
      var now = new Date();
      var time = new Date(value);
      var diffSec = Math.floor((now - time) / 1000);
      if (diffSec < 0) diffSec = 0;
      if (diffSec < 60) return "刚刚";
      if (diffSec < 3600) return Math.floor(diffSec / 60) + "分钟前";
      if (diffSec < 86400) return Math.floor(diffSec / 3600) + "小时前";
      var mm = String(time.getMonth() + 1).padStart(2, "0");
      var dd = String(time.getDate()).padStart(2, "0");
      return mm + "/" + dd;
    }

    function openImConversation(conv) {
      var conversationId = Number(conv.conversation_id || conv.id || 0);
      if (!conversationId || isNaN(conversationId)) {
        alert("会话参数无效，请刷新后重试");
        return;
      }
      var latestOrder = conv.latestOrder && typeof conv.latestOrder === "object" ? conv.latestOrder : null;
      var orderId = Number(conv.orderId || (latestOrder && latestOrder.orderId) || 0);
      var params = {
        conversationId: conversationId,
        role: "booster",
        boosterUserId: Number(conv.boosterUserId || 0) || null,
        latestOrder: latestOrder,
        source: "boosterCenterMessages"
      };
      if (orderId && !isNaN(orderId)) params.orderId = orderId;
      NK.Store.navigate("escortOrderChat", params);
    }

    return h("div", { style: { padding:"16px 16px 24px", overflowY:"auto", flex:1, background:"#F8FAFC" } },
      h("div", {
        onClick: function() { setSubView("dynamicMessages"); },
        style: { display:"flex", alignItems:"center", padding:16, background:"#fff", borderRadius:14, cursor:"pointer", border:"1px solid #E8EEF3", boxShadow:"0 2px 8px rgba(30,41,59,0.04)" }
      },
        h("div", { style: { width:44, height:44, borderRadius:"50%", background:"#EDE9FE", color:"#7C3AED", display:"flex", alignItems:"center", justifyContent:"center", flexShrink:0 } },
          h("span", { style: { width:18, height:14, border:"2px solid currentColor", borderRadius:5, display:"block", position:"relative", boxSizing:"border-box" } },
            h("span", { style: { position:"absolute", left:2, bottom:-4, width:6, height:6, borderLeft:"2px solid currentColor", borderBottom:"2px solid currentColor", transform:"skew(-25deg)", background:"#EDE9FE" } })
          )
        ),
        h("div", { style: { flex:1, minWidth:0, marginLeft:12 } },
          h("div", { style: { fontSize:14, fontWeight:700, color:"#1E293B", marginBottom:3 } }, "动态互动消息"),
          h("div", { style: { fontSize:12, color:"#64748B", overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" } }, "查看点赞、评论和回复" + (dynMsgList.length > 0 ? " · 共" + dynMsgList.length + "条" : ""))
        )
      ),
      h("div", { style: sectionTitleStyle }, "买家私信"),
      messagesLoading ? h("div", { style: { padding:40, textAlign:"center", color:"#64748B", fontSize:13 } }, "消息加载中...") :
      messagesError ? h("div", { style: { padding:40, textAlign:"center" } },
        h("div", { style: { fontSize:13, color:"#64748B", marginBottom:10 } }, messagesError),
        h("button", { onClick:function() { fetchBoosterImConversations(false); }, style: { padding:"7px 20px", background:"#1677ff", color:"#fff", border:"none", borderRadius:8, fontSize:12, cursor:"pointer" } }, "重新加载")
      ) :
      messageList.length === 0 ? h("div", { style: { padding:"38px 16px", textAlign:"center", background:"#fff", borderRadius:14, border:"1px solid #E8EEF3", color:"#64748B", fontSize:13 } }, "暂无买家私信") :
      h("div", null,
        messageList.map(function(conv) {
          var buyerName = conv.peer_nickname || conv.display_title || conv.title || "买家";
          var buyerAvatar = conv.peer_avatar || conv.avatar || "";
          var unreadCount = Number(conv.unread_count || 0);
          var lastMessage = conv.last_message_type === "image" ? "[图片]" : (conv.last_message || "暂无消息");
          var conversationId = conv.conversation_id || conv.id;
          return h("div", {
            key:"booster-im-" + conversationId,
            onClick:function() { openImConversation(conv); },
            style: { background:"#fff", borderRadius:14, padding:"14px 16px", marginBottom:10, display:"flex", alignItems:"center", border:"1px solid #E8EEF3", boxShadow:"0 2px 8px rgba(30,41,59,0.04)", cursor:"pointer" }
          },
            buyerAvatar ? h("img", { src:buyerAvatar, alt:"", style: { width:46, height:46, borderRadius:"50%", objectFit:"cover", flexShrink:0, background:"#E2E8F0" }, onError:function(e) { e.target.style.display="none"; } }) :
              h("div", { style: { width:46, height:46, borderRadius:"50%", background:"#DBEAFE", color:"#1D4ED8", display:"flex", alignItems:"center", justifyContent:"center", flexShrink:0, fontSize:16, fontWeight:700 } }, String(buyerName).charAt(0)),
            h("div", { style: { flex:1, minWidth:0, marginLeft:12 } },
              h("div", { style: { display:"flex", alignItems:"center", justifyContent:"space-between", gap:8, marginBottom:5 } },
                h("div", { style: { flex:1, minWidth:0, fontSize:15, fontWeight:700, color:"#1E293B", overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" } }, buyerName),
                h("span", { style: { flexShrink:0, fontSize:11, color:"#94A3B8" } }, formatTime(conv.last_message_at || conv.updated_at))
              ),
              h("div", { style: { display:"flex", alignItems:"center", justifyContent:"space-between", gap:8 } },
                h("div", { style: { flex:1, minWidth:0, fontSize:13, color:"#64748B", overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" } }, lastMessage),
                unreadCount > 0 ? h("span", { style: { flexShrink:0, minWidth:18, height:18, padding:"0 5px", borderRadius:9, background:"#EF4444", color:"#fff", fontSize:10, lineHeight:"18px", textAlign:"center" } }, unreadCount > 99 ? "99+" : String(unreadCount)) : null
              )
            )
          );
        })
      )
    );
  }


  // === Fetch order records ===
  function fetchOrderRecords(silent) {
    if (silent && boosterOrderRefreshInFlightRef.current) return;
    if (silent) boosterOrderRefreshInFlightRef.current = true;
    else setOrdersLoading(true);
    setOrdersError("");
    NK.Api.Escort.myOrders({ role: "booster" }).then(function(res) {
      if (res && res.code === 0) {
        var list = (res.data && res.data.list) || [];
        setOrderList(list);
      } else {
        setOrdersError((res && res.message) || "订单记录加载失败，请稍后重试");
      }
      if (!silent) setOrdersLoading(false);
      boosterOrderRefreshInFlightRef.current = false;
    }).catch(function(err) {
      setOrdersError("订单记录加载失败，请稍后重试");
      if (!silent) setOrdersLoading(false);
      boosterOrderRefreshInFlightRef.current = false;
    });
  }

  // === Render order records ===
  function renderOrderRecords() {
    var STATUS_TEXT = { 20:"等待打手接单", 30:"打手已接单，等待开启服务", 40:"服务进行中", 60:"打手已完成服务，等待确认", 70:"交易完成", 90:"退款申请中", 91:"退款处理中", 100:"售后处理中", 110:"已退款", 120:"已取消", 130:"订单已冻结" };
    var filterTabs = [
      { key: "all", label: "全部" },
      { key: "today", label: "今日接单" },
      { key: "serving", label: "服务中" },
      { key: "completed", label: "已结单" }
    ];

    // Filter logic
    var filtered = orderList.filter(function(o) {
      var status = Number(o.status);
      if (orderFilter === "serving") return status === 30 || status === 40 || status === 60;
      if (orderFilter === "completed") return status === 70;
      if (orderFilter === "today") {
        if (!o.acceptedAt) return false;
        var today = new Date();
        var accepted = new Date(o.acceptedAt);
        return accepted.getFullYear() === today.getFullYear() &&
               accepted.getMonth() === today.getMonth() &&
               accepted.getDate() === today.getDate();
      }
      return true; // all
    });

    function goToOrder(order) {
      var id = Number(order && order.id);
      if (!id || isNaN(id)) { alert("订单参数异常，请刷新后重试"); return; }
      if (NK.Store.openEscortOrderDetailNative && NK.Store.openEscortOrderDetailNative(id, "booster", { source:"boosterOrderRecords" })) return;
      NK.Store.navigate("escortOrderDetail", { orderId:id, role:"booster", source:"boosterOrderRecords" });
    }

    function goToOrderChat(order) {
      var id = Number(order && order.id);
      if (!id || isNaN(id)) { alert("订单参数异常，请刷新后重试"); return; }
      NK.Api.Im.escortOrderConversation({ order_id:id }).then(function(res) {
        var data = res && res.data || {};
        var conversationId = Number(data.conversation_id || data.id || 0);
        if (!res || res.code !== 0 || !conversationId || isNaN(conversationId)) {
          throw new Error("订单会话连接失败，请稍后重试");
        }
        var next = { orderId:id, role:"booster", conversationId:conversationId, conversationData:data, source:"boosterOrderRecords" };
        if (NK.Store.openNativePage && NK.Store.openNativePage("pages/escort/order-chat", next)) return;
        NK.Store.navigate("escortOrderChat", next);
      }).catch(function() {
        alert("订单会话连接失败，请稍后重试");
      });
    }

    return h("div", { style: { flex:1, display:"flex", flexDirection:"column", overflow:"hidden" } },
      // Back + title bar
      h("div", { style: { display:"flex", alignItems:"center", padding:"12px 16px", background:"#fff", borderBottom:"1px solid #e8e8e8", flexShrink:0 } },
        h("div", { onClick: function() { setSubView(null); }, style: { cursor:"pointer", marginRight:12, display:"flex", alignItems:"center" } },
          h("svg", { width:22, height:22, viewBox:"0 0 24 24", fill:"none", stroke:"#111827", strokeWidth:1.875, strokeLinecap:"round", strokeLinejoin:"round" },
            h("path", { d: "m15 18-6-6 6-6" })
          )
        ),
        h("span", { style: { fontSize:16, fontWeight:600, color:"#111827" } }, "订单记录")
      ),
      // Filter tabs
      h("div", { style: { display:"flex", background:"#fff", borderBottom:"1px solid #f0f0f0", flexShrink:0, overflowX:"auto" } },
        filterTabs.map(function(tab) {
          var active = orderFilter === tab.key;
          return h("div", { key:tab.key, onClick:function() { setOrderFilter(tab.key); }, style: { flex:"0 0 auto", padding:"10px 16px", fontSize:13, fontWeight:active?600:400, color:active?"#1677ff":"#595959", borderBottom:active?"2px solid #1677ff":"2px solid transparent", cursor:"pointer", whiteSpace:"nowrap" } }, tab.label);
        })
      ),
      // Content
      ordersLoading ? h("div", { style: { flex:1, display:"flex", alignItems:"center", justifyContent:"center" } }, h("span", { style: { color:"#999", fontSize:14 } }, "加载中...")) :
      ordersError ? h("div", { style: { flex:1, display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", padding:40 } },
        h("div", { style: { fontSize:14, color:"#999", marginBottom:12 } }, ordersError),
        h("button", { onClick: fetchOrderRecords, style: { padding:"8px 24px", background:"#1677ff", color:"#fff", border:"none", borderRadius:6, fontSize:13, cursor:"pointer" } }, "重新加载")
      ) :
      filtered.length === 0 ? h("div", { style: { flex:1, display:"flex", alignItems:"center", justifyContent:"center" } }, h("span", { style: { color:"#999", fontSize:14 } }, "暂无订单记录")) :
      h("div", { style: { flex:1, overflowY:"auto", padding:"12px 16px", paddingBottom:20 } },
        filtered.map(function(order) {
          var status = Number(order.status);
          var statusColor = status === 70 ? "#16a34a" : (status === 40 || status === 60) ? "#1677ff" : status === 30 ? "#f59e0b" : "#8c8c8c";
          var statusBg = status === 70 ? "#f0fdf4" : (status === 40 || status === 60) ? "#eff6ff" : status === 30 ? "#fffbeb" : "#f9fafb";
          var btnText = (status === 30 || status === 40 || status === 60 || status === 70) ? "查看订单" : "查看详情";
          var acceptedTime = order.acceptedAt ? new Date(order.acceptedAt).toLocaleString("zh-CN", { month:"2-digit", day:"2-digit", hour:"2-digit", minute:"2-digit" }) : "";
          return h("div", { key:order.id, onClick:function() { goToOrder(order); }, style: { background:"#fff", borderRadius:10, boxShadow:"0 1px 3px rgba(0,0,0,0.04)", padding:14, marginBottom:10, cursor:"pointer" } },
            h("div", { style: { display:"flex", justifyContent:"space-between", alignItems:"flex-start", marginBottom:8 } },
              h("span", { style: { fontSize:14, fontWeight:600, color:"#111827", flex:1, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" } }, order.serviceTitle || "护航服务"),
              h("span", { style: { fontSize:12, padding:"2px 8px", borderRadius:4, color:statusColor, background:statusBg, flexShrink:0, marginLeft:8 } }, STATUS_TEXT[status] || ("状态"+status))
            ),
            h("div", { style: { display:"flex", flexWrap:"wrap", gap:"6px 16px", fontSize:12, color:"#8c8c8c", marginBottom:6 } },
              h("span", null, "¥" + (Number(order.amount) || 0).toFixed(2)),
              order.gameServer ? h("span", null, "服务器: " + order.gameServer) : null,
              order.accountId ? h("span", null, "账号: " + order.accountId) : null,
              acceptedTime ? h("span", null, "接单: " + acceptedTime) : null
            ),
            h("div", { style: { display:"flex", justifyContent:"space-between", alignItems:"center" } },
              h("span", { style: { fontSize:11, color:"#bfbfbf" } }, order.orderNo ? "单号: " + order.orderNo.substring(0,16) : ""),
              h("div", { style:{ display:"flex", gap:8 } },
                h("button", { onClick: function(event) { event.stopPropagation(); goToOrderChat(order); }, style: { padding:"5px 12px", background:"#fff", color:"#1677ff", border:"1px solid #1677ff", borderRadius:14, fontSize:12, cursor:"pointer" } }, "联系买家"),
                h("button", { onClick: function(event) { event.stopPropagation(); goToOrder(order); }, style: { padding:"5px 14px", background:"#1677ff", color:"#fff", border:"none", borderRadius:14, fontSize:12, cursor:"pointer" } }, btnText)
              )
            )
          );
        })
      )
    );
  }



  // === Render edit profile page ===
  function renderEditProfile() {
    if (!editDetailLoaded) {
      // Load detail on first render
      fetchEditDetail();
      return h("div",{style:{padding:60,textAlign:"center",flex:1}},h("div",{style:{color:"#999",fontSize:14}},"加载中..."));
    }

    var defaultCover = "linear-gradient(135deg, #1677ff 0%, #0958d9 40%, #003eb3 100%)";
    var cardStyle = { background:"#fff", borderRadius:14, padding:16, boxShadow:"0 1px 4px rgba(0,0,0,0.04)" };

    // Calculate completion rate
    var completed = 0, total = 3;
    if (editName.trim()) completed++;
    if (editBio.trim()) completed++;
    if (editAvatar.trim()) completed++;
    var rate = Math.round(completed * 100 / total);

    return h("div",{style:{flex:1,overflowY:"auto"}},

      // ═══ Cover area ═══
      h("div",{style:{position:"relative",height:160,background:editCover?"url("+editCover+") center/cover no-repeat":defaultCover}},
        // Back button
        h("div",{onClick:function(){setSubView("profileHome")},style:{position:"absolute",top:10,left:16,width:36,height:36,borderRadius:"50%",background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",zIndex:20}},
          h("svg",{width:18,height:18,viewBox:"0 0 24 24",fill:"none",stroke:"#fff",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},h("path",{d:"m15 18-6-6 6-6"}))
        ),

        h("label",{style:{position:"absolute",top:10,right:16,padding:"5px 14px",background:"rgba(0,0,0,0.35)",color:"#fff",border:"1px solid rgba(255,255,255,0.25)",borderRadius:16,fontSize:11,cursor:"pointer",display:"flex",alignItems:"center",gap:4}},
          h("svg",{width:12,height:12,viewBox:"0 0 24 24",fill:"none",stroke:"#fff",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},h("path",{d:"M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"}),h("circle",{cx:12,cy:13,r:4})),
          "更换封面",
          h("input",{type:"file",accept:"image/jpeg,image/png,image/webp,image/gif",onChange:function(e){var f=e.target.files[0];if(f)handleUploadEditImage(f,setEditCover)},style:{display:"none"}})
        )
      ),
      // ═══ Avatar ═══
      h("div",{style:{display:"flex",justifyContent:"center",marginTop:-36,marginBottom:0}},
        h("label",{style:{position:"relative",cursor:"pointer"}},
          editAvatar
            ? h("img",{src:editAvatar,style:{width:72,height:72,borderRadius:"50%",objectFit:"cover",border:"3px solid #fff",boxShadow:"0 2px 8px rgba(0,0,0,0.12)"}})
            : h("div",{style:{width:72,height:72,borderRadius:"50%",background:"#e6f7ff",border:"3px solid #fff",boxShadow:"0 2px 8px rgba(0,0,0,0.12)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:30,fontWeight:600,color:"#1677ff"}},editName.charAt(0)||"?"),
          h("div",{style:{position:"absolute",bottom:0,right:0,width:22,height:22,borderRadius:"50%",background:"#1677ff",display:"flex",alignItems:"center",justifyContent:"center",border:"2px solid #fff"}},
            h("svg",{width:10,height:10,viewBox:"0 0 24 24",fill:"none",stroke:"#fff",strokeWidth:2.5,strokeLinecap:"round",strokeLinejoin:"round"},h("path",{d:"M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"}),h("circle",{cx:12,cy:13,r:4}))
          ),
          h("input",{type:"file",accept:"image/jpeg,image/png,image/webp,image/gif",onChange:function(e){var f=e.target.files[0];if(f)handleUploadEditImage(f,setEditAvatar)},style:{display:"none"}})
        )
      ),
      // Completion rate
      h("div",{style:{textAlign:"center",margin:"6px 0 16px"}},
        h("span",{style:{fontSize:12,color:"#1677ff",fontWeight:500}},"资料完成度 "+rate+"%")
      ),
      // ═══ Settings card ═══
      h("div",{style:{...cardStyle,margin:"0 16px 12px"}},
        // Name row
        h("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 0",borderBottom:"1px solid #f5f5f5",cursor:"pointer"}},
          h("span",{style:{fontSize:14,color:"#1a1a2e",fontWeight:500}},"名称"),
          h("input",{value:editName,onInput:function(e){setEditName(e.target.value)},placeholder:"请输入打手名称",maxLength:12,
            style:{flex:1,textAlign:"right",border:"none",outline:"none",fontSize:14,color:"#595959",background:"transparent",margin:"0 8px"}}),
          h("svg",{width:14,height:14,viewBox:"0 0 24 24",fill:"none",stroke:"#bfbfbf",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round"},h("path",{d:"m9 18 6-6-6-6"}))
        ),
        // Bio row
        h("div",{style:{padding:"14px 0",borderBottom:"1px solid #f5f5f5"}},
          h("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8}},
            h("span",{style:{fontSize:14,color:"#1a1a2e",fontWeight:500}},"简介"),
            h("svg",{width:14,height:14,viewBox:"0 0 24 24",fill:"none",stroke:"#bfbfbf",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round"},h("path",{d:"m9 18 6-6-6-6"}))
          ),
          h("textarea",{value:editBio,onInput:function(e){setEditBio(e.target.value)},placeholder:"介绍一下你的服务经验、擅长内容或接单时间",maxLength:100,rows:3,
            style:{width:"100%",padding:"8px 10px",borderRadius:8,border:"1px solid #e8e8e8",fontSize:13,color:"#595959",outline:"none",resize:"vertical",boxSizing:"border-box",fontFamily:"inherit",background:"#fafafa"}})
        ),
        // Service scope row
        h("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 0",cursor:"pointer"},
          onClick:function(){setSubView("serviceSelect")}},
          h("span",{style:{fontSize:14,color:"#1a1a2e",fontWeight:500}},"陪玩服务"),
          h("div",{style:{display:"flex",alignItems:"center",gap:4}},
            h("span",{style:{fontSize:12,color:"#8c8c8c"}},"已开启 "+scopeList.filter(isServiceEnabled).length+" 个"),
            h("svg",{width:14,height:14,viewBox:"0 0 24 24",fill:"none",stroke:"#bfbfbf",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round"},h("path",{d:"m9 18 6-6-6-6"}))
          )
        )
      ),
      // ═══ Save button ═══
      h("div",{style:{margin:"0 16px 20px"}},
        h("button",{onClick:handleSaveProfile,disabled:editSaving,
          style:{width:"100%",padding:"12px 0",background:editSaving?"#91caff":"#1677ff",color:"#fff",border:"none",borderRadius:10,fontSize:15,fontWeight:600,cursor:editSaving?"default":"pointer",transition:"background 0.2s"}
        },editSaving?"保存中...":"保存资料")
      )
    );
  }


  // === Render service selection modal ===
  function renderServiceModal() {
    return h("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,zIndex:9999,display:"flex",flexDirection:"column"}},
      // Backdrop
      h("div",{onClick:function(){setShowServiceModal(false)},style:{position:"absolute",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.45)"}}),
      // Bottom sheet
      h("div",{style:{position:"relative",marginTop:"auto",background:"#fff",borderRadius:"16px 16px 0 0",maxHeight:"70vh",display:"flex",flexDirection:"column",zIndex:1}},
        // Header
        h("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"16px 20px 8px",flexShrink:0}},
          h("div",{},
            h("div",{style:{fontSize:16,fontWeight:700,color:"#1a1a2e"}},"选择陪玩服务"),
            h("div",{style:{fontSize:12,color:"#8c8c8c",marginTop:4}},"选择你愿意接单的服务项目，买家后续可指定你下单")
          ),
          h("div",{onClick:function(){setShowServiceModal(false)},style:{cursor:"pointer",padding:4}},
            h("svg",{width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:"#8c8c8c",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},h("line",{x1:18,y1:6,x2:6,y2:18}),h("line",{x1:6,y1:6,x2:18,y2:18}))
          )
        ),
        // Content - service list
        h("div",{style:{flex:1,overflowY:"auto",padding:"0 20px 16px"}},
          scopeLoading
            ? h("div",{style:{padding:"40px 0",textAlign:"center",color:"#999",fontSize:14}},"加载中...")
            : scopeError
              ? h("div",{style:{padding:"40px 0",textAlign:"center",color:"#ff4d4f",fontSize:14}},scopeError)
              : scopeList.length === 0
                ? h("div",{style:{padding:"40px 0",textAlign:"center",color:"#999",fontSize:14}},"暂无可选服务")
                : scopeList.filter(function(s){return s.enabledByBooster}).map(function(srv){
                    var isToggling = toggleLoading && toggleLoading["s_"+srv.id];
                    return h("div",{key:"svc_"+srv.id,style:{display:"flex",alignItems:"center",padding:"12px 0",borderBottom:"1px solid #f5f5f5",gap:12}},
                      srv.cover
                        ? h("img",{src:srv.cover,style:{width:44,height:44,borderRadius:8,objectFit:"cover",flexShrink:0}})
                        : h("div",{style:{width:44,height:44,borderRadius:8,background:"#f0f5ff",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"}},
                            h("svg",{width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:"#1677ff",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"},h("rect",{x:3,y:3,width:18,height:18,rx:2,ry:2}),h("circle",{cx:8.5,cy:8.5,r:1.5}),h("polyline",{points:"21 15 16 10 5 21"}))
                          ),
                      h("div",{style:{flex:1,minWidth:0}},
                        h("div",{style:{fontSize:14,fontWeight:500,color:"#1a1a2e"}},srv.name),
                        h("div",{style:{fontSize:11,color:"#8c8c8c",marginTop:2}},
                          (srv.bizType === "delta" ? "三角洲" : "奶块") + " · " + (srv.price ? "¥"+Number(srv.price).toFixed(2)+"起" : "暂无定价")
                        )
                      ),
                      h("button",{
                        onClick:function(){toggleService(srv.id,!srv.enabledByBooster)},
                        disabled:isToggling,
                        style:{
                          padding:"5px 14px",
                          borderRadius:16,
                          border:srv.enabledByBooster ? "1px solid #ff4d4f" : "1px solid #1677ff",
                          background:srv.enabledByBooster ? "#fff" : "#1677ff",
                          color:srv.enabledByBooster ? "#ff4d4f" : "#fff",
                          fontSize:12,fontWeight:500,
                          cursor:isToggling?"default":"pointer",
                          flexShrink:0
                        }
                      },isToggling ? "处理中..." : (srv.enabledByBooster ? "关闭" : "开启"))
                    );
                  })
        ),
        // Bottom button
        h("div",{style:{padding:"12px 20px 20px",flexShrink:0}},
          h("button",{onClick:function(){setShowServiceModal(false)},style:{width:"100%",padding:"11px 0",background:"#1677ff",color:"#fff",border:"none",borderRadius:10,fontSize:15,fontWeight:600,cursor:"pointer"}},"完成")
        )
      ),
      showServiceModal ? renderServiceModal() : null
    );
  }

  // === Render profile home (personal page) ===
  
  // === Render service selection sub-page ===
  function renderServiceSelect() {
    if (scopeLoading) {
      return h("div", { style: { flex:1, display:"flex", flexDirection:"column", background:"#f5f5f5" } },
        h("div", { style: { display:"flex", alignItems:"center", padding:"10px 16px", background:"#fff", borderBottom:"1px solid #f0f0f0" } },
          h("div", { onClick: function() { setSubView("editProfile"); }, style: { cursor:"pointer", display:"flex", alignItems:"center", gap:2 } },
            h("svg", { width:20, height:20, viewBox:"0 0 24 24", fill:"none", stroke:"#111827", strokeWidth:1.875, strokeLinecap:"round", strokeLinejoin:"round" }, h("path", { d:"m15 18-6-6 6-6" })),
            h("span", { style: { fontSize:14, color:"#111827", fontWeight:600 } }, "选择服务")
          )
        ),
        h("div", { style: { flex:1, display:"flex", alignItems:"center", justifyContent:"center" } },
          h("span", { style: { color:"#999", fontSize:14 } }, "加载中...")
        )
      );
    }
    if (scopeError) {
      return h("div", { style: { flex:1, display:"flex", flexDirection:"column", background:"#f5f5f5" } },
        h("div", { style: { display:"flex", alignItems:"center", padding:"10px 16px", background:"#fff", borderBottom:"1px solid #f0f0f0" } },
          h("div", { onClick: function() { setSubView("editProfile"); }, style: { cursor:"pointer", display:"flex", alignItems:"center", gap:2 } },
            h("svg", { width:20, height:20, viewBox:"0 0 24 24", fill:"none", stroke:"#111827", strokeWidth:1.875, strokeLinecap:"round", strokeLinejoin:"round" }, h("path", { d:"m15 18-6-6 6-6" })),
            h("span", { style: { fontSize:14, color:"#111827", fontWeight:600 } }, "选择服务")
          )
        ),
        h("div", { style: { flex:1, display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", gap:10 } },
          h("div", { style: { fontSize:14, color:"#ff4d4f" } }, scopeError),
          h("button", { onClick: fetchScope, style: { padding:"6px 20px", background:"#1677ff", color:"#fff", border:"none", borderRadius:6, fontSize:12, cursor:"pointer" } }, "重新加载")
        )
      );
    }
    if (scopeList.length === 0) {
      return h("div", { style: { flex:1, display:"flex", flexDirection:"column", background:"#f5f5f5" } },
        h("div", { style: { display:"flex", alignItems:"center", padding:"10px 16px", background:"#fff", borderBottom:"1px solid #f0f0f0" } },
          h("div", { onClick: function() { setSubView("editProfile"); }, style: { cursor:"pointer", display:"flex", alignItems:"center", gap:2 } },
            h("svg", { width:20, height:20, viewBox:"0 0 24 24", fill:"none", stroke:"#111827", strokeWidth:1.875, strokeLinecap:"round", strokeLinejoin:"round" }, h("path", { d:"m15 18-6-6 6-6" })),
            h("span", { style: { fontSize:14, color:"#111827", fontWeight:600 } }, "选择服务")
          )
        ),
        h("div", { style: { flex:1, display:"flex", alignItems:"center", justifyContent:"center" } },
          h("span", { style: { color:"#999", fontSize:14 } }, "暂无可选服务")
        )
      );
    }
    return h("div", { style: { flex:1, display:"flex", flexDirection:"column", background:"#f5f5f5" } },
      h("div", { style: { display:"flex", alignItems:"center", padding:"10px 16px", background:"#fff", borderBottom:"1px solid #f0f0f0", flexShrink:0 } },
        h("div", { onClick: function() { setSubView("editProfile"); }, style: { cursor:"pointer", display:"flex", alignItems:"center", gap:2 } },
          h("svg", { width:20, height:20, viewBox:"0 0 24 24", fill:"none", stroke:"#111827", strokeWidth:1.875, strokeLinecap:"round", strokeLinejoin:"round" }, h("path", { d:"m15 18-6-6 6-6" })),
          h("span", { style: { fontSize:14, color:"#111827", fontWeight:600 } }, "选择服务")
        )
      ),
      h("div", { style: { padding:"10px 16px 6px", flexShrink:0 } },
        h("div", { style: { fontSize:12, color:"#8c8c8c" } }, "选择你愿意接单的服务项目，买家后续可指定你下单")
      ),
      h("div", { style: { flex:1, overflowY:"auto", padding:"0 16px 16px" } },
        scopeList.map(function(srv) {
          var isToggling = toggleLoading && toggleLoading["s_" + srv.id];
          var enabled = srv.enabledByBooster;
          var bizLabel = srv.bizType === "delta" ? "三角洲" : "奶块";
          return h("div", { key: "ss_" + srv.id, style: { background:"#fff", borderRadius:12, padding:14, marginBottom:10, boxShadow:"0 1px 3px rgba(0,0,0,0.04)" } },
            h("div", { style: { display:"flex", alignItems:"center", gap:10 } },
              srv.cover
                ? h("img", { src: srv.cover, style: { width:48, height:48, borderRadius:8, objectFit:"cover", flexShrink:0 } })
                : h("div", { style: { width:48, height:48, borderRadius:8, background:"#f0f5ff", flexShrink:0, display:"flex", alignItems:"center", justifyContent:"center" } },
                    h("svg", { width:22, height:22, viewBox:"0 0 24 24", fill:"none", stroke:"#1677ff", strokeWidth:1.5, strokeLinecap:"round", strokeLinejoin:"round" },
                      h("rect", { x:3, y:3, width:18, height:18, rx:2, ry:2 }), h("circle", { cx:8.5, cy:8.5, r:1.5 }), h("polyline", { points:"21 15 16 10 5 21" })
                    )
                  ),
              h("div", { style: { flex:1, minWidth:0 } },
                h("div", { style: { fontSize:14, fontWeight:600, color:"#1a1a2e", marginBottom:2 } }, srv.name || "护航服务"),
                h("div", { style: { fontSize:11, color:"#8c8c8c", marginBottom:2 } }, bizLabel + " · ¥" + (Number(srv.price) || 0).toFixed(2) + "起"),
                h("div", { style: { fontSize:11, fontWeight:500, color: enabled ? "#16a34a" : "#8c8c8c" } }, enabled ? "已开启接单" : "未开启")
              ),
              h("button", {
                onClick: function() { toggleScope(srv.id, !enabled); },
                disabled: isToggling,
                style: {
                  padding:"6px 16px", borderRadius:16,
                  border: enabled ? "1px solid #ff4d4f" : "1px solid #1677ff",
                  background: enabled ? "#fff" : "#1677ff",
                  color: enabled ? "#ff4d4f" : "#fff",
                  fontSize:12, fontWeight:500,
                  cursor: isToggling ? "default" : "pointer", flexShrink:0
                }
              }, isToggling ? "处理中..." : (enabled ? "关闭" : "开启"))
            )
          );
        })
      )
    );
  }

function renderProfileHome() {
    if (!profileData) {
      return h("div", { style: { padding:60, textAlign:"center", flex:1 } }, h("div", { style: { color:"#999", fontSize:14 } }, "加载中..."));
    }

    var p = profileData.profile || {};
    var os = profileData.orderStats || {};
    var rs = profileData.reviewStats || {};
    var gameTypeLabel = (p.gameType === "delta" || p.gameType === "expert") ? "三角洲打手" : "奶块打手";
    var cardStyle = { background:"#fff", borderRadius:14, boxShadow:"0 1px 4px rgba(0,0,0,0.06)" };
    var sectionTitleStyle = { fontSize:13, fontWeight:600, color:"#8c8c8c", marginBottom:10, letterSpacing:0.5 };

    // Tab state (local to this page)
    function handleDeleteDyn(dynId) {
      if (!confirm("确定删除这条动态吗？")) return;
      NK.Api.Booster.deleteDynamic(dynId).then(function(res) {
        if (res && res.code === 0) fetchDynamics();
      }).catch(function() {});
    }

    function formatDynamicTime(d) {
      if (!d) return "-";
      var now = Date.now();
      var 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);
    }
        function formatTime(d) { if (!d) return ""; var t = new Date(d); var mm = String(t.getMonth()+1).padStart(2,"0"); var dd = String(t.getDate()).padStart(2,"0"); return mm+"/"+dd; }

    var tabs = [
      { key:"accompany", label:"陪玩" },
      { key:"dynamics", label:"动态" },
      { key:"reviews", label:"评价" }
    ];

    // Fetch data on first load
    

    function renderTabContent() {
      if (profileTab === "accompany") {
        if (scopeLoading) return h("div",{style:{padding:30,textAlign:"center"}},h("span",{style:{color:"#999",fontSize:13}},"加载中..."));
        if (scopeError) return h("div",{style:{padding:30,textAlign:"center"}},h("div",{style:{fontSize:13,color:"#999",marginBottom:10}},scopeError),h("button",{onClick:fetchScope,style:{padding:"6px 20px",background:"#1677ff",color:"#fff",border:"none",borderRadius:6,fontSize:12,cursor:"pointer"}},"重新加载"));
        if (scopeList.filter(isServiceEnabled).length === 0) return h("div",{style:{padding:30,textAlign:"center"}},h("span",{style:{color:"#999",fontSize:13}},"暂无可接服务"));
        return h("div",{style:{display:"flex",flexDirection:"column",gap:8}},
          scopeList.filter(isServiceEnabled).map(function(srv) {
            var enabled = srv.enabledByBooster;
            var isToggling = toggleLoading[String(srv.id)];
            var bizLabel = srv.bizType === "delta" ? "三角洲" : "奶块";
            return h("div",{key:"scope-"+srv.id,style:{display:"flex",alignItems:"center",gap:10,padding:"10px 0",borderBottom:"1px solid #f5f5f5"}},
              h("div",{style:{width:52,height:52,borderRadius:8,overflow:"hidden",flexShrink:0,background:"#f0f0f0"}},
                srv.cover ? h("img",{src:srv.cover,style:{width:"100%",height:"100%",objectFit:"cover"}}) : h("div",{style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"}},h("svg",{width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:"#bfbfbf",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"},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:13,fontWeight:600,color:"#1a1a2e",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},srv.name||"护航服务"),
                h("div",{style:{fontSize:11,color:"#8c8c8c",marginTop:1}},bizLabel+" · ¥"+(Number(srv.price)||0).toFixed(2)+"起"),
                h("div",{style:{fontSize:11,marginTop:2,color:enabled?"#16a34a":"#8c8c8c",fontWeight:500}},enabled?"已开启接单":"未开启")
              ),
              h("button",{onClick:function(){toggleScope(srv.id,!enabled);},disabled:isToggling,
                style:{padding:"4px 12px",borderRadius:14,border:"1px solid",fontSize:11,cursor:isToggling?"default":"pointer",flexShrink:0,
                  color:enabled?"#ff4d4f":"#1677ff",borderColor:enabled?"#ffccc7":"#91caff",background:"#fff"}
              },isToggling?"处理中...":(enabled?"关闭":"开启"))
            );
          })
        );
      }

      if (profileTab === "dynamics") {
        return dynamicsList.length === 0
          ? h("div",{style:{padding:30,textAlign:"center"}},h("span",{style:{color:"#999",fontSize:13}},"暂无动态"))
          : h("div",{style:{display:"flex",flexDirection:"column",gap:10}},
              dynamicsList.map(function(dyn) {
                var name = dyn.boosterName || p.boosterName || "-";
                var avatar = dyn.boosterAvatar || p.avatar || "";
                var level = dyn.boosterLevel || p.level || 0;
                var type = dyn.boosterType || p.gameType || "";
                var time = formatDynamicTime(dyn.createdAt);
                var text = dyn.content || dyn.title || "";
                if (!text) text = "这个打手还没有填写动态内容";
                var imgs = dyn.images || [];
                var likeCount = dyn.likeCount || 0;
                var commentCount = dyn.commentCount || 0;
                var likedByMe = dyn.likedByMe || false;
                var dynId = dyn.id;
                var cs = profileCommentStates[dynId] || { comments: [], loading: false, inputVal: "", replyTarget: null };
                var levelColors = { 1: "#8b7355", 2: "#cd7f32", 3: "#c0c0c0", 4: "#ffd700", 5: "#e5e4e2", 6: "#b9f2ff", 7: "#ff6b6b" };
                var levelLabels = { 0: "不限", 1: "黑铁", 2: "青铜", 3: "白银", 4: "黄金", 5: "铂金", 6: "钻石", 7: "王者" };
                var typeLabels = { naikuai: "奶块打手", delta: "三角洲打手" };
                return h("div",{key:"phdyn-"+dynId,style:{padding:12,background:"#fff",borderRadius:12,marginBottom:8,boxShadow:"0 1px 3px rgba(0,0,0,0.04)"}},
                  // Header: avatar + name + tags + delete
                  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,minWidth:0}},
                      h("div",{style:{display:"flex",alignItems:"center",gap:4,flexWrap:"wrap"}},
                        h("span",{style:{fontSize:14,fontWeight:600,color:"#1a1a2e"}},name),
                        type ? h("span",{style:{fontSize:10,color:"#fa8c16",background:"#fff7e6",padding:"1px 5px",borderRadius:3}},typeLabels[type]||type) : null,
                        level>0 ? h("span",{style:{fontSize:10,color:levelColors[level]||"#666",background:(levelColors[level]||"#f0f0f0")+"22",padding:"1px 5px",borderRadius:3,border:"1px solid "+(levelColors[level]||"#ddd")+"44"}},levelLabels[level]||"") : null
                      ),
                      h("div",{style:{fontSize:11,color:"#999",marginTop:1}},time)
                    ),
                    h("button",{onClick:function(){handleDeleteDyn(dynId)},style:{padding:"2px 6px",background:"transparent",color:"#ff4d4f",border:"1px solid #ffccc7",borderRadius:8,fontSize:10,cursor:"pointer",flexShrink:0}},"删除")
                  ),
                  // Content
                  h("div",{style:{marginTop:8,fontSize:13,color:"#333",lineHeight:1.6,whiteSpace:"pre-wrap",wordBreak:"break-word"}},text),
                  // Images - full size grid
                  (function(){
                    if(!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"}}));}));
                  })(),
                  // Action bar
                  h("div",{style:{display:"flex",alignItems:"center",gap:20,marginTop:10,paddingTop:8,borderTop:"1px solid #f0f0f0"}},
                    h("span",{onClick:function(){handleProfileLike(dynId)},style:{display:"flex",alignItems:"center",gap:3,cursor:"pointer",fontSize:12,color:likedByMe?"#ff4d4f":"#999"}},
                      h("svg",{width:16,height:16,viewBox:"0 0 24 24",fill:likedByMe?"#ff4d4f":"none",stroke:likedByMe?"#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"})),
                      likeCount>0?likeCount:"点赞"
                    ),
                    h("span",{style:{display:"flex",alignItems:"center",gap:3,fontSize:12,color:"#999"}},
                      h("svg",{width:16,height:16,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"})),
                      commentCount>0?commentCount:"评论"
                    )
                  ),
                  // Comments section
                  cs.loading ? h("div",{style:{marginTop:8,textAlign:"center",color:"#999",fontSize:11}},"评论加载中...") :
                  cs.comments.length===0 ? h("div",{style:{marginTop:8,textAlign:"center",color:"#999",fontSize:11}},"暂无评论") :
                  h("div",{style:{marginTop:8,paddingTop:6,borderTop:"1px solid #f5f5f5"}},
                    cs.comments.map(function(c){
                      var isReply=!!c.parentId;
                      return h("div",{key:"pc-"+c.id,onClick:function(){setProfileReplyTarget(dynId,c.id,c.userId,c.userName||"用户")},style:{padding:"3px 0",fontSize:12,lineHeight:1.5,cursor:"pointer"}},
                        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",marginTop:4,fontSize:11}},
                    h("span",{style:{color:"#1677ff"}},"正在回复 "+(cs.replyTarget.userName||"用户")),
                    h("span",{onClick:function(e){e.stopPropagation();cancelProfileReply(dynId)},style:{color:"#999",cursor:"pointer",marginLeft:6}},"取消")
                  ):null,
                  // Comment input
                  h("div",{style:{display:"flex",gap:6,alignItems:"center",marginTop:6}},
                    h("input",{value:cs.inputVal||"",placeholder:cs.replyTarget?("回复 "+(cs.replyTarget.userName||"用户")+"..."):"说点什么吧...",onInput:function(e){updateProfileInputVal(dynId,e.target.value)},maxLength:500,style:{flex:1,padding:"6px 10px",border:"1px solid #e8e8e8",borderRadius:14,fontSize:12,outline:"none",background:"#f9f9f9"}}),
                    h("button",{onClick:function(){submitProfileComment(dynId)},style:{width:30,height:30,borderRadius:"50%",border:"none",background:"#1677ff",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",flexShrink:0}},
                      h("svg",{width:14,height:14,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"}))
                    )
                  )
                );
              })
            );
      }

      if (profileTab === "reviews") {
        if (reviewsLoading) return h("div",{style:{padding:30,textAlign:"center"}},h("span",{style:{color:"#999",fontSize:13}},"加载中..."));
        var rs = profileData ? (profileData.reviewStats || {}) : {};
        var filtered = (reviewsList || []).filter(function(rv) {
          if (ratingFilter !== "all" && rv.rating !== ratingFilter) return false;
          if (onlyWithImage && (!Array.isArray(rv.images) || rv.images.length === 0)) return false;
          return true;
        });
        return h("div",null,
          h("div",{style:{display:"flex",marginBottom:8}},
            [{label:"总评价",val:rs.totalReviews||0},{label:"好评",val:rs.goodReviews||0,color:"#16a34a"},{label:"中评",val:rs.middleReviews||0,color:"#f59e0b"},{label:"差评",val:rs.badReviews||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));})
          ),
          h("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:6}},
            h("div",{style:{position:"relative"}},
              h("button",{onClick:function(){setShowRatingMenu(!showRatingMenu)},style:{padding:"4px 10px",borderRadius:6,border:"1px solid #e0e0e0",background:"#fff",fontSize:12,cursor:"pointer",display:"flex",alignItems:"center",gap:4}},ratingFilter==="all"?"全部":ratingFilter==="good"?"好评":ratingFilter==="middle"?"中评":"差评",h("svg",{width:10,height:10,viewBox:"0 0 24 24",fill:"none",stroke:"#999",strokeWidth:2},h("path",{d:"m6 9 6 6 6-6"}))),
              showRatingMenu?h("div",{style:{position:"absolute",top:"100%",left:0,zIndex:10,background:"#fff",borderRadius:8,boxShadow:"0 2px 12px rgba(0,0,0,0.12)",overflow:"hidden",minWidth:80,marginTop:4}},[{v:"all",l:"全部"},{v:"good",l:"好评"},{v:"middle",l:"中评"},{v:"bad",l:"差评"}].map(function(o){return h("div",{key:o.v,onClick:function(){setRatingFilter(o.v);setShowRatingMenu(false)},style:{padding:"6px 12px",fontSize:12,cursor:"pointer",background:ratingFilter===o.v?"#f0f5ff":"#fff",color:ratingFilter===o.v?"#1677ff":"#333"}},o.l)})):null
            ),
            h("button",{onClick:function(){setOnlyWithImage(!onlyWithImage)},style:{padding:"4px 10px",borderRadius:6,border:onlyWithImage?"1px solid #1677ff":"1px solid #e0e0e0",background:onlyWithImage?"#f0f5ff":"#fff",fontSize:12,cursor:"pointer",color:onlyWithImage?"#1677ff":"#666"}},"带图评价")
          ),
          filtered.length===0?h("div",{style:{padding:30,textAlign:"center"}},h("span",{style:{color:"#999",fontSize:13}},ratingFilter!=="all"||onlyWithImage?"暂无符合条件的评价":"暂无文字评价")):h("div",null,
            filtered.map(function(rv,rvi){
              var rt=rv.rating==="good"?"好评":rv.rating==="middle"?"中评":"差评";
              var rtc=rv.rating==="good"?"#f59e0b":rv.rating==="middle"?"#d97706":"#ef4444";
              var bl=rv.rating==="good"?"服务不错":rv.rating==="middle"?"体验一般":"体验较差";
              var bi=rv.rating==="good"?"✅":rv.rating==="middle"?"⚠️":"❌";
              var ims=Array.isArray(rv.images)?rv.images:[];
              return h("div",{key:"rev-"+(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:rtc+"18",color:rtc,flexShrink:0}},rt)),
                    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}},bi),bl),
                    rv.comment?h("div",{style:{fontSize:13,color:"#374151",lineHeight:"20px",wordBreak:"break-word"}},rv.comment):null,
                    ims.length>0?h("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:6}},ims.map(function(img,ii){return h("img",{key:"im-"+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 cu=NK.Store.get("user");var cid=cu?(cu.id||cu.userId):null;if(cid!=null&&String(cid)===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("删除成功");loadProfileReviews()}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})()
                    )
                  )
                )
              );
            })
          )
        );
      }

    }

    // --- Main render ---
    var coverBg = p.cover ? "url(" + p.cover + ") center/cover no-repeat" : "linear-gradient(135deg, #1677ff 0%, #0958d9 40%, #003eb3 100%)";
    var isOnline = p.status === 1;
    var levelLabels = ["","黑铁","青铜","白银","黄金","铂金","钻石","王者"];
    var levelLabel = levelLabels[p.level] || "黑铁";

    return h("div", { style: { flex:1, display:"flex", flexDirection:"column", overflowY:"auto", WebkitOverflowScrolling:"touch", paddingBottom:24 } },
      // -- Cover header --
      h("div", { style: { position:"relative", height:160, background:coverBg, flexShrink:0 } },
        // Back button
        h("div", { onClick: function() { setSubView(null); setCurrentTab("profile"); }, style: { position:"absolute", top:10, left:8, width:32, height:32, display:"flex", alignItems:"center", justifyContent:"center", background:"rgba(0,0,0,0.25)", borderRadius:"50%", cursor:"pointer", zIndex:2 } },
          h("svg", { width:16, height:16, 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" }))
        ),
        // Edit button
                h("div", { onClick: function() { fetchEditDetail(); fetchScope(); setSubView("editProfile"); }, style: { position:"absolute", top:10, right:12, width:36, height:36, display:"flex", alignItems:"center", justifyContent:"center", background:"rgba(255,255,255,0.25)", borderRadius:"50%", cursor:"pointer", zIndex:20 } },
                h("svg", { width:18, height:18, viewBox:"0 0 24 24", fill:"none", stroke:"#fff", strokeWidth:2, strokeLinecap:"round", strokeLinejoin:"round" },
                  h("path", { d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915" }),
                  h("circle", { cx:12, cy:12, r:3 })
                )
              )
      ),
      // -- Avatar, name, ID, status --
      h("div", { style: { display:"flex", flexDirection:"column", alignItems:"center", marginTop:-36, padding:"0 16px", position:"relative", zIndex:1 } },
        p.avatar
          ? h("img", { src: p.avatar, style: { width:72, height:72, borderRadius:"50%", objectFit:"cover", border:"3px solid #fff", boxShadow:"0 2px 8px rgba(0,0,0,0.12)" } })
          : h("div", { style: { width:72, height:72, borderRadius:"50%", background:"#e6f7ff", border:"3px solid #fff", boxShadow:"0 2px 8px rgba(0,0,0,0.12)", display:"flex", alignItems:"center", justifyContent:"center", fontSize:30, fontWeight:600, color:"#1677ff" } }, (p.boosterName || "").charAt(0) || "?"),
        h("div", { style: { fontSize:18, fontWeight:700, color:"#1a1a2e", marginTop:8 } }, p.boosterName || "打手"),
        h("div", { style: { fontSize:11, color:"#8c8c8c", marginTop:2 } }, "ID：" + (p.userId || p.id || "")),
        h("div", { style: { display:"flex", gap:8, marginTop:6 } },
          h("span", { style: { padding:"2px 10px", borderRadius:10, fontSize:10, fontWeight:500, background:isOnline?"#f6ffed":"#fff2f0", color:isOnline?"#52c41a":"#ff4d4f", border:isOnline?"1px solid #b7eb8f":"1px solid #ffccc7" } }, isOnline ? "接单中" : "已下线"),
          h("span", { style: { padding:"2px 10px", borderRadius:10, fontSize:10, fontWeight:500, background:"#f0f5ff", color:"#1677ff", border:"1px solid #d6e4ff" } }, gameTypeLabel),
          h("span", { style: { padding:"2px 10px", borderRadius:10, fontSize:10, fontWeight:500, background:"#fffbe6", color:"#d48806", border:"1px solid #ffe58f" } }, levelLabel)
        )
      ),
      // -- White card with tabs --
      h("div", { style: { ...cardStyle, margin:"12px 12px 20px" } },
        // Tab bar
        h("div", { style: { display:"flex", borderBottom:"1px solid #f0f0f0" } },
          tabs.map(function(tab) {
            var isActive = profileTab === tab.key;
            return h("div", { key: tab.key, onClick: function() { setProfileTab(tab.key); }, style: { flex:1, textAlign:"center", padding:"12px 0", cursor:"pointer", color:isActive?"#1677ff":"#8c8c8c", fontWeight:isActive?600:400, fontSize:14, borderBottom:isActive?"2px solid #1677ff":"2px solid transparent", transition:"all 0.2s" } }, tab.label);
          })
        ),
        // Tab content
        h("div", { style: { padding:"12px 4px" } }, renderTabContent())
      )
    );
  }


  // === SubView: Dynamic Messages Page ===
  function renderDynamicMessagesPage() {
    var getDynReplyInputKey = function(msg) { return String(msg.type || "msg") + "_" + String(msg.commentId || msg.dynamicId || 0); };
    var getDynMsgReactKey = function(msg, index) {
      var type = String(msg.type || "msg");
      if (type === "like") {
        return ["like", msg.likeId || msg.id || "", msg.dynamicId || "", msg.userId || "", msg.createdAt || "", index].join("_");
      }
      if (type === "comment" || type === "reply") {
        return [type, msg.commentId || msg.id || "", msg.dynamicId || "", msg.userId || "", msg.createdAt || "", index].join("_");
      }
      return [type, msg.id || msg.commentId || msg.dynamicId || "", msg.userId || msg.createdAt || "", index].join("_");
    }
    var cardStyle = { background: "#fff", borderRadius: 14, padding: 16, marginBottom: 12, boxShadow: "0 1px 4px rgba(0,0,0,0.04)" };

    function submitInlineDynamicReply(msg) {
      var content = (dynReplyInputs[getDynReplyInputKey(msg)] || "").trim();
      if (!content) { alert("请输入回复内容"); return; }
      setDynReplySendingId(getDynReplyInputKey(msg));
      NK.Api.Booster.createDynamicComment(msg.dynamicId, {
        content: content,
        parentId: msg.commentId,
        replyToUserId: msg.userId
      }).then(function(res) {
        if (res && res.code === 0) {
          setDynReplyInputs(function(prev) { var next = Object.assign({}, prev); delete next[getDynReplyInputKey(msg)]; return next; });
          fetchDynamicMessages();
        } else {
          alert((res && res.message) || "回复失败");
        }
      }).catch(function(err) {
        alert((err && err.message) || "回复失败，请稍后重试");
      }).finally(function() {
        setDynReplySendingId(null);
      });
    }

    function updateDynReplyInput(msgId, val) {
      setDynReplyInputs(function(prev) { return Object.assign({}, prev, { [msgId]: val }); });
    }

    function formatTime(d) {
      if (!d) return "";
      var now = new Date();
      var t = new Date(d);
      var diffSec = Math.floor((now - t) / 1000);
      if (diffSec < 0) diffSec = 0;
      if (diffSec < 60) return "刚刚";
      if (diffSec < 3600) return Math.floor(diffSec / 60) + "分钟前";
      if (diffSec < 86400) return Math.floor(diffSec / 3600) + "小时前";
      var mm = String(t.getMonth() + 1).padStart(2, "0");
      var dd = String(t.getDate()).padStart(2, "0");
      var hh = String(t.getHours()).padStart(2, "0");
      var min = String(t.getMinutes()).padStart(2, "0");
      return mm + "/" + dd + " " + hh + ":" + min;
    }

    return h("div", { style: { display: "flex", flexDirection: "column", height: "100%" } },
      h("div", { style: { background: "#fff", padding: "0 16px", height: 48, display: "flex", alignItems: "center", position: "relative", boxShadow: "0 1px 2px rgba(0,0,0,0.04)", flexShrink: 0 } },
        h("div", { onClick: function() { setSubView(null); }, style: { width: 32, height: 32, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", flexShrink: 0 } },
          h("svg", { width: 22, height: 22, viewBox: "0 0 24 24", fill: "none", stroke: "#475569", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round" },
            h("path", { d: "m15 18-6-6 6-6" })
          )
        ),
        h("div", { style: { position: "absolute", left: "50%", transform: "translateX(-50%)", fontSize: 17, fontWeight: 700, color: "#1E293B" } }, "动态互动消息")
      ),
      h("div", { style: { flex: 1, overflowY: "auto", padding: "16px" } },
        dynMsgLoading ? h("div", { style: { padding: 40, textAlign: "center" } }, h("span", { style: { color: "#999", fontSize: 13 } }, "加载中...")) :
        dynMsgError ? h("div", { style: { padding: 40, textAlign: "center" } },
          h("div", { style: { fontSize: 13, color: "#999", marginBottom: 10 } }, dynMsgError),
          h("button", { onClick: fetchDynamicMessages, style: { padding: "6px 20px", background: "#1677ff", color: "#fff", border: "none", borderRadius: 6, fontSize: 12, cursor: "pointer" } }, "重新加载")
        ) :
        dynMsgList.length === 0 ? h("div", { style: { padding: 40, textAlign: "center" } },
          h("svg", { width: 48, height: 48, viewBox: "0 0 24 24", fill: "none", stroke: "#d9d9d9", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round", style: { marginBottom: 12 } },
            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" })
          ),
          h("div", { style: { fontSize: 14, color: "#999" } }, "暂无动态互动消息"),
          h("div", { style: { fontSize: 12, color: "#bbb", marginTop: 4 } }, "用户点赞、评论或回复你的动态后这里会有消息")
        ) :
        h("div", null,
          h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 } },
            h("span", { style: { fontSize: 12, color: "#8c8c8c" } }, "共 " + dynMsgList.length + " 条消息"),
            h("button", { onClick: fetchDynamicMessages, style: { padding: "4px 12px", background: "transparent", color: "#1677ff", border: "1px solid #1677ff", borderRadius: 4, fontSize: 11, cursor: "pointer" } }, "刷新")
          ),
          dynMsgList.map(function(msg, mi) {
            var typeLabel = msg.type === "like" ? "点赞了你的动态" : msg.type === "comment" ? "评论了你的动态" : "回复了你的评论";
            var typeColor = msg.type === "like" ? "#f59e0b" : msg.type === "comment" ? "#1677ff" : "#7C3AED";
            var thumbImg = msg.dynamicFirstImage || (Array.isArray(msg.dynamicImages) ? msg.dynamicImages[0] : "");
            return h("div", { key: getDynMsgReactKey(msg, mi), style: Object.assign({}, cardStyle, { marginBottom: 8 }) },
              h("div", { style: { display: "flex", alignItems: "flex-start", gap: 8, marginBottom: 6 } },
                msg.userAvatar ? h("img", { src: msg.userAvatar, style: { width: 36, height: 36, borderRadius: "50%", objectFit: "cover", flexShrink: 0 }, onError: function(e) { e.target.style.display = "none"; } }) :
                h("div", { style: { width: 36, height: 36, borderRadius: "50%", background: "linear-gradient(135deg, #7C3AED, #60A5FA)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14, color: "#fff", fontWeight: 700, flexShrink: 0 } }, (msg.userName || "用").charAt(0)),
                h("div", { style: { flex: 1, minWidth: 0 } },
                  h("div", { style: { display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" } },
                    h("span", { style: { fontSize: 13, fontWeight: 600, color: "#1E293B" } }, msg.userName || "用户"),
                    h("span", { style: { fontSize: 10, padding: "1px 6px", borderRadius: 4, background: typeColor + "15", color: typeColor, fontWeight: 500 } }, typeLabel)
                  ),
                  h("div", { style: { fontSize: 11, color: "#94A3B8", marginTop: 2 } }, formatTime(msg.createdAt))
                ),
                thumbImg
                  ? h("div", { onClick: function() { alert("动态详情下一步接入"); }, style: { width: 56, height: 56, borderRadius: 8, overflow: "hidden", flexShrink: 0, cursor: "pointer", background: "#F3F4F6" } },
                      h("img", { src: thumbImg, style: { width: "100%", height: "100%", objectFit: "cover" }, onError: function(e) { e.target.style.display = "none"; e.target.parentElement.style.display = "flex"; e.target.parentElement.style.alignItems = "center"; e.target.parentElement.style.justifyContent = "center"; } })
                    )
                  : h("div", { onClick: function() { alert("动态详情下一步接入"); }, style: { width: 56, height: 56, borderRadius: 8, background: "#F3F4F6", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, cursor: "pointer" } },
                      h("svg", { width: 24, height: 24, viewBox: "0 0 24 24", fill: "none", stroke: "#d9d9d9", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" },
                        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: { fontSize: 13, color: "#475569", marginBottom: 4, lineHeight: "18px" } }, msg.content),
              h("div", { style: { fontSize: 11, color: "#bbb", marginBottom: msg.type !== "like" ? 10 : 0 } }, "动态：" + (msg.dynamicContent || "-")),
              msg.type !== "like" ? h("div", { style: { display: "flex", gap: 8, alignItems: "center" } },
                h("input", {
                  value: dynReplyInputs[getDynReplyInputKey(msg)] || "",
                  onInput: function(e) { updateDynReplyInput(getDynReplyInputKey(msg), e.target.value); },
                  placeholder: "回复（" + (msg.userName || "用户") + "）",
                  style: { flex: 1, padding: "7px 10px", borderRadius: 6, border: "1px solid #e8e8e8", fontSize: 12, outline: "none", background: "#fafafa", boxSizing: "border-box" }
                }),
                h("button", {
                  onClick: function() { submitInlineDynamicReply(msg); },
                  disabled: dynReplySendingId === getDynReplyInputKey(msg),
                  style: { padding: "7px 14px", borderRadius: 6, border: "none", background: dynReplySendingId === getDynReplyInputKey(msg) ? "#91caff" : "#1677ff", color: "#fff", fontSize: 12, fontWeight: 500, cursor: dynReplySendingId === getDynReplyInputKey(msg) ? "wait" : "pointer", whiteSpace: "nowrap" }
                }, dynReplySendingId === getDynReplyInputKey(msg) ? "发送中" : "发送")
              ) : null
            );
          })
        )
      )
    );
  }

  // === SubView: Rankings Page ===
  function renderRankingsPage() {
    var LEVEL_NAMES = { 1: "黑铁", 2: "青铜", 3: "白银", 4: "黄金", 5: "铂金", 6: "钻石", 7: "王者" };

    function rankBadge(rank) {
      if (rank === 1) return h("div", { style: { width: 28, height: 28, borderRadius: "50%", background: "linear-gradient(135deg, #FFD700, #FFA500)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 13, fontWeight: 800, color: "#fff", flexShrink: 0 } }, "1");
      if (rank === 2) return h("div", { style: { width: 28, height: 28, borderRadius: "50%", background: "linear-gradient(135deg, #C0C0C0, #A0A0A0)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 13, fontWeight: 800, color: "#fff", flexShrink: 0 } }, "2");
      if (rank === 3) return h("div", { style: { width: 28, height: 28, borderRadius: "50%", background: "linear-gradient(135deg, #CD7F32, #B87333)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 13, fontWeight: 800, color: "#fff", flexShrink: 0 } }, "3");
      return h("div", { style: { width: 28, height: 28, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14, fontWeight: 600, color: "#94A3B8", flexShrink: 0 } }, String(rank));
    }

    return h("div", { style: { display: "flex", flexDirection: "column", height: "100%" } },
      // Header
      h("div", { style: { background: "#fff", padding: "0 16px", height: 48, display: "flex", alignItems: "center", position: "relative", boxShadow: "0 1px 2px rgba(0,0,0,0.04)", flexShrink: 0 } },
        h("div", { onClick: function() { setSubView(null); }, style: { width: 32, height: 32, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", flexShrink: 0 } },
          h("svg", { width: 22, height: 22, viewBox: "0 0 24 24", fill: "none", stroke: "#475569", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round" },
            h("path", { d: "m15 18-6-6 6-6" })
          )
        ),
        h("div", { style: { position: "absolute", left: "50%", transform: "translateX(-50%)", fontSize: 17, fontWeight: 700, color: "#1E293B" } }, "排行榜")
      ),
      // Content
      h("div", { style: { flex: 1, overflowY: "auto", padding: "16px" } },
        // Main type selector
        h("div", { style: { display: "flex", background: "#F1F5F9", borderRadius: 10, padding: 3, marginBottom: 12 } },
          ["spender", "booster"].map(function(t) {
            var active = rankType === t;
            var label = t === "spender" ? "大佬榜" : "接单榜";
            return h("div", { key: t, onClick: function() { setRankType(t); },
              style: { flex: 1, textAlign: "center", padding: "8px 0", borderRadius: 8, fontSize: 14, fontWeight: active ? 700 : 500, color: active ? "#1E293B" : "#94A3B8", background: active ? "#fff" : "transparent", cursor: "pointer", transition: "all 0.2s", boxShadow: active ? "0 1px 3px rgba(0,0,0,0.08)" : "none" }
            }, label);
          })
        ),
        // Period selector
        h("div", { style: { display: "flex", gap: 8, marginBottom: 16 } },
          ["week", "month"].map(function(p) {
            var active = rankPeriod === p;
            var label = p === "week" ? "周榜" : "月榜";
            return h("div", { key: p, onClick: function() { setRankPeriod(p); },
              style: { padding: "5px 14px", borderRadius: 16, fontSize: 12, fontWeight: active ? 600 : 400, color: active ? "#fff" : "#64748B", background: active ? "#1677ff" : "#F1F5F9", cursor: "pointer", transition: "all 0.2s" }
            }, label);
          })
        ),
        // Description
        h("div", { style: { fontSize: 11, color: "#94A3B8", marginBottom: 14, paddingLeft: 2 } },
          rankType === "spender" ? "按服务消费金额排行" : "按已接单数量排行"
        ),
        // List
        rankLoading ? h("div", { style: { padding: 40, textAlign: "center" } }, h("span", { style: { color: "#999", fontSize: 13 } }, "加载中...")) :
        rankError ? h("div", { style: { padding: 40, textAlign: "center" } },
          h("div", { style: { fontSize: 13, color: "#999", marginBottom: 10 } }, rankError),
          h("button", { onClick: function() { setRankError(""); setRankLoading(true); }, style: { padding: "6px 20px", background: "#1677ff", color: "#fff", border: "none", borderRadius: 6, fontSize: 12, cursor: "pointer" } }, "重新加载")
        ) :
        rankList.length === 0 ? h("div", { style: { padding: 40, textAlign: "center" } },
          h("svg", { width: 48, height: 48, viewBox: "0 0 24 24", fill: "none", stroke: "#d9d9d9", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round", style: { marginBottom: 12 } },
            h("path", { d: "M3 3v18h18" }), h("path", { d: "m19 9-5 5-4-4-3 3" })
          ),
          h("div", { style: { fontSize: 14, color: "#999" } }, "暂无排行数据"),
          h("div", { style: { fontSize: 12, color: "#bbb", marginTop: 4 } }, "该时间段暂无有效服务订单数据")
        ) :
        h("div", { style: { background: "#fff", borderRadius: 14, overflow: "hidden", boxShadow: "0 1px 4px rgba(0,0,0,0.04)" } },
          rankList.map(function(item, i) {
            var isClickable = rankType === "booster" && item.boosterUserId && item.boosterProfileId;
            return h("div", { key: "rank-" + i,
              onClick: isClickable ? function() { if (NK.Store.openNativePage && NK.Store.openNativePage("pages/booster/public-profile", { source: "ranking", boosterUserId: item.boosterUserId, boosterProfileId: item.boosterProfileId })) return; NK.Store.navigate("boosterPublicProfile", { boosterUserId: item.boosterUserId, boosterProfileId: item.boosterProfileId }); } : null,
              style: { display: "flex", alignItems: "center", padding: "14px 16px", borderBottom: i < rankList.length - 1 ? "1px solid #F1F5F9" : "none", cursor: isClickable ? "pointer" : "default", transition: "background 0.15s" }
            },
              rankBadge(item.rank),
              item.avatar ? h("img", { src: item.avatar, style: { width: 40, height: 40, borderRadius: "50%", objectFit: "cover", marginLeft: 12, flexShrink: 0 }, onError: function(e) { e.target.style.display = "none"; } }) :
              h("div", { style: { width: 40, height: 40, borderRadius: "50%", background: "linear-gradient(135deg, #7C3AED, #60A5FA)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 15, color: "#fff", fontWeight: 700, marginLeft: 12, flexShrink: 0 } }, (item.nickname || "用").charAt(0)),
              h("div", { style: { flex: 1, marginLeft: 12, minWidth: 0 } },
                h("div", { style: { display: "flex", alignItems: "center", gap: 6 } },
                  h("span", { style: { fontSize: 14, fontWeight: 600, color: "#1E293B", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, item.nickname || "-"),
                  rankType === "booster" && item.levelName ? h("span", { style: { fontSize: 10, padding: "1px 6px", borderRadius: 4, background: "#FEF3C7", color: "#D97706", fontWeight: 500, flexShrink: 0 } }, item.levelName) : null
                )
              ),
              h("div", { style: { fontSize: 15, fontWeight: 700, color: "#1677ff", flexShrink: 0, marginLeft: 8 } }, item.valueText),
              rankType === "booster" ? IconChevronRight("#d9d9d9") : null
            );
          })
        )
      )
    );
  }

  // === TAB: Profile / My (real data) ===
  function renderProfile() {
    if (profileLoading) {
      return h("div", { style: { padding:60, textAlign:"center", flex:1 } },
        h("div", { style: { color:"#999", fontSize:14 } }, "加载中...")
      );
    }
    if (profileError) {
      return h("div", { style: { padding:60, textAlign:"center", flex:1 } },
        h("div", { style: { fontSize:14, color:"#999", marginBottom:12 } }, profileError),
        h("button", { onClick: function() { setProfileData(null); setProfileError(""); }, style: { padding:"8px 24px", borderRadius:8, border:"none", background:"#1677ff", color:"#fff", fontSize:14, cursor:"pointer" } }, "重新加载")
      );
    }
    if (!profileData) {
      return h("div", { style: { padding:60, textAlign:"center", flex:1 } },
        h("div", { style: { color:"#999", fontSize:14 } }, "加载中...")
      );
    }

    var p = profileData.profile || {};
    var os = profileData.orderStats || {};
    var fs = profileData.fundStats || {};
    var rs = profileData.reviewStats || {};
    var gameTypeLabel = (p.gameType === "delta" || p.gameType === "expert") ? "三角洲打手" : "奶块打手";
    var cardStyle = { background:"#fff", borderRadius:14, padding:16, marginBottom:12, boxShadow:"0 1px 4px rgba(0,0,0,0.04)" };
    var sectionTitleStyle = { fontSize:13, fontWeight:600, color:"#8c8c8c", marginBottom:12, letterSpacing:0.5 };

    function fmtMoney(v) { var n = Number(v); return isNaN(n) ? "¥0.00" : "¥" + n.toFixed(2); }

    // Shared stat chip renderer
    function StatChip(label, value, colorOpt) {
      return h("div", { style: { flex:1, textAlign:"center", padding:"10px 4px" } },
        h("div", { style: { fontSize:18, fontWeight:700, color: colorOpt || "#1677ff", marginBottom:3 } }, String(value)),
        h("div", { style: { fontSize:11, color:"#8c8c8c", lineHeight:1.3 } }, label)
      );
    }

    return h("div", { style: { padding:"16px 16px 24px", overflowY:"auto", flex:1 } },

      // ═══ 1) Profile card ═══
      h("div", { style: cardStyle },
        h("div", { style: { display:"flex", alignItems:"center", gap:14 } },
          // Avatar
          h("div", { onClick: function() { setSubView("profileHome"); if (dynamicsList.length === 0) fetchDynamics(); }, style: { cursor:"pointer", flexShrink:0 } },
            p.avatar
              ? h("img", { src: p.avatar, style: { width:52, height:52, borderRadius:"50%", objectFit:"cover" } })
              : h("div", { style: { width:52, height:52, borderRadius:"50%", background:"#e6f7ff", display:"flex", alignItems:"center", justifyContent:"center", fontSize:22, fontWeight:600, color:"#1677ff" } }, (p.boosterName || "?").charAt(0))
          ),
          // Name + identity
          h("div", { style: { flex:1, minWidth:0 } },
            h("div", { style: { fontSize:16, fontWeight:700, color:"#1a1a2e", marginBottom:2 } }, p.boosterName || "未设置"),
            h("div", { style: { fontSize:12, color:"#8c8c8c", marginBottom:4 } }, gameTypeLabel + " · " + (p.levelName || "黑铁")),
            h("div", { style: { fontSize:12, color:"#bfbfbf", lineHeight:1.5, display:"-webkit-box", WebkitLineClamp:2, WebkitBoxOrient:"vertical", overflow:"hidden" } }, p.bio || "这个打手还没有填写简介")
          ),
          // Online toggle
          h("div", { onClick: toggleOnline, style: { flexShrink:0, display:"flex", flexDirection:"column", alignItems:"center", cursor:"pointer", gap:4 } },
            h("div", { style: { width:44, height:24, borderRadius:12, position:"relative", background: online ? "#1677ff" : "#d9d9d9", transition:"background 0.2s" } },
              h("div", { style: { width:20, height:20, borderRadius:"50%", background:"#fff", position:"absolute", top:2, left: online ? 22 : 2, transition:"left 0.2s", boxShadow:"0 1px 2px rgba(0,0,0,0.15)" } })
            ),
            h("span", { style: { fontSize:10, color: online ? "#1677ff" : "#8c8c8c", fontWeight:500 } }, online ? "接单中" : "已下线")
          )
        )
      ),

      // ═══ 2) Fund card ═══
      h("div", { style: cardStyle },
        h("div", { style: sectionTitleStyle }, "我的资金"),
        diamondLoading
          ? h("div", { style: { padding:"20px", textAlign:"center" } }, h("span", { style: { color:"#999", fontSize:13 } }, "加载中..."))
          : h("div", null,
              h("div", { style: { display:"grid", gridTemplateColumns:"1fr 1fr", gap:"2px" } },
                [
                  { label:"保证金", value: "¥" + String(diamondData ? (diamondData.depositAmount || 0).toFixed(2) : "0.00"), onClick: function() { setFundDetailTab("deposit"); setSubView("fundDetail"); } },
                  { label:"可转换钻石", value: String(diamondData ? (diamondData.diamondBalance || 0) : 0), highlight:true, onClick: function() { setFundDetailTab("diamond"); setSubView("fundDetail"); } },
                  { label:"冻结钻石", value: String(diamondData ? (diamondData.frozenDiamond || diamondData.frozenAmount || diamondData.frozen_diamond || 0) : 0), onClick: function() { setFundDetailTab("diamond"); setSubView("fundDetail"); } },
                  { label:"已转换钻石", value: String(diamondData ? (diamondData.totalConvertedDiamond || 0) : 0), onClick: function() { setFundDetailTab("diamond"); setSubView("fundDetail"); } }
                ].map(function(item) {
                  return h("div", { key:item.label, onClick: item.onClick || null,
                    style: { padding:"12px 10px", textAlign:"center", borderRadius:8, background: item.highlight ? "#f0f7ff" : "transparent", cursor: item.onClick ? "pointer" : "default", transition:"background 0.15s" }
                  },
                    h("div", { style: { fontSize:11, color:"#8c8c8c", marginBottom:4 } }, item.label),
                    h("div", { style: { fontSize:16, fontWeight:700, color: item.highlight ? "#1677ff" : "#1a1a2e", fontVariantNumeric:"tabular-nums" } }, item.value)
                  );
                })
              ),
            )
      ),

      // ═══ 3) Service overview (orders + reviews merged) ═══
      h("div", { style: cardStyle },
        h("div", { style: { display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:12 } },
        h("span", { style: { fontSize:13, fontWeight:600, color:"#8c8c8c", letterSpacing:0.5 } }, "服务概览"),
        h("div", { onClick: function() { setSubView("orders"); fetchOrderRecords(); },
          style: { display:"flex", alignItems:"center", gap:2, cursor:"pointer", flexShrink:0 }
        },
          h("span", { style: { fontSize:12, color:"#1677ff", fontWeight:500 } }, "查看订单"),
          h("svg", { width:14, height:14, viewBox:"0 0 24 24", fill:"none", stroke:"#1677ff", strokeWidth:2, strokeLinecap:"round", strokeLinejoin:"round" },
            h("path", { d:"m9 18 6-6-6-6" })
          )
        )
      ),
        // Order stats row
        h("div", { style: { display:"flex", marginBottom:8 } },
          [{label:"总接单",val:os.totalAccepted||0},{label:"今日接单",val:os.todayAccepted||0},{label:"服务中",val:os.servingCount||0},{label:"已结单",val:os.completedCount||0}].map(function(s, si) {
            return h("div", { key:"os-"+si, style:{flex:1} }, StatChip(s.label, s.val));
          })
        ),
        // Divider
        h("div", { style: { height:1, background:"#f0f0f0", margin:"4px 0 12px" } }),
        // Review stats row
        h("div", { style: { display:"flex", marginBottom:8 } },
          [{label:"总评价",val:rs.totalReviews||0},{label:"好评",val:rs.goodReviews||0,color:"#16a34a"},{label:"中评",val:rs.middleReviews||0,color:"#f59e0b"},{label:"差评",val:rs.badReviews||0,color:"#ef4444"}].map(function(r, ri) {
            return h("div", { key:"rs-"+ri, style:{flex:1} }, StatChip(r.label, r.val, r.color));
          })
        ),
      ),

      // ═══ 4) Function entries ═══
      h("div", { style: cardStyle },
        h("div", { style: sectionTitleStyle }, "功能入口"),
        h("div", { style: { display:"grid", gridTemplateColumns:"1fr 1fr", gap:10 } },
          [
            { label:"排行榜", icon: IconTrophy, onClick: function() { setSubView("rankings"); } },
            { label:"打手客服", icon: IconHeadset, onClick: function() { alert("打手客服功能下一步接入"); } }
          ].map(function(entry) {
            return h("div", { key:entry.label, onClick: entry.onClick,
              style: { display:"flex", flexDirection:"column", alignItems:"center", gap:8, padding:"16px 10px", borderRadius:10, background:"#fafafa", cursor:"pointer", transition:"background 0.15s" }
            },
              h("div", { style: { color:"#1677ff" } }, entry.icon("#1677ff")),
              h("span", { style: { fontSize:12, color:"#595959", fontWeight:500 } }, entry.label)
            );
          })
        )
      )
    );
  }
  // === Bottom tab bar ===
  function renderTabBar() {
    var tabs = [
      { key: "hall", label: "接单大厅", iconFn: IconHome },
      { key: "publish", label: "发布动态", iconFn: IconPencil },
      { key: "messages", label: "消息", iconFn: IconMessage },
      { key: "profile", label: "我的", iconFn: IconUser }
    ];
    return h("div", { style: { display:"flex", background:"#fff", borderTop:"1px solid #e8e8e8", flexShrink:0, paddingBottom:"env(safe-area-inset-bottom, 0)" } },
      tabs.map(function(tab) {
        var active = currentTab === tab.key;
        return h("div", { key: tab.key, onClick: function() { setCurrentTab(tab.key); }, style: { flex:1, display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", padding:"8px 0 6px", cursor:"pointer", color: active ? "#1677ff" : "#8c8c8c", transition:"color 0.2s" } },
          h("div", { style: { marginBottom:2 } }, tab.iconFn(active ? "#1677ff" : "#8c8c8c")),
          h("div", { style: { fontSize:10, fontWeight: active ? 600 : 400 } }, tab.label)
        );
      })
    );
  }


  // === Render fund detail page ===
  function renderFundDetail() {
    var cardStyle = { background:"#fff", borderRadius:14, padding:16, marginBottom:12, boxShadow:"0 1px 4px rgba(0,0,0,0.04)" };
    var sectionTitleStyle = { fontSize:13, fontWeight:600, color:"#8c8c8c", marginBottom:12, letterSpacing:0.5 };

    return h("div", { style: { display:"flex", flexDirection:"column", flex:1, minHeight:0, background:"#f5f5f5" } },
      // Header
      h("div", { style: { height:48, display:"flex", alignItems:"center", padding:"0 14px", background:"#fff", borderBottom:"1px solid #f0f0f0", flexShrink:0 } },
        h("div", { onClick: function() { setSubView(null); setCurrentTab("profile"); }, style: { width:40, height:40, display:"flex", alignItems:"center", justifyContent:"center", cursor:"pointer" } },
          h("svg", { width:24, height:24, viewBox:"0 0 24 24", fill:"none", stroke:"#595959", strokeWidth:2, strokeLinecap:"round", strokeLinejoin:"round" },
            h("path", { d:"m15 18-6-6 6-6" })
          )
        ),
        h("div", { style: { flex:1, textAlign:"center", fontSize:16, fontWeight:700, color:"#1a1a2e" } }, "我的资金"),
        h("div", { style: { width:40, height:40 } })
      ),
      // Tabs
      h("div", { style: { display:"flex", background:"#fff", borderBottom:"1px solid #f0f0f0", flexShrink:0 } },
        [{ key:"deposit", label:"保证金" }, { key:"diamond", label:"钻石转换" }].map(function(t) {
          var active = fundDetailTab === t.key;
          return h("div", { key:t.key, onClick: function() { setFundDetailTab(t.key); },
            style: { flex:1, textAlign:"center", padding:"12px 0", cursor:"pointer", color: active ? "#1677ff" : "#8c8c8c", fontWeight: active ? 600 : 400, fontSize:14, borderBottom: active ? "2px solid #1677ff" : "2px solid transparent", transition:"all 0.2s" }
          }, t.label);
        })
      ),
      // Content
      h("div", { style: { flex:1, overflowY:"auto", padding:"16px 16px 24px" } },
        fundDetailTab === "deposit" ? renderDepositTab() : renderDiamondTab()
      )
    );
  }

  function renderDepositTab() {
    var cardStyle = { background:"#fff", borderRadius:14, padding:16, marginBottom:12, boxShadow:"0 1px 4px rgba(0,0,0,0.04)" };
    var dd = diamondData || {};
    var depositVal = dd.depositAmount || 0;
    var requiredVal = dd.requiredDeposit || 100;
    var missingVal = dd.depositMissingAmount || Math.max(requiredVal - depositVal, 0);
    var isEnough = dd.depositEnough === true || depositVal >= requiredVal;
    return h("div", null,
      h("div", { style: cardStyle },
        h("div", { style: { display:"grid", gridTemplateColumns:"1fr 1fr", gap:"12px", marginBottom:12 } },
          [
            { label:"当前已缴纳保证金", value: "¥" + depositVal.toFixed(2) },
            { label:"当前等级要求", value: "¥" + requiredVal.toFixed(2), warn: true }
          ].map(function(item) {
            return h("div", { key:item.label, style: { textAlign:"center", padding:"10px 6px", borderRadius:8, background: item.warn ? "#fffbe6" : "#f8f9fb" } },
              h("div", { style: { fontSize:11, color:"#8c8c8c", marginBottom:4 } }, item.label),
              h("div", { style: { fontSize:18, fontWeight:700, color: item.warn ? "#fa8c16" : "#1a1a2e" } }, item.value)
            );
          })
        ),
        h("div", { style: { display:"flex", justifyContent:"center", alignItems:"center", padding:"12px 0", background: isEnough ? "#f6ffed" : "#fff2f0", borderRadius:8 } },
          h("div", { style: { textAlign:"center" } },
            h("div", { style: { fontSize:11, color:"#8c8c8c", marginBottom:4 } }, isEnough ? "已缴足" : "还需缴纳"),
            h("div", { style: { fontSize:22, fontWeight:700, color: isEnough ? "#52c41a" : "#ff4d4f" } }, isEnough ? "✓" : "¥" + missingVal.toFixed(2))
          )
        )
      ),
      h("div", { style: cardStyle },
        h("div", { style: { fontSize:13, fontWeight:600, color:"#8c8c8c", marginBottom:8, letterSpacing:0.5 } }, "保证金规则"),
        h("div", { style: { fontSize:12, color:"#595959", lineHeight:1.7 } }, dd.depositRuleText || "保证金用于保障服务订单履约。未缴纳足额保证金的打手仍可正常接单和获得钻石，但暂不可将钻石转换到用户端钱包余额。")
      ),
      h("div", { style: { display:"flex", gap:10 } },
        h("button", { onClick: function() { setShowDepositModal(true); }, style: { flex:1, padding:"12px 0", borderRadius:10, border:"none", background:"#1677ff", color:"#fff", fontSize:14, fontWeight:600, cursor:"pointer" } }, "缴纳保证金"),
        h("button", { onClick: function() { alert("提现保证金功能下一步接入"); }, style: { flex:1, padding:"12px 0", borderRadius:10, border:"1px solid #e8e8e8", background:"#fff", color:"#595959", fontSize:14, fontWeight:500, cursor:"pointer" } }, "提现保证金")
      )
    );
  }

  function renderDiamondTab() {
    var cardStyle = { background:"#fff", borderRadius:14, padding:16, marginBottom:12, boxShadow:"0 1px 4px rgba(0,0,0,0.04)" };
    var dd = diamondData || {};
    return h("div", null,
      // Diamond overview
      h("div", { style: cardStyle },
        h("div", { style: { display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:"2px" } },
          [
            { label:"可转换钻石", value: String(dd.diamondBalance || 0), highlight:true },
            { label:"冻结钻石", value: String(dd.frozenDiamond || 0) },
            { label:"已转换钻石", value: String(dd.totalConvertedDiamond || 0) }
          ].map(function(item) {
            return h("div", { key:item.label,
              style: { padding:"12px 6px", textAlign:"center", borderRadius:8, background: item.highlight ? "#f0f7ff" : "transparent" }
            },
              h("div", { style: { fontSize:11, color:"#8c8c8c", marginBottom:4 } }, item.label),
              h("div", { style: { fontSize:18, fontWeight:700, color: item.highlight ? "#1677ff" : "#1a1a2e" } }, item.value)
            );
          })
        )
      ),
      // Convert rate info
      h("div", { style: cardStyle },
        h("div", { style: { display:"flex", justifyContent:"space-between", marginBottom:8 } },
          h("span", { style: { fontSize:12, color:"#8c8c8c" } }, "当前等级"),
          h("span", { style: { fontSize:13, fontWeight:600, color:"#1a1a2e" } }, dd.levelName || "黑铁")
        ),
        h("div", { style: { display:"flex", justifyContent:"space-between", marginBottom:8 } },
          h("span", { style: { fontSize:12, color:"#8c8c8c" } }, "兑换比例"),
          h("span", { style: { fontSize:13, fontWeight:600, color:"#1677ff" } }, (dd.convertRatePercent || 70) + "%")
        ),
        h("div", { style: { display:"flex", justifyContent:"space-between", paddingTop:8, borderTop:"1px solid #f0f0f0" } },
          h("span", { style: { fontSize:12, color:"#8c8c8c" } }, "预估可转余额"),
          h("span", { style: { fontSize:15, fontWeight:700, color:"#1677ff" } }, "¥" + (dd.estimatedWalletAmount || 0).toFixed(2))
        )
      ),
      // Convert button
      // Deposit warning + convert button
      diamondData && !diamondData.depositEnough ? h("div", { style: { background:"#fff", borderRadius:14, padding:16, marginBottom:12, boxShadow:"0 1px 4px rgba(0,0,0,0.04)", borderLeft:"3px solid #ff4d4f" } },
        h("div", { style: { fontSize:13, fontWeight:600, color:"#ff4d4f", marginBottom:6 } }, "保证金未缴足，暂不可转换到钱包"),
        h("div", { style: { fontSize:12, color:"#8c8c8c" } }, "还需缴纳保证金：¥" + (diamondData.depositMissingAmount || 0).toFixed(2))
      ) : null,
      diamondData && diamondData.depositEnough
        ? h("button", { onClick: handleConvertDiamonds, disabled: convertSubmitting, style: { width:"100%", padding:"14px 0", borderRadius:10, border:"none", background: convertSubmitting ? "#91caff" : "#1677ff", color:"#fff", fontSize:15, fontWeight:600, cursor: convertSubmitting ? "wait" : "pointer" } }, convertSubmitting ? "兑换中..." : "钻石兑换")
        : diamondData && !diamondData.depositEnough
          ? h("button", { disabled: true, style: { width:"100%", padding:"14px 0", borderRadius:10, border:"none", background:"#d9d9d9", color:"#999", fontSize:15, fontWeight:600, cursor:"not-allowed" } }, "钻石转换")
          : null
    );
  }


    // === Main render (approved) with tabs ===
  return h("div", { className: "detail-page", style: { display:"flex", flexDirection:"column", height:"100dvh", maxHeight:"100dvh", overflow:"hidden", paddingBottom:0, background:"#f5f5f5" } },
    // Gold header (only on main tabs, not sub-pages)
    subView ? null : h("div", { style: { height:48, display:"flex", alignItems:"center", justifyContent:"space-between", padding:"0 14px", background:"linear-gradient(135deg, #F6C453 0%, #F59E0B 100%)", color:"#fff", boxShadow:"0 2px 8px rgba(245, 158, 11, 0.18)", position:"sticky", top:0, zIndex:30, flexShrink:0 } },
      h("div", { onClick: goBack, style: { width:40, height:40, display:"flex", alignItems:"center", justifyContent:"center", cursor:"pointer" } },
        h("svg", { width:24, height:24, viewBox:"0 0 24 24", fill:"none", stroke:"currentColor", strokeWidth:2, strokeLinecap:"round", strokeLinejoin:"round" },
          h("path", { d:"m15 18-6-6 6-6" })
        )
      ),
      h("div", { style: { flex:1, textAlign:"center", fontSize:17, fontWeight:800 } }, "打手中心"),
      h("div", { style: { width:40, height:40 } })
    ),
    // Tab content area (scrollable)
    h("div", { style: { flex:1, minHeight:0, overflowY:"auto", WebkitOverflowScrolling:"touch", overscrollBehavior:"contain", display:"flex", flexDirection:"column" } },
      subView === "serviceSelect" ? renderServiceSelect() :
      subView === "editProfile" ? renderEditProfile() :
      subView === "profileHome" ? renderProfileHome() :
      subView === "fundDetail" ? renderFundDetail() :
      subView === "dynamicMessages" ? renderDynamicMessagesPage() :
      subView === "rankings" ? renderRankingsPage() :
      subView === "orders" ? renderOrderRecords() :
      currentTab === "hall" ? renderHallContent() :
      currentTab === "publish" ? renderPublish() :
      currentTab === "messages" ? renderMessages() :
      renderProfile()
    ),
    // Bottom tab bar (hidden in sub-pages)


    // Deposit pay modal
    showDepositModal ? h("div", { style: { position:"fixed", top:0, left:0, right:0, bottom:0, background:"rgba(0,0,0,0.5)", display:"flex", alignItems:"center", justifyContent:"center", zIndex:100 } },
      h("div", { style: { background:"#fff", borderRadius:16, padding:24, width:"85%", maxWidth:360 } },
        h("div", { style: { fontSize:16, fontWeight:700, color:"#1a1a2e", marginBottom:16, textAlign:"center" } }, "缴纳保证金"),
        diamondData ? h("div", { style: { marginBottom:16, fontSize:13, color:"#595959", lineHeight:1.8 } },
          h("div", null, "当前可用钻石：" + (diamondData.diamondBalance || 0) + " 💎"),
          h("div", null, "当前兑换比例：" + (diamondData.convertRatePercent || 70) + "%"),
          h("div", { style: { fontWeight:600, color:"#1a1a2e" } }, "当前需要缴纳保证金：¥" + (diamondData.depositMissingAmount || 0).toFixed(2))
        ) : null,
        h("div", { style: { display:"flex", gap:10 } },
          h("button", { onClick: function() { setShowDepositModal(false); setDepositAmount(""); }, style: { flex:1, padding:"10px 0", borderRadius:10, border:"1px solid #e8e8e8", background:"#fff", fontSize:14, fontWeight:500, color:"#595959", cursor:"pointer" } }, "取消"),
          h("button", { onClick: handlePayDeposit, disabled: depositSubmitting || (diamondData && diamondData.depositMissingAmount <= 0), style: { flex:1, padding:"10px 0", borderRadius:10, border:"none", background: (depositSubmitting || (diamondData && diamondData.depositMissingAmount <= 0)) ? "#d9d9d9" : "#1677ff", color:"#fff", fontSize:14, fontWeight:600, cursor: (depositSubmitting || (diamondData && diamondData.depositMissingAmount <= 0)) ? "not-allowed" : "pointer" } }, depositSubmitting ? "缴纳中..." : (diamondData && diamondData.depositMissingAmount <= 0 ? "已缴清" : "确认缴纳"))
        )
      )
    ) : null,
        subView ? null : renderTabBar()
  );
}

window.NK = window.NK || {};
NK.BoosterCenterPage = BoosterCenterPage;


