// 打手入驻申请页
console.log("[DaShouJoin] script loaded v=20260624_dashou_publish_pattern");
const { useState, useRef, useEffect } = React;

function DaShouJoinPage() {
  var h = React.createElement;

  // Form state
  var _server = useState(""); var server = _server[0], setServer = _server[1];
  var _accountId = useState(""); var accountId = _accountId[0], setAccountId = _accountId[1];
  var _gender = useState(""); var gender = _gender[0], setGender = _gender[1];
  var _phone = useState(""); var phone = _phone[0], setPhone = _phone[1];
  var _wechat = useState(""); var wechat = _wechat[0], setWechat = _wechat[1];
  var _detail = useState(""); var detail = _detail[0], setDetail = _detail[1];
  var _images = useState([]); var images = _images[0], setImages = _images[1];
  var _agreed = useState(false); var agreed = _agreed[0], setAgreed = _agreed[1];
  var _realNameVerified = useState(false); var realNameVerified = _realNameVerified[0], setRealNameVerified = _realNameVerified[1];
  var _realNameMasked = useState(""); var realNameMasked = _realNameMasked[0], setRealNameMasked = _realNameMasked[1];
  var _identity = useState({ front: null, back: null, frontUploaded: false, backUploaded: false }); var identity = _identity[0], setIdentity = _identity[1];

  var _errors = useState({}); var errors = _errors[0], setErrors = _errors[1];
  var _submitting = useState(false); var submitting = _submitting[0], setSubmitting = _submitting[1];
  var _showSuccess = useState(false); var showSuccess = _showSuccess[0], setShowSuccess = _showSuccess[1];
  var _toast = useState(""); var toast = _toast[0], setToast = _toast[1];

  // fileRef removed - using dynamic input like PublishPage  // Config from backend
  var _noticeTitle = useState("\u5165\u9a7b\u987b\u77e5"); var noticeTitle = _noticeTitle[0], setNoticeTitle = _noticeTitle[1];
  var _conditionText = useState(""); var conditionText = _conditionText[0], setConditionText = _conditionText[1];
  var _processText = useState(""); var processText = _processText[0], setProcessText = _processText[1];
  var _assessmentText = useState(""); var assessmentText = _assessmentText[0], setAssessmentText = _assessmentText[1];
  var formRef = useRef(null);

  // Load dashou config from backend
  useEffect(function() {
    fetch("/api/dashou/config")
      .then(function(r) { return r.json(); })
      .then(function(json) {
        if (json.code === 0 && json.data) {
          var d = json.data;
          if (d.noticeTitle) setNoticeTitle(d.noticeTitle);
          if (d.conditionText) setConditionText(d.conditionText);
          if (d.processText) setProcessText(d.processText);
          if (d.assessmentText) setAssessmentText(d.assessmentText);
        }
      })
      .catch(function(err) {
        console.error("load dashou config failed:", err);
      });
  }, []);
  // Check user dashou application status
  var _appStatus = useState(null); var appStatus = _appStatus[0], setAppStatus = _appStatus[1];
  var _appStatusLoading = useState(true); var appStatusLoading = _appStatusLoading[0], setAppStatusLoading = _appStatusLoading[1];
  useEffect(function() {
    var isLogin = NK.Store.isLoggedIn();
    if (!isLogin) { setAppStatusLoading(false); return; }
    NK.Api.Dashou.status().then(function(res) {
      if (res.code === 0 && res.data) {
        setRealNameVerified(res.data.realNameVerified === true);
        setRealNameMasked(res.data.realNameMasked || "");
        if (res.data.identityDraft) {
          setIdentity({ front: null, back: null,
            frontUploaded: res.data.identityDraft.frontUploaded === true,
            backUploaded: res.data.identityDraft.backUploaded === true });
        }
        if (res.data.needsRealName === true || res.data.realNameVerified !== true) {
          setAppStatus('realname_required');
          setAppStatusLoading(false);
          return;
        }
        setAppStatus(res.data.state || (res.data.applicationStatus === 0 ? 'pending' : res.data.applicationStatus === 1 ? 'approved' : res.data.applicationStatus === 2 ? 'rejected' : 'none'));
      }
      setAppStatusLoading(false);
    }).catch(function() {
      setAppStatusLoading(false);
    });
  }, []);

  var SERVERS =['绽放之花','无尽之海','遗忘之境','生命之树','狂野之原','轻云之月','飘渺之峰','暗涌之泉','应许之地','参天之树','拉普达','铭心之界'];

  // Toast helper
  function showToast(msg) {
    setToast(msg);
    setTimeout(function() { setToast(""); }, 2500);
  }

        // Pick images - EXACT PublishPage pattern: App=bridge, Web=dynamic input
  function pickImages(e) {
    if (e) { e.preventDefault(); e.stopPropagation(); }

    var max = 6;
    var remain = max - images.length;

    console.log("[DaShouJoin] pickImages called", {
      isApp: !!(window.NK && window.NK.isAppClient && window.NK.isAppClient()),
      hasBridge: !!(window.NK && window.NK.NativeImageBridge && window.NK.NativeImageBridge.chooseImage),
      remain: remain
    });

    if (remain <= 0) { showToast("最多上传6张截图"); return; }

    // APP MODE: use NativeImageBridge (exact PublishPage pattern)
    if (window.NK && window.NK.isAppClient && window.NK.isAppClient()) {
      console.log("[DaShouJoin] use native bridge");

      var bridge = window.NK && window.NK.NativeImageBridge;
      if (!bridge || !window.uni || typeof window.uni.postMessage !== "function") {
        showToast("请更新 App 后重试");
        return;
      }

      bridge.chooseImage({ maxCount: remain }).then(function(urls) {
        console.log("[DaShouJoin] native bridge urls", urls);
        if (urls && urls.length > 0) {
          var newImages = urls.map(function(u) { return { url: u }; });
          setImages(images.concat(newImages));
        }
      }).catch(function(err) {
        console.warn("[DaShouJoin] native choose image failed", err);
        showToast("选择图片失败，请重试");
      });

      return;
    }

    // WEB MODE: dynamic input creation (exact PublishPage pattern)
    console.log("[DaShouJoin] use web file input");
    var inp = document.createElement("input");
    inp.type = "file";
    inp.accept = "image/*";
    inp.multiple = true;
    inp.onchange = function(ev) {
      var files = ev.target.files;
      if (!files || files.length === 0) return;
      var newImages = [];
      for (var i = 0; i < files.length; i++) {
        if (images.length + newImages.length >= max) { showToast("最多上传6张截图"); break; }
        var file = files[i];
        if (!file.type.match(/image\//)) continue;
        var url = URL.createObjectURL(file);
        newImages.push({ file: file, url: url });
      }
      setImages(images.concat(newImages));
    };
    inp.click();
  }

  function removeImage(idx) {
    var next = images.slice();
    var removed = next[idx];
    if (removed && removed.url && removed.url.indexOf("blob:") === 0) {
      URL.revokeObjectURL(removed.url);
    }
    next.splice(idx, 1);
    setImages(next);
  }

  function pickIdentity(side) {
    if (!realNameVerified) { showToast("请先完成实名认证"); return; }
    var input = document.createElement("input");
    input.type = "file";
    input.accept = ".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp";
    input.onchange = async function(event) {
      var file = event.target.files && event.target.files[0];
      if (!file) return;
      var formData = new FormData();
      formData.append("image", file);
      try {
        var response = await fetch("/api/dashou/identity-image/" + side, {
          method: "POST",
          headers: { Authorization: "Bearer " + NK.Api.getToken() },
          body: formData,
        });
        var json = await response.json();
        if (!json || json.code !== 0) { showToast(json && json.message || "证件上传失败"); return; }
        var preview = URL.createObjectURL(file);
        var next = Object.assign({}, identity);
        if (next[side] && next[side].indexOf("blob:") === 0) URL.revokeObjectURL(next[side]);
        next[side] = preview;
        next[side + "Uploaded"] = true;
        setIdentity(next);
        showToast("证件图片已安全上传");
      } catch (_error) {
        showToast("证件上传失败，请稍后重试");
      }
    };
    input.click();
  }

  // Validate
  function validate() {
    var errs = {};
    if (!server.trim()) errs.server = "请选择服务器";
    if (!accountId.trim()) errs.accountId = "请填写账号ID";
    if (!gender) errs.gender = "请选择性别";
    if (!phone.trim()) errs.phone = "请填写联系方式";
    if (!wechat.trim()) errs.wechat = "请填写微信账号";
    if (!detail.trim()) errs.detail = "请填写详细介绍";
    if (images.length === 0) errs.images = "请至少上传1张账号截图";
    if (!identity.frontUploaded || !identity.backUploaded) errs.identity = "请完整上传身份证人像面和国徽面";
    if (!agreed) errs.agreed = "请阅读并同意入驻协议";
    setErrors(errs);
    return Object.keys(errs).length === 0;
  }

  // Submit - real API call with image upload
  async function handleSubmit() {
    if (submitting) return;
    if (!validate()) {
      showToast("请完善必填信息");
      return;
    }
    setSubmitting(true);

    try {
      // Step 1: Upload images first (if any have file objects)
      var uploadedUrls = [];
      for (var i = 0; i < images.length; i++) {
        var img = images[i];
        if (img.file) {
          // Need to upload
          var formData = new FormData();
          formData.append("image", img.file);
          var token = NK.Api ? (NK.Api.getToken ? NK.Api.getToken() : "") : "";
          var uploadRes = await fetch("/api/upload/image", {
            method: "POST",
            headers: token ? { "Authorization": "Bearer " + token } : {},
            body: formData,
          });
          var uploadJson = await uploadRes.json().catch(function() { return {}; });
          if (uploadJson.code === 0 && uploadJson.data && uploadJson.data.url) {
            uploadedUrls.push(uploadJson.data.url);
          } else {
            showToast("图片上传失败: " + (uploadJson.message || "未知错误"));
            setSubmitting(false);
            return;
          }
        } else if (img.url && img.url.indexOf("blob:") !== 0) {
          // Already a server URL
          uploadedUrls.push(img.url);
        } else {
          // blob URL without file - skip (shouldn't happen in submit)
        }
      }

      if (uploadedUrls.length === 0) {
        showToast("请至少上传1张账号截图");
        setSubmitting(false);
        return;
      }

      // Step 2: Submit application
      var token = NK.Api ? (NK.Api.getToken ? NK.Api.getToken() : "") : "";
      var res = await fetch("/api/dashou/apply", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": token ? "Bearer " + token : "",
        },
        body: JSON.stringify({
          server: server.trim(),
          accountId: accountId.trim(),
          gender: gender,
          contact: phone.trim(),
          wechat: wechat.trim(),
          detail: detail.trim(),
          screenshots: uploadedUrls,
        }),
      });

      var json = await res.json().catch(function() { return { code: -1, message: "请求失败" }; });

      if (json.code === 0) {
        setSubmitting(false);
        setShowSuccess(true);
      } else {
        showToast(json.message || "提交失败，请重试");
        setSubmitting(false);
      }
    } catch (err) {
      console.error("DaShouJoin submit error:", err);
      showToast("网络错误，请稍后重试");
      setSubmitting(false);
    }
  }

  // Render field error
  function fieldError(key) {
    return errors[key] ? h("div", { style: { fontSize: 12, color: "#ff6a88", marginTop: 6 } }, errors[key]) : null;
  }

  // Inline styles (Arcade Heartbeat design tokens)
  var C = {
    bg: "#fff8f7",
    surface: "#ffffff",
    primary: "#ff6a88",
    primaryGrad: "linear-gradient(135deg, #ff6a88 0%, #ff9a8b 100%)",
    textMain: "#25181a",
    textSub: "#584144",
    border: "#f0f0f0",
    radius: 24,
    cardShadow: "0 10px 30px rgba(255,106,136,0.12)",
    btnShadow: "0 6px 16px rgba(255,106,136,0.3)",
  };


  // Early return: block form if application is pending or approved
  if (appStatusLoading) {
    return h("div", { style: { minHeight: "100vh", background: C.bg } },
      h("div", { style: { position: "sticky", top: 0, zIndex: 100, display: "flex", alignItems: "center", height: 50, padding: "0 16px", background: "rgba(255,248,247,0.85)", backdropFilter: "blur(10px)" } },
        h("div", { onClick: function() { NK.Store.back("mine"); }, style: { cursor: "pointer", width: 36, height: 36, display: "flex", alignItems: "center", justifyContent: "center" } }, NK.BackIcon ? NK.BackIcon({ size: 22, color: "#584144" }) : h("span", null, "\u2190")),
        h("div", { style: { flex: 1, textAlign: "center", fontSize: 18, fontWeight: 700, color: "#8b1e3f" } }, "\u6253\u624B\u5165\u9A7B"),
        h("div", { style: { width: 36 } })
      ),
      h("div", { style: { padding: "60px 20px", textAlign: "center" } },
        h("div", { style: { color: "#999", fontSize: 14 } }, "\u52A0\u8F7D\u4E2D...")
      )
    );
  }
  if (appStatus === 'pending') {
    return h("div", { style: { minHeight: "100vh", background: C.bg } },
      h("div", { style: { position: "sticky", top: 0, zIndex: 100, display: "flex", alignItems: "center", height: 50, padding: "0 16px", background: "rgba(255,248,247,0.85)", backdropFilter: "blur(10px)" } },
        h("div", { onClick: function() { NK.Store.back("mine"); }, style: { cursor: "pointer", width: 36, height: 36, display: "flex", alignItems: "center", justifyContent: "center" } }, NK.BackIcon ? NK.BackIcon({ size: 22, color: "#584144" }) : h("span", null, "\u2190")),
        h("div", { style: { flex: 1, textAlign: "center", fontSize: 18, fontWeight: 700, color: "#8b1e3f" } }, "\u6253\u624B\u5165\u9A7B"),
        h("div", { style: { width: 36 } })
      ),
      h("div", { style: { margin: "16px", padding: "32px 20px", background: "#fff", borderRadius: 12, textAlign: "center", boxShadow: "0 2px 8px rgba(0,0,0,0.06)" } },
        h("div", { style: { fontSize: 40, marginBottom: 12 } }, "\uD83D\uDCCB"),
        h("div", { style: { fontSize: 16, fontWeight: 600, marginBottom: 8, color: "#333" } }, "\u5165\u9A7B\u7533\u8BF7\u5DF2\u63D0\u4EA4"),
        h("div", { style: { fontSize: 13, color: "#666", lineHeight: 1.6, marginBottom: 20 } }, "\u5F53\u524D\u6B63\u5728\u5BA1\u6838\u4E2D\uFF0C\u8BF7\u8010\u5FC3\u7B49\u5F85\u5E73\u53F0\u5BA1\u6838"),
        h("button", { onClick: function() { NK.Store.back("mine"); }, style: { padding: "8px 32px", background: "#1677ff", color: "#fff", border: "none", borderRadius: 20, fontSize: 14, cursor: "pointer" } }, "\u8FD4\u56DE")
      )
    );
  }
  if (appStatus === 'realname_required') {
    return h("div", { style: { minHeight: "100vh", background: C.bg } },
      h("div", { style: { margin: "16px", padding: "32px 20px", background: "#fff", borderRadius: 12, textAlign: "center" } },
        h("div", { style: { fontSize: 18, fontWeight: 700, marginBottom: 10 } }, "请先完成实名认证"),
        h("div", { style: { fontSize: 13, color: "#666", lineHeight: 1.6, marginBottom: 20 } }, "打手入驻需要先通过阿里云普通用户实名认证。"),
        h("button", { onClick: function() {
          if (!NK.Store.openNativePage("pages/user/certification/realname")) alert("请在App个人资料管理中完成实名认证");
        }, style: { padding: "9px 28px", border: 0, borderRadius: 20, background: "#1677ff", color: "#fff" } }, "前往实名认证")
      )
    );
  }
  if (appStatus === 'approved' || appStatus === 'certified') {
    // Already certified - navigate directly, no intermediate page
    setTimeout(function() { NK.Store.navigate("boosterCenter"); }, 10);
    return null;
  }
  if (appStatus === "approved_no_profile") {
    return h("div", { style: { minHeight: "100vh", background: C.bg } },
      h("div", { style: { position: "sticky", top: 0, zIndex: 100, display: "flex", alignItems: "center", height: 50, padding: "0 16px", background: "rgba(255,248,247,0.85)", backdropFilter: "blur(10px)" } },
        h("div", { onClick: function() { NK.Store.back("mine"); }, style: { cursor: "pointer", width: 36, height: 36, display: "flex", alignItems: "center", justifyContent: "center" } }, NK.BackIcon ? NK.BackIcon({ size: 22, color: "#584144" }) : h("span", null, "\u2190")),
        h("div", { style: { flex: 1, textAlign: "center", fontSize: 18, fontWeight: 700, color: "#8b1e3f" } }, "\u6253\u624B\u5165\u9A7B"),
        h("div", { style: { width: 36 } })
      ),
      h("div", { style: { margin: "16px", padding: "32px 20px", background: "#fff", borderRadius: 12, textAlign: "center", boxShadow: "0 2px 8px rgba(0,0,0,0.06)" } },
        h("div", { style: { fontSize: 40, marginBottom: 12 } }, "\u26A0\uFE0F"),
        h("div", { style: { fontSize: 16, fontWeight: 600, marginBottom: 8, color: "#d48806" } }, "\u8BA4\u8BC1\u72B6\u6001\u5F02\u5E38"),
        h("div", { style: { fontSize: 13, color: "#666", lineHeight: 1.6, marginBottom: 20 } }, "\u60A8\u7684\u5165\u9A7B\u7533\u8BF7\u5DF2\u901A\u8FC7\uFF0C\u4F46\u6253\u624B\u8D44\u6599\u6682\u672A\u540C\u6B65\uFF0C\u8BF7\u5237\u65B0\u9875\u9762\u91CD\u8BD5\u6216\u8054\u7CFB\u5E73\u53F0\u5BA2\u670D"),
        h("button", { onClick: function() { location.reload(); }, style: { padding: "8px 32px", background: "#1677ff", color: "#fff", border: "none", borderRadius: 20, fontSize: 14, cursor: "pointer" } }, "\u5237\u65B0\u9875\u9762")
      )
    );
  }
  return h("div", {
    style: { minHeight: "100vh", background: C.bg, paddingBottom: 40 }
  },
    // === Toast ===
    toast ? h("div", {
      style: { position: "fixed", top: 60, left: "50%", transform: "translateX(-50%)", zIndex: 9999,
        background: "rgba(37,24,26,0.85)", color: "#fff", padding: "10px 24px", borderRadius: 20,
        fontSize: 14, fontWeight: 500, whiteSpace: "nowrap", boxShadow: "0 4px 16px rgba(0,0,0,0.2)" }
    }, toast) : null,

    // === Top Bar ===
    h("div", {
      style: { position: "sticky", top: 0, zIndex: 100, display: "flex", alignItems: "center",
        height: 50, padding: "0 16px", background: "rgba(255,248,247,0.85)", backdropFilter: "blur(10px)" }
    },
      h("div", {
        onClick: function() { NK.Store.back("mine"); },
        style: { cursor: "pointer", width: 36, height: 36, display: "flex", alignItems: "center", justifyContent: "center" }
      }, NK.BackIcon ? NK.BackIcon({ size: 22, color: "#584144" }) : h("span", null, "←")),
      h("div", { style: { flex: 1, textAlign: "center", fontSize: 18, fontWeight: 700, color: "#8b1e3f" } }, "打手入驻"),
      h("div", { style: { width: 36 } })
    ),
    
        // === Notice Card (dynamic from backend config) ===
    h("div", {
      style: { margin: "16px", padding: 20, background: C.surface, borderRadius: C.radius, boxShadow: C.cardShadow }
    },
      h("div", { style: { marginBottom: conditionText ? 20 : 0 } },
        h("div", { style: { fontSize: 16, color: C.primary, fontWeight: 700, marginBottom: 10 } }, noticeTitle || "入驻须知"),
        h("div", { style: { fontSize: 14, color: C.textSub, lineHeight: 1.6, whiteSpace: "pre-wrap" } },
          processText || "1. 请确保填写信息真实有效\n2. 账号截图需清晰展示角色信息与装备\n3. 审核将在 1-3 个工作日内完成\n4. 审核通过后即可开始接单"
        )
      ),
      conditionText ? h("div", null,
        h("div", { style: { fontSize: 16, color: C.primary, fontWeight: 700, marginBottom: 10 } }, "入驻条件"),
        h("div", { style: { fontSize: 14, color: C.textSub, lineHeight: 1.6, whiteSpace: "pre-wrap" } }, conditionText)
      ) : null,
      assessmentText ? h("div", { style: { marginTop: 20 } },
        h("div", { style: { fontSize: 16, color: C.primary, fontWeight: 700, marginBottom: 10 } }, "考核条件"),
        h("div", { style: { fontSize: 14, color: C.textSub, lineHeight: 1.6, whiteSpace: "pre-wrap" } }, assessmentText)
      ) : null
    ),

    // === Form Card ===
    h("div", {
      ref: formRef,
      style: { margin: "20px 16px", padding: "24px 20px", background: C.surface, borderRadius: C.radius, boxShadow: C.cardShadow }
    },
      h("div", { style: { fontSize: 20, color: C.primary, fontWeight: 700, marginBottom: 6 } }, "填写资料"),
      h("div", { style: { fontSize: 13, color: C.textSub, marginBottom: 24 } }, "以下信息将用于审核，请如实填写"),

      // Server select
      h("div", { style: { marginBottom: 20 } },
        h("div", { style: { fontSize: 14, fontWeight: 600, color: C.textMain, marginBottom: 10 } }, "服务器", h("span", { style: { color: C.primary } }, " *")),
        h("select", {
          value: server,
          onChange: function(e) { setServer(e.target.value); },
          style: { width: "100%", padding: "12px 16px", border: "1px solid " + (errors.server ? C.primary : "#f0f0f0"),
            borderRadius: 8, background: "#fffcfb", fontSize: 14, outline: "none", boxSizing: "border-box" }
        },
          h("option", { value: "" }, "请选择服务器"),
          SERVERS.map(function(s) { return h("option", { key: s, value: s }, s); })
        ),
        fieldError("server")
      ),

      // Account ID
      formField("账号ID *", accountId, "请输入游戏账号ID", function(e) { setAccountId(e.target.value); }, errors.accountId, "text"),

      h("div", { style: { marginBottom: 20 } },
        h("div", { style: { fontSize: 14, fontWeight: 600, color: C.textMain, marginBottom: 10 } }, "实名状态"),
        h("div", { style: { padding: "12px 16px", border: "1px solid #e2e8f0", borderRadius: 8, background: "#f8fafc", color: "#334155" } }, "已实名 · " + (realNameMasked || "信息已保护")),
        h("div", { style: { marginTop: 6, fontSize: 12, color: "#64748b" } }, "实名信息由系统核验，不需要在入驻表单中重复填写")
      ),

      // Gender
      h("div", { style: { marginBottom: 20 } },
        h("div", { style: { fontSize: 14, fontWeight: 600, color: C.textMain, marginBottom: 10 } }, "性别", h("span", { style: { color: C.primary } }, " *")),
        h("div", { style: { display: "flex", gap: 12 } },
          genderOption("男", gender === "男", function() { setGender("男"); }),
          genderOption("女", gender === "女", function() { setGender("女"); })
        ),
        fieldError("gender")
      ),

      // Phone
      formField("联系方式 *", phone, "请输入手机号或其他联系方式", function(e) { setPhone(e.target.value); }, errors.phone, "tel"),

      // Wechat
      formField("微信账号 *", wechat, "请输入微信号", function(e) { setWechat(e.target.value); }, errors.wechat, "text"),

      // Detail
      h("div", { style: { marginBottom: 20 } },
        h("div", { style: { fontSize: 14, fontWeight: 600, color: C.textMain, marginBottom: 10 } }, "详细介绍", h("span", { style: { color: C.primary } }, " *")),
        h("textarea", {
          value: detail,
          onChange: function(e) { setDetail(e.target.value); },
          placeholder: "请介绍您的游戏经验、擅长内容、可接单时间等",
          style: { width: "100%", height: 100, padding: "12px 16px", border: "1px solid " + (errors.detail ? C.primary : "#f0f0f0"),
            borderRadius: 8, background: "#fffcfb", fontSize: 14, outline: "none", resize: "none", boxSizing: "border-box",
            fontFamily: "inherit" }
        }),
        fieldError("detail")
      ),

      // Screenshot upload
      h("div", { style: { marginBottom: 20 } },
        h("div", { style: { fontSize: 14, fontWeight: 600, color: C.textMain, marginBottom: 10 } }, "账号截图", h("span", { style: { color: C.primary } }, " *")),
        h("div", { style: { fontSize: 12, color: C.textSub, marginBottom: 12 } }, "请上传游戏内角色截图，最多6张"),
        h("div", { style: { display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 10 } },
          images.map(function(img, idx) {
            return h("div", {
              key: idx,
              style: { aspectRatio: "1/1", borderRadius: 8, overflow: "hidden", position: "relative" }
            },
              h("img", { src: img.url, style: { width: "100%", height: "100%", objectFit: "cover" } }),
              h("div", {
                onClick: function() { removeImage(idx); },
                style: { position: "absolute", top: 4, right: 4, width: 20, height: 20,
                  background: "rgba(0,0,0,0.5)", color: "#fff", borderRadius: "50%",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 12, cursor: "pointer" }
              }, "×")
            );
          }),
          images.length < 6 ? h("div", {
            onClick: function(e) { e.preventDefault(); e.stopPropagation(); pickImages(e); },
            style: { aspectRatio: "1/1", borderRadius: 8, border: "1.5px dashed #ffd8df",
              background: "#fffcfb", display: "flex", alignItems: "center", justifyContent: "center",
              cursor: "pointer" }
          }, h("span", { style: { fontSize: 32, color: C.primary, opacity: 0.6 } }, "+")) : null
        ),
        fieldError("images")
      ),

      h("div", { style: { marginBottom: 20 } },
        h("div", { style: { fontSize: 14, fontWeight: 600, color: C.textMain, marginBottom: 8 } }, "身份证材料 *"),
        h("div", { style: { fontSize: 12, color: "#64748b", marginBottom: 10 } }, "仅用于平台人工审核，不会公开展示"),
        h("div", { style: { display: "grid", gridTemplateColumns: "repeat(2,minmax(0,1fr))", gap: 12 } },
          ["front", "back"].map(function(side) {
            var label = side === "front" ? "身份证人像面" : "身份证国徽面";
            return h("button", { key: side, type: "button", onClick: function() { pickIdentity(side); }, style: { height: 132, padding: 0, overflow: "hidden", position: "relative", border: "1px dashed #94a3b8", borderRadius: 10, background: "#f8fafc", cursor: "pointer" } },
              identity[side] ? h("img", { src: identity[side], style: { position: "absolute", top: 0, left: 0, width: "100%", height: "100%", objectFit: "cover", opacity: .65 } }) : null,
              h("span", { style: { position: "relative", display: "block", color: "#334155", fontSize: 13 } }, label),
              identity[side + "Uploaded"] ? h("span", { style: { position: "relative", display: "block", marginTop: 6, color: "#15803d", fontSize: 11 } }, "已安全上传") : null
            );
          })
        ),
        fieldError("identity")
      )
    ),

    // === Bottom Section ===
    h("div", { style: { padding: "0 20px", marginTop: 16 } },
      h("div", {
        style: { display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: C.textSub, marginBottom: 20 }
      },
        h("input", {
          type: "checkbox",
          checked: agreed,
          onChange: function(e) { setAgreed(e.target.checked); },
          style: { accentColor: C.primary }
        }),
        "我已阅读并同意",
        h("span", { style: { color: C.primary, cursor: "pointer" } }, "《打手入驻协议》")
      ),
      fieldError("agreed"),

      h("div", {
        onClick: handleSubmit,
        style: {
          width: "100%", height: 50, borderRadius: 25, border: "none",
          background: submitting ? "#e0e0e0" : C.primaryGrad,
          color: "#fff", fontSize: 16, fontWeight: 700,
          display: "flex", alignItems: "center", justifyContent: "center",
          boxShadow: submitting ? "none" : C.btnShadow,
          cursor: submitting ? "not-allowed" : "pointer",
          opacity: submitting ? 0.8 : 1,
        }
      },
        submitting ? h("span", { style: { display: "flex", alignItems: "center", gap: 8 } },
          h("span", { style: { width: 16, height: 16, border: "2px solid rgba(255,255,255,0.3)",
            borderTopColor: "#fff", borderRadius: "50%", display: "inline-block",
            animation: "spin 0.8s linear infinite" } }),
          "提交中..."
        ) : "提交申请"
      )
    ),

    // === Success Modal ===
    showSuccess ? h("div", {
      style: { position: "fixed", top: 0, left: 0, right: 0, bottom: 0,
        background: "rgba(0,0,0,0.6)", zIndex: 1000,
        display: "flex", alignItems: "center", justifyContent: "center", padding: 30 }
    },
      h("div", {
        style: { background: "#fff", borderRadius: 16, padding: "30px 20px", textAlign: "center",
          width: "100%", maxWidth: 300, animation: "pop 0.3s ease-out" }
      },
        h("div", {
          style: { width: 60, height: 60, borderRadius: "50%",
            background: C.primaryGrad, color: "#fff", fontSize: 30,
            display: "flex", alignItems: "center", justifyContent: "center",
            margin: "0 auto 20px" }
        }, "✓"),
        h("h3", { style: { fontSize: 18, marginBottom: 12, color: C.textMain } }, "申请已提交"),
        h("p", { style: { fontSize: 14, color: C.textSub, lineHeight: 1.5, marginBottom: 24 } },
          "您的入驻申请已成功提交，我们将在 1-3 个工作日内完成审核，请耐心等待。"),
        h("div", {
          onClick: function() { setShowSuccess(false); NK.Store.back("mine"); },
          style: { width: 140, height: 40, background: "#f5f5f5", borderRadius: 20, fontSize: 14,
            color: "#333", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center",
            margin: "0 auto" }
        }, "我知道了")
      )
    ) : null
  );

  // Helper: form field
  function formField(label, value, placeholder, onChange, error, type) {
    return h("div", { style: { marginBottom: 20 } },
      h("div", { style: { fontSize: 14, fontWeight: 600, color: C.textMain, marginBottom: 10 } }, label),
      h("input", {
        type: type || "text",
        value: value,
        onChange: onChange,
        placeholder: placeholder,
        style: { width: "100%", padding: "12px 16px", border: "1px solid " + (error ? C.primary : "#f0f0f0"),
          borderRadius: 8, background: "#fffcfb", fontSize: 14, outline: "none", boxSizing: "border-box" }
      }),
      fieldError(label.split(" ")[0].replace("*","").toLowerCase())
    );
  }

  // Helper: gender option
  function genderOption(label, active, onClick) {
    return h("div", {
      onClick: onClick,
      style: {
        flex: 1, height: 44, display: "flex", alignItems: "center", justifyContent: "center",
        border: active ? "none" : "1px solid #f0f0f0", borderRadius: 22,
        fontSize: 14, color: active ? "#fff" : C.textSub,
        background: active ? C.primaryGrad : "#fff",
        fontWeight: active ? 700 : 400,
        cursor: "pointer", boxShadow: active ? "0 4px 8px rgba(255,106,136,0.2)" : "none",
      }
    }, label);
  }
}

window.NK = window.NK || {};
NK.DaShouJoinPage = DaShouJoinPage;


