// 接单大厅 - 打手可接订单列表 (real data)
const { useState, useEffect } = React;
console.log("[BoosterHallPage] accept detail realfix2 loaded");

var TAG_LABELS = { naikuai: "奶块", delta: "三角洲", dungeon: "副本", accompany: "陪玩", enchant: "附魔", labor: "苦力", escort: "护航" };
var FILTERS = [
  { key: "all", label: "全部" }, { key: "naikuai", label: "奶块" }, { key: "delta", label: "三角洲" },
  { key: "dungeon", label: "副本" }, { key: "accompany", label: "陪玩" }, { key: "enchant", label: "附魔" },
  { key: "labor", label: "苦力" }, { key: "escort", label: "护航" },
];

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

  var _loading = useState(true), loading = _loading[0], setLoading = _loading[1];
  var _approved = useState(false), approved = _approved[0], setApproved = _approved[1];
  var _filter = useState("all"), filter = _filter[0], setFilter = _filter[1];
  var _orders = useState([]), orders = _orders[0], setOrders = _orders[1];
  var _boosterTags = useState([]), boosterTags = _boosterTags[0];
  var _todayAccepted = useState(0), todayAccepted = _todayAccepted[0], setTodayAccepted = _todayAccepted[1];
  var _servingCount = useState(0), servingCount = _servingCount[0], setServingCount = _servingCount[1];
  var _accepting = useState(null), accepting = _accepting[0], setAccepting = _accepting[1];
  var _levelName = useState(""), levelName = _levelName[0], setLevelName = _levelName[1];
  var _detailOrder = useState(null), detailOrder = _detailOrder[0], setDetailOrder = _detailOrder[1];
  var _acceptMsg = useState(""), acceptMsg = _acceptMsg[0], setAcceptMsg = _acceptMsg[1];

  // Load
  useEffect(function() {
    if (!NK.Store.isLoggedIn()) { setLoading(false); return; }
    Promise.all([NK.Api.Booster.me(), NK.Api.Booster.hall({ filter: "all" })]).then(function(results) {
      var meRes = results[0], hallRes = results[1];
      if (meRes.code === 0 && meRes.data && meRes.data.isBooster) {
        setApproved(true);
        setTodayAccepted(meRes.data.todayAcceptedCount || 0);
        setServingCount(meRes.data.servingCount || 0);
        setLevelName(meRes.data.levelName || "黑铁");
      }
      if (hallRes.code === 0) setOrders(hallRes.data || []);
      setLoading(false);
    }).catch(function() { setLoading(false); });
  }, []);

  function goBack() { NK.Store.navigate("boosterCenter"); }
  function loadHall(f) { setFilter(f); NK.Api.Booster.hall({ filter: f }).then(function(res) { if (res.code === 0) setOrders(res.data || []); }).catch(function() {}); }
  function refreshStats() { NK.Api.Booster.me().then(function(meRes) { if (meRes.code === 0 && meRes.data) { setTodayAccepted(meRes.data.todayAcceptedCount || 0); setServingCount(meRes.data.servingCount || 0); } }); }
  function tagLabel(code) { return TAG_LABELS[code] || code; }

  // ---- ASYNC handleAccept ----
  async function handleAccept(order) {
    if (!order || accepting) return;
    setAccepting(order.id);
    setAcceptMsg("");
    console.log("[accept] clicked order:", order);

    try {
      var sourceType = order.sourceType || order.source_type;
      var sourceId = order.sourceId || order.source_id;
      console.log("[accept] sourceType/sourceId:", sourceType, sourceId);

      if (sourceType !== "escort_service" || !sourceId) {
        throw new Error("订单来源异常，无法接取护航服务订单");
      }

      // Accept the escort order
      var acceptRes = await NK.Api.Escort.acceptOrder(sourceId);
      console.log("[accept] escort accept result:", acceptRes);
      if (!acceptRes || acceptRes.code !== 0) {
        throw new Error((acceptRes && acceptRes.message) || "接单失败");
      }

      // Load detail
      var detailRes = await NK.Api.Escort.boosterDetail(sourceId);
      console.log("[accept] booster detail result:", detailRes);
      if (!detailRes || detailRes.code !== 0 || !detailRes.data) {
        throw new Error((detailRes && detailRes.message) || "接单详情加载失败");
      }

      // Switch to detail view
      console.log("[accept] switch to detail view");
      setDetailOrder(detailRes.data);
      setAcceptMsg("接单成功");
      loadHall(filter);
      refreshStats();
    } catch (err) {
      console.error("[accept] failed:", err);
      setAcceptMsg(err.message || "接单失败，请稍后重试");
      loadHall(filter);
    } finally {
      setAccepting(null);
    }
  }

  // ---- Render: 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 } }, "加载中...")
    );
  }

  // ---- Render: Detail View ----
  if (detailOrder) {
    var d = detailOrder;
    return h("div", { className: "detail-page" },
      h("div", { className: "app-page-header" },
        h("div", { className: "back-btn", onClick: function() { setDetailOrder(null); loadHall(filter); } },
          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" }, "接单详情")
      ),
      // Status Card
      h("div", { style: { background: "#fff", borderRadius: 14, padding: 16, margin: "12px 12px 10px", boxShadow: "0 1px 4px rgba(0,0,0,0.04)", textAlign: "center" } },
        h("div", { style: { display: "inline-block", padding: "4px 16px", borderRadius: 20, background: "#f6ffed", color: "#52c41a", fontSize: 13, fontWeight: 600 } }, "接单成功"),
        h("div", { style: { fontSize: 14, color: "#595959", marginTop: 8 } }, "已有打手接单，请立即查看")
      ),
      // Service Info Card
      h("div", { style: { background: "#fff", borderRadius: 14, padding: 16, margin: "0 12px 10px", boxShadow: "0 1px 4px rgba(0,0,0,0.04)" } },
        h("div", { style: { fontSize: 13, color: "#8b8b8b", marginBottom: 10 } }, "服务信息"),
        h("div", { style: { fontSize: 15, fontWeight: 600, color: "#1a1a2e", marginBottom: 6 } }, d.serviceTitle || ""),
        d.specName ? h("div", { style: { fontSize: 13, color: "#595959", marginBottom: 4 } }, "规格：" + d.specName) : null,
        h("div", { style: { fontSize: 13, color: "#595959", marginBottom: 4 } }, "数量：" + (d.quantity || 1) + " 个"),
        h("div", { style: { fontSize: 13, color: "#595959", marginBottom: 4 } }, "服务金额：" + "\u00A5" + Number(d.amount || 0).toFixed(2)),
        h("div", { style: { fontSize: 12, color: "#bfbfbf" } }, "订单号：" + (d.orderNo || "-")),
        d.acceptedAt ? h("div", { style: { fontSize: 12, color: "#bfbfbf", marginTop: 2 } }, "接单时间：" + new Date(d.acceptedAt).toLocaleString()) : null
      ),
      // Buyer Info Card
      h("div", { style: { background: "#fff", borderRadius: 14, padding: 16, margin: "0 12px 10px", boxShadow: "0 1px 4px rgba(0,0,0,0.04)" } },
        h("div", { style: { fontSize: 13, color: "#8b8b8b", marginBottom: 10 } }, "买家下单信息"),
        d.gameServer ? h("div", { style: { fontSize: 13, color: "#595959", marginBottom: 6 } }, "游戏区服：" + d.gameServer) : null,
        d.accountId ? h("div", { style: { fontSize: 13, color: "#595959", marginBottom: 6 } }, "账号ID：" + d.accountId) : null,
        d.contactPhone ? h("div", { style: { fontSize: 13, color: "#595959", marginBottom: 6 } }, "联系电话：" + d.contactPhone) : null,
        h("div", { style: { fontSize: 13, color: "#8c8c8c", marginBottom: 6, lineHeight: 1.5 } }, "下单备注：" + (d.remark || "暂无备注"))
      ),
      // Bottom Button
      h("div", { style: { padding: "0 12px" } },
        h("button", { onClick: function() { console.log("[BoosterHall] contact buyer - detailOrder:", JSON.stringify({id:detailOrder.id,orderNo:detailOrder.orderNo,status:detailOrder.status})); var orderId = Number(detailOrder.id); if (!orderId || isNaN(orderId)) { alert("订单参数异常，请刷新后重试"); return; } var snapshot = { id: orderId, orderId: orderId, serviceName: detailOrder.serviceTitle || "护航服务", cover: detailOrder.coverImage || "", price: Number(detailOrder.amount) || 0, specName: detailOrder.specName || "", status: Number(detailOrder.status), statusText: detailOrder.statusText || "", serverName: detailOrder.gameServer || "", boosterName: detailOrder.boosterName || "我", remark: detailOrder.remark || "", accountId: detailOrder.accountId || "", bizType: "naikuai", role: "booster", source: "boosterHall" }; try { sessionStorage.setItem("escort_order_chat_" + orderId, JSON.stringify(snapshot)); } catch(e) {} NK.Store.navigate("escortOrderChat", { orderId: orderId, role: "booster", source: "boosterHall", escortOrderSnapshot: snapshot }); }, style: { width: "100%", padding: "12px 0", borderRadius: 12, border: "none", background: "#1677ff", color: "#fff", fontSize: 15, fontWeight: 600, cursor: "pointer", boxShadow: "0 4px 12px rgba(22,119,255,0.3)" } }, "联系买家")
      )
    );
  }

  // ---- Render: 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("div", { style: { padding: "40px 20px", textAlign: "center" } },
        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.Api.Dashou.status().then(function(res) { if (res.code === 0 && res.data && res.data.status === 0) { alert("\u5165\u9a7b\u7533\u8bf7\u5df2\u63d0\u4ea4\uff0c\u5f53\u524d\u6b63\u5728\u5ba1\u6838\u4e2d\uff0c\u8bf7\u8010\u5fc3\u7b49\u5f85\u5e73\u53f0\u5ba1\u6838"); } else { NK.Store.navigate("dashouJoin"); } }).catch(function() { NK.Store.navigate("dashouJoin"); }); }, style: { padding: "10px 32px", background: "#1677ff", color: "#fff", border: "none", borderRadius: 8, fontSize: 15, fontWeight: 600, cursor: "pointer" } }, "申请入驻")
      )
    );
  }

  // ---- Render: Main List ----
  return h("div", { className: "detail-page" },
    h("div", { className: "app-page-header", style: { position: "sticky", top: 0, zIndex: 100 } },
      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" }, "接单大厅")
    ),
    acceptMsg ? h("div", { style: { padding: "8px 16px", background: acceptMsg.indexOf("成功") >= 0 ? "#f6ffed" : "#fff3f3", color: acceptMsg.indexOf("成功") >= 0 ? "#52c41a" : "#d32f2f", fontSize: 13, textAlign: "center" } }, acceptMsg) : null,
    // Stats card
    h("div", { style: { margin: "8px 12px", padding: "12px 16px", background: "#fff", borderRadius: 12, 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", alignItems: "center", gap: 8 } },
          h("span", { style: { fontSize: 13, color: "#8c8c8c" } }, "当前身份"),
          h("span", { style: { padding: "2px 10px", borderRadius: 10, fontSize: 11, fontWeight: 600, background: "#e6f7ff", color: "#1677ff" } }, "已认证打手")
        ),
        h("span", { style: { fontSize: 13, color: "#595959" } }, "打手等级：" + (levelName || "黑铁"))
      ),
      h("div", { style: { display: "flex", gap: 12 } },
        h("div", { style: { flex: 1, textAlign: "center", padding: "8px 0", background: "#fafafa", borderRadius: 8 } },
          h("div", { style: { fontSize: 18, fontWeight: 700, color: "#1677ff" } }, String(todayAccepted)),
          h("div", { style: { fontSize: 11, color: "#8c8c8c", marginTop: 2 } }, "今日接单")
        ),
        h("div", { style: { flex: 1, textAlign: "center", padding: "8px 0", background: "#fafafa", borderRadius: 8 } },
          h("div", { style: { fontSize: 18, fontWeight: 700, color: "#16a34a" } }, String(servingCount)),
          h("div", { style: { fontSize: 11, color: "#8c8c8c", marginTop: 2 } }, "服务中")
        )
      )
    ),
    h("div", { style: { padding: "6px 16px", fontSize: 12, color: "#bfbfbf", textAlign: "center" } }, levelName ? "打手等级：" + levelName + " · 可接订单" : "可接订单"),
    h("div", { style: { margin: "0 0 12px", padding: "8px 12px", overflowX: "auto", whiteSpace: "nowrap", display: "flex", gap: 8 } },
      FILTERS.map(function(f) {
        var active = filter === f.key;
        return h("div", { key: f.key, onClick: function() { loadHall(f.key); }, style: { display: "inline-block", padding: "6px 16px", borderRadius: 18, fontSize: 13, fontWeight: active ? 600 : 400, cursor: "pointer", flexShrink: 0, background: active ? "#1677ff" : "#fff", color: active ? "#fff" : "#595959", border: active ? "1px solid #1677ff" : "1px solid #e8e8e8" } }, f.label);
      })
    ),
    orders.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 12px" } },
          orders.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" } }, "\u00A5" + 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() { handleAccept(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 ? "接单中..." : "接单")
              )
            );
          })
        )
  );
}

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