console.log("PublishPage-FIX-20260610-045144");
// PublishPage - minimal stable version
const { useState, useEffect } = React;

var h = React.createElement;

// ===== Data =====
var SERVERS = ['绽放之花','无尽之海','遗忘之境','生命之树','狂野之原','轻云之月','飘渺之峰','暗涌之泉','应许之地','参天之树','拉普达','铭心之界'];
var LTIERS = ['五阶传说','四阶传说','三阶传说'];
var LTYPES = ['长枪','龙爪','战刃','短匕','刺剑','火铳','短剑','圆盾','镰刀','提灯','星仪','命盘','法杖','奶杖','法典','长弓','箭袋'];
var MFLY = ['四飞','六飞','八飞'];
var MZOD = ['天秤座','天蝎座','射手座','摩羯座','水瓶座','处女座','双鱼座','白羊座','金牛座','双子座','巨蟹座'];
var UTIERS = ["T4","T5","T6","T7","T8"];
var UPROFS = ['战士','输出','法师'];
var UPARTS = {
  '战士':['头盔','胸甲','腿甲','战靴','短剑','圆盾','长枪','龙爪'],
  '输出':['头饰','护胸','护腿','便鞋','战刃','短匕','火铳','短剑','刺剑','长弓','箭袋'],
  '法师':['兜帽','法袍','长裤','软鞋','镰刀','提灯','星仪','命盘','法杖','法典']
};

function empLeg() {
  var o = {};
  LTIERS.forEach(function (t) { o[t] = []; });
  return o;
}

function empUnl() {
  var o = {};
  UTIERS.forEach(function (t) {
    o[t] = { profs: {} };
    UPROFS.forEach(function (p) { o[t].profs[p] = []; });
  });
  return o;
}

function cln(src) {
  try { return JSON.parse(JSON.stringify(src)); } catch (e) { return src; }
}

function safeImg(arr) {
  if (!Array.isArray(arr)) return [];
  return arr.map(function (x) {
    return typeof x === "string" ? x : (x && x.image_url || "");
  }).filter(Boolean);
}


function PublishPage() {
  var pp = NK.Store.get("pageParams") || {};
  var edit = !!(pp.editMode);
  var eid = pp.productId;

  // Form state
  var _f = useState({ auid: "", title: "", server: "", price: "", desc: "", cover: [], detail: [] });
  var f = _f[0], sf = _f[1];
  var _ld = useState(false);
  var ld = _ld[0], sld = _ld[1];
  var _er = useState("");
  var err = _er[0], serr = _er[1];
  var _ok = useState(false);
  var ok = _ok[0], sok = _ok[1];
  var _el = useState(!!edit);
  var eld = _el[0], seld = _el[1];
  var _pt = useState(null);
  var pubType = _pt[0], spubType = _pt[1];
  var _sv = useState(false);
  var srvOpen = _sv[0], ssrvOpen = _sv[1];
  var _toast = useState(""); var toast = _toast[0], setToast = _toast[1];

  // Config state
  var _leg = useState(empLeg());
  var leg = _leg[0], sleg = _leg[1];
  var _ln = useState(false);
  var lnone = _ln[0], slnone = _ln[1];
  var _mt = useState({ mc: "", fl: "", zods: [] });
  var mt = _mt[0], smt = _mt[1];
  var _unl = useState(empUnl());
  var unl = _unl[0], sunl = _unl[1];
  var _pan = useState(null);
  var pan = _pan[0], span = _pan[1];
  var _ltab = useState(LTIERS[0]);
  var ltab = _ltab[0], sltab = _ltab[1];
  var _utab = useState("T8");
  var utab = _utab[0], sutab = _utab[1];
  var _uprof = useState(UPROFS[0]);
  var uprof = _uprof[0], suprof = _uprof[1];

  
  // Preload publish page card images for fast display
  useEffect(function () {
    var imgs = [
      "/assets/publish/finished-account.webp",
      "/assets/publish/initial-account.webp"
    ];
    imgs.forEach(function (src) {
      var img = new Image();
      img.src = src;
    });
  }, []);

  // Load edit data
  useEffect(function () {
    if (!edit || !eid) { seld(false); return; }
    seld(true);
    try {
      NK.Api.Accounts.myDetail(eid).then(function (r) {
        if (r && r.code === 0 && r.data) {
          var p = r.data;
          sf({
            auid: p.account_uid || p.accountUid || "",
            title: p.title || "",
            server: p.server || "",
            price: p.price != null ? String(p.price) : "",
            desc: p.description || "",
            cover: safeImg(p.coverImages),
            detail: safeImg(p.detailImages)
          });
          var dc = p.detailConfig || p.detail_config;
          if (dc && typeof dc === "object") {
            if (dc.legendaryEquipment) {
              if (dc.legendaryEquipment.none === true) { slnone(true); sleg(empLeg()); }
              else { slnone(false); sleg(cln(dc.legendaryEquipment)); }
            }
                        if (dc.legendaryMount) smt(cln(dc.legendaryMount));
            if (dc.equipmentUnlock) sunl(cln(dc.equipmentUnlock));
          }
        }
      }).catch(function () { serr("\u52A0\u8F7D\u5931\u8D25"); }).finally(function () { seld(false); });
    } catch (e) { seld(false); }
  }, []);

  // Signal app.jsx to hide tab bar when in form stage
  useEffect(function () {
    NK.Store.set('publishFormActive', !!pubType);
  }, [pubType]);

  function sF(k, v) {
    sf(function (p) { var n = {}; for (var x in p) n[x] = p[x]; n[k] = v; return n; });
  }

  function sM(k, v) {
    smt(function (p) { var n = {}; for (var x in p) n[x] = p[x]; n[k] = v; return n; });
  }

  // ===== Config helpers =====
  function legSum() {
    try {
      if (lnone) return "\u65E0";
      var cfg = { legendaryEquipment: leg };
      var txt = NK.ConfigUtil && NK.ConfigUtil.legendary ? NK.ConfigUtil.legendary(cfg) : "";
      if (txt) return txt;
      // fallback: count per tier
      var result = [];
      LTIERS.forEach(function (t) {
        var arr = leg[t];
        if (Array.isArray(arr) && arr.length > 0) {
          result.push(arr.length + "\u4EF6" + t.substring(0, 2));
        }
      });
      return result.length ? result.join(" \u8DEF ") : "\u672A\u9009\u62E9";
    } catch (e) { return "?"; }
  }

  function mtSum() {
    try {
      var mc = parseInt(mt.mc) || 0;
      var fl = mt.fl || "";
      var zc = Array.isArray(mt.zods) ? mt.zods.length : 0;
      var hasAny = mc > 0 || !!fl || zc > 0;
      if (!hasAny) return "\u672A\u586B\u5199";
      var cfg = { legendaryMount: { mountCount: mc, flyingLevel: fl, zodiacs: mt.zods || [] } };
      var txt = NK.ConfigUtil && NK.ConfigUtil.mountText ? NK.ConfigUtil.mountText(cfg) : "";
      if (txt) return txt;
      return "\u5DF2\u9009\u62E9";
    } catch (e) { return "?"; }
  }

  function unSum() {
    try {
      var hasT8 = false, hasAny = false;
      var t8obj = unl["T8"];
      if (t8obj && t8obj.profs) {
        UPROFS.forEach(function (prof) {
          var arr = t8obj.profs[prof];
          if (Array.isArray(arr) && arr.length > 0) hasT8 = true;
        });
      }
      UTIERS.forEach(function (tier) {
        var obj = unl[tier];
        if (!obj || !obj.profs) return;
        UPROFS.forEach(function (prof) {
          var arr = obj.profs[prof];
          if (Array.isArray(arr) && arr.length > 0) hasAny = true;
        });
      });
      if (!hasAny) return "\u672A\u9009\u62E9";
      if (hasT8) {
        var cfg = { equipmentUnlock: unl };
        var txt = NK.ConfigUtil && NK.ConfigUtil.unlock ? NK.ConfigUtil.unlock(cfg) : "";
        if (txt) return txt;
      }
      return "\u5DF2\u9009\u62E9";
    } catch (e) { return "?"; }
  }

  function togLeg(tier, item) {
    slnone(false);
    sleg(function (p) {
      var n = cln(p);
      if (!n[tier]) n[tier] = [];
      var i = n[tier].indexOf(item);
      if (i >= 0) n[tier].splice(i, 1);
      else n[tier].push(item);
      return n;
    });
  }

  function hasLeg(tier, item) {
    if (lnone) return false;
    var a = leg[tier];
    return Array.isArray(a) && a.indexOf(item) >= 0;
  }

  function setNone() { slnone(true); sleg(empLeg()); }
  function clrNone() { slnone(false); }

  function togZod(z) {
    smt(function (p) {
      var a = Array.isArray(p.zods) ? p.zods.slice() : [];
      var i = a.indexOf(z);
      if (i >= 0) a.splice(i, 1);
      else a.push(z);
      var n = {};
      for (var x in p) n[x] = p[x];
      n.zods = a;
      return n;
    });
  }

  function hasZod(z) {
    var a = mt.zods;
    return Array.isArray(a) && a.indexOf(z) >= 0;
  }

  function togUnl(part) {
    sunl(function (p) {
      var n = cln(p);
      var t = n[utab];
      if (!t) t = n[utab] = { profs: {} };
      if (!t.profs) t.profs = {};
      if (!t.profs[uprof]) t.profs[uprof] = [];
      var a = t.profs[uprof];
      var i = a.indexOf(part);
      if (i >= 0) a.splice(i, 1);
      else a.push(part);
      return n;
    });
  }

  function hasUnl(part) {
    var t = unl[utab];
    if (!t || !t.profs || !t.profs[uprof]) return false;
    return t.profs[uprof].indexOf(part) >= 0;
  }
  function toggleSelectAllUnl() {
    var parts = UPARTS[uprof] || [];
    if (parts.length === 0) return;
    var allSel = parts.every(function (pt) { return hasUnl(pt); });
    sunl(function (p) {
      var n = cln(p);
      var t = n[utab];
      if (!t) t = n[utab] = { profs: {} };
      if (!t.profs) t.profs = {};
      if (allSel) {
        t.profs[uprof] = [];
      } else {
        t.profs[uprof] = parts.slice();
      }
      return n;
    });
  }



  // ===== Panel content =====
  function panContent() {
    if (pan === "leg") {
      return h("div", null,
        h("div", { style: { margin: "8px 0" } },
          h("div", {
            className: "tag-item" + (lnone ? " selected" : ""),
            onClick: function () { lnone ? clrNone() : setNone(); },
            style: { display: "inline-block", padding: "6px 14px", margin: 4, borderRadius: 16, cursor: "pointer", border: "1px solid #d9d9d9", background: lnone ? "#e6f4ff" : "#fff", color: lnone ? "#1677ff" : "#333", fontSize: 13 }
          }, lnone ? "✓ \u65E0\u4F20\u8BF4\u88C5\u5907" : "\u65E0\u4F20\u8BF4\u88C5\u5907")
        ),
        h("div", { className: "pub3-tiertabs" },
          LTIERS.map(function (t) {
            var has = !!(leg[t] && leg[t].length);
            return h("div", {
              key: t, className: "pub3-tiertab" + (ltab === t ? " active" : ""),
              onClick: function () { sltab(t); },
              style: { position: "relative", display: "inline-block", padding: "6px 12px", margin: "2px 4px", borderRadius: 14, cursor: "pointer", fontSize: 13, background: ltab === t ? "#1677ff" : "#f0f0f0", color: ltab === t ? "#fff" : "#333" }
            }, t, has ? h("span", { style: { position: "absolute", top: -2, right: -2, width: 5, height: 5, borderRadius: "50%", background: "#ff4d4f" } }) : null);
          })
        ),
        h("div", { className: "tag-grid", style: { marginTop: 8 } },
          LTYPES.map(function (tp) {
            var sel = hasLeg(ltab, tp);
            return h("div", {
              key: tp, className: "tag-item" + (sel ? " selected" : ""),
              onClick: function () { togLeg(ltab, tp); },
              style: { display: "inline-block", padding: "5px 10px", margin: 3, borderRadius: 12, cursor: "pointer", fontSize: 12, border: "1px solid " + (sel ? "#1677ff" : "#d9d9d9"), background: sel ? "#e6f4ff" : "#fff", color: sel ? "#1677ff" : "#555" }
            }, tp);
          })
        ),
        h("div", { style: { fontSize: 12, color: "#999", marginTop: 10 } }, "\u5F53\u524D\u9009\u62E9: " + legSum())
      );
    }

    if (pan === "mt") {
      var mcVal = parseInt(mt.mc) || 0;
      return h("div", null,
        h("div", { style: { marginBottom: 10 } },
          h("div", { style: { fontSize: 13, fontWeight: 600, marginBottom: 6 } }, "\u4F20\u8BF4\u5750\u9A91\u6570\u91CF"),
          h("input", {
            type: "number",
            placeholder: "\u8BF7\u8F93\u5165\u4F20\u8BF4\u5750\u9A91\u6570\u91CF",
            value: mcVal > 0 ? String(mcVal) : "",
            onInput: function (ev) { var v = parseInt(ev.target.value.replace(/\D/g, "")) || 0; sM("mc", v); },
            style: { width: "100%", padding: "8px 12px", borderRadius: 8, border: "1px solid #d9d9d9", fontSize: 14, boxSizing: "border-box" }
          })
        ),
        h("div", { style: { marginBottom: 10 } },
          h("div", { style: { fontSize: 13, fontWeight: 600, marginBottom: 6 } }, "\u98DE\u884C\u7B49\u7EA7"),
          h("div", null, MFLY.map(function (lv) {
            return h("span", {
              key: lv,
              onClick: function () { var v = mt.fl === lv ? "" : lv; sM("fl", v); },
              style: { display: "inline-block", padding: "5px 10px", margin: 3, borderRadius: 12, cursor: "pointer", fontSize: 12, border: "1px solid " + (mt.fl === lv ? "#1677ff" : "#d9d9d9"), background: mt.fl === lv ? "#e6f4ff" : "#fff", color: mt.fl === lv ? "#1677ff" : "#555" }
            }, lv);
          }))
        ),
        h("div", { style: { marginBottom: 10 } },
          h("div", { style: { fontSize: 13, fontWeight: 600, marginBottom: 6 } }, "\u661F\u5EA7"),
          h("div", null, MZOD.map(function (z) {
            var sel = hasZod(z);
            return h("span", {
              key: z,
              onClick: function () { togZod(z); },
              style: { display: "inline-block", padding: "5px 10px", margin: 3, borderRadius: 12, cursor: "pointer", fontSize: 12, border: "1px solid " + (sel ? "#1677ff" : "#d9d9d9"), background: sel ? "#e6f4ff" : "#fff", color: sel ? "#1677ff" : "#555" }
            }, z);
          }))
        ),
        h("div", { style: { fontSize: 12, color: "#999", marginTop: 4 } }, "\u5F53\u524D\u9009\u62E9: " + mtSum())
      );
    }

    if (pan === "unl") {
      var parts = UPARTS[uprof] || [];
      return h("div", null,
        h("div", { className: "pub3-tiertabs" },
          UTIERS.map(function (t) {
            var has = !!(unl[t] && unl[t].profs);
            var tObj = unl[t];
            if (has && tObj && tObj.profs) {
              has = false;
              for (var pk in tObj.profs) { if (tObj.profs.hasOwnProperty(pk) && tObj.profs[pk] && tObj.profs[pk].length > 0) { has = true; break; } }
            }
            return h("div", {
              key: t, className: "pub3-tiertab" + (utab === t ? " active" : ""),
              onClick: function () { sutab(t); },
              style: { position: "relative", display: "inline-block", padding: "6px 12px", margin: "2px 4px", borderRadius: 14, cursor: "pointer", fontSize: 13, background: utab === t ? "#1677ff" : "#f0f0f0", color: utab === t ? "#fff" : "#333" }
            }, t, has ? h("span", { style: { position: "absolute", top: -2, right: -2, width: 5, height: 5, borderRadius: "50%", background: "#ff4d4f" } }) : null);
          })
        ),
        h("div", { style: { margin: "8px 0", display: "flex", alignItems: "center", flexWrap: "wrap", gap: 4 } },
          UPROFS.map(function (p) {
            return h("span", {
              key: p,
              onClick: function () { suprof(p); },
              style: { display: "inline-block", padding: "5px 12px", margin: 3, borderRadius: 14, cursor: "pointer", fontSize: 13, background: uprof === p ? "#1677ff" : "#f0f0f0", color: uprof === p ? "#fff" : "#333" }
            }, p);
          }),
          h("span", {
            onClick: function () { toggleSelectAllUnl(); },
            style: { padding: "4px 10px", borderRadius: 10, cursor: "pointer", fontSize: 12, border: "1px solid #d9d9d9", color: "#666", background: "#fafafa", flexShrink: 0 }
          }, parts.length > 0 && parts.every(function (pt) { return hasUnl(pt); }) ? "\u53D6\u6D88\u5168\u9009" : "\u5168\u9009")
        ),
        h("div", { style: { marginTop: 8 } },
          parts.map(function (pt) {
            var sel = hasUnl(pt);
            return h("span", {
              key: pt,
              onClick: function () { togUnl(pt); },
              style: { display: "inline-block", padding: "5px 10px", margin: 3, borderRadius: 12, cursor: "pointer", fontSize: 12, border: "1px solid " + (sel ? "#1677ff" : "#d9d9d9"), background: sel ? "#e6f4ff" : "#fff", color: sel ? "#1677ff" : "#555" }
            }, pt);
          })
        ),
        h("div", { style: { fontSize: 12, color: "#999", marginTop: 10 } }, "\u5F53\u524D\u9009\u62E9: " + unSum())
      );
    }

    return null;
  }

  function renderPan() {
    if (!pan) return null;
    var titles = {
      leg: "\u4F20\u8BF4\u88C5\u5907",
      mt: "\u4F20\u8BF4\u5750\u9A91",
      unl: "\u88C5\u5907\u89E3\u9501"
    };
    return h("div", {
      className: "filter-overlay",
      onClick: function (e) { if (e.target.className === "filter-overlay") span(null); }
    },
      h("div", { className: "filter-panel" },
        h("div", { className: "fp-header" },
          h("div", { className: "fp-title" }, titles[pan] || ""),
          h("div", { style: { fontSize: 20, cursor: "pointer", color: "#999" }, onClick: function () { span(null); } }, String.fromCharCode(215))
        ),
        h("div", { className: "fp-body" }, panContent()),
        h("div", { className: "fp-footer" },
          h("button", { className: "confirm-btn", onClick: function () { span(null); } }, "\u786E\u8BA4")
        )
      )
    );
  }

  // ===== Validation and submit =====
  function vld() {
    if (!f.auid || !f.auid.trim()) return "\u8BF7\u586B\u5199\u6E38\u620F\u8D26\u53F7";
    if (!f.title || !f.title.trim()) return "\u8BF7\u586B\u5199\u5546\u54C1\u6807\u9898";
    if (!f.server) return "\u8BF7\u9009\u62E9\u670D\u52A1\u5668";
    if (!f.price || parseFloat(f.price) <= 0) return "\u8BF7\u586B\u5199\u6709\u6548\u552E\u4EF7";
    function showToast(msg) { setToast(msg); setTimeout(function(){setToast("")}, 2500); }

  if (!Array.isArray(f.cover) || f.cover.length === 0) return "\u8BF7\u4E0A\u4F20\u81F3\u5C11\u4E00\u5F20\u5C01\u9762\u56FE";
    return null;
  }

  function submit() {
    var e = vld();
    if (e) { showToast(e); return; }
    serr("");
    sld(true);
    var body = {
      accountUid: f.auid.trim(),
      accountType: pubType || "",
      title: f.title.trim(),
      server: f.server,
      price: parseFloat(f.price),
      description: f.desc || "",
      coverImages: f.cover || [],
      detailImages: f.detail || []
    };
    // Add config data
    body.detailConfig = {
      legendaryEquipment: lnone ? { none: true } : cln(leg),
      legendaryMount: cln(mt),
      equipmentUnlock: cln(unl)
    };
    var api = edit && eid ? NK.Api.Accounts.edit(eid, body) : NK.Api.Accounts.create(body);
    api.then(function (r) {
      if (r && r.code === 0) sok(true);
      else serr((r && r.message) || "\u63D0\u4EA4\u5931\u8D25");
    }).catch(function (e) {
      serr("\u7F51\u7EDC\u9519\u8BEF: " + (e.message || ""));
    }).finally(function () { sld(false); });
  }


    
    // ===== Image upload =====
    function isAppClient() {
      return document.body.classList.contains("is-app-client") ||
             document.documentElement.classList.contains("is-app-client");
    }

    // NativeImageBridge - App mode album picker via bridge
    (function() {
      if (!window.NK) window.NK = {};
      if (window.NK.NativeImageBridge) return;
      window.NK.NativeImageBridge = {
        _callbacks: {},
        chooseImage: function(options) {
          options = options || {};
          var requestId = "img_" + Date.now() + "_" + Math.random().toString(16).slice(2, 10);
          var maxCount = options.maxCount || 1;
          var self = this;
          return new Promise(function(resolve, reject) {
            self._callbacks[requestId] = { resolve: resolve, reject: reject };
            if (!window.uni || typeof window.uni.postMessage !== "function") {
              delete self._callbacks[requestId];
              reject(new Error("native bridge unavailable"));
              return;
            }
            console.log("[NativeImageBridge] postMessage chooseImageFromAlbum requestId=" + requestId + " maxCount=" + maxCount);
            window.uni.postMessage({
              data: {
                action: "chooseImageFromAlbum",
                requestId: requestId,
                maxCount: maxCount,
                token: (window.NK && window.NK.Api && window.NK.Api.getToken ? window.NK.Api.getToken() : "")
              }
            });
          });
        },
        onResult: function(requestId, result) {
          var cb = this._callbacks[requestId];
          if (!cb) return;
          delete this._callbacks[requestId];
          console.log("[NativeImageBridge] onResult requestId=" + requestId, result);
          if (result && result.ok) {
            cb.resolve(result.urls || []);
          } else {
            cb.reject(new Error(result && result.message || "\u9009\u62E9\u56FE\u7247\u5931\u8D25"));
          }
        }
      };
    })();

    function upImg(key, max) {
      if (isAppClient()) {
        var cur = f[key] || [];
        if (cur.length >= max) { serr("\u6700\u591A" + max + "\u5F20"); return; }
        var remaining = max - cur.length;

        var bridge = window.NK && window.NK.NativeImageBridge;
        if (!bridge || !window.uni || typeof window.uni.postMessage !== "function") {
          serr("\u8BF7\u66F4\u65B0 App \u540E\u91CD\u8BD5");
          return;
        }

        console.log("[PublishPage] app mode choose image via native bridge, remaining=" + remaining);
        sld(true);
        bridge.chooseImage({ maxCount: remaining }).then(function(urls) {
          console.log("[PublishPage] native bridge urls", urls);
          if (urls && urls.length > 0) {
            sf(function(p) {
              var n = {}; for (var x in p) n[x] = p[x];
              var a = (n[key] || []).slice();
              urls.forEach(function(u) {
                if (u && a.indexOf(u) < 0) a.push(u);
              });
              n[key] = a; return n;
            });
          }
          sld(false);
        }).catch(function(err) {
          console.warn("[PublishPage] native choose image failed", err);
          serr("\u9009\u62E9\u56FE\u7247\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5");
          sld(false);
        });
        return;
      }

      // Web mode: existing file input
      var inp = document.createElement("input");
      inp.type = "file";
      inp.accept = "image/jpeg,image/png,image/webp";
      inp.multiple = true;
      inp.onchange = function () {
        var fls = Array.from(inp.files || []);
        var cur2 = f[key] || [];
        if (cur2.length + fls.length > max) { serr("\u6700\u591A" + max + "\u5F20"); return; }
        fls.forEach(function (file) {
          if (file.size > 5 * 1024 * 1024) { serr("\u5355\u5F20<5MB"); return; }
          sld(true);
          NK.Api.Upload.image(file).then(function (r) {
            if (r && r.code === 0 && r.data) {
              var u = r.data.url || r.data.image_url || "";
              sf(function (p) {
                var n = {}; for (var x in p) n[x] = p[x];
                var a = (n[key] || []).slice();
                if (u && a.indexOf(u) < 0) a.push(u);
                n[key] = a; return n;
              });
            } else serr((r && r.message) || "\u4E0A\u4F20\u5931\u8D25");
          }).catch(function () { serr("\u4E0A\u4F20\u5931\u8D25"); })
          .finally(function () { sld(false); });
        });
      };
      inp.click();
    }function rmImg(key, idx) {
    sf(function (p) {
      var n = {}; for (var x in p) n[x] = p[x];
      var a = (n[key] || []).slice();
      a.splice(idx, 1); n[key] = a; return n;
    });
  }

  function imgSec(key, title, hint, max) {
    var imgs = Array.isArray(f[key]) ? f[key] : [];
    var items = [];
    imgs.forEach(function (url, idx) {
      items.push(
        h("div", { key: "i" + idx, className: "upload-thumb", style: { position: "relative" } },
          h("img", { src: url, style: { width: 80, height: 80, objectFit: "cover", borderRadius: 6 } }),
          h("div", {
            style: { position: "absolute", top: -6, right: -6, width: 20, height: 20, borderRadius: "50%", background: "#ff4d4f", color: "#fff", fontSize: 12, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" },
            onClick: function (e) { e.stopPropagation(); rmImg(key, idx); }
          }, String.fromCharCode(215))
        )
      );
    });
    if (imgs.length < max) {
      items.push(
        h("div", {
          key: "add", className: "upload-add-btn",
          style: { minWidth: 80, minHeight: 80, display: "flex", alignItems: "center", justifyContent: "center", border: "1px dashed #d9d9d9", borderRadius: 6, cursor: "pointer", color: "#999", fontSize: 28 },
          onClick: function () { upImg(key, max); }
        }, "+")
      );
    }
    return h("div", null,
      h("div", { className: "sect-title" },
        h("span", null, title),
        hint ? h("span", { style: { fontSize: 11, color: "#bbb", marginLeft: 8 } }, hint) : null
      ),
      h("div", { style: { display: "flex", flexWrap: "wrap", gap: 8, marginTop: 8 } }, items)
    );
  }

  // ===== Render =====

  if (ok) {
    return h("div", { className: "detail-page" },
      h("div", {style:{position:"fixed",bottom:4,right:4,zIndex:99999,background:"rgba(0,0,0,0.7)",color:"#fff",fontSize:10,padding:"2px 6px",borderRadius:3,fontFamily:"monospace",pointerEvents:"none"}}, "PublishPage-REAL-2026-05-29-001"),
      h("div", { style: { textAlign: "center", padding: "60px 24px" } },
        h("div", { style: { fontSize: 56, marginBottom: 12 } }, "✓"),
        h("div", { style: { fontSize: 18, fontWeight: 700, marginBottom: 8 } }, "\u53D1\u5E03\u6210\u529F"),
        h("div", { style: { fontSize: 14, color: "#666", marginBottom: 20 } }, "\u5546\u54C1\u5DF2\u63D0\u4EA4\u5BA1\u6838"),
        h("button", {
          style: { padding: "10px 28px", borderRadius: 20, border: "none", background: "#1677ff", color: "#fff", fontSize: 15, cursor: "pointer" },
          onClick: function () { NK.Store.navigate("home"); }
        }, "\u6769\u65BF\u6D16\u68E3\u682D\u3009")
      )
    );
  }

  if (!NK.Store.isLoggedIn()) {
    return h("div", { className: "detail-page" },
      h("div", { className: "empty-state", style: { paddingTop: 80 } },
        h("div", { className: "eicon" }, "\u9983\u6540"),
        h("div", null, "\u8BF7\u5148\u767B\u5F55\u540E\u53D1\u5E03\u5546\u54C1")
      )
    );
  }

  if (eld) {
    return h("div", { className: "detail-page" },
      h("div", { className: "empty-state", style: { paddingTop: 80 } },
        h("div", null, "\u52A0\u8F7D\u5546\u54C1\u6570\u636E..")
      )
    );
  }

  if (pubType === null) {
    return h("div", { className: "detail-page", style: { background: "#f4f5f9", position: "relative", minHeight: "100vh" } },
      h("div", { style: { padding: "32px 16px 96px 16px" } },
        // Title
        h("div", { style: { display: "flex", alignItems: "center", padding: "8px 0 16px 0" } },
          h("div", { onClick: function() { NK.Store.back("home"); }, style: { cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", width: 32, height: 32, flexShrink: 0 } },
            h("svg", { width: 24, height: 24, viewBox: "0 0 24 24", fill: "none", stroke: "#333", strokeWidth: 1.875, strokeLinecap: "round", strokeLinejoin: "round" },
              h("path", { d: "m15 18-6-6 6-6" })
            )
          ),
          h("div", { style: { flex: 1, textAlign: "center", fontSize: 17, fontWeight: 600, color: "#1a1a2e", marginRight: 32 } }, "\u9009\u62e9\u53d1\u5e03\u7c7b\u578b")
        ),
        // Card 1: 成品号 (active/selected)
        h("div", {
          onClick: function () { spubType("成品号"); },
          style: {
            background: "#fff", borderRadius: 16, padding: "20px 16px", marginBottom: 16,
            border: "2px solid #1677ff", boxShadow: "0 2px 12px rgba(22,119,255,0.12)",
            display: "flex", alignItems: "center", justifyContent: "space-between",
            position: "relative", overflow: "hidden", cursor: "pointer", minHeight: 110, flexShrink: 0
          }
        },
          h("div", { style: { flex: 1, zIndex: 1 } },
            h("div", { style: { fontSize: 20, fontWeight: 700, color: "#1a1a2e", marginBottom: 6 } }, "成品号"),
            h("div", { style: { fontSize: 13, color: "#6b7280" } }, "已养成账号")
          ),
          h("div", {
            style: {
              position: "absolute", right: -4, bottom: -4, height: "115%", width: "35%",
              display: "flex", alignItems: "flex-end", justifyContent: "flex-end",
              pointerEvents: "none", zIndex: 0
            }
          },
            h("img", {
              src: "/assets/publish/finished-account.webp",
              alt: "",
              loading: "eager",
              decoding: "async",
              fetchpriority: "high",
              style: { height: "108%", objectFit: "contain", objectPosition: "right bottom", opacity: 0.90 }
            })
          )
        ),
        // Card 2: 初始号
        h("div", {
          onClick: function () { alert("初始号暂未开放"); },
          style: {
            background: "#fff", borderRadius: 16, padding: "20px 16px", marginBottom: 16,
            border: "2px solid #e5e7eb", boxShadow: "0 2px 12px rgba(0,0,0,0.04)",
            display: "flex", alignItems: "center", justifyContent: "space-between",
            position: "relative", overflow: "hidden", cursor: "not-allowed", opacity: 0.7, minHeight: 110, flexShrink: 0
          }
        },
          h("div", { style: { flex: 1, zIndex: 1 } },
            h("div", { style: { fontSize: 20, fontWeight: 700, color: "#1a1a2e", marginBottom: 6 } }, "初始号"),
            h("div", { style: { fontSize: 13, color: "#6b7280", marginBottom: 8 } }, "适合低养成、基础资源、可重新培养的账号"),
            h("div", { style: { fontSize: 12, fontWeight: 600, color: "#ef4444", marginTop: 4 } }, "暂未开放"),
          ),
          h("div", {
            style: {
              position: "absolute", right: 0, bottom: 0, height: "108%", width: "32%",
              display: "flex", alignItems: "flex-end", justifyContent: "flex-end",
              pointerEvents: "none", zIndex: 0
            }
          },
            h("img", {
              src: "/assets/publish/initial-account.webp",
              alt: "",
              loading: "eager",
              decoding: "async",
              fetchpriority: "high",
              style: { height: "100%", objectFit: "contain", objectPosition: "right bottom", opacity: 0.90 }
            })
          )
        )
      )
    );
  }

  try {
  return h("div", { className: "detail-page", style: { paddingBottom: 80 } },
      h("div", { className: "pub3-header" },
        h("div", {
          className: "bbtn",
          onClick: function () {
            if (edit) { NK.Store.navigate("myProductDetail", { id: eid }); }
            else { spubType(null); }
          }
        }, NK.BackIcon ? NK.BackIcon() : React.createElement("span", null, "←")),
        h("div", { className: "btitle" }, edit ? "\u7F16\u8F91\u5546\u54C1" : "\u53D1\u5E03\u5546\u54C1")
      ),

      // Basic info
      h("div", { className: "pub3-card" },
        h("div", { className: "pub3-ctitle" }, "\u57FA\u7840\u4FE1\u606F"),
        h("div", null,
          h("div", { className: "pub3-inrow readonly" },
            h("div", { className: "pub3-ilabel" }, "\u8D26\u53F7\u7C7B\u578B"),
            h("input", { value: pubType || "成品号", readOnly: true, style: { textAlign: "right", color: "#333" } })
          ),
          h("div", { className: "pub3-inrow" },
            h("div", { className: "pub3-ilabel" }, h("span", { className: "req" }, "*"), "\u8D26\u53F7"),
            h("input", {
              placeholder: "\u8BF7\u8F93\u5165\u6E38\u620F\u8D26\u53F7",
              value: f.auid || "",
              onInput: function (ev) { var v = ev.target.value.replace(/[^a-zA-Z0-9]/g, ""); sF("auid", v); }
            })
          ),
          h("div", { className: "pub3-inrow", onClick: function () { ssrvOpen(!srvOpen); } },
        h("div", { className: "pub3-ilabel" }, h("span", { className: "req" }, "*"), "\u670D\u52A1\u5668"),
        h("div", { style: { flex: 1, textAlign: "right", color: f.server ? "#333" : "#bbb", fontSize: 14 } }, f.server || "\u8BF7\u9009\u62E9\u670D\u52A1\u5668"),
        h("span", { style: { color: "#999", fontSize: 16, flexShrink: 0 } }, "›")
          ),
          srvOpen ? h("div", { style: { marginTop: 4, background: "#f9f9f9", borderRadius: 8, padding: 8, maxHeight: 200, overflow: "auto" } },
            SERVERS.map(function (s) {
              return h("div", {
                key: s,
                style: { padding: "8px 12px", borderRadius: 6, cursor: "pointer", background: f.server === s ? "#e6f4ff" : "transparent" },
                onClick: function () { sF("server", s); ssrvOpen(false); }
              }, s);
            })
          ) : null
        )
      ),

      // Config card
      h("div", { className: "pub3-card" },
        h("div", null,
          h("div", { className: "pub3-inrow", onClick: function () { span("leg"); } },
            h("div", { className: "pub3-ilabel" }, "\u4F20\u8BF4\u88C5\u5907"),
            h("div", { style: { flex: 1, textAlign: "right", color: "#333", fontSize: 14 } }, legSum()),
        h("span", { style: { color: "#999", fontSize: 16, flexShrink: 0 } }, "›")
          ),
          h("div", { className: "pub3-inrow", onClick: function () { span("mt"); } },
            h("div", { className: "pub3-ilabel" }, "\u4F20\u8BF4\u5750\u9A91"),
            h("div", { style: { flex: 1, textAlign: "right", color: "#333", fontSize: 14 } }, mtSum()),
        h("span", { style: { color: "#999", fontSize: 16, flexShrink: 0 } }, "›")
          ),
          h("div", { className: "pub3-inrow", onClick: function () { span("unl"); } },
            h("div", { className: "pub3-ilabel" }, "\u88C5\u5907\u89E3\u9501"),
            h("div", { style: { flex: 1, textAlign: "right", color: "#333", fontSize: 14 } }, unSum()),
        h("span", { style: { color: "#999", fontSize: 16, flexShrink: 0 } }, "›")
          )
        )
      ),

      // Description card
      h("div", { className: "pub3-card" },
        h("div", null,
          h("div", { className: "pub3-row" },
            h("div", { className: "pub3-label" }, "\u5546\u54C1\u6807\u9898 *"),
            h("textarea", {
              className: "pub3-textarea",
              placeholder: "\u4F8B\u5982\uFF1A\u9AD8\u914D\u6218\u58EB\u53F7",
              value: f.title || "",
              maxLength: 55,
              onChange: function (ev) { sF("title", ev.target.value); },
              rows: 2
            }),
            h("div", { className: "pub3-char-count" }, (f.title || "").length + "/55")
          ),
          h("div", { style: { marginTop: 14 } },
            h("div", { className: "pub3-label" }, "\u5546\u54C1\u8BE6\u7EC6\u63CF\u8FF0"),
            h("textarea", {
              className: "pub3-textarea",
              placeholder: "\u8BF7\u63CF\u8FF0\u8D26\u53F7\u88C5\u5907\u3001\u8D44\u6E90\u3001\u5750\u9A91\u7B49...",
              value: f.desc || "",
              maxLength: 200,
              onChange: function (ev) { sF("desc", ev.target.value); },
              rows: 4
            }),
            h("div", { className: "pub3-char-count" }, (f.desc || "").length + "/200")
          )
        )
      ),

      // Images card
      h("div", { className: "pub3-card" },
        h("div", null,
          imgSec("cover", "\u5546\u54C1\u5C01\u9762\u56FE *", "\u6700\u591A4\u5F20", 4),
          h("div", { style: { marginTop: 18 } },
            imgSec("detail", "\u5546\u54C1\u8BE6\u60C5\u8865\u5145\u56FE", "\u53EF\u9009", 99)
          )
        )
      ),

      // Price card
      h("div", { className: "pub3-card" },
        h("div", null,
          h("div", { className: "pub3-label" }, "\u4EF7\u683C *"),
          h("div", { className: "pub3-price-wrap" },
            h("input", {
              className: "pub3-input",
              type: "number",
              placeholder: "\u8BF7\u8F93\u5165\u4EF7\u683C",
              value: f.price || "",
              min: "0.01",
              step: "0.01",
              onChange: function (ev) { sF("price", ev.target.value); }
            }),
            h("span", { className: "pub3-price-yen" }, "\u00A5")
          ),
          (f.price && parseFloat(f.price) > 0)
            ? h("div", { style: { fontSize: 12, color: "#FF4D5A", marginTop: 8 } },
                "\u9884\u8BA1\u6536\u5165\uFF1A¥" + (parseFloat(f.price) * 0.92).toFixed(2) + "\uFF08\u5DF2\u6263\u9664 8% \u670D\u52A1\u8D39\uFF09"
              )
            : null
        )
      ),

        err ? h("div", { style: { color: "#ff4d4f", fontSize: 13, padding: "0 12px", marginBottom: 8 } }, err) : null,

      h("div", { className: "pub3-bottom-bar" },
        h("button", { className: "pub3-btn primary", onClick: submit, disabled: ld },
          ld ? "\u63D0\u4EA4\u4E2D..." : (edit ? "\u63D0\u4EA4\u5BA1\u6838" : "\u53D1\u5E03\u5546\u54C1")
        )
      ),

      // Toast notification
      toast ? h("div",{style:{position:"fixed",top:60,left:"50%",transform:"translateX(-50%)",zIndex:9999,background:"rgba(0,0,0,0.78)",color:"#fff",padding:"10px 24px",borderRadius:20,fontSize:14,fontWeight:500,maxWidth:"90%",textAlign:"center",whiteSpace:"nowrap",boxShadow:"0 4px 16px rgba(0,0,0,0.2)",animation:"dt-fade-in 200ms ease-out"}},toast) : null,
      renderPan()
    );
  } catch (e) {
    console.error("PublishPage:", e.message, e.stack);
    return h("div", { className: "detail-page" },
      h("div", { className: "pub3-header" },
        h("div", { className: "bbtn", onClick: function () { NK.Store.back("home"); } }, NK.BackIcon ? NK.BackIcon() : React.createElement("span", null, "←")),
        h("div", { className: "btitle" }, "\u53D1\u5E03\u5546\u54C1")
      ),
      h("div", { style: { padding: 20, color: "#ff4d4f", background: "#fff2f0", margin: 12, borderRadius: 8 } },
        h("div", { style: { fontSize: 16, fontWeight: 700, marginBottom: 8 } }, "\u53D1\u5E03\u9875\u6E32\u67D3\u5931\u8D25"),
        h("div", { style: { fontSize: 13 } }, "\u9519\u8BEF\u4FE1\u606F: " + (e.message || "")),
        h("pre", { style: { fontSize: 11, marginTop: 8, whiteSpace: "pre-wrap", wordBreak: "break-all", background: "#fff", padding: 8, borderRadius: 4 } }, (e.stack || "").substring(0, 500))
      )
    );
  }
}

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