// pricing.jsx — Pricing page: Subscriptions + Coin packages (dynamic from API)

const PLAN_COLORS = { free: '#94a3b8', month: '#22d3ee', year: '#a78bfa', week: '#fbbf24', day: '#4ade80' };

// ─── Plan card (整张卡可点击) ───────────────────────────────────────────────
const PlanCard = ({ plan, isActive, onSelect }) => {
  const { t } = useI18n();
  const color = PLAN_COLORS[plan.type] || '#22d3ee';
  const isFree = plan.base_price === 0;
  const hasPromo = plan.promotion && plan.current_price < plan.base_price;
  const price = plan.current_price || plan.base_price;
  const clickable = !isActive && !isFree;

  const handleClick = () => { if (clickable) onSelect(plan); };
  const handleKey = (e) => { if (clickable && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); onSelect(plan); } };

  return (
    <div
      role={clickable ? 'button' : undefined}
      tabIndex={clickable ? 0 : undefined}
      onClick={handleClick}
      onKeyDown={handleKey}
      aria-disabled={isActive ? 'true' : undefined}
      aria-label={clickable ? `${t('pricing2.subscribe')} ${plan.name}` : plan.name}
      className="yt-clickcard"
      style={{
        flex: 1, minWidth: 220, maxWidth: 300, borderRadius: 14, overflow: 'hidden',
        border: isActive ? `2px solid ${color}` : '1px solid var(--line-2)',
        background: isActive ? `rgba(${color === '#22d3ee' ? '34,211,238' : '167,139,250'},0.04)` : 'rgba(255,255,255,0.02)',
        display: 'flex', flexDirection: 'column', position: 'relative',
        cursor: clickable ? 'pointer' : 'default',
        transition: 'transform .12s, border-color .12s, background .12s',
      }}
    >
      {isActive && (
        <div style={{ position: 'absolute', top: 10, right: 10, padding: '2px 8px', borderRadius: 5, background: 'rgba(74,222,128,0.15)', color: '#4ade80', fontSize: 10, fontWeight: 600 }}>{t('pricing2.currentPlan')}</div>
      )}
      <div style={{ padding: '18px 18px 16px' }}>
        <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--fg-0)', marginBottom: 2 }}>{plan.name}</div>
        <div style={{ fontSize: 11, color: 'var(--fg-3)', marginBottom: 12 }}>
          {plan.type === 'month' ? t('pricing2.monthly') : plan.type === 'year' ? t('pricing2.yearly') : plan.type === 'week' ? t('pricing2.weekly') : plan.type === 'day' ? t('pricing2.daily') : ''}
          {plan.duration_days > 0 ? ` · ${plan.duration_days} ${t('pricing2.days')}` : ''}
        </div>
        {isFree ? (
          <div style={{ fontSize: 32, fontWeight: 700, color: 'var(--fg-0)', marginBottom: 4 }}>{t('pricing2.free')}</div>
        ) : (
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 4 }}>
            <span style={{ fontSize: 28, fontWeight: 700, color: 'var(--fg-0)', fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.02em' }}>${price.toFixed(2)}</span>
            {hasPromo && <span style={{ fontSize: 13, color: 'var(--fg-3)', textDecoration: 'line-through', fontVariantNumeric: 'tabular-nums' }}>${plan.base_price.toFixed(2)}</span>}
          </div>
        )}
        {plan.first_purchase_price > 0 && plan.first_purchase_price < plan.base_price && !isActive && (
          <div style={{ fontSize: 11, color: '#4ade80', fontWeight: 600, marginBottom: 6 }}>{t('pricing2.firstPurchase')} ${plan.first_purchase_price.toFixed(2)}</div>
        )}
        {plan.bonus_coins > 0 && (
          <div style={{ fontSize: 12, color: 'var(--accent)', fontWeight: 600, marginBottom: 6 }}>{t('pricing2.bonus')} {plan.bonus_coins.toLocaleString()} {t('common.credits')}</div>
        )}
        {hasPromo && plan.promotion.name && (
          <div style={{ fontSize: 11, padding: '2px 7px', borderRadius: 4, background: 'rgba(251,191,36,0.12)', color: '#fbbf24', fontWeight: 600, display: 'inline-block', marginBottom: 6 }}>
            {plan.promotion.name}
          </div>
        )}
      </div>
    </div>
  );
};

// ─── Mobile single-card carousel for plans ──────────────────────────────────
const MobilePlanCarousel = ({ plans, activeSubId, onSelect }) => {
  const { t } = useI18n();
  const [idx, setIdx] = React.useState(0);
  React.useEffect(() => {
    // 默认选中 popular（month），否则中间一张
    const popularIdx = plans.findIndex(p => p.type === 'month');
    setIdx(popularIdx >= 0 ? popularIdx : Math.floor(plans.length / 2));
  }, [plans.length]);

  if (!plans.length) return null;
  const plan = plans[idx];
  if (!plan) return null;
  const isActive = activeSubId === plan.id;
  const color = PLAN_COLORS[plan.type] || '#22d3ee';
  const isPopular = plan.type === 'month';
  const price = plan.current_price || plan.base_price;
  const hasFirstPurchase = plan.first_purchase_price > 0 && plan.first_purchase_price < plan.base_price && !isActive;
  const periodSuffix = plan.type === 'month' ? '/mo' : plan.type === 'year' ? '/yr' : plan.type === 'week' ? '/wk' : '';

  // i18n features payload from backend (gateway_product.features)
  // Shape: { zh: {description, billed_label, sections: [{title, items:[]}]}, en: {...} }
  const lang = (typeof window !== 'undefined' && window.i18n && window.i18n.getLang && window.i18n.getLang()) || 'zh';
  const fI18n = plan.features || {};
  const f = fI18n[lang] || fI18n.en || fI18n.zh || Object.values(fI18n)[0] || {};
  const billedText = f.billed_label || (plan.type === 'month' ? 'Billed monthly' : plan.type === 'year' ? 'Billed yearly' : plan.type === 'week' ? 'Billed weekly' : '');
  const description = f.description || '';
  const sections = Array.isArray(f.sections) ? f.sections : [];
  // 与月卡比较省多少（仅年卡显示）
  const monthlyPlan = plans.find(p => p.type === 'month');
  let savePct = 0;
  if (plan.type === 'year' && monthlyPlan && monthlyPlan.base_price > 0) {
    const yearAsMonthly = plan.base_price / 12;
    savePct = Math.round((1 - yearAsMonthly / monthlyPlan.base_price) * 100);
  }

  // touch swipe
  const touchStart = React.useRef(null);
  const onTouchStart = e => { touchStart.current = e.touches[0].clientX; };
  const onTouchEnd = e => {
    if (touchStart.current == null) return;
    const dx = e.changedTouches[0].clientX - touchStart.current;
    if (Math.abs(dx) > 50) {
      if (dx < 0 && idx < plans.length - 1) setIdx(idx + 1);
      if (dx > 0 && idx > 0) setIdx(idx - 1);
    }
    touchStart.current = null;
  };

  const ArrowBtn = ({ dir, disabled }) => (
    <button
      onClick={() => setIdx(dir === 'left' ? Math.max(0, idx - 1) : Math.min(plans.length - 1, idx + 1))}
      disabled={disabled}
      style={{
        width: 36, height: 36, borderRadius: 999,
        border: '1px solid var(--line-2)',
        background: disabled ? 'transparent' : 'rgba(255,255,255,0.04)',
        color: disabled ? 'var(--fg-3)' : 'var(--fg-1)',
        cursor: disabled ? 'default' : 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        opacity: disabled ? 0.4 : 1,
      }}
      aria-label={dir === 'left' ? '上一个' : '下一个'}
    >
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ transform: dir === 'right' ? 'rotate(180deg)' : '' }}>
        <polyline points="15 18 9 12 15 6"/>
      </svg>
    </button>
  );

  return (
    <div style={{ maxWidth: 480, margin: '0 auto' }}>
      {/* Carousel control */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16, padding: '0 4px' }}>
        <ArrowBtn dir="left" disabled={idx === 0} />
        <div style={{ display: 'flex', gap: 6 }}>
          {plans.map((_, i) => (
            <button key={i} onClick={() => setIdx(i)} style={{
              width: i === idx ? 18 : 6, height: 6, borderRadius: 3,
              border: 'none', cursor: 'pointer',
              background: i === idx ? 'var(--accent)' : 'rgba(255,255,255,0.18)',
              transition: 'all .2s',
            }} aria-label={`套餐 ${i+1}`} />
          ))}
        </div>
        <ArrowBtn dir="right" disabled={idx === plans.length - 1} />
      </div>

      {/* Single plan card */}
      <div
        onTouchStart={onTouchStart}
        onTouchEnd={onTouchEnd}
        style={{
          borderRadius: 18, overflow: 'hidden',
          border: isActive ? `2px solid ${color}` : isPopular ? `1.5px solid var(--accent)` : '1px solid var(--line-2)',
          background: isPopular ? 'linear-gradient(180deg, rgba(34,211,238,0.04), rgba(255,255,255,0.02))' : 'rgba(255,255,255,0.02)',
          padding: '24px 22px',
          position: 'relative',
        }}
      >
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 22, fontWeight: 700, color: 'var(--fg-0)', letterSpacing: '-0.02em' }}>{plan.name}</span>
          {isPopular && (
            <span style={{ fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 4, background: 'var(--accent)', color: '#052028', letterSpacing: '0.04em' }}>POPULAR</span>
          )}
          {isActive && (
            <span style={{ fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 4, background: 'rgba(74,222,128,0.15)', color: '#4ade80', border: '1px solid rgba(74,222,128,0.3)' }}>{t('pricing2.currentPlan')}</span>
          )}
          {savePct > 0 && (
            <span style={{ fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 4, background: 'rgba(167,139,250,0.15)', color: 'var(--accent-2)', border: '1px solid rgba(167,139,250,0.3)' }}>省 {savePct}%</span>
          )}
        </div>
        {description && (
          <div style={{ fontSize: 13, color: 'var(--fg-3)', marginBottom: 18 }}>
            {description}
          </div>
        )}

        {/* Price */}
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 4 }}>
          <span style={{ fontSize: 44, fontWeight: 800, color: 'var(--fg-0)', letterSpacing: '-0.03em', fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>
            ${price.toFixed(2)}
          </span>
          <span style={{ fontSize: 13, color: 'var(--fg-3)', fontWeight: 500 }}>USD{periodSuffix}</span>
        </div>
        {hasFirstPurchase && (
          <div style={{ fontSize: 12, color: '#4ade80', fontWeight: 600, marginTop: 4 }}>
            {t('pricing2.firstPurchase')} ${plan.first_purchase_price.toFixed(2)}
          </div>
        )}
        {billedText && (
          <div style={{ fontSize: 12, color: 'var(--fg-3)', marginTop: 6, marginBottom: 20 }}>
            {billedText}
          </div>
        )}

        {/* CTA */}
        <button
          onClick={() => onSelect(plan)}
          disabled={isActive}
          style={{
            width: '100%', height: 48, borderRadius: 12, border: 'none',
            background: isActive ? 'rgba(255,255,255,0.06)' : `linear-gradient(135deg, var(--accent), var(--accent-2))`,
            color: isActive ? 'var(--fg-3)' : '#052028',
            fontSize: 15, fontWeight: 700, cursor: isActive ? 'default' : 'pointer',
            opacity: isActive ? 0.6 : 1,
            marginBottom: 22,
            letterSpacing: '0.01em',
          }}
        >
          {isActive ? t('pricing2.currentPlan') : t('pricing2.subscribe')}
        </button>

        {/* i18n sections from product.features[lang].sections */}
        {sections.map((sec, si) => (
          <React.Fragment key={si}>
            <div style={{ height: 1, background: 'var(--line)', margin: si === 0 ? '0 0 16px' : '12px 0 16px' }} />
            <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--fg-3)', letterSpacing: '0.1em', marginBottom: 10, textTransform: 'uppercase' }}>{sec.title}</div>
            {(sec.items || []).map((item, i) => <FeatureItem key={i} text={item} />)}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
};

// ─── Feature list item with check icon ──────────────────────────────────────
const FeatureItem = ({ text, highlight }) => (
  <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '6px 0' }}>
    <div style={{ flexShrink: 0, width: 18, height: 18, borderRadius: 999, background: highlight ? 'rgba(74,222,128,0.15)' : 'rgba(34,211,238,0.12)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginTop: 1 }}>
      <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke={highlight ? '#4ade80' : 'var(--accent)'} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
        <polyline points="20 6 9 17 4 12"/>
      </svg>
    </div>
    <span style={{ fontSize: 13, color: 'var(--fg-1)', lineHeight: 1.5 }}>{text}</span>
  </div>
);

// ─── Mobile single-card carousel for coin packages ──────────────────────────
const MobileCoinCarousel = ({ packages, onSelect }) => {
  const { t } = useI18n();
  const [idx, setIdx] = React.useState(0);
  React.useEffect(() => {
    const popularIdx = packages.findIndex(p => p.tag === 'popular');
    setIdx(popularIdx >= 0 ? popularIdx : Math.floor(packages.length / 2));
  }, [packages.length]);

  if (!packages.length) return null;
  const pkg = packages[idx];
  if (!pkg) return null;
  const hasBonus = pkg.bonus_coins > 0;
  const totalCoins = pkg.coins + (hasBonus ? pkg.bonus_coins : 0);
  const perCreditCents = totalCoins > 0 ? (pkg.amount / totalCoins * 100) : 0;
  const isPopular = pkg.tag === 'popular';
  const isRecommended = pkg.tag === 'recommended';

  // 与上一档比较省多少
  const prevPkg = packages[idx - 1];
  let savePct = 0;
  if (prevPkg && prevPkg.coins > 0 && pkg.coins > 0) {
    const prevPerCent = prevPkg.amount / (prevPkg.coins + (prevPkg.bonus_coins || 0));
    const curPerCent = pkg.amount / totalCoins;
    if (curPerCent < prevPerCent) {
      savePct = Math.round((1 - curPerCent / prevPerCent) * 100);
    }
  }

  // touch swipe
  const touchStart = React.useRef(null);
  const onTouchStart = e => { touchStart.current = e.touches[0].clientX; };
  const onTouchEnd = e => {
    if (touchStart.current == null) return;
    const dx = e.changedTouches[0].clientX - touchStart.current;
    if (Math.abs(dx) > 50) {
      if (dx < 0 && idx < packages.length - 1) setIdx(idx + 1);
      if (dx > 0 && idx > 0) setIdx(idx - 1);
    }
    touchStart.current = null;
  };

  const ArrowBtn = ({ dir, disabled }) => (
    <button
      onClick={() => setIdx(dir === 'left' ? Math.max(0, idx - 1) : Math.min(packages.length - 1, idx + 1))}
      disabled={disabled}
      style={{
        width: 36, height: 36, borderRadius: 999,
        border: '1px solid var(--line-2)',
        background: disabled ? 'transparent' : 'rgba(255,255,255,0.04)',
        color: disabled ? 'var(--fg-3)' : 'var(--fg-1)',
        cursor: disabled ? 'default' : 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        opacity: disabled ? 0.4 : 1,
      }}
      aria-label={dir === 'left' ? '上一个' : '下一个'}
    >
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ transform: dir === 'right' ? 'rotate(180deg)' : '' }}>
        <polyline points="15 18 9 12 15 6"/>
      </svg>
    </button>
  );

  return (
    <div style={{ maxWidth: 480, margin: '0 auto' }}>
      {/* Carousel control */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16, padding: '0 4px' }}>
        <ArrowBtn dir="left" disabled={idx === 0} />
        <div style={{ display: 'flex', gap: 6 }}>
          {packages.map((_, i) => (
            <button key={i} onClick={() => setIdx(i)} style={{
              width: i === idx ? 18 : 6, height: 6, borderRadius: 3,
              border: 'none', cursor: 'pointer',
              background: i === idx ? 'var(--accent)' : 'rgba(255,255,255,0.18)',
              transition: 'all .2s',
            }} aria-label={`套餐 ${i+1}`} />
          ))}
        </div>
        <ArrowBtn dir="right" disabled={idx === packages.length - 1} />
      </div>

      {/* Single card */}
      <div
        onTouchStart={onTouchStart}
        onTouchEnd={onTouchEnd}
        style={{
          borderRadius: 18, overflow: 'hidden',
          border: isPopular ? '1.5px solid var(--accent)' : '1px solid var(--line-2)',
          background: isPopular ? 'linear-gradient(180deg, rgba(34,211,238,0.04), rgba(255,255,255,0.02))' : 'rgba(255,255,255,0.02)',
          padding: '24px 22px',
        }}
      >
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 22, fontWeight: 700, color: 'var(--fg-0)', letterSpacing: '-0.02em' }}>
            {totalCoins.toLocaleString()} <span style={{ fontSize: 14, fontWeight: 400, color: 'var(--fg-3)' }}>{t('common.credits')}</span>
          </span>
          {isPopular && (
            <span style={{ fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 4, background: 'var(--accent)', color: '#052028', letterSpacing: '0.04em' }}>POPULAR</span>
          )}
          {isRecommended && (
            <span style={{ fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 4, background: 'rgba(167,139,250,0.15)', color: 'var(--accent-2)', border: '1px solid rgba(167,139,250,0.3)', letterSpacing: '0.04em' }}>RECOMMENDED</span>
          )}
          {savePct > 0 && (
            <span style={{ fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 4, background: 'rgba(167,139,250,0.15)', color: 'var(--accent-2)', border: '1px solid rgba(167,139,250,0.3)' }}>更划算 {savePct}%</span>
          )}
        </div>
        <div style={{ fontSize: 13, color: 'var(--fg-3)', marginBottom: 18 }}>
          {pkg.name || '一次性充值'}
        </div>

        {/* Price */}
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 4 }}>
          <span style={{ fontSize: 44, fontWeight: 800, color: 'var(--fg-0)', letterSpacing: '-0.03em', fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>
            ${pkg.amount.toFixed(2)}
          </span>
          <span style={{ fontSize: 13, color: 'var(--fg-3)', fontWeight: 500 }}>{pkg.currency || 'USD'}</span>
        </div>
        {totalCoins > 0 ? (
          <div style={{ fontSize: 12, color: 'var(--fg-3)', marginTop: 6, marginBottom: 20 }}>
            ≈ ${perCreditCents.toFixed(1)}¢ / 额度 · 一次性付款
          </div>
        ) : (
          <div style={{ fontSize: 12, color: 'var(--warn, #fbbf24)', marginTop: 6, marginBottom: 20 }}>⚠ 未配置额度数</div>
        )}

        {/* CTA */}
        <button
          onClick={() => onSelect(pkg)}
          style={{
            width: '100%', height: 48, borderRadius: 12, border: 'none',
            background: `linear-gradient(135deg, var(--accent), var(--accent-2))`,
            color: '#052028',
            fontSize: 15, fontWeight: 700, cursor: 'pointer',
            marginBottom: 22,
            letterSpacing: '0.01em',
          }}
        >
          {t('pricing2.buy')}
        </button>

        {/* CREDITS section */}
        <div style={{ height: 1, background: 'var(--line)', margin: '0 0 16px' }} />
        <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--fg-3)', letterSpacing: '0.1em', marginBottom: 10 }}>CREDITS</div>
        <FeatureItem text={`${pkg.coins.toLocaleString()} 基础额度`} />
        {hasBonus && <FeatureItem text={`+${pkg.bonus_coins.toLocaleString()} 赠送额度`} highlight />}

        {/* INCLUDES section */}
        <div style={{ height: 1, background: 'var(--line)', margin: '12px 0 16px' }} />
        <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--fg-3)', letterSpacing: '0.1em', marginBottom: 10 }}>INCLUDES</div>
        <FeatureItem text="即时到账，永久有效" />
        <FeatureItem text="无需订阅，按需购买" />
      </div>
    </div>
  );
};

// ─── Coin package card (整张卡可点击) ─────────────────────────────────────
const CoinCard = ({ pkg, onSelect }) => {
  const { t } = useI18n();
  const hasBonus = pkg.bonus_coins > 0;
  const totalCoins = pkg.coins + (hasBonus ? pkg.bonus_coins : 0);
  const perCreditCents = totalCoins > 0 ? (pkg.amount / totalCoins * 100) : 0;
  const disabled = totalCoins === 0;

  const handleClick = () => { if (!disabled) onSelect(pkg); };
  const handleKey = (e) => { if (!disabled && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); onSelect(pkg); } };

  return (
    <div
      role={disabled ? undefined : 'button'}
      tabIndex={disabled ? undefined : 0}
      onClick={handleClick}
      onKeyDown={handleKey}
      aria-disabled={disabled ? 'true' : undefined}
      aria-label={`${t('pricing2.buy')} ${totalCoins} ${t('common.credits')} - $${pkg.amount.toFixed(2)}`}
      className="yt-clickcard"
      style={{
        flex: 1, minWidth: 180, maxWidth: 240, borderRadius: 14, overflow: 'hidden',
        border: pkg.tag === 'popular' ? '2px solid var(--accent)' : '1px solid var(--line-2)',
        background: pkg.tag === 'popular' ? 'rgba(34,211,238,0.04)' : 'rgba(255,255,255,0.02)',
        display: 'flex', flexDirection: 'column', position: 'relative',
        cursor: disabled ? 'not-allowed' : 'pointer',
        opacity: disabled ? 0.6 : 1,
        transition: 'transform .12s, border-color .12s, background .12s',
      }}
    >
      {pkg.tag && (
        <div style={{ position: 'absolute', top: 10, right: 10, padding: '2px 8px', borderRadius: 4, fontSize: 10, fontWeight: 700,
          background: pkg.tag === 'popular' ? 'var(--accent)' : pkg.tag === 'recommended' ? '#a78bfa' : 'var(--fg-3)',
          color: '#052028',
        }}>{pkg.tag === 'popular' ? t('shared.badge.hot') : pkg.tag === 'recommended' ? t('pricing2.recommended') : pkg.tag.toUpperCase()}</div>
      )}
      <div style={{ padding: '22px 18px 18px', textAlign: 'center' }}>
        <div style={{ fontSize: 28, fontWeight: 700, color: 'var(--fg-0)', marginBottom: 4 }}>
          {totalCoins.toLocaleString()}
          <span style={{ fontSize: 14, fontWeight: 400, color: 'var(--fg-3)' }}> {t('common.credits')}</span>
        </div>
        {hasBonus && (
          <div style={{ fontSize: 12, color: '#4ade80', fontWeight: 600, marginBottom: 4 }}>{t('pricing2.includesBonus')} {pkg.bonus_coins.toLocaleString()}</div>
        )}
        <div style={{ fontSize: 22, fontWeight: 700, color: 'var(--accent)', marginTop: 8 }}>${pkg.amount.toFixed(2)}</div>
        {totalCoins > 0 ? (
          <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 4 }}>≈ ${perCreditCents.toFixed(1)}¢ {t('pricing2.perCredit')}</div>
        ) : (
          <div style={{ fontSize: 11, color: 'var(--warn, #fbbf24)', marginTop: 4 }}>⚠ 未配置额度数</div>
        )}
      </div>
    </div>
  );
};

// ─── Main screen ──────────────────────────────────────────────────────────────
const PricingScreen = () => {
  const { t } = useI18n();
  const { isMobile } = useBreakpoint();
  const [tab, setTab] = React.useState('plans'); // 'plans' | 'coins'
  const [plans, setPlans] = React.useState([]);
  const [coins, setCoins] = React.useState([]);
  const [activeSub, setActiveSub] = React.useState(null);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    Promise.all([
      window.YiteAPI?.subscription?.plans?.() || fetch('/api/v1/subscriptions/plans').then(r => r.json()),
      window.YiteAPI?.subscription?.coinPackages?.() || fetch('/api/v1/subscriptions/coin-packages').then(r => r.json()),
      window.YiteAPI?.isLoggedIn?.() ? (window.YiteAPI.subscription.active().catch(() => ({ subscription: null }))) : Promise.resolve({ subscription: null }),
    ]).then(([planRes, coinRes, subRes]) => {
      setPlans(planRes.items || []);
      setCoins(coinRes.items || []);
      setActiveSub(subRes.subscription || null);
      setLoading(false);
    }).catch(() => setLoading(false));
  }, []);

  const handleSelectPlan = plan => {
    if (!window.YiteAPI?.isLoggedIn?.()) { showLoginModal(); return; }
    if (plan.base_price === 0) return;
    window.location.href = '/checkout?plan_id=' + plan.id + '&combo=' + plan.type;
  };

  const handleSelectCoin = pkg => {
    if (!window.YiteAPI?.isLoggedIn?.()) { showLoginModal(); return; }
    window.location.href = '/checkout?coin_package_id=' + pkg.id;
  };

  const sortedPlans = [...plans].sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0));
  const sortedCoins = [...coins].sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0));

  return (
    <AppShell active="">
      <div style={{ overflowY: 'auto', height: '100%' }}>
        <div style={{ padding: isMobile ? '24px 16px 180px' : '40px 32px 80px' }}>

          {/* Header */}
          <div style={{ textAlign: 'center', marginBottom: isMobile ? 28 : 48 }}>
            <h1 style={{ fontSize: isMobile ? 24 : 36, fontWeight: 700, color: 'var(--fg-0)', margin: '0 0 8px', letterSpacing: '-0.02em' }}>{t('pricing2.chooseYourPlan')}</h1>
            <p style={{ fontSize: isMobile ? 13 : 16, color: 'var(--fg-2)', margin: 0 }}>{t('pricing2.description')}</p>
          </div>

          {/* Tab toggle */}
          <div style={{ display: 'flex', justifyContent: 'center', gap: 4, marginBottom: 40 }}>
            <div style={{ display: 'flex', borderRadius: 10, border: '1px solid var(--line-2)', overflow: 'hidden' }}>
              {[
                { id: 'plans', label: t('pricing2.plans') },
                { id: 'coins', label: t('pricing2.coins') },
              ].map(tb => (
                <button key={tb.id} onClick={() => setTab(tb.id)} style={{
                  height: isMobile ? 36 : 40, padding: isMobile ? '0 18px' : '0 24px', border: 'none', cursor: 'pointer',
                  fontSize: isMobile ? 13 : 14, fontWeight: tab === tb.id ? 600 : 400,
                  background: tab === tb.id ? 'rgba(34,211,238,0.1)' : 'transparent',
                  color: tab === tb.id ? 'var(--fg-0)' : 'var(--fg-3)',
                }}>{tb.label}</button>
              ))}
            </div>
          </div>

          {loading ? (
            <div style={{ display: 'flex', justifyContent: 'center', padding: 60 }}><div className="yt-spinner" style={{ width: 32, height: 32 }} /></div>
          ) : tab === 'plans' ? (
            /* ── Subscription plans ── */
            <div>
              {sortedPlans.length > 0 ? (
                isMobile ? (
                  <MobilePlanCarousel plans={sortedPlans} activeSubId={activeSub?.plan_id} onSelect={handleSelectPlan} />
                ) : (
                  <div style={{ maxWidth: 1200, margin: '0 auto' }}>
                    <div style={{ display: 'flex', flexDirection: 'row', gap: 16, justifyContent: 'center', flexWrap: 'wrap', alignItems: 'flex-start' }}>
                      {sortedPlans.map(p => (
                        <div key={p.id}>
                          <PlanCard plan={p} isActive={activeSub?.plan_id === p.id} onSelect={handleSelectPlan} />
                        </div>
                      ))}
                    </div>
                  </div>
                )
              ) : (
                <div style={{ textAlign: 'center', padding: 60, color: 'var(--fg-3)' }}>
                  <div style={{ fontSize: 15 }}>{t('pricing2.noPlans')}</div>
                  <div style={{ fontSize: 13, marginTop: 8 }}>{t('pricing2.configPlans')}</div>
                </div>
              )}

              {/* Active subscription info */}
              {activeSub && (
                <div style={{ maxWidth: 500, margin: '32px auto 0', padding: '16px 20px', borderRadius: 12, border: '1px solid rgba(74,222,128,0.3)', background: 'rgba(74,222,128,0.06)', textAlign: 'center' }}>
                  <div style={{ fontSize: 14, color: '#4ade80', fontWeight: 600, marginBottom: 4 }}>{t('pricing2.activeSubscription')}</div>
                  <div style={{ fontSize: 13, color: 'var(--fg-3)' }}>
                    {t('pricing2.expiryDate')}{new Date(activeSub.expires_at).toLocaleDateString()} · {t('pricing2.paid')}${activeSub.paid_amount} {activeSub.currency}
                  </div>
                </div>
              )}
            </div>
          ) : (
            /* ── Coin packages ── */
            <div>
              {sortedCoins.length > 0 ? (
                isMobile ? (
                  <MobileCoinCarousel packages={sortedCoins} onSelect={handleSelectCoin} />
                ) : (
                  <div style={{ maxWidth: 1200, margin: '0 auto' }}>
                    <div style={{ display: 'flex', flexDirection: 'row', gap: 16, justifyContent: 'center', flexWrap: 'wrap', alignItems: 'flex-start' }}>
                      {sortedCoins.map(p => (
                        <div key={p.id}>
                          <CoinCard pkg={p} onSelect={handleSelectCoin} />
                        </div>
                      ))}
                    </div>
                  </div>
                )
              ) : (
                <div style={{ textAlign: 'center', padding: 60, color: 'var(--fg-3)' }}>
                  <div style={{ fontSize: 15 }}>{t('pricing2.noCoins')}</div>
                  <div style={{ fontSize: 13, marginTop: 8 }}>{t('pricing2.configCoins')}</div>
                </div>
              )}
            </div>
          )}

          {/* FAQ / Contact */}
          <div style={{ marginTop: 80, padding: isMobile ? '24px 20px' : 36, borderRadius: 18, background: 'linear-gradient(135deg, rgba(34,211,238,0.06), rgba(167,139,250,0.04))', border: '1px solid rgba(34,211,238,0.2)', textAlign: 'center' }}>
            <h3 style={{ fontSize: isMobile ? 18 : 22, fontWeight: 600, margin: '0 0 8px', color: 'var(--fg-0)' }}>{t('pricing2.customSolution')}</h3>
            <p style={{ fontSize: 14, color: 'var(--fg-2)', margin: '0 0 20px', maxWidth: 480, marginInline: 'auto' }}>{t('pricing2.enterpriseDesc')}</p>
            <a href="mailto:business@yiteai.com" className="yt-btn yt-btn-primary" style={{ height: 42, padding: '0 22px', textDecoration: 'none' }}>{t('pricing2.contactUs')}</a>
          </div>
        </div>
      </div>
    </AppShell>
  );
};

Object.assign(window, { PricingScreen });
