// quota_provider.dart — 免费版每日额度状态(Riverpod)
//
// 设计约定(design/CLAUDE.md §7 / §2):免费额度权威在服务端。
// 总额度取自 plans 的 free.daily_minutes,今日剩余取自 me.quota_today_min
// (后端已算好 = 上限 − 今日已用)。adUnlocked 为本地会话态(看广告需 ad SDK,
// 尚未接入,保留本地乐观置位)。
import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'account_providers.dart';

/// 免费额度快照。
class FreeQuotaState {
  const FreeQuotaState({
    this.totalMinutes = 10,
    this.remainingMinutes = 10,
    this.adUnlocked = false,
  });

  /// 每日总额度(分钟)。§7:免费版每日 10 分钟。
  final int totalMinutes;

  /// 今日剩余分钟(展示值,权威以服务端为准)。
  final int remainingMinutes;

  /// 今日是否已观看激励视频解锁。
  final bool adUnlocked;

  /// 进度(0–1),用于进度条宽度。
  double get progress =>
      totalMinutes == 0 ? 0 : (remainingMinutes / totalMinutes).clamp(0.0, 1.0);

  /// 是否进入低额度警示(≤3 分钟切 warning 色)。
  bool get isLow => remainingMinutes <= 3;

  FreeQuotaState copyWith({int? totalMinutes, int? remainingMinutes, bool? adUnlocked}) =>
      FreeQuotaState(
        totalMinutes: totalMinutes ?? this.totalMinutes,
        remainingMinutes: remainingMinutes ?? this.remainingMinutes,
        adUnlocked: adUnlocked ?? this.adUnlocked,
      );
}

class QuotaController extends StateNotifier<FreeQuotaState> {
  QuotaController(this._ref) : super(const FreeQuotaState()) {
    _sync();
    // me / plans 任一就绪或变化都重算。
    _ref.listen(meProvider, (_, __) => _sync());
    _ref.listen(plansProvider, (_, __) => _sync());
  }

  final Ref _ref;

  void _sync() {
    final me = _ref.read(meProvider).valueOrNull;
    final plans = _ref.read(plansProvider).valueOrNull;
    var total = 10; // §7 默认免费 10 分钟,plans 就绪后以其为准
    if (plans != null) {
      for (final p in plans) {
        if (p.code == 'free' && p.dailyMinutes != null) total = p.dailyMinutes!;
      }
    }
    final remaining = (me?.quotaTodayMin ?? total).clamp(0, total);
    state = state.copyWith(totalMinutes: total, remainingMinutes: remaining);
  }

  /// 观看激励视频后解锁今日使用(本地乐观;真实 ad 校验待 ad SDK 接入)。
  void watchAd() => state = state.copyWith(adUnlocked: true);
}

final quotaProvider = StateNotifierProvider<QuotaController, FreeQuotaState>(
  (ref) => QuotaController(ref),
);
