// 共享流程组件:购物车抽屉 / 结算 / 支付 / 授权证书
// 三版通用(样式会随当前版本微调);以传入的 theme 对象定制外观

// theme: { bg, paper, ink, muted, line, accent, font, radius }

function CheckoutFlow({ theme, open, onClose, cart, removeCart, initialArt, initialLicense }) {
  // step: cart → payment → success(certificate preview)
  const [step, setStep] = React.useState('cart');
  const [pay, setPay] = React.useState('wxpay');
  const [license, setLicense] = React.useState({});  // {artId: 'non_exclusive'|'exclusive'|'buyout'}
  const [agreed, setAgreed] = React.useState(false);
  const [coupon, setCoupon] = React.useState('');
  const [orderId] = React.useState(() => 'SC' + Date.now().toString().slice(-10));

  React.useEffect(() => {
    if (open) {
      setStep('cart');
      setAgreed(false);
      const l = {};
      cart.forEach(c => { l[c.id] = initialLicense?.[c.id] || 'non_exclusive'; });
      setLicense(l);
    }
  }, [open, cart.length]);

  const priceOf = (a, type) => {
    if (type === 'exclusive') return a.exclusive || a.price;
    if (type === 'buyout') return a.buyout || a.price;
    return a.price;
  };
  const subtotal = cart.reduce((s, a) => s + priceOf(a, license[a.id] || 'non_exclusive'), 0);
  const discount = coupon === 'NEW50' ? 50 : 0;
  const total = Math.max(0, subtotal - discount);

  if (!open) return null;

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(20,18,14,.6)', zIndex: 100,
      display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: theme.font,
      backdropFilter: 'blur(4px)',
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        background: theme.paper, width: step === 'success' ? 720 : 780, maxHeight: '88vh',
        borderRadius: theme.radius ?? 0, overflow: 'hidden', display: 'flex', flexDirection: 'column',
        border: `1px solid ${theme.line}`, boxShadow: '0 30px 80px rgba(0,0,0,.35)',
      }}>
        {/* 头 */}
        <div style={{ padding: '18px 28px', borderBottom: `1px solid ${theme.line}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: theme.bg }}>
          <div style={{ fontSize: 16, fontWeight: 600, color: theme.ink, letterSpacing: theme.letterSpacing ?? 0 }}>
            {step === 'cart' && (theme.labels?.cart || '购物车 · 确认订单')}
            {step === 'payment' && (theme.labels?.payment || '支付订单')}
            {step === 'success' && (theme.labels?.success || '授权完成 · 证书已生成')}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, fontSize: 12, color: theme.muted }}>
            <StepDot active={step==='cart' || step==='payment' || step==='success'} label="订单" theme={theme} />
            <div style={{ width: 40, height: 1, background: theme.line }} />
            <StepDot active={step==='payment' || step==='success'} label="支付" theme={theme} />
            <div style={{ width: 40, height: 1, background: theme.line }} />
            <StepDot active={step==='success'} label="证书" theme={theme} />
            <span onClick={onClose} style={{ cursor: 'pointer', color: theme.muted, fontSize: 22, marginLeft: 14 }}>×</span>
          </div>
        </div>

        {/* 内容 */}
        <div style={{ overflow: 'auto', flex: 1 }}>
          {step === 'cart' && (
            <div style={{ padding: 28 }}>
              {cart.length === 0 && <div style={{ textAlign: 'center', padding: 60, color: theme.muted }}>购物车暂无作品</div>}
              {cart.map(a => (
                <div key={a.id} style={{ display: 'flex', gap: 16, padding: '16px 0', borderBottom: `1px solid ${theme.line}` }}>
                  <div style={{ width: 84, height: 84, background: PATTERNS[a.pattern].bg, backgroundSize: PATTERNS[a.pattern].bgSize || 'auto', border: `1px solid ${theme.line}`, borderRadius: theme.radius ? theme.radius / 2 : 0, flexShrink: 0 }} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 600, color: theme.ink, marginBottom: 2 }}>{a.title}</div>
                    <div style={{ fontSize: 11, color: theme.muted, marginBottom: 10 }}>№ {a.id} · {a.designer}</div>
                    {/* 授权选择 */}
                    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                      {[['non_exclusive', '非独家', a.price], a.exclusive && ['exclusive', '独家', a.exclusive], a.buyout && ['buyout', '买断', a.buyout]].filter(Boolean).map(([k, l, p]) => (
                        <span key={k} onClick={() => setLicense(s => ({ ...s, [a.id]: k }))} style={{
                          padding: '4px 10px', fontSize: 11, cursor: 'pointer',
                          border: `1px solid ${license[a.id] === k ? theme.accent : theme.line}`,
                          background: license[a.id] === k ? theme.accent : 'transparent',
                          color: license[a.id] === k ? '#fff' : theme.ink,
                          borderRadius: theme.radius ? 999 : 0,
                        }}>{l} · ¥{p.toLocaleString()}</span>
                      ))}
                    </div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: 18, fontWeight: 700, color: theme.ink }}>¥{priceOf(a, license[a.id] || 'non_exclusive').toLocaleString()}</div>
                    <span onClick={() => removeCart(a.id)} style={{ fontSize: 11, color: theme.muted, cursor: 'pointer', marginTop: 10, display: 'inline-block' }}>移除</span>
                  </div>
                </div>
              ))}

              {/* 优惠 */}
              {cart.length > 0 && (
                <div style={{ padding: '16px 0', borderBottom: `1px solid ${theme.line}`, display: 'flex', gap: 10, alignItems: 'center' }}>
                  <span style={{ fontSize: 13, color: theme.muted }}>优惠码</span>
                  <input value={coupon} onChange={e => setCoupon(e.target.value)} placeholder="试试 NEW50" style={{
                    flex: 1, padding: '8px 12px', border: `1px solid ${theme.line}`, background: theme.bg, fontSize: 13,
                    borderRadius: theme.radius ? theme.radius / 2 : 0, fontFamily: theme.font, outline: 'none',
                  }} />
                  <button style={{ padding: '8px 16px', background: 'transparent', border: `1px solid ${theme.ink}`, color: theme.ink, fontSize: 12, cursor: 'pointer', fontFamily: theme.font, borderRadius: theme.radius ? theme.radius / 2 : 0 }}>使用</button>
                </div>
              )}

              {/* 汇总 */}
              {cart.length > 0 && (
                <div style={{ padding: '20px 0 0', fontSize: 13 }}>
                  <SumRow k="作品合计" v={`¥${subtotal.toLocaleString()}`} theme={theme} />
                  {discount > 0 && <SumRow k="优惠码 NEW50" v={`-¥${discount}`} theme={theme} color={theme.accent} />}
                  <SumRow k="支付手续费" v="¥0" theme={theme} />
                  <div style={{ height: 1, background: theme.line, margin: '12px 0' }} />
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                    <span style={{ color: theme.muted, fontSize: 13 }}>应付金额</span>
                    <span style={{ fontSize: 28, fontWeight: 700, color: theme.accent }}>¥{total.toLocaleString()}</span>
                  </div>
                </div>
              )}
            </div>
          )}

          {step === 'payment' && (
            <div style={{ padding: 28 }}>
              <div style={{ fontSize: 13, color: theme.muted, marginBottom: 12 }}>订单号</div>
              <div style={{ fontSize: 15, fontFamily: 'monospace', color: theme.ink, marginBottom: 20 }}>{orderId}</div>

              <div style={{ fontSize: 13, color: theme.muted, marginBottom: 10 }}>支付方式</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, marginBottom: 24 }}>
                {[
                  { k: 'wxpay', l: '微信支付', icon: '💚' },
                  { k: 'alipay', l: '支付宝', icon: '💙' },
                  { k: 'bank', l: '对公转账', icon: '🏦' },
                  { k: 'balance', l: '余额 ¥3,200', icon: '💰' },
                ].map(o => (
                  <div key={o.k} onClick={() => setPay(o.k)} style={{
                    padding: '14px 10px', textAlign: 'center', cursor: 'pointer',
                    border: `2px solid ${pay === o.k ? theme.accent : theme.line}`,
                    borderRadius: theme.radius ? theme.radius / 2 : 0,
                    background: pay === o.k ? theme.paper : 'transparent',
                  }}>
                    <div style={{ fontSize: 24, marginBottom: 4 }}>{o.icon}</div>
                    <div style={{ fontSize: 12, fontWeight: 600, color: theme.ink }}>{o.l}</div>
                  </div>
                ))}
              </div>

              {pay === 'wxpay' && (
                <div style={{ padding: 24, textAlign: 'center', border: `1px solid ${theme.line}`, background: theme.bg, borderRadius: theme.radius ? theme.radius / 2 : 0 }}>
                  <div style={{
                    width: 180, height: 180, margin: '0 auto 12px',
                    background: `
                      repeating-linear-gradient(90deg, #000 0 4px, transparent 4px 8px),
                      repeating-linear-gradient(0deg, #000 0 4px, transparent 4px 8px)
                    `,
                    backgroundColor: '#fff',
                    backgroundSize: '8px 8px',
                    position: 'relative',
                  }}>
                    <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', background: '#fff', padding: '8px 14px', border: '2px solid #000', fontSize: 12, fontWeight: 700 }}>微信</div>
                  </div>
                  <div style={{ fontSize: 13, color: theme.ink, fontWeight: 600 }}>扫码支付 ¥{total.toLocaleString()}</div>
                  <div style={{ fontSize: 11, color: theme.muted, marginTop: 4 }}>订单 {orderId} · 14:59 后失效</div>
                </div>
              )}
              {pay !== 'wxpay' && (
                <div style={{ padding: 32, textAlign: 'center', border: `1px solid ${theme.line}`, background: theme.bg, borderRadius: theme.radius ? theme.radius / 2 : 0, color: theme.muted, fontSize: 13 }}>
                  {pay === 'alipay' && '跳转支付宝中...'}
                  {pay === 'bank' && '已生成转账信息,请对公打款后上传凭证。'}
                  {pay === 'balance' && `将从余额扣除 ¥${total.toLocaleString()}`}
                </div>
              )}

              <div style={{ marginTop: 20, padding: '14px 16px', background: theme.bg, fontSize: 12, color: theme.muted, lineHeight: 1.8, borderRadius: theme.radius ? theme.radius / 2 : 0, border: `1px dashed ${theme.line}` }}>
                支付成功后,系统将自动生成 <b style={{ color: theme.ink }}>授权证书 PDF</b> 和 <b style={{ color: theme.ink }}>原稿下载链接</b>,有效期 15 分钟。
              </div>
            </div>
          )}

          {step === 'success' && (
            <div style={{ padding: 28 }}>
              {/* 成功状态 */}
              <div style={{ textAlign: 'center', padding: '20px 0 28px' }}>
                <div style={{ width: 64, height: 64, borderRadius: '50%', background: theme.accent, color: '#fff', fontSize: 32, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16 }}>✓</div>
                <div style={{ fontSize: 20, fontWeight: 700, color: theme.ink, marginBottom: 4 }}>授权成功</div>
                <div style={{ fontSize: 13, color: theme.muted }}>订单号 {orderId} · 共 {cart.length} 件作品 · 合计 ¥{total.toLocaleString()}</div>
              </div>

              {/* 证书预览 */}
              <Certificate theme={theme} cart={cart} license={license} total={total} orderId={orderId} />

              <div style={{ display: 'flex', gap: 10, marginTop: 20 }}>
                <button style={{ flex: 1, padding: 14, background: theme.ink, color: theme.paper, border: 'none', fontSize: 13, cursor: 'pointer', fontFamily: theme.font, borderRadius: theme.radius ? theme.radius / 2 : 0, letterSpacing: 2 }}>⬇ 下载原稿</button>
                <button style={{ flex: 1, padding: 14, background: 'transparent', color: theme.ink, border: `1px solid ${theme.ink}`, fontSize: 13, cursor: 'pointer', fontFamily: theme.font, borderRadius: theme.radius ? theme.radius / 2 : 0, letterSpacing: 2 }}>⬇ 授权证书 PDF</button>
                <button style={{ flex: 1, padding: 14, background: 'transparent', color: theme.ink, border: `1px solid ${theme.line}`, fontSize: 13, cursor: 'pointer', fontFamily: theme.font, borderRadius: theme.radius ? theme.radius / 2 : 0 }}>申请发票</button>
              </div>
            </div>
          )}
        </div>

        {/* 底部操作 */}
        {step === 'cart' && cart.length > 0 && (
          <div style={{ padding: 20, borderTop: `1px solid ${theme.line}`, background: theme.bg, display: 'flex', alignItems: 'center', gap: 12 }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: theme.muted, cursor: 'pointer', flex: 1 }}>
              <input type="checkbox" checked={agreed} onChange={e => setAgreed(e.target.checked)} />
              我已阅读并同意《数字作品授权协议》与《平台服务条款》
            </label>
            <button disabled={!agreed} onClick={() => agreed && setStep('payment')} style={{
              padding: '12px 32px', background: agreed ? theme.accent : theme.line,
              color: '#fff', border: 'none', fontSize: 14, fontWeight: 600, cursor: agreed ? 'pointer' : 'not-allowed',
              fontFamily: theme.font, letterSpacing: 2,
              borderRadius: theme.radius ? theme.radius / 2 : 0,
            }}>去支付 · ¥{total.toLocaleString()}</button>
          </div>
        )}
        {step === 'payment' && (
          <div style={{ padding: 20, borderTop: `1px solid ${theme.line}`, background: theme.bg, display: 'flex', gap: 12 }}>
            <button onClick={() => setStep('cart')} style={{ padding: '12px 24px', background: 'transparent', color: theme.ink, border: `1px solid ${theme.line}`, fontSize: 13, cursor: 'pointer', fontFamily: theme.font, borderRadius: theme.radius ? theme.radius / 2 : 0 }}>返回订单</button>
            <div style={{ flex: 1 }} />
            <button onClick={() => setStep('success')} style={{
              padding: '12px 32px', background: theme.accent, color: '#fff', border: 'none',
              fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: theme.font, letterSpacing: 2,
              borderRadius: theme.radius ? theme.radius / 2 : 0,
            }}>模拟支付成功 →</button>
          </div>
        )}
      </div>
    </div>
  );
}

function StepDot({ active, label, theme }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      <div style={{
        width: 20, height: 20, borderRadius: '50%',
        background: active ? theme.accent : 'transparent',
        border: `1px solid ${active ? theme.accent : theme.line}`,
        color: '#fff', fontSize: 11, display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>{active ? '✓' : ''}</div>
      <span style={{ color: active ? theme.ink : theme.muted, fontSize: 12 }}>{label}</span>
    </div>
  );
}

function SumRow({ k, v, color, theme }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 13 }}>
      <span style={{ color: theme.muted }}>{k}</span>
      <span style={{ color: color || theme.ink, fontWeight: 500 }}>{v}</span>
    </div>
  );
}

// 授权证书预览
function Certificate({ theme, cart, license, total, orderId }) {
  const main = cart[0];
  if (!main) return null;
  const licenseMap = { non_exclusive: '非独家授权', exclusive: '独家授权', buyout: '买断(著作权转让)' };
  return (
    <div style={{
      background: '#faf6ee', border: `1px solid ${theme.line}`, padding: '40px 36px', position: 'relative',
      borderRadius: theme.radius ? theme.radius / 2 : 0, fontFamily: theme.certFont || 'serif',
    }}>
      {/* 水印底纹 */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        backgroundImage: `repeating-linear-gradient(45deg, transparent 0 30px, rgba(166,58,42,0.04) 30px 31px)`,
      }} />
      <div style={{ position: 'relative' }}>
        <div style={{ textAlign: 'center', marginBottom: 20 }}>
          <div style={{ fontSize: 10, letterSpacing: 6, color: '#a63a2a', marginBottom: 6 }}>SU CHANG · AUTHORIZATION CERTIFICATE</div>
          <h2 style={{ fontSize: 28, margin: 0, letterSpacing: 8, fontWeight: 600, color: '#1a1814' }}>作 品 授 权 证 书</h2>
          <div style={{ fontSize: 11, color: '#8a857d', marginTop: 6, letterSpacing: 2 }}>证书编号 CERT-{orderId}-{String(Math.floor(Math.random()*9999)).padStart(4,'0')}</div>
        </div>
        <div style={{ height: 1, background: 'linear-gradient(90deg, transparent, #d4cbb8, transparent)', margin: '20px 0' }} />

        <div style={{ fontSize: 13, color: '#3d3a34', lineHeight: 2.2, letterSpacing: 1, textIndent: '2em', marginBottom: 18 }}>
          兹证明 <b style={{ color: '#a63a2a' }}>李晨 / 上海暮光服饰有限公司</b>(下称"被授权方")于 {new Date().toLocaleDateString('zh-CN')} 通过素裳平台,依约取得下列作品之 <b>{licenseMap[license[main.id] || 'non_exclusive']}</b> 使用权:
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '90px 1fr', rowGap: 10, fontSize: 13, padding: '16px 20px', background: 'rgba(255,255,255,.4)', border: `1px dashed ${theme.line}`, marginBottom: 18 }}>
          <span style={{ color: '#8a857d' }}>作品名</span><b style={{ color: '#1a1814' }}>《{main.title}》</b>
          <span style={{ color: '#8a857d' }}>花型编号</span><span>{main.id}</span>
          <span style={{ color: '#8a857d' }}>分类 / 尺寸</span><span>{main.cat_cn} · {main.size} · {main.dpi} DPI</span>
          <span style={{ color: '#8a857d' }}>设计师</span><span>{main.designer}</span>
          <span style={{ color: '#8a857d' }}>授权类型</span><b style={{ color: '#a63a2a' }}>{licenseMap[license[main.id] || 'non_exclusive']}</b>
          <span style={{ color: '#8a857d' }}>授权范围</span><span>商用 · 服装 / 家纺 / 印刷品 / 数字媒体</span>
          <span style={{ color: '#8a857d' }}>地区</span><span>全球</span>
          <span style={{ color: '#8a857d' }}>有效期</span><span>{license[main.id] === 'buyout' ? '永久(著作权转让)' : '自签发之日起 5 年'}</span>
          <span style={{ color: '#8a857d' }}>成交价</span><b>¥{total.toLocaleString()}</b>
        </div>

        {/* 签章 */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginTop: 24, fontSize: 12, color: '#3d3a34' }}>
          <div>
            <div style={{ color: '#8a857d', marginBottom: 4 }}>签发日期</div>
            <div>{new Date().toLocaleDateString('zh-CN')}</div>
          </div>
          <div style={{ position: 'relative', width: 100, height: 100 }}>
            <div style={{
              position: 'absolute', inset: 0, border: '3px solid #a63a2a', color: '#a63a2a',
              display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14,
              fontWeight: 700, letterSpacing: 3, transform: 'rotate(-8deg)', borderRadius: 4,
              fontFamily: 'serif', textAlign: 'center', padding: 8,
            }}>素裳<br/>授权<br/>专用章</div>
          </div>
        </div>

        <div style={{ marginTop: 24, fontSize: 10, color: '#8a857d', lineHeight: 1.6, letterSpacing: 1, textAlign: 'center' }}>
          本证书由素裳平台系统自动签发,已上链存证。区块链 Hash: 0x7a3f...c8e1 · 验证地址 verify.suchang.cn/{orderId}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CheckoutFlow, Certificate });
