// 支付页面 - refined UI
const { useState, useEffect } = React;

function PaymentPage() {
  var _order = useState(null); var order = _order[0], setOrder = _order[1];
  var _loading = useState(true); var loading = _loading[0], setLoading = _loading[1];
  var _paying = useState(false); var paying = _paying[0], setPaying = _paying[1];
  var _cancelling = useState(false); var cancelling = _cancelling[0], setCancelling = _cancelling[1];
  var _method = useState("wechat"); var method = _method[0], setMethod = _method[1];
  var h = React.createElement;
function svgArrL(c){return h('svg',{width:20,height:20,viewBox:'0 0 24 24',fill:'none',stroke:c||'#334155',strokeWidth:1.875,strokeLinecap:'round',strokeLinejoin:'round'},h('path',{d:'M15 18l-6-6 6-6'}));}


  var pp = NK.Store.get("pageParams") || {};
  var orderId = pp.orderId;

  useEffect(function() {
    console.log('[pay-debug] PaymentPage orderId:', orderId, 'loggedIn:', NK.Store.isLoggedIn());
    if (!orderId) { console.log('[pay-debug] no orderId, stop loading'); setLoading(false); return; }
    if (!NK.Store.isLoggedIn()) { console.log('[pay-debug] not logged in, stop loading'); setLoading(false); return; }
    setLoading(true);
    NK.Api.Orders.paymentDetail(orderId).then(function(r) {
      console.log('[pay-debug] paymentDetail response:', JSON.stringify(r));
      if (r && r.code === 0) setOrder(r.data);
      else { console.log('[pay-debug] paymentDetail failed:', r); setOrder(null); }
    }).catch(function(e) { console.error("Payment load err:", e); setOrder(null); })
    .finally(function() { setLoading(false); });
  }, [orderId]);

  var fmt = function(n) { var v = Number(n); return "¥" + (Number.isFinite(v) ? v.toFixed(2) : "0.00"); };

  var handlePay = async function() {
    if (!order) return;
    setPaying(true);
    try {
      var r = await NK.Api.Orders.mockPay(order.orderId, { payMethod: "mock" });
      if (r && r.code === 0) {
        alert("支付成功");
        NK.Store.navigate("tradeRoom", { orderId: order.orderId, source: "payment" });
      } else {
        alert((r && r.message) || "支付失败");
      }
    } catch(e) { alert("网络错误"); }
    finally { setPaying(false); }
  };

  var handleCancel = async function() {
    if (!order) return;
    if (!confirm("确定要取消这笔订单吗？取消后商品将重新上架。")) return;
    setCancelling(true);
    try {
      var r = await NK.Api.Orders.cancel(order.orderId);
      if (r && r.code === 0) {
        alert(r.message || "订单已取消");
        NK.Store.back();
      } else {
        alert((r && r.message) || "取消失败");
      }
    } catch(e) { alert("网络错误"); }
    finally { setCancelling(false); }
  };

  var methods = [
    { key: "wechat", name: "微信支付", icon: "💚" },
    { key: "alipay", name: "支付宝", icon: "💙" },
    { key: "balance", name: "平台余额", icon: "💰" }
  ];

  var card = { background:"#fff", borderRadius:14, margin:"0 12px 10px", padding:14, boxShadow:"0 1px 4px rgba(0,0,0,0.04)" };

  if (loading) {
    return h("div",{className:"detail-page"},
      h("div",{className:"back-header"},
        h("div",{className:"bbtn",onClick:function(){NK.Store.back();}},svgArrL()),
        h("div",{className:"btitle"},"确认支付")
      ),
      h("div",{className:"page-loading"},
        h("div",{className:"spinner"}),
        h("div",{style:{color:"#999",fontSize:14}},"加载中...")
      )
    );
  }

  if (!order) {
    return h("div",{className:"detail-page"},
      h("div",{className:"back-header"},
        h("div",{className:"bbtn",onClick:function(){NK.Store.back();}},svgArrL()),
        h("div",{className:"btitle"},"确认支付")
      ),
      h("div",{className:"empty-state",style:{paddingTop:60}},
        h("div",{style:{fontSize:40,color:"#ddd",marginBottom:10}},"✖"),
        h("div",{style:{fontSize:15,color:"#999"}},"订单不存在或已失效")
      )
    );
  }

  var hasImg = order.coverImage && order.coverImage.length > 0;
  var serverText = order.server || "";
  var typeText = order.accountType || "";

  return h("div",{style:{background:"#F6F7FA",minHeight:"100vh",paddingBottom:80}},

    // Header
    h("div",{className:"back-header"},
      h("div",{className:"bbtn",onClick:function(){NK.Store.back();}},svgArrL()),
      h("div",{className:"btitle"},"确认支付")
    ),

    // 1. Product card
    h("div",{style:card},
      h("div",{style:{display:"flex",gap:12}},
        // Left: image
        hasImg
          ? h("img",{src:order.coverImage,style:{width:72,height:72,borderRadius:10,objectFit:"cover",flexShrink:0},onError:function(e){e.target.style.display="none";}})
          : h("div",{style:{width:72,height:72,borderRadius:10,flexShrink:0,background:"#f5f5f5",display:"flex",alignItems:"center",justifyContent:"center"}},h("svg",{width:28,height:28,viewBox:"0 0 24 24",fill:"none",stroke:"#d0d0d0",strokeWidth:1.5},h("rect",{x:3,y:3,width:18,height:18,rx:3}),h("circle",{cx:8.5,cy:8.5,r:1.5}),h("path",{d:"M21 15l-5-5L5 21"}))),
        // Right: info
        h("div",{style:{flex:1,display:"flex",flexDirection:"column",justifyContent:"space-between",minWidth:0}},
          h("div",{style:{fontSize:16,fontWeight:700,color:"#1a1a1a",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},order.productTitle || "商品"),
          (serverText || typeText) && h("div",{style:{fontSize:12,color:"#999",marginTop:2}},
            serverText + (typeText ? " | " + typeText : "")
          ),
          h("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginTop:4}},
            h("span",{style:{fontSize:20,fontWeight:800,color:"#FF3B4F"}},fmt(order.price))
          )
        )
      )
    ),

    // 2. Order info card
    h("div",{style:card},
      h("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"4px 0"}},
        h("span",{style:{fontSize:13,color:"#999"}},"订单编号"),
        h("span",{style:{fontSize:13,color:"#333"}},order.orderNo || "")
      ),
      h("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"6px 0"}},
        h("span",{style:{fontSize:13,color:"#999"}},"订单状态"),
        h("span",{style:{fontSize:12,color:"#FF3B4F",background:"#FFF3F5",padding:"2px 10px",borderRadius:999,fontWeight:600}},"待支付")
      ),
      h("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"4px 0"}},
        h("span",{style:{fontSize:13,color:"#999"}},"支付金额"),
        h("span",{style:{fontSize:13,fontWeight:700,color:"#FF3B4F"}},fmt(order.price))
      )
    ),

    // 3. Coupon card
    h("div",{style:{...card,display:"flex",alignItems:"center",justifyContent:"space-between",height:52,cursor:"pointer"},onClick:function(){alert("暂无可用优惠券");}},
      h("span",{style:{fontSize:14,color:"#333",fontWeight:500}},"优惠券"),
      h("span",{style:{fontSize:13,color:"#bbb"}},"暂无可用优惠券 ›")
    ),

    // 4. Payment method card
    h("div",{style:{...card,padding:"14px 14px 10px"}},
      h("div",{style:{fontSize:14,fontWeight:600,color:"#1a1a1a",marginBottom:10}},"支付方式"),
      methods.map(function(m) {
        var active = method === m.key;
        return h("div",{key:m.key,
          style:{display:"flex",alignItems:"center",padding:"10px 12px",marginBottom:6,borderRadius:12,cursor:"pointer",background:active?"#FFF3F5":"#F8FAFC",border:"1.5px solid "+(active?"#FFCDD2":"transparent"),height:50},
          onClick:function(){setMethod(m.key);}
        },
          h("span",{style:{fontSize:22,marginRight:10}},m.icon),
          h("span",{style:{flex:1,fontSize:14,fontWeight:500,color:"#333"}},m.name),
          h("div",{style:{width:18,height:18,borderRadius:"50%",border:"2px solid "+(active?"#FF3B4F":"#ddd"),display:"flex",alignItems:"center",justifyContent:"center"}},
            active && h("div",{style:{width:10,height:10,borderRadius:"50%",background:"#FF3B4F"}})
          )
        );
      })
    ),

    // 5. Risk hint
    h("div",{style:{margin:"0 12px 10px",background:"#FFF8E6",borderRadius:12,padding:"10px 14px"}},
      h("div",{style:{fontSize:11,color:"#B7791F",lineHeight:"17px"}},"当前为模拟支付页面，确认支付后将进入交易流程。请勿在线下私下交易，避免造成损失。")
    ),

    // 6. Bottom bar - refined compact
    h("div",{style:{position:"fixed",bottom:0,left:"50%",transform:"translateX(-50%)",width:"100%",maxWidth:430,zIndex:100,background:"#fff",padding:"10px 16px",paddingBottom:"max(10px, env(safe-area-inset-bottom))",boxSizing:"border-box",borderTop:"1px solid #eef0f3",display:"flex",alignItems:"center",gap:10}},
      // Left: price
      h("div",{style:{flex:1,minWidth:0}},
        h("div",{style:{fontSize:12,color:"#999"}},"待支付"),
        h("div",{style:{fontSize:24,fontWeight:700,color:"#FF4D5A",lineHeight:"28px"}},fmt(order.price))
      ),
      // Cancel button - subtle
      h("button",{style:{height:38,padding:"0 14px",borderRadius:12,border:"1px solid #E5E7EB",background:"#fff",color:"#999",fontSize:13,fontWeight:500,cursor:"pointer",whiteSpace:"nowrap",flexShrink:0},onClick:handleCancel,disabled:cancelling},
        cancelling ? "取消中..." : "取消订单"
      ),
      // Pay button - compact primary
      h("button",{style:{width:150,height:46,borderRadius:14,border:"none",background:"linear-gradient(135deg, #FF5A6A, #FF4D5A)",color:"#fff",fontSize:16,fontWeight:600,cursor:"pointer",boxShadow:"0 4px 12px rgba(255,77,90,0.3)",opacity:paying?0.6:1,whiteSpace:"nowrap",flexShrink:0},onClick:handlePay,disabled:paying},
        paying ? "支付中..." : "确认支付"
      )
    )
  );
}

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