// 护航服务详情页
const { useState, useEffect } = React;

// bizType / category 映射
var BIZ_MAP = { naikuai: "奶块", delta: "三角洲", mall: "奶块", expert: "三角洲" };
var CAT_MAP2 = { mall: "商城", dungeon: "副本", accompany: "陪玩", enchant: "附魔", labor: "苦力" };

// 标签/角标颜色
var TAG_COLORS = {
  "爆款单": { bg: "#fff0f0", color: "#e53e3e" },
  "小时单": { bg: "#fff7e6", color: "#d46b08" },
  "副本单": { bg: "#e6f7ff", color: "#096dd9" },
  "陪玩单": { bg: "#f0e6ff", color: "#722ed1" },
};

// 解析详情图（支持 JSON 数组、逗号分隔、单个 URL）
function parseDetailImages(raw) {
  if (!raw || !raw.trim()) return [];
  var s = raw.trim();
  // JSON 数组
  if (s.startsWith("[")) {
    try {
      var arr = JSON.parse(s);
      if (Array.isArray(arr)) return arr.filter(function(u) { return u && typeof u === "string" && u.trim(); });
    } catch(e) {}
  }
  // 逗号分隔
  if (s.indexOf(",") >= 0) return s.split(",").map(function(u) { return u.trim(); }).filter(Boolean);
  // 单个 URL
  return [s];
}

// 修正图片路径
function fixImageUrl(url) {
  if (!url || !url.trim()) return null;
  var u = url.trim();
  if (u.startsWith("http://") || u.startsWith("https://")) return u;
  if (u.startsWith("/")) return u;
  if (u.startsWith("uploads/")) return "/" + u;
  return "/" + u;
}

function EscortDetailPage() {
  var h = React.createElement;
  var params = NK.Store.get("pageParams") || {};
  var serviceId = params.id;

  var _data = useState(null); var data = _data[0]; var setData = _data[1];
  var _loading = useState(true); var loading = _loading[0]; var setLoading = _loading[1];
  var _error = useState(""); var error = _error[0]; var setError = _error[1];
  var _selectedSpecIdx = useState(0); var selectedSpecIdx = _selectedSpecIdx[0]; var setSelectedSpecIdx = _selectedSpecIdx[1];
  var _consultLoading = useState(false); var consultLoading = _consultLoading[0]; var setConsultLoading = _consultLoading[1];

  useEffect(function() {
    if (!serviceId) {
      setLoading(false);
      setError("服务ID无效");
      return;
    }
    setLoading(true);
    setError("");
    NK.Api.Escort.detail(serviceId).then(function(res) {
      setLoading(false);
      if (res && res.code === 0 && res.data) {
        setData(res.data);
      } else {
        setError(res && res.message || "服务不存在或已下架");
      }
    }).catch(function() {
      setLoading(false);
      setError("加载失败，请稍后重试");
    });
  }, [serviceId]);

  var handleBack = function() {
    NK.Store.navigate("escortHome");
  };

  var handleServiceChat = function() {
    if (consultLoading) return;
    if (!NK.Store.isLoggedIn()) { alert("请先登录"); NK.Store.navigate("login"); return; }
    var svcId = data && data.id;
    if (!svcId) return;
    setConsultLoading(true);
    NK.Api.Im.escortServiceConversation({ service_id: svcId, assignment_mode: "random" }).then(function(r) {
      if (r && r.code === 0 && r.data) {
        var convId = Number(r.data.conversation_id || 0);
        if (!convId) throw new Error("客服会话信息异常");
        NK.Store.navigate("supportChat", { conversationId: convId, conversationData: r.data });
      } else {
        alert((r && r.message) || "创建客服会话失败");
      }
    }).catch(function(err) {
      alert((err && err.message) || "网络错误，请稍后重试");
    }).finally(function() {
      setConsultLoading(false);
    });
  };

  // Loading
  if (loading) {
    return h("div", { style: { display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", minHeight: "100vh", background: "#f5f5f5", padding: 20 } },
      h("div", { style: { fontSize: 14, color: "#999" } }, "加载中...")
    );
  }

  // Error
  if (error || !data) {
    return h("div", { style: { display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", minHeight: "100vh", background: "#f5f5f5", padding: 20 } },
      h("div", { style: { fontSize: 48, marginBottom: 12 } }, "\uD83D\uDE14"),
      h("div", { style: { fontSize: 14, color: "#999", marginBottom: 16 } }, error || "服务不存在或已下架"),
      h("button", { onClick: handleBack, style: { padding: "8px 28px", borderRadius: 20, border: "1px solid #6366f1", background: "#fff", color: "#6366f1", fontSize: 14, cursor: "pointer" } }, "返回护航商城")
    );
  }

  // Detail
  var coverUrl = fixImageUrl(data.coverImage);
  var detailUrls = parseDetailImages(data.detailImages);
  var tagStyle = TAG_COLORS[data.tagText] || { bg: "#f0f0f0", color: "#666" };

  return h("div", { style: { display: "flex", flexDirection: "column", minHeight: "100vh", background: "#f5f5f5", paddingBottom: 68 } },
    // === 顶部返回栏 ===
    h("div", { style: { background: "#fff", padding: "12px 16px", display: "flex", alignItems: "center", borderBottom: "1px solid #f0f0f0", position: "sticky", top: 0, zIndex: 50 } },
      h("div", { onClick: handleBack, style: { cursor: "pointer", display: "flex", alignItems: "center", padding: "4px 0" } },
        NK.BackIcon ? NK.BackIcon({ size: 22, color: '#333' }) : null
      ),
      h("div", { style: { flex: 1, textAlign: "center", fontSize: 16, fontWeight: 600, color: "#1a1a2e", marginRight: 24 } }, "服务详情")
    ),

    // === 主体内容 ===
    h("div", { style: { flex: 1, padding: 12 } },

      // 封面图
      h("div", { style: { borderRadius: 12, overflow: "hidden", marginBottom: 12, position: "relative" } },
        coverUrl
          ? h("img", { src: coverUrl, style: { width: "100%", aspectRatio: "16/9", objectFit: "cover", display: "block" }, onError: function(e) { e.target.style.display = "none"; } })
          : h("div", { style: { width: "100%", aspectRatio: "16/9", background: "linear-gradient(135deg, #6366f1, #8b5cf6)", display: "flex", alignItems: "center", justifyContent: "center" } },
              h("span", { style: { color: "rgba(255,255,255,0.7)", fontSize: 40, fontWeight: 700 } }, data.title.substring(0, 2) || "护航")
            ),
        data.badgeText ? h("div", { style: { position: "absolute", top: 10, left: 10, background: "linear-gradient(135deg, #ff6b6b, #ee5a24)", color: "#fff", fontSize: 12, fontWeight: 600, padding: "4px 10px", borderRadius: 4, boxShadow: "0 2px 6px rgba(238,90,36,0.3)" } }, data.badgeText) : null
      ),

      // 类型 + 分类 + 标签
      h("div", { style: { display: "flex", gap: 6, marginBottom: 10, flexWrap: "wrap", alignItems: "center" } },
        h("span", { style: { fontSize: 12, color: "#6366f1", background: "#f0f0ff", padding: "2px 8px", borderRadius: 4, fontWeight: 500 } }, BIZ_MAP[data.bizType] || data.bizType),
        h("span", { style: { fontSize: 12, color: "#6366f1", background: "#f0f0ff", padding: "2px 8px", borderRadius: 4, fontWeight: 500 } }, CAT_MAP2[data.category] || data.category),
        data.tagText && h("span", { style: { fontSize: 11, fontWeight: 500, background: tagStyle.bg, color: tagStyle.color, padding: "2px 8px", borderRadius: 4 } }, data.tagText)
      ),

      // 标题
      h("div", { style: { fontSize: 19, fontWeight: 700, color: "#1a1a2e", lineHeight: 1.4, marginBottom: 8, overflow: "hidden", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical" } }, data.title),

      // 简介
      data.summary && h("div", { style: { fontSize: 13, color: "#999", lineHeight: 1.5, marginBottom: 10 } }, data.summary),

      // 价格行 - 动态跟随选中规格
      (function(){
        var specs = data.specs && Array.isArray(data.specs) ? data.specs : [];
        var selSpec = specs.length > 0 && selectedSpecIdx < specs.length ? specs[selectedSpecIdx] : null;
        var displayPrice = selSpec ? selSpec.price : data.price;
        var displayOriginPrice = selSpec && selSpec.originPrice != null ? selSpec.originPrice : data.originPrice;
        return h("div", { style: { display: "flex", alignItems: "baseline", gap: 6, marginBottom: 16, padding: "12px 0", borderTop: "1px solid #f0f0f0", borderBottom: "1px solid #f0f0f0" } },
          h("span", { style: { fontSize: 14, color: "#ff6b35", fontWeight: 600 } }, "\uFFE5"),
          h("span", { style: { fontSize: 28, fontWeight: 800, color: "#ff6b35", lineHeight: 1 } }, (Number.isFinite(Number(displayPrice)) ? Number(displayPrice).toFixed(2) : "0.00")),
          displayOriginPrice && Number(displayOriginPrice) > Number(displayPrice) && h("span", { style: { fontSize: 14, color: "#bbb", textDecoration: "line-through" } }, "\uFFE5" + (Number.isFinite(Number(displayOriginPrice)) ? Number(displayOriginPrice).toFixed(2) : "0.00"))
        );
      })(),

      // 服务说明
      data.content
        ? h("div", { style: { marginBottom: 16 } },
            h("div", { style: { fontSize: 15, fontWeight: 600, color: "#1a1a2e", marginBottom: 8 } }, "服务说明"),
            h("div", { style: { fontSize: 13, color: "#666", lineHeight: 1.8, whiteSpace: "pre-wrap", background: "#fff", padding: 12, borderRadius: 8 } }, data.content)
          )
        : h("div", { style: { marginBottom: 16, fontSize: 13, color: "#999", background: "#fff", padding: 12, borderRadius: 8, textAlign: "center" } }, "暂无服务说明"),

      // 选择规格
      (function(){
        var specs = data.specs && Array.isArray(data.specs) ? data.specs : [];
        if (specs.length === 0) return null;
        return h("div", { style: { marginBottom: 16 } },
          h("div", { style: { fontSize: 15, fontWeight: 600, color: "#1a1a2e", marginBottom: 10 } }, "选择规格"),
          h("div", { style: { display: "flex", flexWrap: "wrap", gap: 0 } },
            specs.map(function(spec, idx) {
              var isActive = idx === selectedSpecIdx;
              return h("div", {
                key: spec.id || idx,
                onClick: function() { setSelectedSpecIdx(idx); },
                style: {
                  display: "inline-flex", alignItems: "center",
                  padding: "8px 14px", margin: "0 8px 8px 0",
                  border: isActive ? "2px solid #ff7a2f" : "1px solid #ddd",
                  borderRadius: 8,
                  background: isActive ? "#fff7f0" : "#fff",
                  cursor: "pointer", fontSize: 14,
                  transition: "all 0.15s",
                  userSelect: "none"
                }
              },
                h("span", { style: { color: "#333" } }, spec.specName || "未命名规格"),
                h("span", { style: { color: "#ff4d1f", marginLeft: 6, fontWeight: 600 } }, "\uFFE5" + (spec.price != null ? Number(spec.price).toFixed(2) : "0.00"))
              );
            })
          )
        );
      })(),

      // 详情图
      detailUrls.length > 0 && h("div", { style: { marginBottom: 16 } },
        h("div", { style: { fontSize: 15, fontWeight: 600, color: "#1a1a2e", marginBottom: 10 } }, "详情图"),
        h("div", { style: { display: "flex", flexDirection: "column", gap: 10 } },
          detailUrls.map(function(url, i) {
            var fixed = fixImageUrl(url);
            if (!fixed) return null;
            return h("img", {
              key: i,
              src: fixed,
              style: { width: "100%", borderRadius: 12, display: "block", background: "#f0f0f0" },
              onError: function(e) { e.target.style.display = "none"; }
            });
          })
        )
      ),

      // 浏览量
      h("div", { style: { fontSize: 12, color: "#bbb", marginBottom: 16 } }, "浏览量：" + (data.viewCount || 0))
    ),

    // === 底部操作区 ===
    h("div", { style: { position: "fixed", bottom: 0, left: "50%", transform: "translateX(-50%)", width: "100%", maxWidth: 430, background: "#fff", padding: "10px 16px", borderTop: "1px solid #f0f0f0", display: "flex", gap: 10, zIndex: 100, paddingBottom: "calc(10px + env(safe-area-inset-bottom))" } },
      h("button", {
        onClick: handleServiceChat,
        disabled: consultLoading,
        style: { flex: 1, height: 42, borderRadius: 21, border: "1px solid #0f766e", background: consultLoading ? "#f1f5f4" : "#fff", color: "#0f766e", fontSize: 14, fontWeight: 600, cursor: consultLoading ? "not-allowed" : "pointer" }
      }, consultLoading ? "正在连接" : "服务私聊"),
      h("button", {
        onClick: function() {
          var specs = data.specs && Array.isArray(data.specs) ? data.specs : [];
          var selSpec = specs.length > 0 && selectedSpecIdx < specs.length ? specs[selectedSpecIdx] : null;
          NK.Store.navigate("escortPay", {
            serviceId: data.id,
            title: data.title,
            coverImage: data.coverImage || "",
            bizType: data.bizType || "",
            category: data.category || "",
            specId: selSpec ? selSpec.id : null,
            specName: selSpec ? selSpec.specName : "",
            price: selSpec ? selSpec.price : (data.price || 0),
            originPrice: selSpec ? (selSpec.originPrice || selSpec.price) : (data.originPrice || data.price || 0)
          });
        },
        style: { flex: 1, height: 42, borderRadius: 21, border: "none", background: "linear-gradient(135deg, #FF5A6A, #FF4D5A)", color: "#fff", fontSize: 14, fontWeight: 600, cursor: "pointer", boxShadow: "0 2px 8px rgba(255,77,90,0.3)" }
      }, "立即购买")
    )
  );
}

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