// lvpai-mine.jsx — 我的（资产 / 取片卡 / 服务 / 隐私）+ 资产列表 + 设置
const { LV_T: M_T, Icon: MIcon, Photo: MPhoto, Btn: MBtn, Card: MCard, Eyebrow: MEye,
  Price: MPrice, Divider: MDiv, WeChatNav: MNav, Screen: MScreen, StatusChip: MChip, Sheet: MSheet } = window;

function AssetTile({ icon, label, count, unit, onClick, gold }) {
  const T = M_T;
  const G = window.LV_GOLD || { grad: 'linear-gradient(135deg, #F4DC9A 0%, #E6BE68 46%, #CC9C40 100%)', text: '#4A3209', hi: '#E8C87A' };
  return (
    <button onClick={onClick} style={{ background: gold ? G.grad : T.card, border: 'none', borderRadius: 8, padding: '16px 12px', cursor: 'pointer',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 9, boxShadow: gold ? '0 8px 20px rgba(204,156,64,0.35), inset 0 1px 0 rgba(255,255,255,0.5)' : '0 2px 10px rgba(26,25,22,0.05)' }}>
      <MIcon name={icon} size={24} color={gold ? G.text : T.ink} stroke={1.6} />
      <span style={{ fontFamily: T.sans, fontSize: 12, fontWeight: 600, color: gold ? G.text : T.ink }}>{label}</span>
      {count != null && <span style={{ fontFamily: T.serif, fontSize: 15, fontWeight: gold ? 700 : 400, color: gold ? G.text : T.muted }}>{count}{unit || ''}</span>}
    </button>
  );
}

function MineScreen({ store, nav }) {
  const T = M_T;
  const ownedOriginals = Object.values(store.photos).filter(s => s === 'bought' || s === 'free').length;
  const [cyPick, setCyPick] = React.useState(false);
  const cyByScenic = [{ name: '蓝月谷', sets: 2 }, { name: '洱海廊道', sets: 1 }];
  const cyRemaining = cyByScenic.reduce((a, s) => a + s.sets, 0);
  const cyBaseOrder = (store.orders || []).find((o) => o.cat === '创意摄影' && ['部分主题待定制', '待定制'].includes(o.state));
  const cyConfirmed = cyBaseOrder && cyBaseOrder.confirmedSets ? cyBaseOrder.confirmedSets : 0;
  const goingOrders = store.orders.filter(o => ['制作中', '正在制作', '已定制', '待确认', '待自提', '待定制', '部分主题待定制', '等待领取', '正在同步'].includes(o.state));
  const pickup = store.orders.filter(o => o.pickupCode && o.state !== '已完成').length;
  const making = store.orders.filter(o => ['制作中', '正在制作', '待确认', '待定制', '部分主题待定制', '等待领取'].includes(o.state)).length;

  const listGroup = (rows) => (
    <div style={{ background: T.card, borderRadius: 8, overflow: 'hidden', boxShadow: '0 2px 10px rgba(26,25,22,0.04)' }}>
      {rows.map((r, i) => (
        <div key={r.label}>
          <button onClick={r.onClick} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', background: 'none', border: 'none', cursor: 'pointer' }}>
            <MIcon name={r.icon} size={20} color={T.ink} stroke={1.6} />
            <span style={{ flex: 1, textAlign: 'left', fontFamily: T.sans, fontSize: 14.5, color: T.ink }}>{r.label}</span>
            {r.detail && <span style={{ fontFamily: T.sans, fontSize: 12.5, color: T.muted }}>{r.detail}</span>}
            <MIcon name="chevR" size={15} color={T.faint} stroke={1.8} />
          </button>
          {i < rows.length - 1 && <div style={{ height: 1, background: T.lineSoft, marginLeft: 48 }} />}
        </div>
      ))}
    </div>
  );

  return (
    <MScreen
      nav={<MNav title="我的" />}
      body={<div style={{ paddingBottom: 28 }}>
        {/* user */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '6px 20px 22px' }}>
          <div style={{ width: 58, height: 58, borderRadius: 999, overflow: 'hidden', flexShrink: 0, boxShadow: 'inset 0 0 0 1px ' + T.line }}><MPhoto seed={0.05} pos="center 22%" /></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: T.sans, fontSize: 18, fontWeight: 700, color: T.ink }}>微信用户</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 5 }}>
              <span style={{ fontFamily: T.sans, fontSize: 12, color: T.muted }}>{store.bound ? '手机号未绑定' : '未绑定取片卡'}</span>
            </div>
          </div>
        </div>

        {/* assets */}
        <div style={{ padding: '0 18px' }}>
          <MEye style={{ margin: '0 2px 12px' }}>我的影像资产</MEye>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8 }}>
            <AssetTile icon="sparkle" label="剩余可定制" count={cyRemaining} unit="套" gold onClick={() => setCyPick(true)} />
            <AssetTile icon="wand" label="创意摄影成片" count={2} unit="套" onClick={() => nav.push('product', { focusSection: 'customized' })} />
            <AssetTile icon="image" label="高清底片" count={8} unit="张" onClick={() => nav.push('product', { focusSection: 'yuanpian' })} />
          </div>
        </div>

        <MSheet open={cyPick} onClose={() => setCyPick(false)} title="开始定制创意摄影">
          <div style={{ fontFamily: T.sans, fontSize: 13, color: T.muted, margin: '0 0 14px' }}>不同景区的套餐不可通用，请先选择</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {cyByScenic.map((s) => (
              <button key={s.name} onClick={() => { setCyPick(false); nav.push('customize', { sel: [], scenic: s.name, scenicSets: s.sets }); }} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%', textAlign: 'left', background: T.card, border: 'none', borderRadius: 8, padding: '15px 16px', cursor: 'pointer', boxShadow: 'inset 0 0 0 1px ' + T.line }}>
                <span style={{ fontFamily: T.sans, fontSize: 15, fontWeight: 600, color: T.ink }}>{s.name}</span>
                <span style={{ display: 'flex', alignItems: 'center', gap: 6, fontFamily: T.sans, fontSize: 13.5, color: T.muted }}>x {s.sets} 套<MIcon name="chevR" size={15} color={T.faint} stroke={1.8} /></span>
              </button>
            ))}
          </div>
        </MSheet>

        {/* 设置 */}
        <div style={{ padding: '24px 18px 0' }}>
          <img src={window.lvAsset('assets/banner-mine.png')} alt="" draggable="false" style={{ display: 'block', width: '100%', borderRadius: 8, marginBottom: 18, boxShadow: '0 2px 10px rgba(26,25,22,0.06)' }} />
          <MEye style={{ margin: '0 2px 12px' }}>设置</MEye>
          {listGroup([
            { icon: 'headset', label: '联系客服', onClick: () => nav.push('service') },
            { icon: 'question', label: '常见问题', onClick: () => nav.push('bindHelp') },
            { icon: 'shield', label: '用户协议与隐私政策', onClick: () => nav.push('settings', { legal: true }) },
          ])}
        </div>

        <div style={{ textAlign: 'center', padding: '28px 0 0' }}>
          <div style={{ fontFamily: T.serif, fontSize: 13, color: T.faint, letterSpacing: 2 }}>帧集快拍</div>
          <div style={{ fontFamily: T.sans, fontSize: 11, color: T.faint, marginTop: 5 }}>©️2026 V1.01</div>
        </div>
      </div>}
    />
  );
}

// ── 资产列表 ──────────────────────────────────────────────────────
function AssetListScreen({ store, nav, kind }) {
  const T = M_T;
  const meta = {
    yuanpian: { title: '我的原片', sub: '已领取或已购买的照片' },
    chuangyi: { title: '创意作品', sub: '按 6 张作品集展示' },
    wenchuang: { title: '我的文创', sub: '购买过的实体商品记录' },
  }[kind] || { title: '我的资产', sub: '' };

  const owned = kind === 'yuanpian' ? store.group.photos.filter(p => ['bought', 'free'].includes(store.photos[p.id])) : [];
  const wenOrders = kind === 'wenchuang' ? store.orders.filter(o => o.cat === '文创') : [];
  const making = store.orders.filter(o => kind === 'chuangyi' && o.cat === '创意摄影').filter(o => o.state !== '已完成');

  return (
    <MScreen nav={<MNav title={meta.title} onBack={() => nav.pop()} rightIcons={[{ name: 'share', onClick: () => {} }]} />}
      body={<div style={{ padding: '8px 18px 24px' }}>
        <div style={{ fontFamily: T.sans, fontSize: 12.5, color: T.muted, margin: '2px 2px 16px' }}>{meta.sub}</div>

        {making.length > 0 && (
          <MCard pad={14} style={{ marginBottom: 16 }} onClick={() => nav.reset('orders')}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <MChip label={making[0].state} tone="going" />
              <span style={{ flex: 1, fontFamily: T.sans, fontSize: 13, color: T.inkSoft }}>{making.length} 个制作中 · 完成后在此查看</span>
              <MIcon name="chevR" size={15} color={T.faint} stroke={1.8} />
            </div>
          </MCard>
        )}

        {kind === 'yuanpian' && (
          owned.length > 0 ? (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8 }}>
              {owned.map(p => (
                <div key={p.id} style={{ position: 'relative', borderRadius: 6, overflow: 'hidden' }}>
                  <MPhoto src={p.src} seed={window.lvSeed(p.id)} ratio="3 / 4" tag={store.photos[p.id] === 'free' ? { text: '免费', bg: window.lvAccent(), color: '#fff' } : null} />
                </div>
              ))}
            </div>
          ) : <Empty text="还没有原片，先去领取或购买" nav={nav} />
        )}
        {kind === 'wenchuang' && (
          wenOrders.length > 0 ? wenOrders.map(o => (
            <MCard key={o.id} pad={14} style={{ marginBottom: 10 }} onClick={() => nav.push('orderDetail', { orderId: o.id })}>
              <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                <div style={{ width: 50, height: 50, borderRadius: 6, overflow: 'hidden' }}><MPhoto src={o.src} pos={o.src ? 'center' : 'center 32%'} seed={window.lvSeed(o.id)} /></div>
                <div style={{ flex: 1 }}><div style={{ fontFamily: T.sans, fontSize: 14, fontWeight: 700, color: T.ink }}>{o.name}</div><div style={{ fontFamily: T.sans, fontSize: 12, color: T.muted, marginTop: 4 }}>{o.state}</div></div>
                <MIcon name="chevR" size={15} color={T.faint} stroke={1.8} />
              </div>
            </MCard>
          )) : <Empty text="还没有文创订单" nav={nav} />
        )}
        {kind === 'chuangyi' && making.length === 0 && <Empty text="完成交付后在此查看" nav={nav} />}

        {kind === 'yuanpian' && owned.length > 0 && (
          <div style={{ marginTop: 18, display: 'flex', gap: 10 }}>
            <MBtn kind="soft" full icon="sparkle" onClick={() => nav.push('product', { cat: 'chuangyi' })}>做创意摄影</MBtn>
            <MBtn kind="soft" full icon="gift" onClick={() => nav.push('product', { cat: 'wenchuang' })}>做文创</MBtn>
          </div>
        )}
      </div>} />
  );
}

function Empty({ text, nav }) {
  const T = M_T;
  return (
    <div style={{ textAlign: 'center', padding: '60px 20px' }}>
      <MIcon name="image" size={38} color={T.faint} stroke={1.3} style={{ margin: '0 auto 14px' }} />
      <div style={{ fontFamily: T.sans, fontSize: 14, color: T.muted, marginBottom: 16 }}>{text}</div>
      <MBtn kind="soft" size="sm" onClick={() => nav.reset('works')}>去作品页</MBtn>
    </div>
  );
}

// ── 设置与隐私 ────────────────────────────────────────────────────
function SettingsScreen({ store, nav, legal: legalInit }) {
  const T = M_T;
  const [face, setFace] = React.useState(false);
  const [promo, setPromo] = React.useState(false);
  const [notify, setNotify] = React.useState(true);

  const Toggle = ({ on, onChange }) => (
    <button onClick={() => onChange(!on)} style={{ width: 46, height: 28, borderRadius: 4, border: 'none', cursor: 'pointer', background: on ? T.ink : '#D8D3C8', position: 'relative', transition: 'background .2s', flexShrink: 0 }}>
      <span style={{ position: 'absolute', top: 3, left: on ? 21 : 3, width: 22, height: 22, borderRadius: 4, background: '#fff', transition: 'left .2s', boxShadow: '0 1px 3px rgba(0,0,0,0.2)' }} />
    </button>
  );
  const Row = ({ label, sub, right, last, onClick }) => (
    <div>
      <div onClick={onClick} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', cursor: onClick ? 'pointer' : 'default' }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: T.sans, fontSize: 14.5, color: T.ink }}>{label}</div>
          {sub && <div style={{ fontFamily: T.sans, fontSize: 11.5, color: T.muted, marginTop: 4, lineHeight: 1.5 }}>{sub}</div>}
        </div>
        {right}
      </div>
      {!last && <div style={{ height: 1, background: T.lineSoft, marginLeft: 16 }} />}
    </div>
  );
  const [legal, setLegal] = React.useState(!!legalInit);
  const Group = ({ children }) => <div style={{ background: T.card, borderRadius: 8, overflow: 'hidden', marginBottom: 18, boxShadow: '0 2px 10px rgba(26,25,22,0.04)' }}>{children}</div>;

  if (legal) return (
    <MScreen nav={<MNav title="用户协议与隐私政策" onBack={() => legalInit ? nav.pop() : setLegal(false)} />}
      body={<div style={{ padding: '12px 18px 24px' }}>
        <div style={{ fontFamily: T.sans, fontSize: 13, color: T.inkSoft, lineHeight: 1.85, padding: '2px 2px 16px' }}>感谢您使用帧集！我们非常重视你的感受和隐私安全，以下条款说明了我们如何收集、使用与保护您的个人信息。如有隐私相关问题可联系：<span style={{ color: T.ink, fontWeight: 600 }}>privacy@lvpai.ai</span></div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, padding: '2px 2px' }}>
          {['《用户协议》', '《AI生成服务协议》', '《隐私政策》', '《敏感个人信息处理说明》', '《无显式标识版本说明》'].map((t) =>
          <button key={t} style={{ display: 'block', textAlign: 'left', background: 'none', border: 'none', padding: 0, cursor: 'pointer', fontFamily: T.sans, fontSize: 14, color: '#576B95' }}>{t}</button>)}
        </div>
      </div>} />);

  return (
    <MScreen nav={<MNav title="设置与隐私" onBack={() => nav.pop()} />}
      body={<div style={{ padding: '12px 18px 24px' }}>
        <MEye style={{ margin: '0 2px 12px' }}>账号</MEye>
        <Group>
          <Row label="个人资料" right={<MIcon name="chevR" size={15} color={T.faint} stroke={1.8} />} />
          <Row label="手机号" sub="支付、通知、售后需要时再获取" right={<span style={{ fontFamily: T.sans, fontSize: 13, color: T.muted }}>去绑定</span>} last />
        </Group>

        <MEye style={{ margin: '0 2px 12px' }}>通知</MEye>
        <Group>
          <Row label="消息通知" sub="照片到达、交付、自提与售后提醒" right={<Toggle on={notify} onChange={setNotify} />} last />
        </Group>

        <MEye style={{ margin: '0 2px 12px' }}>隐私与授权</MEye>
        <Group>
          <Row label="人脸授权管理" sub={face ? '已授权 · 限定景区与时间范围，可随时撤回' : '仅用于丢卡/错绑兜底找回，默认关闭'} right={<Toggle on={face} onChange={setFace} />} />
          <Row label="宣传展示授权" sub={promo ? '已开启 · 你的案例可能用于展示，可撤回' : '与购买、免费领取分开，不默认勾选'} right={<Toggle on={promo} onChange={setPromo} />} last />
        </Group>

        <Group>
          <Row label="用户协议与隐私政策" onClick={() => setLegal(true)} right={<MIcon name="chevR" size={15} color={T.faint} stroke={1.8} />} />
          <Row label="删除人脸信息" sub="撤回不影响已绑定和已购买照片" right={<MIcon name="chevR" size={15} color={T.faint} stroke={1.8} />} />
          <Row label="注销账号 / 数据处理" right={<MIcon name="chevR" size={15} color={T.faint} stroke={1.8} />} last />
        </Group>

        <div style={{ textAlign: 'center', fontFamily: T.serif, fontSize: 12, color: T.faint, letterSpacing: 1.5, marginTop: 6 }}>帧集快拍 · V1.1</div>
      </div>} />
  );
}

Object.assign(window, { MineScreen, AssetListScreen, SettingsScreen });
