/// 结账 SKU（买断 / 订阅 / 单次）— © 2026 Jason Li（泽森）
/// 权益档仍见 [ProductTier]；本枚举描述「怎么付」。
library;

import '../config/app_config.dart';
import '../l10n/l10n.dart';
import 'tiers.dart';

/// 可购买的结账条目
enum BillingSku {
  /// 专业板买断
  proLifetime,

  /// 键共振买断（全价；若已有专业板则结账用升级价）
  masterLifetime,

  /// 键共振月订阅
  masterMonthly,

  /// 键共振年订阅
  masterYearly,

  /// 单次判局通行证（24h，解锁判局/导出）
  singleJudgment,
}

extension BillingSkuX on BillingSku {
  ProductTier get grantsTier => switch (this) {
        BillingSku.proLifetime => ProductTier.pro,
        BillingSku.masterLifetime ||
        BillingSku.masterMonthly ||
        BillingSku.masterYearly =>
          ProductTier.resonanceMaster,
        BillingSku.singleJudgment => ProductTier.free, // 临时权益，不升档
      };

  bool get isSubscription =>
      this == BillingSku.masterMonthly || this == BillingSku.masterYearly;

  bool get isSinglePass => this == BillingSku.singleJudgment;

  String get productId => switch (this) {
        BillingSku.proLifetime => 'kr_pro_499',
        BillingSku.masterLifetime => 'kr_resonance_2499',
        BillingSku.masterMonthly => 'kr_resonance_mo_999',
        BillingSku.masterYearly => 'kr_resonance_yr_7900',
        BillingSku.singleJudgment => 'kr_single_judgment_199',
      };

  /// 标价美分（升级抵扣见 [checkoutCents]）
  int get listPriceCents => switch (this) {
        BillingSku.proLifetime => AppConfig.pricesUsdCents[ProductTier.pro]!,
        BillingSku.masterLifetime =>
          AppConfig.pricesUsdCents[ProductTier.resonanceMaster]!,
        BillingSku.masterMonthly => AppConfig.masterMonthlyUsdCents,
        BillingSku.masterYearly => AppConfig.masterYearlyUsdCents,
        BillingSku.singleJudgment => AppConfig.singleJudgmentUsdCents,
      };

  /// 实际结账美分：已拥有专业板买键共振买断时只补差价
  int checkoutCents({required ProductTier ownedTier}) {
    if (this == BillingSku.masterLifetime &&
        ownedTier == ProductTier.pro) {
      return AppConfig.masterUpgradeFromProUsdCents;
    }
    return listPriceCents;
  }

  String priceLabel({
    required AppLang lang,
    required ProductTier ownedTier,
  }) {
    final cents = checkoutCents(ownedTier: ownedTier);
    final usd = '\$${(cents / 100).toStringAsFixed(2)}';
    final suffix = switch (this) {
      BillingSku.masterMonthly => switch (lang) {
          AppLang.zh => '/月',
          AppLang.ja => '/月',
          _ => '/mo',
        },
      BillingSku.masterYearly => switch (lang) {
          AppLang.zh => '/年',
          AppLang.ja => '/年',
          _ => '/yr',
        },
      BillingSku.singleJudgment => switch (lang) {
          AppLang.zh => ' · 24小时',
          AppLang.ja => ' · 24時間',
          _ => ' · 24h',
        },
      _ => '',
    };
    final upgradeNote = this == BillingSku.masterLifetime &&
            ownedTier == ProductTier.pro
        ? switch (lang) {
            AppLang.zh => '（专业板已抵扣）',
            AppLang.ja => '（専門板差引）',
            AppLang.es => ' (crédito Pro)',
            AppLang.ar => ' (رصيد Pro)',
            AppLang.en => ' (Pro credit)',
          }
        : '';
    if (lang == AppLang.zh) {
      final yuan = switch (this) {
        BillingSku.proLifetime => AppConfig.pricesCnyYuan[ProductTier.pro],
        BillingSku.masterLifetime => ownedTier == ProductTier.pro
            ? AppConfig.masterUpgradeFromProCnyYuan
            : AppConfig.pricesCnyYuan[ProductTier.resonanceMaster],
        BillingSku.masterMonthly => AppConfig.masterMonthlyCnyYuan,
        BillingSku.masterYearly => AppConfig.masterYearlyCnyYuan,
        BillingSku.singleJudgment => AppConfig.singleJudgmentCnyYuan,
      };
      if (yuan != null) {
        return '$usd$suffix（约¥$yuan）$upgradeNote';
      }
    }
    return '$usd$suffix$upgradeNote';
  }

  String titleOf(AppLang lang) => switch (this) {
        BillingSku.proLifetime => ProductTier.pro.labelOf(lang),
        BillingSku.masterLifetime => switch (lang) {
            AppLang.zh => '键共振 · 买断',
            AppLang.ja => 'キー共鳴 · 買い切り',
            AppLang.es => 'Resonancia · permanente',
            AppLang.ar => 'رنين · دائم',
            AppLang.en => 'Key Resonance · lifetime',
          },
        BillingSku.masterMonthly => switch (lang) {
            AppLang.zh => '键共振 · 月订阅',
            AppLang.ja => 'キー共鳴 · 月額',
            AppLang.es => 'Resonancia · mensual',
            AppLang.ar => 'رنين · شهري',
            AppLang.en => 'Key Resonance · monthly',
          },
        BillingSku.masterYearly => switch (lang) {
            AppLang.zh => '键共振 · 年订阅',
            AppLang.ja => 'キー共鳴 · 年額',
            AppLang.es => 'Resonancia · anual',
            AppLang.ar => 'رنين · سنوي',
            AppLang.en => 'Key Resonance · yearly',
          },
        BillingSku.singleJudgment => switch (lang) {
            AppLang.zh => '单次判局通行证',
            AppLang.ja => '単回判局パス',
            AppLang.es => 'Pase de juicio (24h)',
            AppLang.ar => 'تصريح حكم (24س)',
            AppLang.en => 'Single judgment pass',
          },
      };

  String valuePropOf(AppLang lang) => switch (this) {
        BillingSku.proLifetime => TierPolicy.valuePropOf(ProductTier.pro, lang),
        BillingSku.masterLifetime => TierPolicy.valuePropOf(
              ProductTier.resonanceMaster,
              lang,
            ),
        BillingSku.masterMonthly => switch (lang) {
            AppLang.zh =>
              '月订阅：键共振全功能（含专业板）按月续费；可随时取消。适合先试用深度模型。',
            AppLang.ja => '月額：キー共鳴全機能（専門板含む）。いつでも解約可。',
            AppLang.es =>
              'Mensual: Resonancia completa (incluye Pro). Cancele cuando quiera.',
            AppLang.ar => 'شهري: رنين كامل (يشمل الاحترافي). إلغاء في أي وقت.',
            AppLang.en =>
              'Monthly: full Key Resonance (includes Pro). Cancel anytime.',
          },
        BillingSku.masterYearly => switch (lang) {
            AppLang.zh =>
              '年订阅：键共振全功能；约合月费更低，适合长期研究命盘与导出命书。',
            AppLang.ja => '年額：キー共鳴全機能。月額よりお得。長期研究向け。',
            AppLang.es =>
              'Anual: Resonancia completa; mejor precio/mes para uso continuo.',
            AppLang.ar => 'سنوي: رنين كامل بسعر أفضل للشهر.',
            AppLang.en =>
              'Yearly: full Key Resonance at a lower effective monthly rate.',
          },
        BillingSku.singleJudgment => switch (lang) {
            AppLang.zh =>
              '24 小时内解锁结构化判局全文与 Markdown 导出；不升档。适合只看这一次。',
            AppLang.ja => '24時間：判局全文と Markdown 出力を解除（ランクは上がりません）。',
            AppLang.es =>
              '24h: juicio estructurado + export Markdown. No sube de plan.',
            AppLang.ar => '24س: الحكم المنظم وتصدير Markdown دون ترقية الخطة.',
            AppLang.en =>
              '24h unlock of structured judgment + Markdown export. Does not raise tier.',
          },
      };
}
