﻿// 护航模块 - 服务首页（商城/大佬 Tab + 分类筛选 + 双列服务卡片）
const { useState } = React;

// ===== Mock fallback (only used when API fails) =====
const MOCK_FALLBACK = [];

// ===== 分类值映射（前端中文 -> 接口英文） =====
var CAT_MAP = {
  "全部": "all",
  "商城": "mall",
  "副本": "dungeon",
  "陪玩": "accompany",
  "附魔": "enchant",
  "苦力": "labor",
};

var TAB_MAP = {
  mall: "商城",
  expert: "大佬",
};

const CATEGORIES = ["全部", "商城", "副本", "陪玩", "附魔", "苦力"];

// 颜色映射（类 → 底色 + 文字色）
const CAT_COLORS = {
  "爆款单": { bg: "#fff0f0", color: "#e53e3e" },
  "小时单": { bg: "#fff7e6", color: "#d46b08" },
  "副本单": { bg: "#e6f7ff", color: "#096dd9" },
  "陪玩单": { bg: "#f0e6ff", color: "#722ed1" },
};

// ===== 内联 SVG 分类图标 =====
var catIconAttrs = { width: 16, height: 16, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round" };
var catIcons = {
  "商城": React.createElement("svg", catIconAttrs,
    React.createElement("path", { d: "M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z" }),
    React.createElement("line", { x1: 3, y1: 6, x2: 21, y2: 6 }),
    React.createElement("path", { d: "M16 10a4 4 0 0 1-8 0" })
  ),
  "副本": React.createElement("svg", catIconAttrs,
    React.createElement("path", { d: "M12 2L2 7l10 5 10-5-10-5z" }),
    React.createElement("path", { d: "M2 17l10 5 10-5" }),
    React.createElement("path", { d: "M2 12l10 5 10-5" })
  ),
  "陪玩": React.createElement("svg", catIconAttrs,
    React.createElement("path", { d: "M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" }),
    React.createElement("circle", { cx: 9, cy: 7, r: 4 }),
    React.createElement("path", { d: "M23 21v-2a4 4 0 0 0-3-3.87" }),
    React.createElement("path", { d: "M16 3.13a4 4 0 0 1 0 7.75" })
  ),
  "附魔": React.createElement("svg", catIconAttrs,
    React.createElement("polygon", { points: "12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" })
  ),
  "苦力": React.createElement("svg", catIconAttrs,
    React.createElement("rect", { x: 2, y: 7, width: 20, height: 14, rx: 2 }),
    React.createElement("path", { d: "M16 7V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2" }),
    React.createElement("circle", { cx: 12, cy: 14, r: 2 })
  ),
};

function EscortHomePage() {
  var h = React.createElement;

  // ---- 状态 ----
  var _mainTab = useState("mall"); var mainTab = _mainTab[0]; var setMainTab = _mainTab[1];
  var _filterCat = useState("全部"); var filterCat = _filterCat[0]; var setFilterCat = _filterCat[1];
  var _services = useState([]); var services = _services[0]; var setServices = _services[1];
  var _loading = useState(false); var loading = _loading[0]; var setLoading = _loading[1];
  var _total = useState(0); var total = _total[0]; var setTotal = _total[1];
  var _gameFilter = useState("naikuai"); var gameFilter = _gameFilter[0]; var setGameFilter = _gameFilter[1];
  var _rankType = useState("spender"); var rankType = _rankType[0]; var setRankType = _rankType[1];
  var _rankPeriod = useState("week"); var rankPeriod = _rankPeriod[0]; var setRankPeriod = _rankPeriod[1];
  var _rankList = useState([]); var rankList = _rankList[0]; var setRankList = _rankList[1];
  var _rankLoading = useState(false); var rankLoading = _rankLoading[0]; var setRankLoading = _rankLoading[1];
  var _rankError = useState(""); var rankError = _rankError[0]; var setRankError = _rankError[1];

  // ---- 请求真实接口 ----
  var fetchServices = function() {
    setLoading(true);
    var params = {};
    if (mainTab === "mall") {
      if (gameFilter === "delta") params.bizType = "delta";
      else params.bizType = "mall";
    }
    else if (mainTab === "expert") params.bizType = "expert";
    if (filterCat !== "全部") params.category = CAT_MAP[filterCat] || "all";
    params.pageSize = 50;

    NK.Api.Escort.list(params).then(function(res) {
      setLoading(false);
      if (res && res.code === 0 && res.data) {
        setServices(res.data.list || []);
        setTotal(res.data.total || 0);
      } else {
        setServices(MOCK_FALLBACK);
        setTotal(0);
      }
    }).catch(function() {
      setLoading(false);
      setServices(MOCK_FALLBACK);
      setTotal(0);
    });
  };

  // Tab 切换重新请求
  var _prevTab = React.useRef(mainTab);
  var _prevCat = React.useRef(filterCat);
  React.useEffect(function() {
    if (_prevTab.current !== mainTab || _prevCat.current !== filterCat) {
      _prevTab.current = mainTab;
      _prevCat.current = filterCat;
    }
    fetchServices();
  }, [mainTab, filterCat, gameFilter]);

  // 请求排行榜数据
  React.useEffect(function() {
    if (mainTab !== "expert") return;
    setRankLoading(true);
    setRankError("");
    NK.Api.Booster.rankings({ type: rankType, period: rankPeriod }).then(function(res) {
      setRankLoading(false);
      if (res && res.code === 0) {
        setRankList((res.data && res.data.list) || []);
      } else {
        setRankError((res && res.message) || "排行榜加载失败");
      }
    }).catch(function() {
      setRankError("排行榜加载失败，请稍后重试");
      setRankLoading(false);
    });
  }, [mainTab, rankType, rankPeriod]);

  // ---- 卡片点击 ----
  var handleCardClick = function(service) {
    NK.Store.navigate("escortDetail", { id: service.id });
  };

  // ---- 渲染卡片 ----
  var renderCard = function(s) {
    var hasBadge = s.badgeText && s.badgeText.length > 0;
    var tagStyle = CAT_COLORS[s.tagText] || { bg: "#f0f0f0", color: "#666" };
    var coverUrl = s.coverImage || "";
    if (coverUrl && coverUrl.indexOf("http") !== 0 && coverUrl.charAt(0) !== "/") coverUrl = "/" + coverUrl;

    var gradients = ["#667eea,#764ba2","#f093fb,#f5576c","#4facfe,#00f2fe","#43e97b,#30cf4b","#fa709a,#fee140","#a18cd1,#fbc2eb","#667eea,#764ba2","#f5576c,#f093fb","#4facfe,#00f2fe","#fa709a,#fee140","#30cf4b,#43e97b","#764ba2,#667eea"];
    var gradient = gradients[s.id % 12];

    return h("div", {
      key: s.id,
      onClick: function() { handleCardClick(s); },
      style: {
        width: "calc(50% - 5px)",
        background: "#fff",
        borderRadius: 10,
        overflow: "hidden",
        boxShadow: "0 1px 8px rgba(0,0,0,0.05)",
        cursor: "pointer",
        display: "flex",
        flexDirection: "column",
      }
    },
      h("div", {
        style: {
          width: "100%", paddingTop: "66.67%", position: "relative",
          background: "linear-gradient(135deg, " + gradient + ")",
          overflow: "hidden",
        }
      },
        coverUrl ? h("img", {
          src: coverUrl,
          style: { position: "absolute", top: 0, left: 0, width: "100%", height: "100%", objectFit: "cover" },
          onError: function(e) { e.target.style.display = "none"; }
        }) : null,
        h("div", {
          style: {
            position: "absolute", top: "50%", left: "50%",
            transform: "translate(-50%,-50%)",
            color: "rgba(255,255,255,0.85)", fontSize: 22, fontWeight: 700,
            textAlign: "center", lineHeight: 1.3,
            textShadow: "0 2px 8px rgba(0,0,0,0.3)",
            padding: "0 12px", pointerEvents: "none",
          }
        }, s.title.substring(0, 6)),
        hasBadge ? h("div", {
          style: {
            position: "absolute", top: 8, left: 8, zIndex: 2,
            background: "linear-gradient(135deg, #ff6b6b, #ee5a24)",
            color: "#fff", fontSize: 11, fontWeight: 600,
            padding: "2px 8px", borderRadius: 4,
            boxShadow: "0 2px 6px rgba(238,90,36,0.35)",
          }
        }, s.badgeText) : null
      ),
      h("div", { style: { padding: "10px 10px 12px", flex: 1, display: "flex", flexDirection: "column" } },
        h("div", {
          style: { fontSize: 13, fontWeight: 600, color: "#1a1a2e", lineHeight: 1.4,
            overflow: "hidden", textOverflow: "ellipsis", display: "-webkit-box",
            WebkitLineClamp: 2, WebkitBoxOrient: "vertical", minHeight: 36, marginBottom: 4 }
        }, s.title),
        h("div", {
          style: { fontSize: 11, color: "#999", lineHeight: 1.4, marginBottom: 8,
            overflow: "hidden", textOverflow: "ellipsis", display: "-webkit-box",
            WebkitLineClamp: 1, WebkitBoxOrient: "vertical" }
        }, s.summary || s.desc),
        h("div", { style: { display: "flex", alignItems: "baseline", justifyContent: "space-between", marginTop: "auto" } },
          h("div", { style: { display: "flex", alignItems: "baseline", gap: 4 } },
            h("span", { style: { fontSize: 11, color: "#ff6b35", fontWeight: 600 } }, "¥"),
            h("span", { style: { fontSize: 18, fontWeight: 700, color: "#ff6b35", lineHeight: 1 } }, s.defaultSpecPrice != null ? s.defaultSpecPrice : s.price),
            (s.defaultSpecOriginPrice != null ? s.defaultSpecOriginPrice : s.originPrice) && (s.defaultSpecOriginPrice != null ? s.defaultSpecOriginPrice : s.originPrice) > (s.defaultSpecPrice != null ? s.defaultSpecPrice : s.price) ? h("span", {
              style: { fontSize: 11, color: "#bbb", textDecoration: "line-through", marginLeft: 2 }
            }, "¥" + (s.defaultSpecOriginPrice != null ? s.defaultSpecOriginPrice : s.originPrice)) : null
          ),
          h("span", {
            style: {
              fontSize: 10, fontWeight: 500,
              background: tagStyle.bg, color: tagStyle.color,
              padding: "2px 6px", borderRadius: 4,
              whiteSpace: "nowrap",
            }
          }, s.tagText)
        )
      )
    );
  };

  // ---- 渲染内容区 ----
  var renderContent = function() {
    return h("div", {
      style: {
        background: "#f6f7fb", borderRadius: "20px 20px 0 0",
        marginTop: -18, padding: "16px 0 0",
        minHeight: "100vh",
      }
    },
      // 公告条
      h("div", {
        style: {
          margin: "0 12px", background: "#EDEEFC", borderRadius: 12,
          height: 32, display: "flex", alignItems: "center", justifyContent: "center",
          fontSize: 12, color: "#6B6FA0",
        }
      }, "公告：未成年人禁止下单"),

      // 游戏分区入口
      h("div", {
        style: {
          display: "flex", gap: 10, padding: "12px 12px 4px",
          justifyContent: "center"
        }
      },
        [
          { key: "naikuai", label: "奶块", icon: "/official/assets/SC/NK.jpg" },
          { key: "delta", label: "三角洲", icon: "/official/assets/SC/SJZ.jpg" }
        ].map(function(game) {
          var active = gameFilter === game.key;
          return h("div", {
            key: game.key,
            onClick: function() { setGameFilter(game.key); },
            style: {
              display: "flex", flexDirection: "column", alignItems: "center", gap: 6,
              cursor: "pointer", padding: "8px 20px", borderRadius: 14,
              background: active ? "#fff" : "rgba(255,255,255,0.35)",
              boxShadow: active ? "0 2px 10px rgba(0,0,0,0.08)" : "none",
              transition: "all 0.2s",
              minWidth: 80
            }
          },
            h("img", {
              src: game.icon,
              style: { width: 40, height: 40, borderRadius: 10, objectFit: "cover",
                opacity: active ? 1 : 0.5, transition: "opacity 0.2s" }
            }),
            h("span", {
              style: { fontSize: 12, fontWeight: active ? 700 : 500,
                color: active ? "#1E293B" : "#94A3B8", transition: "all 0.2s" }
            }, game.label)
          );
        })
      ),

      // 分类筛选
      h("div", {
        style: {
          display: "flex", gap: 8, padding: "14px 12px 10px",
          overflowX: "auto", whiteSpace: "nowrap",
          scrollbarWidth: "none", msOverflowStyle: "none",
        }
      },
        CATEGORIES.map(function(cat) {
          var active = filterCat === cat;
          return h("div", {
            key: cat,
            onClick: function() { setFilterCat(cat); },
            style: {
              display: "inline-flex", alignItems: "center", gap: 4,
              flexShrink: 0, padding: "6px 14px", borderRadius: 18,
              fontSize: 12, fontWeight: active ? 600 : 400,
              cursor: "pointer",
              background: active ? "linear-gradient(135deg, #6366f1, #8b5cf6)" : "#fff",
              color: active ? "#fff" : "#555",
              transition: "all .2s",
              boxShadow: active ? "0 2px 8px rgba(99,102,241,0.3)" : "0 1px 3px rgba(0,0,0,0.04)",
            }
          },
            catIcons[cat] || null,
            cat
          );
        })
      ),

      // 加载中
      loading && h("div", { style: { textAlign: "center", padding: "40px 20px", color: "#999" } }, "加载中..."),

      // 服务卡片列表
      h("div", {
        style: {
          display: "flex", flexWrap: "wrap", gap: 10,
          padding: "0 12px 20px", justifyContent: "space-between",
        }
      }, services.map(function(s) { return renderCard(s); })),

      // 空状态
      !loading && services.length === 0 && h("div", {
        style: { textAlign: "center", padding: "60px 20px", color: "#999" }
      },
        h("div", { style: { fontSize: 48, marginBottom: 12 } }, "🔍"),
        h("div", { style: { fontSize: 14 } }, "暂无相关服务")
      )
    );
  };

  // 排行榜徽章
  var rankBadge = function(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));
  };

  // 排行榜主内容
  var renderRankings = function() {
    return h("div", {
      style: {
        background: "#f6f7fb", borderRadius: "20px 20px 0 0",
        marginTop: -18, padding: "16px 12px 20px",
        minHeight: "60vh",
      }
    },
      // 大佬榜/接单榜切换
      h("div", { style: { display: "flex", background: "#F1F5F9", borderRadius: 10, padding: 3, marginBottom: 12 } },
        [{ value: "spender", label: "大佬榜" }, { value: "booster", label: "接单榜" }].map(function(t) {
          var active = rankType === t.value;
          return h("div", { key: t.value, onClick: function() { setRankType(t.value); },
            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" }
          }, t.label);
        })
      ),
      // 周榜/月榜切换
      h("div", { style: { display: "flex", gap: 8, marginBottom: 16 } },
        [{ value: "week", label: "周榜" }, { value: "month", label: "月榜" }].map(function(p) {
          var active = rankPeriod === p.value;
          return h("div", { key: p.value, onClick: function() { setRankPeriod(p.value); },
            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" }
          }, p.label);
        })
      ),
      // 描述
      h("div", { style: { fontSize: 11, color: "#94A3B8", marginBottom: 14 } },
        rankType === "spender" ? "按服务消费金额排行" : "按已接单数量排行"
      ),
      // 加载中
      rankLoading ? h("div", { style: { padding: 40, textAlign: "center", 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: { background: "#fff", borderRadius: 14, overflow: "hidden", boxShadow: "0 1px 4px rgba(0,0,0,0.04)" } },
        rankList.map(function(item, i) {
          return h("div", { key: "rank-" + i,
            style: { display: "flex", alignItems: "center", padding: "14px 16px", borderBottom: i < rankList.length - 1 ? "1px solid #F1F5F9" : "none" }
          },
            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)
          );
        })
      )
    );
  };
  // ========== 主渲染 ==========
  return h("div", {
    style: {
      display: "flex", flexDirection: "column", minHeight: "100vh",
      background: "#f6f7fb",
    }
  },
    // ---- Hero 区（紧凑型） ----
    h("div", {
      style: {
        padding: "20px 16px 28px",
        background: "linear-gradient(135deg, #3868ff, #8064ff)",
      }
    },
      
      

      // 商城/大佬 胶囊 Tab
      h("div", { style: { display: "flex", alignItems: "center", gap: 26, paddingTop: 14 } },
        h("div", {
          onClick: function() { setMainTab("mall"); },
          style: {
            fontSize: 21, fontWeight: 700,
            cursor: "pointer", background: "transparent",
            color: mainTab === "mall" ? "#fff" : "rgba(255,255,255,0.55)",
            transition: "all .2s",
          }
        }, "商城"),
        h("div", {
          onClick: function() { setMainTab("expert"); },
          style: {
            fontSize: 21, fontWeight: 700,
            cursor: "pointer", background: "transparent",
            color: mainTab === "expert" ? "#fff" : "rgba(255,255,255,0.55)",
            transition: "all .2s",
          }
        }, "排行榜")
      )
    ),

    // ---- 排行榜 Tab 内容 ----
    mainTab === "expert" && renderRankings(),

    // ---- 商城 Tab 内容 ----
    mainTab === "mall" && renderContent()
  );
}

window.NK = window.NK || {};
NK.EscortHomePage = EscortHomePage;