// lvpai-orders.jsx — 订单列表 + 订单详情
const { LV_T: O_T, Icon: OIcon, Btn: OBtn, Card: OCard, Divider: ODiv,
  WeChatNav: ONav, Screen: OScreen } = window;

const O_ORANGE = '#C8791E';

// 生成撕口锯齿（向下三角形）clip-path 多边形点串
function zigzagPoints(n) {
  const pts = ['0% 0%', '100% 0%'];
  for (let k = n - 1; k >= 0; k--) {
    pts.push(((k + 0.5) / n * 100) + '% 100%');
    pts.push((k / n * 100) + '% 0%');
  }
  return pts.join(',');
}

// 进行中 / 待办状态用橙色，正在制作/创作中用绿色，已完成/已定制用灰色
function statusColor(state, T) {
  if (state === '已退款') return '#C0492E';
  if (state === '已完成' || state === '已定制' || state === '已超时') return T.muted;
  if (state === '正在制作') return T.ink;
  if (state === '创作中') return '#3DA56E';
  return O_ORANGE;
}

// 创意摄影订单：按状态统一派生操作按钮，保证各状态展示风格一致
// 流程：确认全部主题内容并提交 → 正在制作（不可再修改）→ 已定制 → 已完成；若仅确认部分主题则为部分主题待定制
function cpAction(o) {
  return null;
}

function resolveAction(o) {
  if (o.cat === '文创') return wcAction(o);
  if (o.cat === '创意摄影') return cpAction(o);
  return o.action;
}

// 文创订单：按状态统一派生操作按钮，保证各状态展示风格一致
// 业务流程：上传定制内容 → 等待制作（供应商接单前可改）→ 正在制作 → 等待领取 → 已完成
function wcAction(o) {
  if (o.cat !== '文创') return o.action;
  const gift = o.gift || (o.action && o.action.gift);
  switch (o.state) {
    case '待定制': return { label: '去定制', target: 'wcCustomize', gift };
    case '等待制作': return { label: '修改内容', target: 'wcCustomize', gift };
    case '正在制作': return { label: '修改内容', target: 'wcCustomize', gift, disabled: true };
    case '等待领取': return { label: '去领取', target: 'mine' };
    case '已超时': return null;
    case '已完成': return null;
    default: return o.action;
  }
}

function OrderRow({ o, nav }) {
  const T = O_T;
  const act = resolveAction(o);
  const isRefunded = o.state === '已退款' || o.state === '已部分退款';
  const hasFootRow = o.progress || o.pickupCode || act;
  const goAction = (e) => {
    e.stopPropagation();
    if (!act || act.disabled) return;
    if (act.target === 'customize') nav.push('customize', { sel: [], orderId: o.id, mode: act.mode });
    else if (act.target === 'wcCustomize') nav.push('wcCustomize', { gift: act.gift, orderId: o.id });
    else nav.reset(act.target || 'works');
  };
  return (
    <OCard pad={0} style={{ overflow: 'hidden', marginBottom: 14 }}>
      <div style={{ padding: '16px 16px 16px' }} onClick={() => nav.push('orderDetail', { orderId: o.id })}>
        {/* title + status */}
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 9 }}>
          <span style={{ fontFamily: T.sans, fontSize: 16, fontWeight: 700, color: isRefunded ? T.faint : T.ink, flexShrink: 0 }}>{o.name}</span>
          {o.sub && <span style={{ fontFamily: T.sans, fontSize: 13, color: T.faint, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{o.sub}</span>}
          <div style={{ marginLeft: 'auto', flexShrink: 0, display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
            <span style={{ fontFamily: T.sans, fontSize: 18, fontWeight: 700, color: isRefunded ? T.faint : T.ink }}>¥{o.amount}</span>
          </div>
        </div>
        {/* date + status */}
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginTop: 11 }}>
          <span style={{ fontFamily: T.sans, fontSize: 13, color: isRefunded ? T.faint : T.muted }}>{o.created}</span>
          {(isRefunded || /线下/.test(o.pay || '')) && <span style={{ fontFamily: T.sans, fontSize: 13.5, fontWeight: 700, color: T.faint }}>{isRefunded ? o.state : '线下支付'}</span>}
        </div>
        {/* progress / pickup + action */}
        {hasFootRow && o.cat !== '创意摄影' && (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginTop: 16 }}>
            <span style={{ fontFamily: T.sans, fontSize: 13, color: T.muted }}>
              {o.progress && (typeof o.progress === 'object'
                ? <>{o.progress.label}: <b style={{ color: T.ink, fontWeight: 700, fontSize: 15 }}>{o.progress.value}</b></>
                : o.progress)}
              {o.pickupCode && <>取件码: <b style={{ color: T.ink, fontWeight: 700, fontSize: 15 }}>{o.pickupCode}</b></>}
              {!o.progress && !o.pickupCode && o.cat === '文创' && o.state === '待定制' && <>此赠品定制 2 天内有效<span style={{ color: O_ORANGE, fontWeight: 700 }}>（剩余：{o.remain || '23:33'}）</span></>}
              {!o.progress && !o.pickupCode && o.cat === '文创' && o.state === '已超时' && <>已超过定制时效，本赠品已失效</>}
              {!o.progress && !o.pickupCode && o.cat === '文创' && o.state === '等待制作' && <>供应商接单前，你仍可修改内容</>}
              {!o.progress && !o.pickupCode && o.cat === '文创' && o.state === '正在制作' && <>供应商已接单，内容不可再修改</>}
            </span>
            {act && (
              <button onClick={goAction} disabled={act.disabled} style={{
                flexShrink: 0, fontFamily: T.sans, fontSize: 14.5, fontWeight: 600,
                color: act.disabled ? T.faint : T.ink, background: '#fff',
                border: '1.5px solid ' + (act.disabled ? T.line : T.ink), borderRadius: 7,
                padding: '11px 22px', cursor: act.disabled ? 'default' : 'pointer',
                display: 'inline-flex', alignItems: 'center', gap: 6, WebkitTapHighlightColor: 'transparent' }}>
                {act.label}
              </button>
            )}
          </div>
        )}
      </div>
    </OCard>
  );
}

function OrdersScreen({ store, nav }) {
  const T = O_T;
  const [filter, setFilter] = React.useState('全部');
  const filters = ['全部', '已完成', '已退款'];
  const orders = store.orders.filter((o) => o.cat !== '文创');
  const match = (o) => {
    if (filter === '全部') return true;
    if (o.cat === '创意摄影') { if (filter === '已完成') return o.state === '已完成'; if (filter === '已退款') return o.state === '已退款'; return false; }
    if (filter === '已完成') return o.state === '已完成';
    if (filter === '已退款') return o.state === '已退款';
    return false;
  };
  const list = orders.filter(match);

  return (
    <OScreen
      nav={<ONav title="订单" />}
      body={<div style={{ paddingBottom: 24 }}>
        {/* underline tabs */}
        <div style={{ position: 'sticky', top: 0, zIndex: 6, background: T.paper, padding: '2px 18px 0', boxShadow: '0 1px 0 ' + T.lineSoft }}>
          <div style={{ display: 'flex', gap: 26 }}>
            {filters.map(f => {
              const on = filter === f;
              return (
                <button key={f} onClick={() => setFilter(f)} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '10px 0 12px', position: 'relative', WebkitTapHighlightColor: 'transparent' }}>
                  <span style={{ fontFamily: T.sans, fontSize: 16, fontWeight: on ? 700 : 500, color: on ? T.ink : T.muted, letterSpacing: 0.3 }}>{f}</span>
                  {on && <span style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: 2.5, borderRadius: 3, background: T.ink }} />}
                </button>
              );
            })}
          </div>
        </div>

        <div style={{ padding: '16px 18px 0' }}>
          {list.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '70px 20px' }}>
              <OIcon name="receipt" size={40} color={T.faint} stroke={1.3} style={{ margin: '0 auto 14px' }} />
              <div style={{ fontFamily: T.sans, fontSize: 14, color: T.muted }}>暂无{filter === '全部' ? '' : filter}订单</div>
            </div>
          ) : list.map(o => <OrderRow key={o.id} o={o} nav={nav} />)}
        </div>
      </div>}
    />
  );
}

// ── 订单详情 ──────────────────────────────────────────────────────
function OrderDetailScreen({ store, nav, orderId }) {
  const T = O_T;
  const o = store.orders.find(x => x.id === orderId) || store.orders[0];
  const [copied, setCopied] = React.useState(false);
  const copyId = () => {
    const text = o.id;
    const done = () => { setCopied(true); setTimeout(() => setCopied(false), 1500); };
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(text).then(done).catch(done);
    } else {
      const ta = document.createElement('textarea');
      ta.value = text; ta.style.position = 'fixed'; ta.style.opacity = '0';
      document.body.appendChild(ta); ta.select();
      try { document.execCommand('copy'); } catch (e) {}
      document.body.removeChild(ta); done();
    }
  };
  const THEMES = (window.LV_DATA && window.LV_DATA.THEMES) || [];
  const isCreative = o.cat === '创意摄影' || (o.cat === '套餐' && /创意摄影/.test(o.name || ''));
  const theme = isCreative ? THEMES.find((t) => t.tone === o.tone) : null;
  const refPortrait = (window.LV_PORTRAITS || [])[0];
  const refThumb = refPortrait && (refPortrait.front[0] || refPortrait.side[0] || refPortrait.back[0]);
  const ownedOriginals = Object.values(store.photos || {}).filter((s) => s === 'bought' || s === 'free').length;

  return (
    <OScreen
      nav={<ONav title="订单详情" onBack={() => nav.pop()} />}
      body={<div style={{ padding: '8px 18px 24px' }}>
        {/* status banner */}
        <div style={{ position: 'relative', padding: '24px 22px', borderRadius: 8, background: T.ink, marginBottom: 18, overflow: 'hidden' }}>
          <svg width="140" height="140" viewBox="0 0 140 140" style={{ position: 'absolute', top: -30, right: -30, opacity: 0.08 }}>
            <circle cx="70" cy="70" r="68" fill="none" stroke="#fff" strokeWidth="1.5" />
            <circle cx="70" cy="70" r="46" fill="none" stroke="#fff" strokeWidth="1.5" />
          </svg>
          <svg width="90" height="90" viewBox="0 0 90 90" style={{ position: 'absolute', bottom: -22, left: -18, opacity: 0.07 }}>
            <path d="M0 45 Q22 5 45 45 T90 45" fill="none" stroke="#fff" strokeWidth="1.5" />
          </svg>
          <div style={{ position: 'relative', fontFamily: T.sans, fontSize: 26, fontWeight: 700, color: '#fff' }}>{o.state === '已购买' ? '已支付' : o.state}</div>
          <div style={{ position: 'relative', fontFamily: T.sans, fontSize: 13.5, color: 'rgba(255,255,255,0.62)', marginTop: 10, lineHeight: 1.6 }}>{o.statusSub || o.eta}</div>
        </div>

        {/* payment info */}
        <div style={{ background: T.card, borderRadius: '8px 8px 0 0', padding: '18px 18px 10px', boxShadow: '0 1px 2px rgba(26,25,22,0.04), 0 8px 24px rgba(26,25,22,0.04)' }}>
          {[['商品名称', o.name || '创意摄影'], ['订单金额', '¥' + o.amount], ['支付方式', o.pay || '微信支付'], ['订单编号', o.id], ['下单时间', o.created || '今天']].map(([a, b]) => (
            <div key={a} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '9px 0', fontFamily: T.sans, fontSize: 14 }}>
              <span style={{ color: T.muted }}>{a}</span>
              {a === '订单编号' ? (
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}>
                  <span style={{ color: T.ink, fontWeight: 600 }}>{b}</span>
                  <button onClick={copyId} aria-label="复制订单编号" style={{ display: 'inline-flex', alignItems: 'center', gap: 3, background: 'none', border: 'none', padding: '2px 2px', margin: 0, cursor: 'pointer', color: copied ? '#3DA56E' : T.muted, WebkitTapHighlightColor: 'transparent' }}>
                    <OIcon name={copied ? 'checkSm' : 'copy'} size={15} color={copied ? '#3DA56E' : T.muted} stroke={2} />
                    {copied && <span style={{ fontFamily: T.sans, fontSize: 12, fontWeight: 600 }}>已复制</span>}
                  </button>
                </span>
              ) : (
                <span style={{ color: T.ink, fontWeight: 600 }}>{b}</span>
              )}
            </div>
          ))}
        </div>
        <div style={{ height: 7, background: T.card, clipPath: 'polygon(' + zigzagPoints(40) + ')' }} />
        <div style={{ height: 14 }} />

        {theme && /线下/.test(o.pay || '') &&
        <OCard pad={18} style={{ marginTop: 14 }}>
          <button onClick={() => nav.push('product', { openPos: 1 })} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%', padding: '9px 0', background: 'none', border: 'none', cursor: 'pointer', fontFamily: T.sans, fontSize: 14 }}>
            <span style={{ color: T.muted }}>高清底片</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              <span style={{ color: T.ink, fontWeight: 600 }}>{ownedOriginals} 张</span>
              <OIcon name="chevR" size={14} color={T.faint} stroke={2} />
            </span>
          </button>
          <button onClick={() => o.freePlan ? nav.push('cyLocked', { count: 6 }) : nav.push('product', { focusSection: 'customized', openTheme: theme.name })} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%', padding: '9px 0', background: 'none', border: 'none', cursor: 'pointer', fontFamily: T.sans, fontSize: 14 }}>
            <span style={{ color: T.muted }}>创意摄影</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              <span style={{ color: T.ink, fontWeight: 600 }}>6 张</span>
              <OIcon name="chevR" size={14} color={T.faint} stroke={2} />
            </span>
          </button>
        </OCard>}

        <div style={{ textAlign: 'center', marginTop: 22, fontFamily: T.sans, fontSize: 13.5, color: T.muted }}>
          对此订单有疑问？<button onClick={() => nav.push('service')} style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', fontFamily: T.sans, fontSize: 13.5, fontWeight: 700, color: T.ink }}>咨询在线客服</button>
        </div>
      </div>}
    />
  );
}

function CreativeLockedScreen({ store, nav, count = 6 }) {
  const T = O_T;
  const G = window.LV_GOLD || { grad: 'linear-gradient(135deg, #F4DC9A 0%, #E6BE68 46%, #CC9C40 100%)', text: '#4A3209' };
  const [buy, setBuy] = React.useState(false);
  const [confirmDel, setConfirmDel] = React.useState(false);
  const [gone, setGone] = React.useState(false);
  return (
    <>
    <OScreen nav={<ONav title="创意摄影" onBack={() => nav.pop()} />} body={
      <div style={{ minHeight: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '40px 30px 96px', textAlign: 'center' }}>
        <svg width="104" height="104" viewBox="0 0 64 64" fill="none" stroke={T.faint} strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
          <path d="M14.5 17.8c-.2-2 1.2-3.6 3.2-3.8l28-2.4c2-.2 3.7 1.2 3.9 3.1l2.7 31.4c.2 2-1.3 3.7-3.3 3.9l-27.8 2.3c-2 .2-3.7-1.3-3.9-3.2L14.5 17.8Z" />
          <path d="M11.6 21.3c1.7-.5 3.4-.8 5.2-.9M12.4 30.6c1.7-.4 3.5-.7 5.2-.8M13.2 39.9c1.7-.4 3.5-.6 5.3-.7" />
          <path d="M20.5 44.2c3-4.4 5.6-6.6 7.7-6.5 2.3.2 3 3.4 5.4 3.6 2.2.2 3.6-2.6 5.8-2.4 2 .2 3.9 2.6 5.6 5.4" />
          <circle cx="39.6" cy="24.4" r="3.6" />
          <path d="M26.2 24.8c.9-.8 2-.8 2.9 0M32.2 31.6c1.6 1.6 4.2 1.4 5.6-.4" />
        </svg>
        <div style={{ fontFamily: T.sans, fontSize: 15, color: T.inkSoft, lineHeight: 1.75, marginTop: 26, maxWidth: 260 }}>
          {gone ? '照片已删除' : <>您有 {count} 张创意摄影，<br />购买套餐后可查看及下载成片</>}
        </div>
        {!gone &&
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, width: '100%', maxWidth: 280, marginTop: 30 }}>
          <button onClick={() => setBuy(true)} style={{ width: '100%', padding: '14px 0', border: 'none', borderRadius: 8, background: G.grad, color: G.text, fontFamily: T.sans, fontSize: 15.5, fontWeight: 700, cursor: 'pointer', boxShadow: '0 8px 20px rgba(204,156,64,0.3)' }}>立即购买</button>
          <button onClick={() => setConfirmDel(true)} style={{ width: '100%', padding: '14px 0', border: 'none', borderRadius: 8, background: T.field, color: T.muted, fontFamily: T.sans, fontSize: 15.5, fontWeight: 600, cursor: 'pointer' }}>删除照片</button>
        </div>}
      </div>} />
    {window.ChuangyiBuySheet && <window.ChuangyiBuySheet open={buy} onClose={() => setBuy(false)} store={store} onPaid={() => { setBuy(false); nav.reset('orders'); }} />}
    {window.WChDialog && <window.WChDialog open={confirmDel} body={<>确定要删除这 {count} 张创意摄影吗？<br />删除后将无法恢复。</>} okText="删除" onCancel={() => setConfirmDel(false)} onOk={() => { setConfirmDel(false); setGone(true); }} />}
    </>);
}

Object.assign(window, { OrdersScreen, OrderDetailScreen, CreativeLockedScreen });
