ソースコード source code

下記アプリの主要なソースコードを公開しています。アプリ開発の参考になれば幸いです。

画像等が別途必要ですので下記情報のみでアプリが完成するものではありません。 アプリは少しずつ機能拡張していますのでストア公開されているアプリと内容が異なる場合があります。 コードはコピーして自由にお使いいただけます。ただし著作権は放棄しておりませんので全部の再掲載はご遠慮ください。部分的に再掲載したり、改変して再掲載するのは構いません。 自身のアプリ作成の参考として個人使用・商用問わず自由にお使いいただけます。 コード記述のお手本を示すものではありません。ミニアプリですので変数名などさほど気遣いしていない部分も有りますし間違いも有るかと思いますので参考程度にお考え下さい。 他の賢者の皆様が公開されているコードを参考にした箇所も含まれます。Flutter開発の熟練者が書いたコードではありません。 エンジニア向け技術情報共有サービスではありませんので説明は省いています。 GitHubなどへの公開は予定しておりません。

下記コードの最終ビルド日: 2025-10-15

name: roulette
description: "Roulette"
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 2.3.1+35

environment:
  sdk: ^3.9.2

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  shared_preferences: ^2.5.2
  flutter_localizations:    # flutter gen-l10n
    sdk: flutter
  intl: ^0.20.2
  google_mobile_ads: ^6.0.0
  flutter_tts: ^4.0.2
  just_audio: ^0.10.4
  equatable: ^2.0.7
  collection: ^1.18.0

dev_dependencies:
  flutter_test:
    sdk: flutter

  flutter_launcher_icons: ^0.14.3    #flutter pub run flutter_launcher_icons
  flutter_native_splash: ^2.3.6     #flutter pub run flutter_native_splash:create

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^6.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

flutter_icons:
  android: "launcher_icon"
  ios: true
  image_path: "assets/icon/icon.png"
  adaptive_icon_background: "assets/icon/icon_back.png"
  adaptive_icon_foreground: "assets/icon/icon_fore.png"

flutter_native_splash:
  color: '#9da9f5'
  image: 'assets/image/splash.png'
  color_dark: '#9da9f5'
  image_dark: 'assets/image/splash.png'
  fullscreen: true
  android_12:
    icon_background_color: '#9da9f5'
    image: 'assets/image/splash.png'
    icon_background_color_dark: '#9da9f5'
    image_dark: 'assets/image/splash.png'

# The following section is specific to Flutter packages.
flutter:
  generate: true

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  assets:
    - assets/image/

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/to/resolution-aware-images

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/to/asset-from-package

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/to/font-from-package
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:google_mobile_ads/google_mobile_ads.dart';

import 'package:roulette/ad_manager.dart';

class AdBannerWidget extends StatefulWidget {
  final AdManager adManager;
  const AdBannerWidget({super.key, required this.adManager});
  @override
  State<AdBannerWidget> createState() => _AdBannerWidgetState();
}

class _AdBannerWidgetState extends State<AdBannerWidget> {
  int _lastBannerWidthDp = 0;
  bool _isAdLoaded = false;
  bool _isLoading = false;
  @override
  Widget build(BuildContext context) {
    if (kIsWeb) {
      return const SizedBox.shrink();
    }
    return SafeArea(
      child: LayoutBuilder(
        builder: (context, constraints) {
          final int width = constraints.maxWidth.isFinite
              ? constraints.maxWidth.truncate()
              : MediaQuery.of(context).size.width.truncate();
          final bannerAd = widget.adManager.bannerAd;
          if (width > 0) {
            WidgetsBinding.instance.addPostFrameCallback((_) {
              if (mounted) {
                final bannerAd = widget.adManager.bannerAd;
                final bool widthChanged = _lastBannerWidthDp != width;
                final bool sizeMismatch =
                    bannerAd == null || bannerAd.size.width != width;
                if ((widthChanged || !_isAdLoaded || sizeMismatch) &&
                    !_isLoading) {
                  _lastBannerWidthDp = width;
                  setState(() {
                    _isAdLoaded = false;
                    _isLoading = true;
                  });
                  widget.adManager.loadAdaptiveBannerAd(width, () {
                    if (mounted) {
                      setState(() {
                        _isAdLoaded = true;
                        _isLoading = false;
                      });
                    }
                  });
                }
              }
            });
          }
          if (_isAdLoaded && bannerAd != null) {
            return Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const SizedBox(height: 10),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    SizedBox(
                      width: bannerAd.size.width.toDouble(),
                      height: bannerAd.size.height.toDouble(),
                      child: AdWidget(ad: bannerAd),
                    ),
                  ],
                ),
              ],
            );
          } else {
            return const SizedBox.shrink();
          }
        },
      ),
    );
  }
}
/*
 *	mainへの記述
 *	void main() async {
 *		WidgetsFlutterBinding.ensureInitialized();
 *		if (!kIsWeb) {
 *			//AdMob初期化
 *			MobileAds.instance.initialize();
 *			//NPAポリシーの集中設定(将来拡張もここで) 現時点は使用していないので記述しなくても良い
 *			await AdManager.initForNPA();
 *		}
 *		runApp(const MyApp());
 *	}
 */

import 'dart:async';
import 'dart:io' show Platform;
import 'dart:ui';

import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:google_mobile_ads/google_mobile_ads.dart';

class AdManager {
  //Test IDs
  //static const String _androidAdUnitId = "ca-app-pub-3940256099942544/6300978111";
  //static const String _iosAdUnitId     = "ca-app-pub-3940256099942544/2934735716";

  //Production IDs
  static const String _androidAdUnitId = "ca-app-pub-0/0";
  static const String _iosAdUnitId     = "ca-app-pub-0/0";

  static String get _adUnitId => Platform.isIOS ? _iosAdUnitId : _androidAdUnitId;

  BannerAd? _bannerAd;
  int _lastWidthPx = 0;
  VoidCallback? _onLoadedCb;
  Timer? _retryTimer;
  int _retryAttempt = 0;

  BannerAd? get bannerAd => _bannerAd;

  //(任意)アプリ起動時などに呼ぶ。将来のCMP/NPA関連設定を集中管理。
  static Future<void> initForNPA() async {
    if (kIsWeb) {
      return;
    }
    //ここでグローバルなRequestConfigurationを設定しておく(必要に応じて拡張)
    await MobileAds.instance.updateRequestConfiguration(
      RequestConfiguration(
        //例:最大コンテンツレーティング等を付けたい場合はここに追加
        //maxAdContentRating: MaxAdContentRating.g,	//例
        //tagForChildDirectedTreatment: TagForChildDirectedTreatment.unspecified,
        //tagForUnderAgeOfConsent: TagForUnderAgeOfConsent.unspecified,
      ),
    );
  }

  Future<void> loadAdaptiveBannerAd(
    int widthPx,
    VoidCallback onAdLoaded,
  ) async {
    if (kIsWeb) {
      return;
    }
    _onLoadedCb = onAdLoaded;
    _lastWidthPx = widthPx;
    _retryAttempt = 0;
    _retryTimer?.cancel();
    _startLoad(widthPx);
  }

  Future<void> _startLoad(int widthPx) async {
    if (kIsWeb) {
      return;
    }
    _bannerAd?.dispose();

    AnchoredAdaptiveBannerAdSize? adaptiveSize;
    try {
      adaptiveSize =
          await AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(
            widthPx,
          );
    } catch (_) {
      adaptiveSize = null;
    }
    final AdSize size = adaptiveSize ?? AdSize.fullBanner;

    //常にNPAで配信(CMP対応)
    const adRequest = AdRequest(
      nonPersonalizedAds: true,	//NPA Non-Personalized Ads(非パーソナライズ広告)指定
    );

    _bannerAd = BannerAd(
      adUnitId: _adUnitId,
      request: adRequest,
      size: size,
      listener: BannerAdListener(
        onAdLoaded: (ad) {
          _retryTimer?.cancel();
          _retryAttempt = 0;
          final cb = _onLoadedCb;
          if (cb != null) {
            cb();
          }
        },
        onAdFailedToLoad: (ad, err) {
          ad.dispose();
          _scheduleRetry();
        },
      ),
    )..load();
  }

  void _scheduleRetry() {
    if (kIsWeb) {
      return;
    }
    _retryTimer?.cancel();
    // Exponential backoff: 3s, 6s, 12s, max 30s
    _retryAttempt = (_retryAttempt + 1).clamp(1, 5);
    final seconds = _retryAttempt >= 4 ? 30 : (3 << (_retryAttempt - 1));
    _retryTimer = Timer(Duration(seconds: seconds), () {
      _startLoad(_lastWidthPx > 0 ? _lastWidthPx : 320);
    });
  }

  void dispose() {
    _bannerAd?.dispose();
    _retryTimer?.cancel();
  }
}

/*
広告配信について
本アプリでは、Google AdMob を利用して広告を表示しています。
当アプリの広告はすべて「非パーソナライズ広告(NPA)」として配信しており、ユーザーの行動履歴や個人情報をもとにしたパーソナライズは一切行っていません。
Google AdMob によって、広告の表示のために以下の情報が利用される場合があります:
- 端末情報(例:OSの種類、画面サイズなど)
- おおまかな位置情報(国・地域レベル)
これらの情報は、パーソナライズを目的としたトラッキングやプロファイリングには使用されません。
詳しくは、Google のプライバシーポリシーをご覧ください:
https://policies.google.com/privacy


Advertising
This app uses Google AdMob to display advertisements.
All ads in this app are served as non-personalized ads (NPA).
This means that we do not use personal data or user behavior information to personalize the ads you see.
Google AdMob may use certain information in order to display ads properly, such as:
- Device information (e.g., OS type, screen size)
- Approximate location information (country/region level)
This information is not used for tracking or profiling for advertising purposes.
For more details, please refer to Google Privacy Policy:
https://policies.google.com/privacy
*/
/*
  CMP(Consent Management Platform)「同意管理プラットフォーム」
  UMP とは、Google AdMobでGDPRの同意を取得するために使用されるライブラリ User Messaging Platform (UMP) SDK

  ad_manager.dart で NPA Non-Personalized Ads(非パーソナライズ広告)指定 している。

  必要な変数
  late final UmpConsentController _adUmp;
  AdUmpState _adUmpState = AdUmpState.initial;

  @override
  void initState() {
    super.initState();
    _adUmp = UmpConsentController();
    _refreshConsentInfo();
  }

  必要な関数
  Future<void> _refreshConsentInfo() async {
    _adUmpState = await _adUmp.updateConsentInfo(current: _adUmpState);
    if (mounted) {
      setState(() {});
    }
  }
  Future<void> _onTapPrivacyOptions() async {
    final err = await _adUmp.showPrivacyOptions();
    await _refreshConsentInfo();
    if (err != null && mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('プライバシー設定画面を表示できませんでした: ${err.message}')),
      );
    }
  }
 */

import 'dart:async';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:flutter/widgets.dart';

import 'package:roulette/l10n/app_localizations.dart';

/// UMP状態格納用
class AdUmpState {
  final PrivacyOptionsRequirementStatus privacyStatus;
  final ConsentStatus consentStatus;
  final bool privacyOptionsRequired;
  final bool isChecking;
  const AdUmpState({
    required this.privacyStatus,
    required this.consentStatus,
    required this.privacyOptionsRequired,
    required this.isChecking,
  });

  AdUmpState copyWith({
    PrivacyOptionsRequirementStatus? privacyStatus,
    ConsentStatus? consentStatus,
    bool? privacyOptionsRequired,
    bool? isChecking,
  }) {
    return AdUmpState(
      privacyStatus: privacyStatus ?? this.privacyStatus,
      consentStatus: consentStatus ?? this.consentStatus,
      privacyOptionsRequired:
      privacyOptionsRequired ?? this.privacyOptionsRequired,
      isChecking: isChecking ?? this.isChecking,
    );
  }

  static const initial = AdUmpState(
    privacyStatus: PrivacyOptionsRequirementStatus.unknown,
    consentStatus: ConsentStatus.unknown,
    privacyOptionsRequired: false,
    isChecking: false,
  );
}

//UMPコントローラ
class UmpConsentController {
  //デバッグ用:EEA地域を強制するか(本番ではfalseにすること)
  final bool forceEeaForDebug = false;
  //埋め込みのテストデバイスID
  static const List<String> _testDeviceIds = [
    '608970392F100B87D62A1174996C952C', //arrows We2 (M07)
  ];

  ConsentRequestParameters _buildParams() {
    if (forceEeaForDebug && _testDeviceIds.isNotEmpty) {
      return ConsentRequestParameters(
        consentDebugSettings: ConsentDebugSettings(
          debugGeography: DebugGeography.debugGeographyEea,
          testIdentifiers: _testDeviceIds,
        ),
      );
    }
    return ConsentRequestParameters();
  }

  //同意情報を更新して状態を返す
  Future<AdUmpState> updateConsentInfo({AdUmpState current = AdUmpState.initial}) async {
    if (kIsWeb) return current;
    var state = current.copyWith(isChecking: true);

    try {
      final params = _buildParams();
      final completer = Completer<AdUmpState>();

      ConsentInformation.instance.requestConsentInfoUpdate(
        params,
            () async {
          final s = await ConsentInformation.instance.getPrivacyOptionsRequirementStatus();
          final c = await ConsentInformation.instance.getConsentStatus();
          completer.complete(
            state.copyWith(
              privacyStatus: s,
              consentStatus: c,
              privacyOptionsRequired: s == PrivacyOptionsRequirementStatus.required,
              isChecking: false,
            ),
          );
        },
            (FormError e) {
          completer.complete(
            state.copyWith(
              privacyStatus: PrivacyOptionsRequirementStatus.unknown,
              consentStatus: ConsentStatus.unknown,
              privacyOptionsRequired: false,
              isChecking: false,
            ),
          );
        },
      );

      state = await completer.future;
      return state;
    } catch (_) {
      return state.copyWith(isChecking: false);
    }
  }

  //プライバシーオプションフォームを表示
  Future<FormError?> showPrivacyOptions() async {
    if (kIsWeb) return null;
    final completer = Completer<FormError?>();
    ConsentForm.showPrivacyOptionsForm((FormError? e) {
      completer.complete(e);
    });
    return completer.future;
  }
}

extension ConsentStatusL10n on ConsentStatus {
  String localized(BuildContext context) {
    final l = AppLocalizations.of(context)!;
    switch (this) {
      case ConsentStatus.obtained:
        return l.cmpConsentStatusObtained;
      case ConsentStatus.required:
        return l.cmpConsentStatusRequired;
      case ConsentStatus.notRequired:
        return l.cmpConsentStatusNotRequired;
      case ConsentStatus.unknown:
        return l.cmpConsentStatusUnknown;
    }
  }
}

class ConstValue {
  ConstValue._();

  static const String prefItemName = 'itemName';  //0-19 e.g. itemName5
  static const String prefItemRate = 'itemRate';  //0-19
  static const String prefItemSplit= 'itemSplit';
  static const String prefFixBackColor = 'fixBackColor';
  static const String prefRotationTime = 'rotationTime';
  static const String prefRotationShort = 'rotationShort';
  static const String prefTextSizeAdjustResult = 'textSizeAdjustResult';
  static const String prefTextSizeAdjustRoulette = 'textSizeAdjustRoulette';
  static const String prefTtsEnabled = 'ttsEnabled';
  static const String prefTtsVoiceId = 'ttsVoiceId';
  static const String prefTtsVolume = 'ttsVolume';
  static const String prefThemeNumber = 'themeNumber';    // 0|1|2
  static const String prefLanguageCode = 'languageCode';  // e.g. ja

}
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';

import 'package:roulette/preferences.dart';
import 'package:roulette/text_to_speech.dart';
import 'package:roulette/l10n/app_localizations.dart';
import 'package:roulette/ad_manager.dart';
import 'package:roulette/ad_banner_widget.dart';
import 'package:roulette/roulette_painter.dart';
import 'package:roulette/setting_page.dart';
import 'package:roulette/theme_mode_number.dart';
import 'package:roulette/three_phase_roulette_curve.dart';
import 'package:roulette/roulette_item.dart';
import 'package:roulette/main.dart';
import 'package:roulette/parse_locale_tag.dart';
import 'package:roulette/loading_screen.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _animation;
  String? _rouletteResult;
  String? _currentItemName;
  Color? _currentBackgroundColor;
  final _random = Random();
  final Color _fixedBgColor = const Color(0xFFaaaaaa);
  late AdManager _adManager;
  bool _isReady = false;

  // Roulette Colors from CustomSurfaceView.kt
  final List<Color> _rouletteColors = [
    const Color.fromARGB(255, 234, 123, 132),
    const Color.fromARGB(255, 240, 196, 123),
    const Color.fromARGB(255, 247, 239, 123),
    const Color.fromARGB(255, 192, 217, 139),
    const Color.fromARGB(255, 123, 197, 156),
    const Color.fromARGB(255, 123, 201, 235),
    const Color.fromARGB(255, 123, 173, 211),
    const Color.fromARGB(255, 138, 139, 189),
    const Color.fromARGB(255, 194, 127, 186),
    const Color.fromARGB(255, 233, 123, 185),
  ];

  final List<Color> _rouletteDarkColors = [
    const Color.fromARGB(255, 222, 0, 17),
    const Color.fromARGB(255, 234, 145, 0),
    const Color.fromARGB(255, 247, 232, 0),
    const Color.fromARGB(255, 137, 188, 30),
    const Color.fromARGB(255, 0, 147, 66),
    const Color.fromARGB(255, 0, 154, 225),
    const Color.fromARGB(255, 0, 101, 176),
    const Color.fromARGB(255, 28, 31, 131),
    const Color.fromARGB(255, 140, 7, 126),
    const Color.fromARGB(255, 220, 0, 123),
  ];

  @override
  void initState() {
    super.initState();
    _initState();
  }

  void _initState() async {
    super.initState();
    _adManager = AdManager();
    _animationController =
    AnimationController(vsync: this, duration: const Duration(seconds: 10))
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          _determineWinner();
        }
      });
    _animation = Tween<double>(begin: 0, end: 360 * 30).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: Curves.easeInOutCubic, // Dummy curve, will be replaced in _onClickStart
      ),
    );
    _updateColorAndItemNameForAngle(0.0); // Set initial color and item name
    _applyTts();
    setState(() {
      _isReady = true;
    });
  }

  @override
  void dispose() {
    _animationController.dispose();
    TextToSpeech.stop();
    _adManager.dispose();
    super.dispose();
  }

  Future<void> _applyTts() async {
    await TextToSpeech.getInstance();
    await TextToSpeech.setTtsVoiceId(Preferences.ttsVoiceId);
    await TextToSpeech.setVolume(Preferences.ttsVolume);
  }

  void _onClickSetting() async {
    final updatedSettings = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => SettingScreen(),
      ),
    );
    if (updatedSettings != null) {
      _updateColorAndItemNameForAngle(_animation.value);
      if (mounted) {
        _applyTts();
        //
        final mainState = context.findAncestorStateOfType<MyAppState>();
        if (mainState != null) {  //MyAppStateに反映する
          mainState
            ..locale = parseLocaleTag(Preferences.languageCode)
            ..themeMode = ThemeModeNumber.numberToThemeMode(Preferences.themeNumber)
            ..setState(() {});
        }
      }
    }
  }

  void _onClickStart() {
    setState(() {
      _rouletteResult = null; // Clear previous result
      _currentItemName = '...';
    });
    // Define animation phases duration
    final double scale = Preferences.rotationShort ? 0.1 : 1.0;
    final double easeInDuration = 1.0 * scale;
    final double easeOutDuration = 8.0 * scale;
    final double linearDuration = Preferences.rotationTime * scale;
    final double totalDuration = easeInDuration + linearDuration + easeOutDuration;
    _animationController.duration = Duration(
      milliseconds: (totalDuration * 1000).round(),
    );
    // Adjust rotation amount based on duration to keep speed consistent
    const double baseEaseIn = 1.0;
    const double baseLinearDuration = 5.0; // Default linear duration
    const double baseEaseOut = 8.0;
    const double baseTotalDuration =
        baseEaseIn + baseLinearDuration + baseEaseOut;
    const double baseRotationAmount =
        360 * 28; // A base rotation amount for the base duration
    final double targetRotationAmount =
        baseRotationAmount * (totalDuration / baseTotalDuration);
    // Add a bit of randomness to the final position
    final double randomExtraRotation =
        360 * (_random.nextDouble() - 0.5); // +/- 180 degrees
    final double beginAngle = _animation.value;
    final double endAngle = beginAngle + targetRotationAmount + randomExtraRotation;
    _animation = Tween<double>(begin: beginAngle, end: endAngle).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: ThreePhaseRouletteCurve(
          easeInDuration: easeInDuration,
          linearDuration: linearDuration,
          easeOutDuration: easeOutDuration,
        ),
      ),
    );
    _animationController.forward(from: 0.0);
  }

  List<RouletteItem> _getActiveItems() {
    final activeItems = Preferences.rouletteItems
        .where((item) => item.name.isNotEmpty)
        .toList();
    if (Preferences.itemSplit && activeItems.isNotEmpty) {
      activeItems.addAll(List.from(activeItems));
    }
    return activeItems;
  }

  void _updateCurrentItem() {
    final double currentAngle = _animation.value;
    double effectiveAngle = (360 - (currentAngle % 360) + 270) % 360;

    double currentAngleSum = 0.0;
    final List<RouletteItem> activeItems = _getActiveItems();
    double totalRate = activeItems.fold(0.0, (sum, item) => sum + item.rate);
    if (totalRate == 0) {
      _currentItemName = AppLocalizations.of(context)!.noItemsToSpin;
      return;
    }
    for (int i = 0; i < activeItems.length; i++) {
      final item = activeItems[i];
      final double sweepAngle = (item.rate / totalRate) * 360;
      if (effectiveAngle >= currentAngleSum &&
          effectiveAngle < currentAngleSum + sweepAngle) {
        final originalItemsCount = Preferences.rouletteItems
            .where((i) => i.name.isNotEmpty)
            .length;
        if (originalItemsCount == 0) {
          return;
        }
        _currentItemName = item.name;
        final Color segColor =
            _rouletteColors[i % originalItemsCount % _rouletteColors.length];
        if (_animationController.isAnimating && Preferences.fixBackColor) {
          _currentBackgroundColor = _fixedBgColor;
        } else {
          _currentBackgroundColor = segColor;
        }
        return;
      }
      currentAngleSum += sweepAngle;
    }
  }

  void _determineWinner() {
    final double finalAngle = _animation.value; // This is 0-360 degrees
    // Assuming the pointer is at the "top" of the wheel, which is 0 degrees if we consider the top as the reference.
    // The animation value is the total rotation.
    // We need to find which segment is at the 0-degree mark after the rotation.

    // The angle on the unrotated wheel that is now at the pointer (top = 270 degrees).
    // If the wheel rotated by `finalAngle` clockwise, then the segment that was originally at `(270 - finalAngle) % 360` is now at the top.
    // Our drawing logic has 0 degrees on the right. So top is 270.
    double effectiveAngle = (360 - (finalAngle % 360) + 270) % 360;
    double currentAngle = 0.0;
    final List<RouletteItem> activeItems = _getActiveItems();
    double totalRate = activeItems.fold(0.0, (sum, item) => sum + item.rate);
    if (totalRate == 0) {
      setState(() {
        _rouletteResult = AppLocalizations.of(context)!.noItemsToSpin;
      });
      return;
    }
    for (int i = 0; i < activeItems.length; i++) {
      final item = activeItems[i];
      final double sweepAngle = (item.rate / totalRate) * 360; // in degrees
      if (effectiveAngle >= currentAngle &&
          effectiveAngle < currentAngle + sweepAngle) {
        setState(() {
          final originalItemsCount = Preferences.rouletteItems
            .where((i) => i.name.isNotEmpty)
            .length;
          if (originalItemsCount == 0) {
            return;
          }
          _rouletteResult = item.name;
          _currentItemName = item.name;
          _currentBackgroundColor = _rouletteColors[i % originalItemsCount % _rouletteColors.length];
          if (Preferences.ttsEnabled && Preferences.ttsVolume > 0.0) {
            unawaited(TextToSpeech.speak(item.name));
          }
        });
        return;
      }
      currentAngle += sweepAngle;
    }
    setState(() {
      _rouletteResult = AppLocalizations.of(context)!.errorDeterminingWinner;
    });
  }

  void _updateColorAndItemNameForAngle(double angle) {
    // This method calculates the color and item name for a given angle.
    double effectiveAngle = (360 - (angle % 360) + 270) % 360;
    double currentAngleSum = 0.0;
    final List<RouletteItem> activeItems = _getActiveItems();
    double totalRate = activeItems.fold(0.0, (sum, item) => sum + item.rate);
    if (totalRate == 0) {
      setState(() {
        _currentItemName = AppLocalizations.of(context)?.noItemsToSpin;
        _currentBackgroundColor = null; // Or a default color
      });
      return;
    }
    for (int i = 0; i < activeItems.length; i++) {
      final item = activeItems[i];
      final double sweepAngle = (item.rate / totalRate) * 360;
      if (effectiveAngle >= currentAngleSum &&
          effectiveAngle < currentAngleSum + sweepAngle) {
        setState(() {
          final originalItemsCount = Preferences.rouletteItems
              .where((i) => i.name.isNotEmpty)
              .length;
          if (originalItemsCount == 0) return;

          // When the wheel is not spinning, this sets the result.
          if (!_animationController.isAnimating) {
            _rouletteResult = item.name;
          }
          _currentItemName = item.name;
          _currentBackgroundColor =
              _rouletteColors[i % originalItemsCount % _rouletteColors.length];
        });
        return;
      }
      currentAngleSum += sweepAngle;
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!_isReady) {
      return LoadingScreen2();
    }
    final l = AppLocalizations.of(context)!;
    final bool isLight = Theme.of(context).brightness == Brightness.light;
    final double textSizeResult = 48 * Preferences.textSizeAdjustResult / 100.0;
    final double textSizeRoulette = 16 * Preferences.textSizeAdjustRoulette / 100.0;
    return AnimatedBuilder(
      animation: _animationController,
      builder: (context, child) {
        _updateCurrentItem();
        return Scaffold(
          backgroundColor: _currentBackgroundColor,
          appBar: AppBar(
            elevation: 0,
            actions: [
              IconButton(
                icon: const Icon(Icons.settings),
                onPressed: _onClickSetting,
              ),
              const SizedBox(width: 10),
            ],
          ),
          body: SafeArea(
            child: Stack(
              children: [
                Column(
                  children: [
                    // Progress bar below the app bar
                    LinearProgressIndicator(
                      value: _animationController.value,
                      minHeight: 5.0,
                      backgroundColor: Colors.white.withValues(alpha: 0.3),
                      valueColor: AlwaysStoppedAnimation<Color>(
                        Colors.white.withValues(alpha: 0.8),
                      ),
                    ),
                    const Spacer(flex: 1),
                    SizedBox(
                      child: Visibility(
                        visible: _animationController.isAnimating || _rouletteResult != null,
                        maintainState: true,
                        maintainAnimation: true,
                        maintainSize: true,
                        child: Padding(
                          padding: const EdgeInsets.all(16.0),
                          child: Text(
                            _currentItemName ?? _rouletteResult ?? '',
                            style: TextStyle(fontSize: textSizeResult,
                              height: 1,  //行間
                              color: (isLight ? Colors.white : Colors.black)
                            ),
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 5,
                      child: Stack(
                        children: [
                          Positioned.fill(
                            child: Center(
                              child: CustomPaint(
                                painter: RoulettePainter(
                                  animationValue: _animation.value,
                                  activeItems: _getActiveItems(),
                                  rouletteColors: _rouletteColors,
                                  rouletteDarkColors: _rouletteDarkColors,
                                  fontSize: textSizeRoulette,
                                ),
                                child: Container(),
                              ),
                            ),
                          ),
                          Positioned.fill(
                            child: Align(
                              alignment: Alignment.center,
                              child: AnimatedOpacity(
                                opacity: _animationController.isAnimating ? 0.0 : 1.0,
                                duration: const Duration(milliseconds: 600),
                                child: GestureDetector(
                                  onTap: _onClickStart,
                                  child: Container(
                                    width: 100,
                                    height: 100,
                                    decoration: BoxDecoration(
                                      color: const Color.fromRGBO(0,0,0,0.6),
                                      shape: BoxShape.circle,
                                    ),
                                    alignment: Alignment.center,
                                    child: Text(
                                      l.rouletteStart,
                                      style: Theme.of(context)
                                          .textTheme
                                          .bodyLarge
                                          ?.copyWith(color: Colors.white),
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    const Spacer(flex: 1),
                  ],
                ),
              ],
            ),
          ),
          bottomNavigationBar: AdBannerWidget(adManager: _adManager),
        );
      },
    );
  }
}
import 'package:flutter/material.dart';

class LoadingScreen extends StatelessWidget {
  const LoadingScreen({super.key});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.deepPurple,
      body: const Center(
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Colors.purpleAccent),
          backgroundColor: Colors.white,
        ),
      ),
    );
  }
}

class LoadingScreen2 extends StatelessWidget {
  const LoadingScreen2({super.key});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.orange,
      body: const Center(
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Colors.orangeAccent),
          backgroundColor: Colors.white,
        ),
      ),
    );
  }
}
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

import 'package:roulette/home_page.dart';
import 'package:roulette/l10n/app_localizations.dart';
import 'package:roulette/preferences.dart';
import 'package:roulette/theme_mode_number.dart';
import 'package:roulette/parse_locale_tag.dart';
import 'package:roulette/loading_screen.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
  SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
    statusBarColor: Colors.transparent,
    systemNavigationBarColor: Colors.transparent,
  ));
  MobileAds.instance.initialize();
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});
  @override
  State<MyApp> createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  ThemeMode themeMode = ThemeMode.light;
  Locale? locale;
  bool _isReady = false;

  @override
  void initState() {
    super.initState();
    _initState();
  }

  void _initState() async {
    await Preferences.ensureReady();
    themeMode = ThemeModeNumber.numberToThemeMode(Preferences.themeNumber);
    locale = parseLocaleTag(Preferences.languageCode);
    setState(() {
      _isReady = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (!_isReady) {
      return MaterialApp(
        home: Scaffold(
          body: Center(
            child: LoadingScreen(),
          ),
        ),
      );
    }
    const seed = Colors.purple;
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      localizationsDelegates: AppLocalizations.localizationsDelegates,
      supportedLocales: AppLocalizations.supportedLocales,
      locale: locale,
      themeMode: themeMode,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: seed),
        useMaterial3: true,
        appBarTheme: AppBarTheme(
          backgroundColor: Colors.grey[700]!,
          foregroundColor: Colors.white,
          systemOverlayStyle: SystemUiOverlayStyle.light,
        ),
      ),
      darkTheme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: seed,
          brightness: Brightness.dark,
        ),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}
import 'dart:ui';

Locale? parseLocaleTag(String tag) {
  if (tag.isEmpty) {
    return null;
  }
  final parts = tag.split('-');
  final language = parts[0];
  String? script, country;
  if (parts.length >= 2) {
    parts[1].length == 4 ? script = parts[1] : country = parts[1];
  }
  if (parts.length >= 3) {
    parts[2].length == 4 ? script = parts[2] : country = parts[2];
  }
  return Locale.fromSubtags(
    languageCode: language,
    scriptCode: script,
    countryCode: country,
  );
}

import 'package:shared_preferences/shared_preferences.dart';
import 'package:roulette/roulette_item.dart';
import 'package:roulette/const_value.dart';

class Preferences {
  Preferences._();

  static bool _ready = false;
  static final List<RouletteItem> _rouletteItems = [
    RouletteItem('Item 1',1.0), //0
    RouletteItem('Item 2',1.0), //1
    RouletteItem('Item 3',1.0), //2
    RouletteItem('Item 4',1.0), //3
    RouletteItem('Item 5',1.0),
    RouletteItem('',1.0),
    RouletteItem('',1.0),
    RouletteItem('',1.0),
    RouletteItem('',1.0),
    RouletteItem('',1.0),
    RouletteItem('',1.0), //10
    RouletteItem('',1.0),
    RouletteItem('',1.0),
    RouletteItem('',1.0),
    RouletteItem('',1.0),
    RouletteItem('',1.0),
    RouletteItem('',1.0),
    RouletteItem('',1.0),
    RouletteItem('',1.0),
    RouletteItem('',1.0), //19
  ];
  static bool _itemSplit = false;
  static bool _fixBackColor = false;
  static int _rotationTime = 1;
  static bool _rotationShort = false;
  static int _textSizeAdjustResult = 100;
  static int _textSizeAdjustRoulette = 100;
  static bool _ttsEnabled = true;
  static double _ttsVolume = 1.0;
  static String _ttsVoiceId = '';
  static int _themeNumber = 0;
  static String _languageCode = ''; //e.g. ja

  static bool get ready => _ready;
  static List<RouletteItem> get rouletteItems => _rouletteItems;
  static bool get itemSplit => _itemSplit;
  static bool get fixBackColor => _fixBackColor;
  static int get rotationTime => _rotationTime;
  static bool get rotationShort => _rotationShort;
  static int get textSizeAdjustResult => _textSizeAdjustResult;
  static int get textSizeAdjustRoulette => _textSizeAdjustRoulette;
  static bool get ttsEnabled => _ttsEnabled;
  static String get ttsVoiceId => _ttsVoiceId;
  static double get ttsVolume => _ttsVolume;
  static int get themeNumber => _themeNumber;
  static String get languageCode => _languageCode;

  static Future<void> ensureReady() async {
    if (_ready) {
      return;
    }
    final prefs = await SharedPreferences.getInstance();
    //
    if (await _hasLegacyKey(prefs)) {
      _ready = true;
      return; //古いキーが有った場合は古いキーを削除して初期値を使用する。
    }
    //
    String tmpNameSum = '';
    for (int i = 0; i < 5; i++) {   //5個の記録が有るか?
      tmpNameSum += prefs.getString("${ConstValue.prefItemName}$i") ?? '';
    }
    if (tmpNameSum != '') {   //5個の記録が有れば読み込む。無ければ初期値を使用
      for (int i = 0; i < _rouletteItems.length; i++) {
        final String name = prefs.getString("${ConstValue.prefItemName}$i") ?? '';
        final double rate = prefs.getDouble("${ConstValue.prefItemRate}$i") ?? 1.0;
        _rouletteItems[i] = RouletteItem(name, rate);
      }
    }
    //
    _itemSplit = prefs.getBool(ConstValue.prefItemSplit) ?? false;
    _fixBackColor = prefs.getBool(ConstValue.prefFixBackColor) ?? false;
    _rotationTime = (prefs.getInt(ConstValue.prefRotationTime) ?? 1).clamp(1,15);
    _rotationShort = prefs.getBool(ConstValue.prefRotationShort) ?? false;
    _textSizeAdjustResult = (prefs.getInt(ConstValue.prefTextSizeAdjustResult) ?? 100).clamp(41,1070);
    _textSizeAdjustRoulette = (prefs.getInt(ConstValue.prefTextSizeAdjustRoulette) ?? 100).clamp(41,1070);
    _ttsEnabled = prefs.getBool(ConstValue.prefTtsEnabled) ?? true;
    _ttsVoiceId = prefs.getString(ConstValue.prefTtsVoiceId) ?? '';
    _ttsVolume = (prefs.getDouble(ConstValue.prefTtsVolume) ?? 1.0).clamp(0.0, 1.0);
    _themeNumber = (prefs.getInt(ConstValue.prefThemeNumber) ?? 0).clamp(0, 2);
    _languageCode = prefs.getString(ConstValue.prefLanguageCode) ?? '';
    _ready = true;
  }

  static Future<bool> _hasLegacyKey(SharedPreferences prefs) async {
    if (prefs.getDouble('maxSpeedDuration') == null) {
      return false;  //古いキーが無い
    }
    await prefs.clear();  //全てのキーを削除
    return true; //古いキーが有った
  }

  static Future<void> setRouletteItem(RouletteItem value, int idx) async {
    _rouletteItems[idx] = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString("${ConstValue.prefItemName}$idx", value.name);
    await prefs.setDouble("${ConstValue.prefItemRate}$idx", value.rate);
  }

  static Future<void> setItemSplit(bool value) async {
    _itemSplit = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(ConstValue.prefItemSplit, value);
  }

  static Future<void> setFixBackColor(bool value) async {
    _fixBackColor = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(ConstValue.prefFixBackColor, value);
  }

  static Future<void> setRotationTime(int value) async {
    _rotationTime = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt(ConstValue.prefRotationTime, value);
  }

  static Future<void> setRotationShort(bool value) async {
    _rotationShort = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(ConstValue.prefRotationShort, value);
  }

  static Future<void> setTextSizeAdjustResult(int value) async {
    _textSizeAdjustResult = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt(ConstValue.prefTextSizeAdjustResult, value);
  }

  static Future<void> setTextSizeAdjustRoulette(int value) async {
    _textSizeAdjustRoulette = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt(ConstValue.prefTextSizeAdjustRoulette, value);
  }

  static Future<void> setTtsEnabled(bool value) async {
    _ttsEnabled = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(ConstValue.prefTtsEnabled, value);
  }

  static Future<void> setTtsVoiceId(String value) async {
    _ttsVoiceId = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(ConstValue.prefTtsVoiceId, value);
  }

  static Future<void> setTtsVolume(double value) async {
    _ttsVolume = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setDouble(ConstValue.prefTtsVolume, value);
  }

  static Future<void> setThemeNumber(int value) async {
    _themeNumber = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt(ConstValue.prefThemeNumber, value);
  }

  static Future<void> setLanguageCode(String value) async {
    _languageCode = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(ConstValue.prefLanguageCode, value);
  }

}

class RouletteItem {
  final String name;
  final double rate;

  const RouletteItem(this.name, this.rate);

  RouletteItem copyWith({String? name, double? rate}) {
    return RouletteItem(
      name ?? this.name,
      rate ?? this.rate,
    );
  }

}
import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'package:roulette/roulette_item.dart';
import 'package:roulette/preferences.dart';

class RoulettePainter extends CustomPainter {
  final double animationValue;
  final List<RouletteItem> activeItems;
  final List<Color> rouletteColors;
  final List<Color> rouletteDarkColors;
  final double fontSize;

  RoulettePainter({
    required this.animationValue,
    required this.activeItems,
    required this.rouletteColors,
    required this.rouletteDarkColors,
    required this.fontSize,
  });

  @override
  void paint(Canvas canvas, Size size) {
    // Implement roulette drawing logic here based on CustomSurfaceView.kt
    // This is a placeholder for now.
    final double centerX = size.width / 2;
    final double centerY = size.height / 2;
    final double radius = min(centerX, centerY) * 0.8;

    final Paint whitePaint = Paint()..color = Colors.white;
    // Draw a 359-degree arc to create a 1-degree gap at the top.
    final double gap = pi / 180; // 1 degree in radians
    canvas.drawArc(
      Rect.fromCircle(center: Offset(centerX, centerY), radius: radius + 10),
      -pi / 2 + gap / 2, // Start angle (top is -pi/2), offset by half the gap
      2 * pi - gap, // Sweep angle (359 degrees)
      true,
      whitePaint,
    );

    double startAngle = animationValue * (pi / 180); // Convert degrees to radians

    // Filter out empty items and calculate total rate for active items
    double totalRate = activeItems.fold(0.0, (sum, item) => sum + item.rate);
    if (totalRate == 0) return;

    final originalItemsCount = Preferences.rouletteItems.where((i) => i.name.isNotEmpty).length;
    if (originalItemsCount == 0) return;

    for (int i = 0; i < activeItems.length; i++) {
      final item = activeItems[i];

      final double sweepAngle = (item.rate / totalRate) * 2 * pi;

      final Paint segmentPaint = Paint()..color = rouletteColors[i % originalItemsCount % rouletteColors.length];
      canvas.drawArc(
        Rect.fromCircle(center: Offset(centerX, centerY), radius: radius),
        startAngle,
        sweepAngle,
        true,
        segmentPaint,
      );

      final Paint darkSegmentPaint = Paint()..color = rouletteDarkColors[i % originalItemsCount % rouletteDarkColors.length];
      canvas.drawArc(
        Rect.fromCircle(center: Offset(centerX, centerY), radius: radius / 2),
        startAngle,
        sweepAngle,
        true,
        darkSegmentPaint,
      );

      // Draw text
      final double textAngle = startAngle + sweepAngle / 2;
      final double textRadius = radius * 0.8;
      final double textX = centerX + textRadius * cos(textAngle);
      final double textY = centerY + textRadius * sin(textAngle);

      final TextPainter textPainter = TextPainter(
        text: TextSpan(
          text: item.name,
          style: TextStyle(color: Colors.black, fontSize: fontSize),
        ),
        textDirection: TextDirection.ltr,
      );
      textPainter.layout();
      canvas.save();
      canvas.translate(textX, textY);
      canvas.rotate(textAngle + pi / 2); // Rotate text to align with segment
      textPainter.paint(canvas, Offset(-textPainter.width / 2, -textPainter.height / 2));
      canvas.restore();

      startAngle += sweepAngle;
    }
  }

  @override
  bool shouldRepaint(covariant RoulettePainter oldDelegate) {
    return oldDelegate.animationValue != animationValue ||
        !listEquals(oldDelegate.activeItems, activeItems);
  }
}
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

import 'package:roulette/l10n/app_localizations.dart';
import 'package:roulette/ad_manager.dart';
import 'package:roulette/ad_banner_widget.dart';
import 'package:roulette/ad_ump_status.dart';
import 'package:roulette/theme_color.dart';
import 'package:roulette/roulette_item.dart';
import 'package:roulette/preferences.dart';
import 'package:roulette/text_to_speech.dart';
import 'package:roulette/loading_screen.dart';

class SettingScreen extends StatefulWidget {
  const SettingScreen({super.key});
  @override
  State<SettingScreen> createState() => _SettingScreenState();
}

class _SettingScreenState extends State<SettingScreen> {
  late AdManager _adManager;
  final List<TextEditingController> _nameControllers = [];
  final List<TextEditingController> _rateControllers = [];
  int _visibleItemIndex = 5;
  bool _itemSplit = false;
  bool _fixBackColor = false;
  int _rotationTime = 1;
  bool _rotationShort = false;
  int _textSizeAdjustResult = 100;
  int _textSizeAdjustRoulette = 100;
  late List<TtsOption> _ttsVoices;
  bool _ttsEnabled = true;
  String _ttsVoiceId = '';
  double _ttsVolume = 1.0;
  late ThemeColor _themeColor;
  int _themeNumber = 0;
  String _languageCode = '';
  bool _isReady = false;
  bool _isFirst = true;
  //AdUmpState
  late final UmpConsentController _adUmp;
  AdUmpState _adUmpState = AdUmpState.initial;
  static const List<int> _percentOptions = [
    41,
    51,
    64,
    80,
    100,
    120,
    144,
    173,
    207,
    249,
    299,
    358,
    430,
    516,
    619,
    743,
    892,
    1070
  ];

  @override
  void initState() {
    super.initState();
    _initState();
  }

  void _initState() async {
    _adManager = AdManager();
    //
    for (int i = 0; i < Preferences.rouletteItems.length; i++) {
      if (Preferences.rouletteItems[i].name.isNotEmpty) {
        _visibleItemIndex = i;
      }
    }
    _visibleItemIndex = max(4, _visibleItemIndex);
    for (int i = 0; i < Preferences.rouletteItems.length; i++) {
      _nameControllers.add(TextEditingController(text: Preferences.rouletteItems[i].name));
      _rateControllers.add(TextEditingController(text: Preferences.rouletteItems[i].rate.toString()));
    }
    //
    _itemSplit = Preferences.itemSplit;
    _fixBackColor = Preferences.fixBackColor;
    _rotationTime = Preferences.rotationTime;
    _rotationShort = Preferences.rotationShort;
    _textSizeAdjustResult = Preferences.textSizeAdjustResult;
    _textSizeAdjustRoulette = Preferences.textSizeAdjustRoulette;
    _ttsEnabled = Preferences.ttsEnabled;
    _ttsVoiceId = Preferences.ttsVoiceId;
    _ttsVolume = Preferences.ttsVolume;
    _themeNumber = Preferences.themeNumber;
    _languageCode = Preferences.languageCode;
    //speech
    await TextToSpeech.getInstance();
    _ttsVoices = TextToSpeech.ttsVoices;
    TextToSpeech.setVolume(_ttsVolume);
    TextToSpeech.setTtsVoiceId(_ttsVoiceId);
    //AdUmpState
    _adUmp = UmpConsentController();
    _refreshConsentInfo();
    //
    setState(() {
      _isReady = true;
    });
  }

  @override
  void dispose() {
    for (var controller in _nameControllers) {
      controller.dispose();
    }
    for (var controller in _rateControllers) {
      controller.dispose();
    }
    _adManager.dispose();
    unawaited(TextToSpeech.stop());
    super.dispose();
  }

  void _onApply() async {
    FocusScope.of(context).unfocus();
    for (int i = 0; i < Preferences.rouletteItems.length; i++) {
      final name = _nameControllers[i].text;
      final rate = double.tryParse(_rateControllers[i].text) ?? 1.0;
      await Preferences.setRouletteItem(RouletteItem(name,rate),i);
    }
    await Preferences.setItemSplit(_itemSplit);
    await Preferences.setFixBackColor(_fixBackColor);
    await Preferences.setRotationTime(_rotationTime);
    await Preferences.setRotationShort(_rotationShort);
    await Preferences.setTextSizeAdjustResult(_textSizeAdjustResult);
    await Preferences.setTextSizeAdjustRoulette(_textSizeAdjustRoulette);
    await Preferences.setTtsEnabled(_ttsEnabled);
    await Preferences.setTtsVoiceId(_ttsVoiceId);
    await Preferences.setTtsVolume(_ttsVolume);
    await Preferences.setThemeNumber(_themeNumber);
    await Preferences.setLanguageCode(_languageCode);
    if (!mounted) {
      return;
    }
    Navigator.of(context).pop(true);
  }

  Future<void> _refreshConsentInfo() async {
    _adUmpState = await _adUmp.updateConsentInfo(current: _adUmpState);
    if (mounted) {
      setState(() {});
    }
  }

  Future<void> _onTapPrivacyOptions() async {
    final err = await _adUmp.showPrivacyOptions();
    await _refreshConsentInfo();
    if (err != null && mounted) {
      final l = AppLocalizations.of(context)!;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('${l.cmpErrorOpeningSettings} ${err.message}')),
      );
    }
  }

  int _nearestIndexForScale(int scale) {
    for (int i = 0; i < _percentOptions.length; i++) {
      if (_percentOptions[i] == scale) {
        return i;
      } else if (_percentOptions[i] >= scale) {
        return max(0, i - 1);
      }
    }
    return 0;
  }

  int _scaleForIndex(int index) {
    final i = index.clamp(0, _percentOptions.length - 1).toInt();
    return _percentOptions[i];
  }

  @override
  Widget build(BuildContext context) {
    if (!_isReady) {
      return const LoadingScreen();
    }
    if (_isFirst) {
      _isFirst = false;
      _themeColor = ThemeColor(themeNumber: _themeNumber, context: context);
    }
    final l = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: _themeColor.backColor,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        foregroundColor: _themeColor.appBarForegroundColor,
        leading: IconButton(
          icon: Icon(Icons.close, color: _themeColor.appBarForegroundColor),
          onPressed: () => Navigator.pop(context),
        ),
        actions: [
          IconButton(
            icon: Icon(Icons.check, color: _themeColor.appBarForegroundColor),
            onPressed: _onApply,
          ),
          const SizedBox(width: 10),
        ],
      ),
      body: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: SafeArea(
          child: Column(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.fromLTRB(8, 12, 8, 100),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      _buildItemRatioCard(l),
                      _buildSplitItem(l),
                      _buildFixBackColor(l),
                      _buildRotationTime(l),
                      _buildTextSize(l),
                      _buildSpeechSettings(l),
                      _buildTheme(l),
                      _buildLanguage(l),
                      _buildCmp(l),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      bottomNavigationBar: AdBannerWidget(adManager: _adManager),
    );
  }

  InputDecoration _inputDecoration({String? labelText, String? hintText}) {
    final radius = BorderRadius.circular(8);
    return InputDecoration(
      labelText: labelText,
      hintText: hintText,
      isDense: true,
      filled: true,
      fillColor: _themeColor.inputFillColor,
      contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
      border: OutlineInputBorder(
        borderRadius: radius,
        borderSide: BorderSide(color: _themeColor.borderColor),
      ),
      enabledBorder: OutlineInputBorder(
        borderRadius: radius,
        borderSide: BorderSide(color: _themeColor.borderColor),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: radius,
        borderSide: BorderSide(color: Theme.of(context).colorScheme.primary),
      ),
    );
  }

  Widget _buildItemRatioCard(AppLocalizations l) {
    return Card(
      color: _themeColor.cardColor,
      margin: const EdgeInsets.symmetric(vertical: 6),
      elevation: 0,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(l.itemRatio),
            const SizedBox(height: 12),
            Table(
              columnWidths: const {
                0: FlexColumnWidth(0.2),
                1: FlexColumnWidth(2),
                2: FlexColumnWidth(1),
              },
              border: TableBorder.all(color: Colors.transparent),
              children: List.generate(_visibleItemIndex + 1, (index) {
                return TableRow(
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(top: 14),
                      child: Text('${index + 1}'),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 8),
                      child: TextField(
                        controller: _nameControllers[index],
                        decoration: _inputDecoration(),
                        keyboardType: TextInputType.text,
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 8, left: 6),
                      child: TextField(
                        controller: _rateControllers[index],
                        decoration: _inputDecoration(),
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.allow(RegExp(r'[0-9.]')),
                        ],
                      ),
                    ),
                  ],
                );
              }),
            ),
            const SizedBox(height: 12),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                IconButton(
                  icon: const Icon(Icons.add_circle_outline),
                  onPressed: () => {
                    setState(() {
                      _visibleItemIndex = min(19, _visibleItemIndex + 1);
                    })
                  },
                  color: Theme.of(context).colorScheme.primary,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSplitItem(AppLocalizations l) {
    return Card(
      color: _themeColor.cardColor,
      margin: const EdgeInsets.symmetric(vertical: 6),
      elevation: 0,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Expanded(child: Text(l.itemSplit)),
                Switch.adaptive(value: _itemSplit,
                  onChanged: (bool value) {
                    setState(() {
                      _itemSplit = value;
                    });
                  }
                )
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildFixBackColor(AppLocalizations l) {
    return Card(
      color: _themeColor.cardColor,
      margin: const EdgeInsets.symmetric(vertical: 6),
      elevation: 0,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Expanded(child: Text(l.fixBackColor)),
                Switch.adaptive(value: _fixBackColor,
                  onChanged: (bool value) {
                    setState(() {
                      _fixBackColor = value;
                    });
                  }
                )
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildRotationTime(AppLocalizations l) {
    return Column(children: [
      Card(
        margin: const EdgeInsets.only(left: 0, top: 6, right: 0, bottom: 0),
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(12),
            topRight: Radius.circular(12),
            bottomLeft: Radius.circular(0),
            bottomRight: Radius.circular(0),
          ),
        ),
        color: _themeColor.cardColor,
        elevation: 0,
        child: Padding(
          padding: const EdgeInsets.only(left: 16, right: 16, top: 16, bottom: 4),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(l.rotationTime),
              Row(
                children: [
                  Text(_rotationTime.toStringAsFixed(0)),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Slider(
                      value: _rotationTime.toDouble(),
                      min: 1.0,
                      max: 15.0,
                      divisions: 14,
                      label: _rotationTime.toStringAsFixed(0),
                      onChanged: (double value) {
                        setState(() {
                          _rotationTime = value.toInt();
                        });
                      },
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
      Card(
        margin: const EdgeInsets.only(left: 0, top: 2, right: 0, bottom: 0),
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(0),
            topRight: Radius.circular(0),
            bottomLeft: Radius.circular(12),
            bottomRight: Radius.circular(12),
          ),
        ),
        color: _themeColor.cardColor,
        elevation: 0,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Expanded(child: Text(l.rotationShort)),
                  Switch.adaptive(value: _rotationShort,
                      onChanged: (bool value) {
                        setState(() {
                          _rotationShort = value;
                        });
                      }
                  )
                ],
              ),
            ],
          ),
        ),
      )
    ]);
  }

  Widget _buildTextSize(AppLocalizations l) {
    return Column(children: [
      Card(
          margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(12),
              topRight: Radius.circular(12),
              bottomLeft: Radius.circular(0),
              bottomRight: Radius.circular(0),
            ),
          ),
          color: _themeColor.cardColor,
          elevation: 0,
          shadowColor: Colors.transparent,
          surfaceTintColor: Colors.transparent,
          child: Padding(
            padding:
            const EdgeInsets.only(left: 0, top: 16, right: 16, bottom: 0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: const EdgeInsets.only(left: 16),
                  child: Text(l.textSizeAdjustResult),
                ),
                Row(
                  children: [
                    Expanded(
                      child: Slider(
                        min: 0,
                        max: (_percentOptions.length - 1).toDouble(),
                        divisions: _percentOptions.length - 1,
                        value: _nearestIndexForScale(_textSizeAdjustResult).toDouble(),
                        label: '${_percentOptions[_nearestIndexForScale(_textSizeAdjustResult)]}%',
                        onChanged: (v) {
                          final idx = v.round();
                          setState(() {
                            _textSizeAdjustResult = _scaleForIndex(idx).toInt();
                          });
                        },
                      ),
                    ),
                    Text('${_percentOptions[_nearestIndexForScale(_textSizeAdjustResult)]}%'),
                  ],
                ),
              ],
            ),
          )
      ),
      Card(
        margin: const EdgeInsets.only(left: 0, top: 2, right: 0, bottom: 0),
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(0),
            topRight: Radius.circular(0),
            bottomLeft: Radius.circular(12),
            bottomRight: Radius.circular(12),
          ),
        ),
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: Padding(
          padding: const EdgeInsets.only(left: 0, top: 16, right: 16, bottom: 0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: const EdgeInsets.only(left: 16.0),
                child: Text(l.textSizeAdjustRoulette),
              ),
              Row(
                children: [
                  Expanded(
                    child: Slider(
                      min: 0,
                      max: (_percentOptions.length - 1).toDouble(),
                      divisions: _percentOptions.length - 1,
                      value: _nearestIndexForScale(_textSizeAdjustRoulette).toDouble(),
                      label: '${_percentOptions[_nearestIndexForScale(_textSizeAdjustRoulette)]}%',
                      onChanged: (v) {
                        final idx = v.round();
                        setState(() {
                          _textSizeAdjustRoulette = _scaleForIndex(idx).toInt();
                        });
                      },
                    ),
                  ),
                  Text('${_percentOptions[_nearestIndexForScale(_textSizeAdjustRoulette)]}%'),
                ],
              ),
            ],
          ),
        ),
      )
    ]);
  }

  Widget _buildSpeechSettings(AppLocalizations l) {
    if (_ttsVoices.isEmpty) {
      return SizedBox.shrink();
    }
    return Column(children: [
      Card(
        margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(12),
            topRight: Radius.circular(12),
            bottomLeft: Radius.circular(0),
            bottomRight: Radius.circular(0),
          ),
        ),
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: Column(
          children: [
            Padding(
              padding:
              const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
              child: Row(
                children: [
                  Expanded(
                    child: Text(l.ttsEnabled),
                  ),
                  Switch(
                    value: _ttsEnabled,
                    onChanged: (bool value) {
                      setState(() {
                        _ttsEnabled = value;
                      });
                      unawaited(TextToSpeech.setVolume(value ? _ttsVolume : 0.0));
                    },
                  ),
                ],
              ),
            ),
          ],
        )
      ),
      Card(
        margin: const EdgeInsets.only(left: 0, top: 2, right: 0, bottom: 0),
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(0),
            topRight: Radius.circular(0),
            bottomLeft: Radius.circular(0),
            bottomRight: Radius.circular(0),
          ),
        ),
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.only(left: 16, right: 16, top: 12),
              child: Row(
                children: [
                  Text(l.ttsVolume),
                  const Spacer(),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(left: 16, right: 16),
              child: Row(
                children: <Widget>[
                  Text(_ttsVolume.toStringAsFixed(1)),
                  Expanded(
                    child: Slider(
                      value: _ttsVolume,
                      min: 0.0,
                      max: 1.0,
                      divisions: 10,
                      label: _ttsVolume.toStringAsFixed(1),
                      onChanged: _ttsEnabled
                          ? (double value) {
                        setState(() {
                          _ttsVolume = double.parse(
                            value.toStringAsFixed(1),
                          );
                        });
                        unawaited(TextToSpeech.setVolume(_ttsVolume));
                      }
                      : null,
                    ),
                  ),
                ],
              ),
            ),
          ],
        )
      ),
      Card(
        margin: const EdgeInsets.only(left: 0, top: 2, right: 0, bottom: 0),
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(0),
            topRight: Radius.circular(0),
            bottomLeft: Radius.circular(12),
            bottomRight: Radius.circular(12),
          ),
        ),
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.only(left: 16, right: 16, top: 4, bottom: 16),
              child: DropdownButtonFormField<String>(
                dropdownColor: _themeColor.dropdownColor,
                initialValue: () {
                  if (_ttsVoiceId.isNotEmpty &&
                      _ttsVoices.any((o) => o.id == _ttsVoiceId)) {
                    return _ttsVoiceId;
                  }
                  return _ttsVoices.first.id;
                }(),
                items: _ttsVoices
                    .map((o) => DropdownMenuItem<String>(
                    value: o.id, child: Text(o.label)))
                    .toList(),
                onChanged: (v) {
                  if (v == null) {
                    return;
                  }
                  setState(() => _ttsVoiceId = v);
                },
              ),
            ),
          ],
        )
      )
    ]);
  }

  Widget _buildTheme(AppLocalizations l) {
    return Card(
      margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ListTile(
              title: Text(l.theme,style: Theme.of(context).textTheme.bodyMedium),
              contentPadding: EdgeInsets.zero,
              trailing: DropdownButton<int>(
                value: _themeNumber,
                items: [
                  DropdownMenuItem(value: 0, child: Text(l.systemDefault)),
                  DropdownMenuItem(value: 1, child: Text(l.lightTheme)),
                  DropdownMenuItem(value: 2, child: Text(l.darkTheme)),
                ],
                onChanged: (value) {
                  if (value == null) {
                    return;
                  }
                  setState(() {
                    _themeNumber = value;
                  });
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLanguage(AppLocalizations l) {
    final Map<String,String> languageNames = {
      'en': 'English',
      'bg': 'Български',
      'cs': 'Čeština',
      'da': 'Dansk',
      'de': 'Deutsch',
      'el': 'Ελληνικά',
      'es': 'Español',
      'es-419': 'Español (Latinoamérica)',
      'fi': 'Suomi',
      'fr': 'Français',
      'hu': 'Magyar',
      'id': 'Indonesia',
      'it': 'Italiano',
      'ja': '日本語',
      'ko': '한국어',
      'nb': 'Norsk (Bokmål)',
      'nl': 'Nederlands',
      'pl': 'Polski',
      'pt-BR': 'Português (Brasil)',
      'pt-PT': 'Português (Portugal)',
      'ro': 'Română',
      'ru': 'Русский',
      'sv': 'Svenska',
      'th': 'ไทย',
      'tr': 'Türkçe',
      'uk': 'Українська',
      'vi': 'Tiếng Việt',
      'zh-Hans': '中文(简体)',
      'zh-Hant': '中文(繁體)',
      'ar': 'العربية',
    };
    return Card(
      margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ListTile(
              title: Text(l.language,style: Theme.of(context).textTheme.bodyMedium),
              contentPadding: const EdgeInsets.symmetric(horizontal: 0),
              trailing: DropdownButton<String?>(
                value: _languageCode.isEmpty ? null : _languageCode,
                items: [
                  DropdownMenuItem<String?>(
                    value: null,
                    child: const Text('Default'),
                  ),
                  ...languageNames.entries.map(
                    (entry) => DropdownMenuItem<String?>(
                      value: entry.key,
                      child: Text(entry.value),
                    ),
                  ),
                ],
                onChanged: (String? value) {
                  setState(() {
                    _languageCode = value ?? '';
                  });
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCmp(AppLocalizations l) {
    String statusLabel;
    IconData statusIcon;
    final l = AppLocalizations.of(context)!;
    final showButton = _adUmpState.privacyStatus == PrivacyOptionsRequirementStatus.required;
    statusLabel = l.cmpCheckingRegion;
    statusIcon = Icons.help_outline;
    switch (_adUmpState.privacyStatus) {
      case PrivacyOptionsRequirementStatus.required:
        statusLabel = l.cmpRegionRequiresSettings;
        statusIcon = Icons.privacy_tip;
        break;
      case PrivacyOptionsRequirementStatus.notRequired:
        statusLabel = l.cmpRegionNoSettingsRequired;
        statusIcon = Icons.check_circle_outline;
        break;
      case PrivacyOptionsRequirementStatus.unknown:
        statusLabel = l.cmpRegionCheckFailed;
        statusIcon = Icons.error_outline;
        break;
    }
    return Card(
      margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.only(left: 16, right: 16, top: 16, bottom: 22),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(l.cmpSettingsTitle),
            const SizedBox(height: 8),
            Text(l.cmpConsentDescription, style: Theme.of(context).textTheme.bodySmall),
            const SizedBox(height: 8),
            Center(
              child: Column(
                children: [
                  Chip(
                    avatar: Icon(statusIcon, size: 18),
                    label: Text(statusLabel),
                    side: BorderSide.none,
                  ),
                  const SizedBox(height: 4),
                  Text('${l.cmpConsentStatusLabel} ${_adUmpState.consentStatus.localized(context)}',
                    style: Theme.of(context).textTheme.bodySmall,
                  ),
                  if (showButton)
                    Column(
                      children: [
                        const SizedBox(height: 16),
                        ElevatedButton.icon(
                          onPressed: _adUmpState.isChecking ? null : _onTapPrivacyOptions,
                          icon: const Icon(Icons.settings),
                          label: Text(_adUmpState.isChecking ? l.cmpConsentStatusChecking : l.cmpOpenConsentSettings),
                          style: ElevatedButton.styleFrom(
                            elevation: 0,
                            side: BorderSide(
                              width: 1,
                            ),
                          ),
                        ),
                        const SizedBox(height: 16),
                        OutlinedButton.icon(
                          onPressed: _adUmpState.isChecking ? null : _refreshConsentInfo,
                          icon: const Icon(Icons.refresh),
                          label: Text(l.cmpRefreshStatus),
                        ),
                        const SizedBox(height: 16),
                        OutlinedButton.icon(
                          onPressed: () async {
                            await ConsentInformation.instance.reset();
                            await _refreshConsentInfo();
                            if (mounted) {
                              ScaffoldMessenger.of(context)
                                .showSnackBar(SnackBar(content: Text(l.cmpResetStatusDone)));
                            }
                          },
                          icon: const Icon(Icons.refresh),
                          label: Text(l.cmpResetStatus),
                        ),
                      ]
                    )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

}
import 'package:flutter_tts/flutter_tts.dart';
import 'dart:io' show Platform;
import 'package:collection/collection.dart';

class TtsOption {
  final String locale;
  final String name;
  const TtsOption(this.locale, this.name);
  String get id => '$locale|$name';
  String get label => '$locale $name';
}

//外部からの利用方法
//await TextToSpeech.getInstance();
//await TextToSpeech.setTtsVoiceId(Preferences.ttsVoiceId);
//await TextToSpeech.setVolume(Preferences.ttsVolume);
class TextToSpeech {
  static late FlutterTts _tts;
  static final List<TtsOption> ttsVoices = [];
  static String ttsVoiceId = '';

  static TextToSpeech? _instance;
  static bool _initialized = false;

  TextToSpeech._internal();

  static Future<TextToSpeech> getInstance() async {
    _instance ??= TextToSpeech._internal();
    if (!_initialized) {
      await _instance!._initial();
      _initialized = true;
    }
    return _instance!;
  }

  //声リスト作成
  Future<void> _initial() async {
    _tts = FlutterTts();
    try {
      List<dynamic>? vs;
      for (int i = 0; i < 10; i++) {
        vs = await _tts.getVoices;
        if (vs != null) {
          break;
        }
        await Future.delayed(Duration(seconds: 1));
      }
      if (vs is List) {
        ttsVoices.clear();
        for (final v in vs) {
          if (v is Map && v['name'] is String && v['locale'] is String) {
            ttsVoices.add(TtsOption(v['locale']!, v['name']!));
          }
        }
      }
      ttsVoices.sort((a, b) => a.label.compareTo(b.label));
      ttsVoices.insert(0, TtsOption("Default", ""));
      ttsVoiceId = ttsVoices.first.id;
      await _tts.awaitSpeakCompletion(true);
    } catch (_) {}
  }

  //ttsVoiceIdを登録
  static Future<void> setTtsVoiceId(String newTtsVoiceId) async {
    final exists = ttsVoices.any((o) => o.id == newTtsVoiceId);
    if (exists) {
      ttsVoiceId = newTtsVoiceId;
    } else {
      ttsVoiceId = ttsVoices.first.id;
    }
    await _setSpeechVoiceFromId();
  }

  //ttsVoiceIdの声を用意
  static Future<void> _setSpeechVoiceFromId() async {
    if (ttsVoices.isEmpty || ttsVoiceId.isEmpty) {
      return;
    }
    final idx = ttsVoiceId.indexOf('|');
    String selLocale = '';
    String selName = ttsVoiceId;
    if (idx >= 0) {
      selLocale = ttsVoiceId.substring(0, idx);
      selName = ttsVoiceId.substring(idx + 1);
    }
    TtsOption? match;
    if (selLocale.isNotEmpty) {
      match = ttsVoices.firstWhereOrNull(
        (e) => e.name == selName && e.locale == selLocale,
      );
    }
    match ??= ttsVoices.firstWhereOrNull((e) => e.name == selName);
    if (match != null) {
      final locale = match.locale;
      final name = match.name;
      try {
        if (Platform.isAndroid) {
          // Prefer Google TTS if available; ignore errors if not installed
          try {
            await _tts.setEngine('com.google.android.tts');
          } catch (_) {}
          if (locale.isNotEmpty) {
            await _tts.setLanguage(locale);
          }
          await _tts.setVoice({'name': name, 'locale': locale});
        } else if (Platform.isIOS) {
          // On iOS, setting voice is sufficient; avoid setLanguage overriding the voice
          await _tts.setVoice({'name': name, 'locale': locale});
        } else {
          // Fallback for other platforms
          if (locale.isNotEmpty) {
            await _tts.setLanguage(locale);
          }
          await _tts.setVoice({'name': name, 'locale': locale});
        }
      } catch (_) {}
    }
  }

  //文字列を音声再生
  static Future<void> speak(String text) async {
    try {
      await _tts.stop();
      await _tts.speak(text);
    } catch (_) {}
  }

  //音声再生を停止
  static Future<void> stop() async {
    try {
      await _tts.stop();
    } catch (_) {}
  }

  //音声再生の速度
  static Future<void> setVolume(double volume) async {
    try {
      await _tts.setVolume(volume);
    } catch (_) {}
  }

  //音声の高さ
  static Future<void> setPitch(double pitch) async {
    try {
      await _tts.setPitch(pitch);
    } catch (_) {}
  }

  //音声の速度
  static Future<void> setSpeechRate(double speechRate) async {
    try {
      await _tts.setSpeechRate(speechRate);
    } catch (_) {}
  }
}
import 'package:flutter/material.dart';

class ThemeColor {
  final int? themeNumber;
  final BuildContext context;

  ThemeColor({this.themeNumber, required this.context});

  Brightness get _effectiveBrightness {
    switch (themeNumber) {
      case 1:
        return Brightness.light;
      case 2:
        return Brightness.dark;
      default:
        return Theme.of(context).brightness;
    }
  }

  bool get _isLight => _effectiveBrightness == Brightness.light;

  Color get backColor => _isLight ? Colors.grey[300]! : Colors.grey[900]!;
  Color get cardColor => _isLight ? Colors.white : Colors.grey[800]!;
  Color get appBarForegroundColor => _isLight ? Colors.grey[700]! : Colors.white70;
  Color get dropdownColor => cardColor;
  Color get borderColor => _isLight ? Colors.grey[300]! : Colors.grey[700]!;
  Color get inputFillColor => _isLight ? Colors.grey[50]! : Colors.grey[900]!;
}
import 'package:flutter/material.dart';

class ThemeModeNumber {
  static ThemeMode numberToThemeMode(int value) {
    switch (value) {
      case 1:
        return ThemeMode.light;
      case 2:
        return ThemeMode.dark;
      default:
        return ThemeMode.system;
    }
  }
}
import 'package:flutter/animation.dart';

/// Curve that models a three-phase roulette spin: ease-in, linear, and ease-out.
class ThreePhaseRouletteCurve extends Curve {
  final double easeInDuration;
  final double linearDuration;
  final double easeOutDuration;

  const ThreePhaseRouletteCurve({
    required this.easeInDuration,
    required this.linearDuration,
    required this.easeOutDuration,
  });

  @override
  double transformInternal(double t) {
    final totalDuration = easeInDuration + linearDuration + easeOutDuration;
    final easeInFraction = easeInDuration / totalDuration;
    final linearFraction = linearDuration / totalDuration;

    // Distances assuming max normalized speed of 1.0.
    final distEaseIn = 0.5 * easeInDuration;
    final distLinear = 1.0 * linearDuration;
    final distEaseOut = 0.5 * easeOutDuration;
    final totalDistance = distEaseIn + distLinear + distEaseOut;

    if (t < easeInFraction) {
      final timeInPhase = t * totalDuration;
      final distance = 0.5 * timeInPhase * timeInPhase / easeInDuration;
      return distance / totalDistance;
    } else if (t < easeInFraction + linearFraction) {
      final timeInPhase = (t - easeInFraction) * totalDuration;
      final distance = distEaseIn + timeInPhase;
      return distance / totalDistance;
    } else {
      final timeInPhase = (t - easeInFraction - linearFraction) * totalDuration;
      final initialVelocity = 1.0;
      final acceleration = -initialVelocity / easeOutDuration;
      final distance = distEaseIn + distLinear +
          (initialVelocity * timeInPhase + 0.5 * acceleration * timeInPhase * timeInPhase);
      return distance / totalDistance;
    }
  }
}