Source code

We have made the main source code publicly available. We hope it will be helpful as a reference for app development.

● Japanese ● ご注意 ● このページで公開しているのはDartコードのみです。アプリの動作には画像・音声・多言語テキストなどの追加データが必要なため、ここに掲載している情報だけではアプリを完全に再現することはできません。 ● アプリは継続的に機能拡張しているため、ストアで公開している最新版とコード内容が異なる場合があります。 ● コードはコピーして自由にご利用いただけますが、著作権は放棄していません。そのため、コード全体の再掲載はご遠慮ください。一部の引用や改変しての再掲載は問題ありません。個人利用・商用利用を問わず、アプリ開発の参考として自由にお使いください。 ● このコードは「お手本」として公開しているものではありません。ミニアプリとして作成しているため、変数名など細部に配慮していない箇所や誤りが含まれる可能性があります。参考程度にご覧ください。 ● 他の開発者の公開コードを参考にした部分も含まれています。アプリ開発の熟練者が書いたコードではない点もご了承ください。 ● ここはエンジニア向けの技術情報共有サービスではないため、詳細な説明は省略しています。 ● 本コードは無保証であり、動作や品質を保証するものではありません。
Copyright© エーオーシステム株式会社

● English ● Notice ● Only the Dart source code is provided on this page. Additional assets such as images, audio files, and multilingual text are required for the application to function. Therefore, the information here alone is not sufficient to fully reproduce the app. ● The app is continuously being improved, so the code published here may differ from the latest version available on the app stores. ● You are free to copy and use the code, but the copyright is not waived. For this reason, please refrain from redistributing (reposting) the entire code. Partial quotation or redistribution of modified portions is allowed. You may use the code freely for reference in your own app development, whether for personal or commercial use. ● This code is not intended to serve as a coding example or best practice. As this is a small sample app, some variable names and details may lack refinement, and there may be mistakes. Please use it only as a reference. ● Some parts of the code are based on publicly available examples from other developers. Please note that this code was not written by an expert in Android app development. ● This is not a technical knowledge-sharing service for engineers, so detailed explanations are omitted. ● The code is provided "as is" without any warranty of any kind.
Copyright© ao-system, Inc.

Last build date: 2026-05-28

name: wheellotterymachine
description: "wheellotterymachine"

publish_to: 'none'

version: 2.11.1+54

environment:
  sdk: ^3.11.5

dependencies:     #flutter pub upgrade --major-versions
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
  intl: ^0.20.2               #flutter gen-l10n
  shared_preferences: ^2.2.2
  flutter_tts: ^4.2.3
  audioplayers: ^6.5.1
  google_mobile_ads: ^8.0.0
  collection: ^1.19.1
  wakelock_plus: ^1.4.0
  in_app_review: ^2.0.11
  app_settings: ^7.0.0

dev_dependencies:
  flutter_lints: ^6.0.0
  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

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'

flutter:
  generate: true
  uses-material-design: true
  config:
    enable-swift-package-manager: true

  assets:
    - assets/image/
    - assets/sound/

/// Copyright© ao-system, Inc.

import 'package:flutter/cupertino.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

import 'package:wheellotterymachine/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) {
    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: [
                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();
          }
        },
      ),
    );
  }
}
/// Copyright© ao-system, Inc.

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';
import 'package:flutter/widgets.dart';

import 'package:wheellotterymachine/_secrets.dart';

class AdManager {
  static String get _adUnitId => Platform.isIOS ? Secrets.adUnitIdIos : Secrets.adUnitIdAndroid;
  BannerAd? _bannerAd;
  int _lastWidthPx = 0;
  VoidCallback? _onLoadedCb;
  Timer? _retryTimer;
  int _retryAttempt = 0;

  BannerAd? get bannerAd => _bannerAd;

  /// アプリ起動時の設定
  /// UMP(同意管理)を導入したため、手動のNPA設定は不要になった。
  static Future<void> initForNPA() async {
    if (kIsWeb) {
      return;
    }
    // UMP SDK が保存した同意情報を MobileAds SDK が自動で読み取るため、
    // ここで RequestConfiguration を使って NPA を強制する必要はない。
    await MobileAds.instance.updateRequestConfiguration(
      RequestConfiguration(
        tagForChildDirectedTreatment: TagForChildDirectedTreatment.unspecified,
        testDeviceIds: Secrets.umpConsentTestDeviceIds, //テストデバイスID:広告の誤クリック防止
      ),
    );
  }

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

  static AdRequest getAdRequest() {
    // ユーザーの同意状態(TCF信号)は、SDKによって自動的に付与される。
    // 手動で npa: 1 を送ると、UMPでのユーザーの選択と競合する可能性があるため、空で返す。
    // AdRequest(nonPersonalizedAds: true);にはしない
    return const AdRequest();
  }

  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;
    _bannerAd = BannerAd(
      adUnitId: _adUnitId,
      request: getAdRequest(),
      size: size,
      listener: BannerAdListener(
        onAdLoaded: (ad) {
          _retryTimer?.cancel();
          _retryTimer = null;
          _retryAttempt = 0;
          final cb = _onLoadedCb;
          if (cb != null) {
            cb();
          }
        },
        onAdFailedToLoad: (ad, err) {
          ad.dispose();
          _scheduleRetry();
        },
      ),
    )..load();
  }

  void _scheduleRetry() {
    if (kIsWeb) return;
    _retryTimer?.cancel();
    _retryTimer = null;
    _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();
    _retryTimer = null;
  }
}
/// Copyright© ao-system, Inc.

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:wheellotterymachine/l10n/app_localizations.dart';
import 'package:wheellotterymachine/_secrets.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 AdUmpConsentController {
  //デバッグ用:同意フォームの表示テスト:EEA地域を強制する(本番ではfalseにすること)
  final bool forceEeaForDebug = false;
  //デバッグ用:同意フォームの表示テスト:EEA地域を強制するテストデバイスID
  static final List<String> _testDeviceIds = Secrets.umpConsentTestDeviceIds;

  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 {
          //同意フォームが必要なら表示する
          ConsentForm.loadAndShowConsentFormIfRequired((formError) 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(isChecking: false));
        },
      );
      return await completer.future;
    } 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;
  }
}

class AdUmpService {
  final AdUmpConsentController _adUmpConsentController = AdUmpConsentController();

  Future<AdUmpState> updateConsentInfo(AdUmpState current) async {
    return await _adUmpConsentController.updateConsentInfo(current: current);
  }

  Future<void> requestConsentInfoUpdate(ConsentRequestParameters params) async {
    final completer = Completer<void>();
    ConsentInformation.instance.requestConsentInfoUpdate(
      params,
          () => completer.complete(),
          (FormError error) => completer.completeError(error),
    );
    return completer.future;
  }

  Future<FormError?> showPrivacyOptions() async {
    return await _adUmpConsentController.showPrivacyOptions();
  }
}

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;
    }
  }
}
/// Copyright© ao-system, Inc.

import 'package:flutter/services.dart';

///App Tracking Transparency サービス
///iOS 14以降で広告トラッキングの許可をリクエストする
class AttService {
  //チャンネル名をiOS側と一致させる
  static const _channel = MethodChannel('aosystem.att');

  static final AttService _instance = AttService._internal();
  factory AttService() => _instance;
  AttService._internal();

  ///トラッキング許可をリクエスト
  ///戻り値: AttStatus (enum)
  Future<AttStatus> requestTracking() async {
    try {
      //iOS側からInt値を受け取る
      final result = await _channel.invokeMethod<int>('requestTracking');
      //enumに変換して返却
      return parseAttStatus(result);
    } on MissingPluginException catch (_) {
      //ハンドラ未登録(iOS以外/旧バイナリ等)はアプリ全体を落とさない
      return AttStatus.unknown;
    } on PlatformException catch (_) {
      return AttStatus.unknown;
    }
  }

  ///現在のトラッキング許可状態を取得
  ///戻り値:AttStatus(enum)
  Future<AttStatus> getTrackingStatus() async {
    try {
      //iOS側からInt値を受け取る
      final result = await _channel.invokeMethod<int>('getTrackingStatus');
      //enumに変換して返却
      return parseAttStatus(result);
    } on MissingPluginException catch (_) {
      return AttStatus.unknown;
    } on PlatformException catch (_) {
      return AttStatus.unknown;
    }
  }

  ///トラッキングが許可されているか
  Future<bool> isTrackingAuthorized() async {
    final status = await getTrackingStatus();
    return status == AttStatus.authorized;
  }
}

//一緒に利用する enum とヘルパー関数

enum AttStatus {
  notDetermined, // 0
  restricted,    // 1
  denied,        // 2
  authorized,    // 3
  unknown,       // 4
}

AttStatus parseAttStatus(int? value) {
  switch (value) {
    case 0:
      return AttStatus.notDetermined;
    case 1:
      return AttStatus.restricted;
    case 2:
      return AttStatus.denied;
    case 3:
      return AttStatus.authorized;
    default:
      return AttStatus.unknown;
  }
}
/// Copyright© ao-system, Inc.

import 'dart:ui' as ui;
import 'package:flutter/cupertino.dart';

class FramePainter extends CustomPainter {
  final ui.Image frame;
  FramePainter(this.frame);
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint();
    // 1. フレームの短辺を基準に正方形にクロップ
    final side = frame.width < frame.height ? frame.width : frame.height;
    final src = Rect.fromLTWH(
      (frame.width - side) / 2.0,
      (frame.height - side) / 2.0,
      side.toDouble(),
      side.toDouble(),
    );
    // 2. 描画先も正方形に制限
    final length = size.shortestSide;
    final dx = (size.width - length) / 2.0;
    final dy = (size.height - length) / 2.0;
    final dst = Rect.fromLTWH(dx, dy, length, length);
    canvas.drawImageRect(frame, src, dst, paint);
  }
  @override
  bool shouldRepaint(covariant FramePainter oldDelegate) {
    return oldDelegate.frame != frame;
  }
}
/// Copyright© ao-system, Inc.

import 'dart:async';
import 'dart:math';
import 'dart:ui' as ui;
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:wakelock_plus/wakelock_plus.dart';

import 'package:wheellotterymachine/ad_banner_widget.dart';
import 'package:wheellotterymachine/frame_painter.dart';
import 'package:wheellotterymachine/l10n/app_localizations.dart';
import 'package:wheellotterymachine/pin_prompt.dart';
import 'package:wheellotterymachine/setting_page.dart';
import 'package:wheellotterymachine/text_to_speech.dart';
import 'package:wheellotterymachine/item_state.dart';
import 'package:wheellotterymachine/model.dart';
import 'package:wheellotterymachine/machine_frame_cache.dart';
import 'package:wheellotterymachine/theme_color.dart';
import 'package:wheellotterymachine/main.dart';
import 'package:wheellotterymachine/loading_screen.dart';

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

class _HomePageState extends State<MainHomePage> with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  late List<ui.Image> _decodedFrames = [];
  final List<String> _balls = const [
    'assets/image/ball_gold.png',
    'assets/image/ball_silver.png',
    'assets/image/ball_purple.png',
    'assets/image/ball_blue.png',
    'assets/image/ball_green.png',
    'assets/image/ball_yellow.png',
    'assets/image/ball_red.png',
    'assets/image/ball_white.png',
  ];
  final Map<int, Offset> _pos = const {
    95: Offset(440, 540),
    96: Offset(457, 558),
    97: Offset(474, 589),
    98: Offset(492, 630),
    99: Offset(508, 620),
    100: Offset(527, 614),
    101: Offset(547, 616),
    102: Offset(567, 627),
    103: Offset(586, 651),
    104: Offset(601, 647),
    105: Offset(617, 650),
    106: Offset(634, 665),
    107: Offset(646, 670),
    108: Offset(657, 680),
    109: Offset(669, 709),
    110: Offset(680, 710),
  };
  final _audio = AudioPlayer();
  late AnimationController _machineAnimationController;
  bool _busy = false;
  int _frame = 0;
  int _choice = 0;
  String _result = '';
  bool _showResult = false;
  late List<ItemState> _items;
  Offset? _lastBallNormPos; // in 900x900 machine coordinates
  //
  late ThemeColor _themeColor;
  bool _isReady = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _initState();
  }

  void _initState() async {
    _themeColor = ThemeColor(themeNumber: Model.themeNumber, context: context);
    await TextToSpeech.applyPreferences(Model.ttsVoiceId,Model.ttsVolume);
    _itemsUpdate();
    _machineAnimationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1),
    )
    ..addListener(() {
      final value = _machineAnimationController.value;
      final step = _frameStep();
      final frame = (value * _displayedFrameCount()).floor() * step;
      if (frame != _frame) {
        setState(() {
          _frame = frame;
        });
      }
    })
    ..addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        setState(() {
          _busy = false;
          final lastFrameIndex = _decodedFrames.isEmpty
              ? 119
              : min(119, _decodedFrames.length - 1);
          _frame = lastFrameIndex;
          _showResult = true;
        });
      }
    });
    //
    await _warmMachineFrames();
    _wakelock();
    if (mounted) {
      setState(() {
        _isReady = true;
      });
    }
  }

  void _itemsUpdate() {
    _items = [
      ItemState(name: Model.itemName1, qty: Model.itemQty1),
      ItemState(name: Model.itemName2, qty: Model.itemQty2),
      ItemState(name: Model.itemName3, qty: Model.itemQty3),
      ItemState(name: Model.itemName4, qty: Model.itemQty4),
      ItemState(name: Model.itemName5, qty: Model.itemQty5),
      ItemState(name: Model.itemName6, qty: Model.itemQty6),
      ItemState(name: Model.itemName7, qty: Model.itemQty7),
      ItemState(name: Model.itemName8, qty: Model.itemQty8),
    ];
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    WakelockPlus.disable();
    _machineAnimationController.dispose();
    _audio.dispose();
    unawaited(TextToSpeech.stop());
    super.dispose();
  }

  //need with WidgetsBindingObserver
  //WidgetsBinding.instance.addObserver(this);
  //WidgetsBinding.instance.removeObserver(this);
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        _wakelock();
        break;
      case AppLifecycleState.inactive:
      case AppLifecycleState.paused:
      case AppLifecycleState.detached:
      case AppLifecycleState.hidden:
        WakelockPlus.disable();
        break;
    }
  }

  void _wakelock() {
    if (Model.wakelockEnabled) {
      WakelockPlus.enable();
    } else {
      WakelockPlus.disable();
    }
  }

  Future<void> _speakResult() async {
    if (_result != '' && Model.ttsEnabled && Model.ttsVolume > 0.0) {
      TextToSpeech.speak(_result);
    }
  }

  Future<void> _warmMachineFrames() async {
    try {
      final frames = await MachineFrameCache.load();
      if (!mounted) {
        return;
      }
      setState(() {
        _decodedFrames = frames;
      });
    } catch (_) {
    }
  }

  Widget _frameImage(int idx, int targetWidthPx) {
    if (_decodedFrames.isEmpty) {
      return const SizedBox.shrink();
    }
    final safeIndex = idx.clamp(0, _decodedFrames.length - 1).toInt();
    return Center(
      child: SizedBox(
        width: targetWidthPx.toDouble(),
        height: targetWidthPx.toDouble(),
        child: CustomPaint(painter: FramePainter(_decodedFrames[safeIndex])),
      ),
    );
  }

  Future<void> _onStart() async {
    if (_busy) {
      return;
    }
    setState(() {
      _busy = true;
      _result = '';
      _showResult = false;
      _frame = 0;
      _lastBallNormPos = null;
    });
    final sum = _items.fold<int>(0, (p, e) => p + e.qty);
    if (sum == 0) {
      setState(() {
        _result = AppLocalizations.of(context)!.empty;
        _showResult = true;
        _busy = false;
      });
      return;
    }
    final rnd = Random();
    int remain = rnd.nextInt(sum);
    int choice = 0;
    for (int i = 0; i < _items.length; i++) {
      final q = _items[i].qty;
      if (q == 0) {
        continue;
      }
      if (remain >= q) {
        remain -= q;
      } else {
        choice = i; //0|1|2|3|4|5|6|7
        await Model.setQtyResult(choice);  //結果保存
        _itemsUpdate();
        break;
      }
    }
    _choice = choice;
    //機械の音
    if (Model.machineVolume > 0) {
      try {
        await _audio.setSource(AssetSource('sound/garagara2.wav'));
        await _audio.setVolume(Model.machineVolume);
        await _audio.setPlaybackRate((Model.animationQuick + 1).toDouble());
        unawaited(_audio.resume());
      } catch (_) {}
    }
    //機械の回転
    _machineAnimationController
      ..duration = Duration(milliseconds: Model.animationSpeed * _displayedFrameCount())
      ..reset();
    await _machineAnimationController.forward();
    //結果表示
    _result = _items[_choice].name;
    //音声再生
    unawaited(_speakResult());
  }

  int _frameStep() {
    switch (Model.animationQuick) {
      case 1:
        return 2; // 60 frames
      case 2:
        return 3; // 40 frames
      case 3:
        return 4; // 30 frames
      case 4:
        return 6; // 20 frames
      default:
        return 1; // 120 frames
    }
  }

  int _displayedFrameCount() {
    final step = _frameStep();
    return (120 / step).round();
  }

  Future<void> _onSetting() async {
    if (_busy) {
      return;
    }
    if (Model.pin.isNotEmpty) {
      final ok = await PinPrompt.show(context, correctPin: Model.pin);
      if (!ok) {
        return;
      }
    }
    if (!mounted) {
      return;
    }
    final updated = await Navigator.push<bool>(
      context,
      MaterialPageRoute(builder: (_) => const SettingPage()),
    );
    if (mounted && updated == true) {
      MainApp.of(context).rebuildApp();
      _themeColor = ThemeColor(themeNumber: Model.themeNumber, context: context);
      await TextToSpeech.applyPreferences(Model.ttsVoiceId,Model.ttsVolume);
      _itemsUpdate();
      _wakelock();
    }
    if (mounted) {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!_isReady) {
      return const LoadingScreen();
    }
    return Scaffold(
      backgroundColor: _themeColor.mainBack2Color,
      body: Stack(children:[
        Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [_themeColor.mainBack2Color, _themeColor.mainBackColor],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
            image: DecorationImage(
              image: AssetImage('assets/image/tile.png'),
              repeat: ImageRepeat.repeat,
              opacity: 0.1,
            ),
          ),
        ),
        SafeArea(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Row(
                children: [
                  const Spacer(),
                  Padding(
                    padding: const EdgeInsets.only(right: 10),
                    child: IconButton(
                      onPressed: _busy ? null : _onSetting,
                      tooltip: AppLocalizations.of(context)!.setting,
                      icon: Icon(
                        Icons.settings,
                        color: Colors.white.withValues(alpha: 0.85),
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 5),
              Expanded(
                child: LayoutBuilder(
                  builder: (context, c) {
                    final box = min(c.maxWidth, c.maxHeight);
                    final ml = (c.maxWidth - box) / 2;
                    final mt = (c.maxHeight - box) / 2;
                    final bs = box / 25;
                    final op = (_frame >= 95 || _showResult) ? 1.0 : 0.0;
                    Offset? p = _pos[_frame];
                    if (p == null && _frame >= 95) {
                      final keys = _pos.keys.where((k) => k <= _frame).toList()
                        ..sort();
                      if (keys.isNotEmpty) p = _pos[keys.last];
                    }
                    if (p != null) {
                      _lastBallNormPos = p;
                    }
                    // When animation finished, keep showing last position
                    final useP = p ?? (_showResult ? _lastBallNormPos : null);
                    double? x, y;
                    if (useP != null) {
                      final px = box / 900.0;
                      final h = bs / 2;
                      x = ml + px * useP.dx - h;
                      y = mt + px * useP.dy - h;
                    }
                    final idx = _frame.clamp(0, 119).toInt();
                    final dpr = MediaQuery.of(context).devicePixelRatio;
                    final targetWidthPx = max(1, (box * dpr).round());
                    return Stack(
                      children: [
                        _frameImage(idx, targetWidthPx),
                        if (x != null && y != null)
                          Positioned(
                            left: x,
                            top: y,
                            width: bs,
                            height: bs,
                            child: Opacity(
                              opacity: op,
                              child: Image.asset(
                                _balls[_choice],
                                cacheWidth: max(1, (bs * dpr).round()),
                                filterQuality: FilterQuality.low,
                              ),
                            ),
                          ),
                        // Result text at bottom inside the machine area
                        Positioned(
                          left: ml,
                          top: mt,
                          width: box,
                          height: box,
                          child: IgnorePointer(
                            child: AnimatedOpacity(
                              opacity: _showResult ? 1.0 : 0.0,
                              duration: const Duration(milliseconds: 300),
                              child: Align(
                                alignment: Alignment.bottomCenter,
                                child: Padding(
                                  padding: const EdgeInsets.only(bottom: 0),
                                  child: Text(
                                    _result,
                                    textAlign: TextAlign.center,
                                    style: const TextStyle(
                                      color: Colors.white,
                                      fontSize: 24,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    );
                  },
                ),
              ),
              const SizedBox(height: 12),
              Center(
                child: Opacity(
                  opacity: _busy ? 0.4 : 1.0,
                  child: ElevatedButton(
                    onPressed: _busy ? null : _onStart,
                    style: ElevatedButton.styleFrom(
                      shape: const CircleBorder(),
                      fixedSize: const Size(130, 130),
                      backgroundColor: Colors.white.withValues(alpha: 0.25),
                      foregroundColor: Colors.white,
                      elevation: 0,
                    ),
                    child: FittedBox(
                      fit: BoxFit.scaleDown,
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          AppLocalizations.of(context)!.drawLot,
                          textAlign: TextAlign.center,
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 48,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        )
      ]),
      bottomNavigationBar: Container(
        decoration: BoxDecoration(color: _themeColor.mainBackColor),
        child: AdBannerWidget(adManager: MainApp.of(context).adManager),
      ),
    );
  }

}
/// Copyright© ao-system, Inc.

class ItemState {
  String name;
  int qty;

  ItemState({required this.name, required this.qty});

  ItemState copy() => ItemState(name: name, qty: qty);
}
/// Copyright© ao-system, Inc.

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

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

  @override
  State<LoadingScreen> createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> with SingleTickerProviderStateMixin {
  late AnimationController _animationController;

  @override
  void initState() {
    super.initState();
    final randomStart = Random().nextDouble();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 6),
      value: randomStart,
    )..repeat();
  }

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

  Color _rainbowColor(double value) {
    final hue = _animationController.value * 360;
    return HSVColor.fromAHSV(1, hue, 1, value).toColor();
  }

  @override
  Widget build(BuildContext context) {
    final barHeight = MediaQuery.of(context).size.height * 0.4;
    return AnimatedBuilder(
      animation: _animationController,
      builder: (context, _) {
        final foreColor = _rainbowColor(1.0);
        final backColor = _rainbowColor(0.08);
        return Scaffold(
          backgroundColor: backColor,
          body: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(
                  height: barHeight,
                  child: RotatedBox(
                    quarterTurns: -1,
                    child: LinearProgressIndicator(
                      minHeight: 1,
                      valueColor: AlwaysStoppedAnimation(foreColor),
                      backgroundColor: Colors.transparent,
                    ),
                  ),
                ),
                const SizedBox(height: 5),
                Text(
                  'LOADING',
                  style: TextStyle(
                    color: foreColor,
                    fontSize: 18,
                    letterSpacing: 16,
                  ),
                ),
                const SizedBox(height: 5),
                SizedBox(
                  height: barHeight,
                  child: RotatedBox(
                    quarterTurns: 1,
                    child: LinearProgressIndicator(
                      minHeight: 1,
                      valueColor: AlwaysStoppedAnimation(foreColor),
                      backgroundColor: Colors.transparent,
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
/// Copyright© ao-system, Inc.

import 'dart:ui' as ui;
import 'package:flutter/services.dart';

class MachineFrameCache {
  static const int _frameCount = 120;
  static Future<List<ui.Image>>? _pending;
  static List<ui.Image>? _frames;

  static Future<List<ui.Image>> load() {
    final frames = _frames;
    if (frames != null) {
      return Future.value(frames);
    }
    final pending = _pending;
    if (pending != null) {
      return pending;
    }
    final future = _loadFrames();
    _pending = future;
    return future;
  }

  static Future<List<ui.Image>> _loadFrames() async {
    try {
      final decodedFrames = <ui.Image>[];
      for (var i = 0; i < _frameCount; i++) {
        final index = (i + 1).toString().padLeft(3, '0');
        final data = await rootBundle.load('assets/image/machine$index.webp');
        final codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
        final frame = await codec.getNextFrame();
        decodedFrames.add(frame.image);
      }
      _frames = decodedFrames;
      return decodedFrames;
    } finally {
      _pending = null;
    }
  }
}
/// Copyright© ao-system, Inc.

import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

import 'package:wheellotterymachine/l10n/app_localizations.dart';
import 'package:wheellotterymachine/home_page.dart';
import 'package:wheellotterymachine/model.dart';
import 'package:wheellotterymachine/theme_mode_number.dart';
import 'package:wheellotterymachine/parse_locale_tag.dart';
import 'package:wheellotterymachine/loading_screen.dart';
import 'package:wheellotterymachine/ad_ump_status.dart';
import 'package:wheellotterymachine/att_service.dart';
import 'package:wheellotterymachine/ad_manager.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  //UI設定
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      systemNavigationBarColor: Colors.transparent,
      statusBarColor: Colors.transparent,
      systemNavigationBarContrastEnforced: false,
      systemStatusBarContrastEnforced: false,
    ),
  );
  runApp(const MainApp());
}

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

  static MainAppState of(BuildContext context) {
    return context.findAncestorStateOfType<MainAppState>()!;
  }

  @override
  State<MainApp> createState() => MainAppState();
}

class MainAppState extends State<MainApp> {
  late final AdManager adManager;
  ThemeMode _themeMode = ThemeMode.system;
  Locale? _locale;
  bool _hasError = false;
  bool _isReady = false;

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

  void _initState() async {
    try {
      //ad
      adManager = AdManager();
      //アプリの基本データ
      await Model.ensureReady();
      //ATT
      //iOSは「アプリがactive/resumed状態」でないとrequestTrackingがダイアログを出さず即座にnotDeterminedを返すため、ライフサイクルがresumedになるまで待つ。
      //(iOSは「設定→トラッキング」でトグルを変えるとアプリプロセスをkillして再起動するので、起動時にgetTrackingStatusを読めば常に最新の値が手に入る)
      if (!kIsWeb && Platform.isIOS) {
        if (await _waitForResumed()) {
          final attService = AttService();
          //未決定(初回起動)のときだけダイアログ表示。既に決定済みならスキップ。
          if (await attService.getTrackingStatus() == AttStatus.notDetermined) {
            await attService.requestTracking();
          }
        }
      }
      //UMP(ATTの後)
      final adUmpConsentController = AdUmpConsentController();
      await adUmpConsentController.updateConsentInfo();
      //Mobile Ads SDK(同意確定後)
      await MobileAds.instance.initialize();
      //自前の広告設定
      await AdManager.initForNPA();
      //UI更新
      if (mounted) {
        setState(() {
          _themeMode = ThemeModeNumber.numberToThemeMode(Model.themeNumber);
          _locale = parseLocaleTag(Model.languageCode);
          _isReady = true;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _hasError = true;
        });
      }
    }
  }

  @override
  void dispose() {
    adManager.dispose();
    super.dispose();
  }

  //アプリがactive/resumed状態になるまで待つ。すでにresumedならすぐにtrueを返す。タイムアウト時はfalse。
  Future<bool> _waitForResumed({
    Duration timeout = const Duration(seconds: 5),
  }) async {
    final binding = WidgetsBinding.instance;
    if (binding.lifecycleState == AppLifecycleState.resumed) {
      return true;
    }
    final completer = Completer<bool>();
    late final AppLifecycleListener listener;
    listener = AppLifecycleListener(
      onStateChange: (state) {
        if (state == AppLifecycleState.resumed && !completer.isCompleted) {
          completer.complete(true);
        }
      },
    );
    try {
      return await completer.future.timeout(timeout, onTimeout: () => false);
    } finally {
      listener.dispose();
    }
  }

  void rebuildApp() {
    setState(() {
      _themeMode = ThemeModeNumber.numberToThemeMode(Model.themeNumber);
      _locale = parseLocaleTag(Model.languageCode);
    });
  }

  Color _getRainbowAccentColor(int hue) {
    return HSVColor.fromAHSV(1.0, hue.toDouble(), 1.0, 1.0).toColor();
  }

  ThemeData _createTheme(Brightness brightness, Color seed) {
    final colorScheme = ColorScheme.fromSeed(seedColor: seed, brightness: brightness);
    return ThemeData(
      useMaterial3: true,
      colorScheme: colorScheme,
      appBarTheme: const AppBarTheme(backgroundColor: Colors.transparent),
      elevatedButtonTheme: ElevatedButtonThemeData(
        style: ElevatedButton.styleFrom(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        ),
      ),
      sliderTheme: SliderThemeData(
        showValueIndicator: ShowValueIndicator.onDrag,
        valueIndicatorTextStyle: TextStyle(
          color: brightness == Brightness.light ? Colors.white : Colors.black,
        ),
      ),
      outlinedButtonTheme: OutlinedButtonThemeData(
        style: OutlinedButton.styleFrom(
          side: BorderSide(color: colorScheme.primary),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_hasError) {
      return _buildErrorMessage();
    }
    Color seed = _getRainbowAccentColor(Model.schemeColor);
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      localizationsDelegates: AppLocalizations.localizationsDelegates,
      supportedLocales: AppLocalizations.supportedLocales,
      locale: _locale,
      themeMode: _themeMode,
      theme: _createTheme(Brightness.light, seed),
      darkTheme: _createTheme(Brightness.dark, seed),
      home: _isReady ? const MainHomePage() : const Scaffold(body: LoadingScreen()),
    );
  }

  Widget _buildErrorMessage() {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: Padding(
            padding: EdgeInsets.all(24.0),
            child: Text(
              'Initialization failed. Please restart the app.',
              textAlign: TextAlign.center,
            ),
          ),
        ),
      ),
    );
  }

}
/// Copyright© ao-system, Inc.

import 'dart:ui' as ui;
import 'package:shared_preferences/shared_preferences.dart';

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

class Model {
  Model._();

  static const String _prefItemName1 = 'itemName1';
  static const String _prefItemName2 = 'itemName2';
  static const String _prefItemName3 = 'itemName3';
  static const String _prefItemName4 = 'itemName4';
  static const String _prefItemName5 = 'itemName5';
  static const String _prefItemName6 = 'itemName6';
  static const String _prefItemName7 = 'itemName7';
  static const String _prefItemName8 = 'itemName8';
  static const String _prefItemQty1 = 'itemQty1';
  static const String _prefItemQty2 = 'itemQty2';
  static const String _prefItemQty3 = 'itemQty3';
  static const String _prefItemQty4 = 'itemQty4';
  static const String _prefItemQty5 = 'itemQty5';
  static const String _prefItemQty6 = 'itemQty6';
  static const String _prefItemQty7 = 'itemQty7';
  static const String _prefItemQty8 = 'itemQty8';
  static const String _prefPin = 'pin';
  static const String _prefAnimationSpeed = 'animationSpeed';
  static const String _prefAnimationQuick = 'animationQuick';
  static const String _prefMachineVolume = 'machineVolume';
  static const String _prefTtsEnabled = 'ttsEnabled';
  static const String _prefTtsVolume = 'ttsVolume';
  static const String _prefTtsVoiceId = 'ttsVoiceId';
  static const String _prefWakelockEnabled = 'wakelockEnabled';
  static const String _prefSchemeColor = 'schemeColor';
  static const String _prefThemeNumber = 'themeNumber';
  static const String _prefLanguageCode = 'languageCode';

  static bool _ready = false;
  static String _itemName1 = 'Grand Prize';
  static String _itemName2 = 'Second Prize';
  static String _itemName3 = 'Premium Prize';
  static String _itemName4 = 'Prize A';
  static String _itemName5 = 'Prize B';
  static String _itemName6 = 'Prize C';
  static String _itemName7 = 'Consolation Prize';
  static String _itemName8 = 'Thank You Prize';
  static int _itemQty1 = 1;
  static int _itemQty2 = 1;
  static int _itemQty3 = 2;
  static int _itemQty4 = 2;
  static int _itemQty5 = 3;
  static int _itemQty6 = 10;
  static int _itemQty7 = 100;
  static int _itemQty8 = 500;
  static String _pin = '';
  static int _animationSpeed = 25; // 1..1000
  static int _animationQuick = 0; // 0..4
  static double _machineVolume = 1.0; // 0..1
  static bool _ttsEnabled = true;
  static double _ttsVolume = 1.0;
  static String _ttsVoiceId = '';
  static bool _wakelockEnabled = false;
  static int _schemeColor = 120;
  static int _themeNumber = 0;
  static String _languageCode = '';

  static String get itemName1 => _itemName1;
  static String get itemName2 => _itemName2;
  static String get itemName3 => _itemName3;
  static String get itemName4 => _itemName4;
  static String get itemName5 => _itemName5;
  static String get itemName6 => _itemName6;
  static String get itemName7 => _itemName7;
  static String get itemName8 => _itemName8;
  static int get itemQty1 => _itemQty1;
  static int get itemQty2 => _itemQty2;
  static int get itemQty3 => _itemQty3;
  static int get itemQty4 => _itemQty4;
  static int get itemQty5 => _itemQty5;
  static int get itemQty6 => _itemQty6;
  static int get itemQty7 => _itemQty7;
  static int get itemQty8 => _itemQty8;
  static String get pin => _pin;
  static int get animationSpeed => _animationSpeed;
  static bool get ttsEnabled => _ttsEnabled;
  static double get ttsVolume => _ttsVolume;
  static String get ttsVoiceId => _ttsVoiceId;
  static int get animationQuick => _animationQuick;
  static double get machineVolume => _machineVolume;
  static bool get wakelockEnabled => _wakelockEnabled;
  static int get schemeColor => _schemeColor;
  static int get themeNumber => _themeNumber;
  static String get languageCode => _languageCode;

  static Future<void> ensureReady() async {
    if (_ready) {
      return;
    }
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    //
    _itemName1 = prefs.getString(_prefItemName1) ?? '';
    _itemName2 = prefs.getString(_prefItemName2) ?? '';
    _itemName3 = prefs.getString(_prefItemName3) ?? '';
    _itemName4 = prefs.getString(_prefItemName4) ?? '';
    _itemName5 = prefs.getString(_prefItemName5) ?? '';
    _itemName6 = prefs.getString(_prefItemName6) ?? '';
    _itemName7 = prefs.getString(_prefItemName7) ?? '';
    _itemName8 = prefs.getString(_prefItemName8) ?? '';
    _itemQty1 = (prefs.getInt(_prefItemQty1) ?? 0).clamp(0,9999999);
    _itemQty2 = (prefs.getInt(_prefItemQty2) ?? 0).clamp(0,9999999);
    _itemQty3 = (prefs.getInt(_prefItemQty3) ?? 0).clamp(0,9999999);
    _itemQty4 = (prefs.getInt(_prefItemQty4) ?? 0).clamp(0,9999999);
    _itemQty5 = (prefs.getInt(_prefItemQty5) ?? 0).clamp(0,9999999);
    _itemQty6 = (prefs.getInt(_prefItemQty6) ?? 0).clamp(0,9999999);
    _itemQty7 = (prefs.getInt(_prefItemQty7) ?? 0).clamp(0,9999999);
    _itemQty8 = (prefs.getInt(_prefItemQty8) ?? 0).clamp(0,9999999);
    _pin = prefs.getString(_prefPin) ?? '';
    _animationSpeed = (prefs.getInt(_prefAnimationSpeed) ?? 25).clamp(1, 1000);
    _animationQuick = (prefs.getInt(_prefAnimationQuick) ?? 0).clamp(0, 4);
    _machineVolume = (prefs.getDouble(_prefMachineVolume) ?? 1.0).clamp(0.0, 1.0);
    _ttsEnabled = prefs.getBool(_prefTtsEnabled) ?? true;
    _ttsVolume = (prefs.getDouble(_prefTtsVolume) ?? 1.0).clamp(0.0, 1.0);
    _ttsVoiceId = prefs.getString(_prefTtsVoiceId) ?? '';
    _wakelockEnabled = prefs.getBool(_prefWakelockEnabled) ?? false;
    _schemeColor = (prefs.getInt(_prefSchemeColor) ?? 120).clamp(0, 360);
    _themeNumber = (prefs.getInt(_prefThemeNumber) ?? 0).clamp(0, 2);
    _languageCode = prefs.getString(_prefLanguageCode) ?? ui.PlatformDispatcher.instance.locale.languageCode;
    _languageCode = _resolveLanguageCode(_languageCode);
    _setDefaultItems();
    _ready = true;
  }

  static String _resolveLanguageCode(String code) {
    final supported = AppLocalizations.supportedLocales;
    if (supported.any((l) => l.languageCode == code)) {
      return code;
    } else {
      return '';
    }
  }

  static void _setDefaultItems() async {
    if (	_itemName1 == ''
        && _itemName2 == ''
        && _itemName3 == ''
        && _itemName4 == ''
        && _itemName5 == ''
        && _itemName6 == ''
        && _itemName7 == ''
        && _itemName8 == ''
    ) {
      _itemName1 = 'Grand Prize';
      _itemName2 = 'Second Prize';
      _itemName3 = 'Premium Prize';
      _itemName4 = 'Prize A';
      _itemName5 = 'Prize B';
      _itemName6 = 'Prize C';
      _itemName7 = 'Consolation Prize';
      _itemName8 = 'Thank You Prize';
      _itemQty1 = 1;
      _itemQty2 = 1;
      _itemQty3 = 2;
      _itemQty4 = 2;
      _itemQty5 = 3;
      _itemQty6 = 10;
      _itemQty7 = 100;
      _itemQty8 = 500;
      await setItemName1(_itemName1);
      await setItemName2(_itemName2);
      await setItemName3(_itemName3);
      await setItemName4(_itemName4);
      await setItemName5(_itemName5);
      await setItemName6(_itemName6);
      await setItemName7(_itemName7);
      await setItemName8(_itemName8);
      await setItemQty1(_itemQty1);
      await setItemQty2(_itemQty2);
      await setItemQty3(_itemQty3);
      await setItemQty4(_itemQty4);
      await setItemQty5(_itemQty5);
      await setItemQty6(_itemQty6);
      await setItemQty7(_itemQty7);
      await setItemQty8(_itemQty8);
    }
  }

  static Future<void> setQtyResult(int choice) async {
    if (choice == 0) {
      await setItemQty1(_itemQty1 - 1);
    } else if (choice == 1) {
      await setItemQty2(_itemQty2 - 1);
    } else if (choice == 2) {
      await setItemQty3(_itemQty3 - 1);
    } else if (choice == 3) {
      await setItemQty4(_itemQty4 - 1);
    } else if (choice == 4) {
      await setItemQty5(_itemQty5 - 1);
    } else if (choice == 5) {
      await setItemQty6(_itemQty6 - 1);
    } else if (choice == 6) {
      await setItemQty7(_itemQty7 - 1);
    } else if (choice == 7) {
      await setItemQty8(_itemQty8 - 1);
    }
  }

  static Future<void> setItemName1(String value) async {
    _itemName1 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefItemName1, value);
  }

  static Future<void> setItemName2(String value) async {
    _itemName2 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefItemName2, value);
  }

  static Future<void> setItemName3(String value) async {
    _itemName3 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefItemName3, value);
  }

  static Future<void> setItemName4(String value) async {
    _itemName4 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefItemName4, value);
  }

  static Future<void> setItemName5(String value) async {
    _itemName5 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefItemName5, value);
  }

  static Future<void> setItemName6(String value) async {
    _itemName6 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefItemName6, value);
  }

  static Future<void> setItemName7(String value) async {
    _itemName7 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefItemName7, value);
  }

  static Future<void> setItemName8(String value) async {
    _itemName8 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefItemName8, value);
  }

  static Future<void> setItemQty1(int value) async {
    _itemQty1 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefItemQty1, value);
  }

  static Future<void> setItemQty2(int value) async {
    _itemQty2 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefItemQty2, value);
  }

  static Future<void> setItemQty3(int value) async {
    _itemQty3 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefItemQty3, value);
  }

  static Future<void> setItemQty4(int value) async {
    _itemQty4 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefItemQty4, value);
  }

  static Future<void> setItemQty5(int value) async {
    _itemQty5 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefItemQty5, value);
  }

  static Future<void> setItemQty6(int value) async {
    _itemQty6 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefItemQty6, value);
  }

  static Future<void> setItemQty7(int value) async {
    _itemQty7 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefItemQty7, value);
  }

  static Future<void> setItemQty8(int value) async {
    _itemQty8 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefItemQty8, value);
  }

  static Future<void> setPin(String value) async {
    _pin = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefPin, value);
  }

  static Future<void> setAnimationSpeed(int value) async {
    _animationSpeed = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefAnimationSpeed, value);
  }

  static Future<void> setAnimationQuick(int value) async {
    _animationQuick = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefAnimationQuick, value);
  }

  static Future<void> setMachineVolume(double value) async {
    _machineVolume = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setDouble(_prefMachineVolume, value);
  }

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

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

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

  static Future<void> setWakelockEnabled(bool value) async {
    _wakelockEnabled = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_prefWakelockEnabled, value);
  }

  static Future<void> setSchemeColor(int value) async {
    _schemeColor = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefSchemeColor, value);
  }

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

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

}
/// Copyright© ao-system, Inc.

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,
  );
}
/// Copyright© ao-system, Inc.

import 'package:flutter/material.dart';

class PinPrompt {
  static Future<bool> show(BuildContext context, {required String correctPin}) async {
    final c = TextEditingController();
    final ok = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('PIN'),
        content: TextField(
          controller: c,
          keyboardType: TextInputType.number,
          obscureText: true,
          decoration: const InputDecoration(hintText: 'Enter PIN'),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('OK'),
          ),
        ],
      ),
    );
    if (ok != true) {
      return false;
    }
    return c.text == correctPin;
  }
}
/// Copyright© ao-system, Inc.

import 'package:flutter/material.dart';

import 'package:wheellotterymachine/theme_color.dart';
import 'package:wheellotterymachine/model.dart';

/// 設定画面専用のカスタムCardウィジェット
class SettingCard extends StatelessWidget {
  final Widget child;
  final ShapeBorder shape;
  final EdgeInsetsGeometry margin;

  const SettingCard({
    super.key,
    required this.child,
    this.margin = const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
  }) : shape = const RoundedRectangleBorder(
    borderRadius: BorderRadius.all(Radius.circular(12)),
  );

  const SettingCard.top({
    super.key,
    required this.child,
    this.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),
    ),
  );

  const SettingCard.flat({
    super.key,
    required this.child,
    this.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),
    ),
  );

  const SettingCard.bottom({
    super.key,
    required this.child,
    this.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),
    ),
  );

  @override
  Widget build(BuildContext context) {
    final themeColor = ThemeColor(
      themeNumber: Model.themeNumber,
      context: context,
    );
    return SizedBox(
      width: double.infinity,
      child: Card(
        elevation: 0,
        margin: margin,
        surfaceTintColor: Colors.transparent,
        shadowColor: Colors.transparent,
        color: themeColor.cardColor,
        shape: shape,
        child: child,
      ),
    );
  }
}
/// Copyright© ao-system, Inc.

import 'dart:async';
import "dart:io";
import "package:app_settings/app_settings.dart";
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import "package:flutter/foundation.dart";
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:in_app_review/in_app_review.dart';

import "package:wheellotterymachine/setting_card.dart";
import 'package:wheellotterymachine/l10n/app_localizations.dart';
import 'package:wheellotterymachine/ad_banner_widget.dart';
import 'package:wheellotterymachine/ad_ump_status.dart';
import 'package:wheellotterymachine/model.dart';
import 'package:wheellotterymachine/text_to_speech.dart';
import 'package:wheellotterymachine/theme_color.dart';
import 'package:wheellotterymachine/loading_screen.dart';
import 'package:wheellotterymachine/_secrets.dart';
import 'package:wheellotterymachine/main.dart';
import 'package:wheellotterymachine/att_service.dart';

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

  @override
  State<SettingPage> createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  AdUmpState _adUmpState = AdUmpState.initial;
  late final AdUmpService _adUmpService;
  late ThemeColor _themeColor;
  bool _wakelockEnabled = false;
  int _themeNumber = 0;
  String _languageCode = '';
  final _inAppReview = InAppReview.instance;
  bool _isReady = false;
  //
  final List<TextEditingController> _nameControls = [
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
  ];
  final List<TextEditingController> _qtyControls = [
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
  ];
  late final TextEditingController _pinControl;
  late final TextEditingController _animationSpeedControl;
  int _animationQuick = 0;
  double _machineVolume = 1.0;
  bool _ttsEnabled = true;
  double _ttsVolume = 1.0;
  String _ttsVoiceId = '';
  int _schemeColor = 0;
  Color _accentColor = Colors.red;
  //
  final List<String> _ballAssets = const [
    'assets/image/ball_gold.png',
    'assets/image/ball_silver.png',
    'assets/image/ball_purple.png',
    'assets/image/ball_blue.png',
    'assets/image/ball_green.png',
    'assets/image/ball_yellow.png',
    'assets/image/ball_red.png',
    'assets/image/ball_white.png',
  ];
  final List<String> _ballLabels = const [
    'GOLD',
    'SILVER',
    'PURPLE',
    'BLUE',
    'GREEN',
    'YELLOW',
    'RED',
    'WHITE',
  ];

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

  Future<void> _initState() async {
    //ump
    _adUmpService = AdUmpService();
    await _refreshConsentInfo();
    //model
    _nameControls[0] = TextEditingController(text: Model.itemName1);
    _nameControls[1] = TextEditingController(text: Model.itemName2);
    _nameControls[2] = TextEditingController(text: Model.itemName3);
    _nameControls[3] = TextEditingController(text: Model.itemName4);
    _nameControls[4] = TextEditingController(text: Model.itemName5);
    _nameControls[5] = TextEditingController(text: Model.itemName6);
    _nameControls[6] = TextEditingController(text: Model.itemName7);
    _nameControls[7] = TextEditingController(text: Model.itemName8);
    _qtyControls[0] = TextEditingController(text: Model.itemQty1.toString());
    _qtyControls[1] = TextEditingController(text: Model.itemQty2.toString());
    _qtyControls[2] = TextEditingController(text: Model.itemQty3.toString());
    _qtyControls[3] = TextEditingController(text: Model.itemQty4.toString());
    _qtyControls[4] = TextEditingController(text: Model.itemQty5.toString());
    _qtyControls[5] = TextEditingController(text: Model.itemQty6.toString());
    _qtyControls[6] = TextEditingController(text: Model.itemQty7.toString());
    _qtyControls[7] = TextEditingController(text: Model.itemQty8.toString());
    _pinControl = TextEditingController(text: Model.pin);
    _animationSpeedControl = TextEditingController(text: Model.animationSpeed.toString());
    _animationQuick = Model.animationQuick;
    _machineVolume = Model.machineVolume;
    _ttsEnabled = Model.ttsEnabled;
    _ttsVolume = Model.ttsVolume;
    _ttsVoiceId = Model.ttsVoiceId;
    _wakelockEnabled = Model.wakelockEnabled;
    _schemeColor = Model.schemeColor;
    _themeNumber = Model.themeNumber;
    _languageCode = Model.languageCode;
    _accentColor = _getRainbowAccentColor(_schemeColor);
    //speech
    await TextToSpeech.applyPreferences(Model.ttsVoiceId,Model.ttsVolume);
    setState(() {
      _isReady = true;
    });
  }

  @override
  void dispose() {
    _pinControl.dispose();
    _animationSpeedControl.dispose();
    for (final c in _nameControls) {
      c.dispose();
    }
    for (final c in _qtyControls) {
      c.dispose();
    }
    unawaited(TextToSpeech.stop());
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _themeColor = ThemeColor(themeNumber: Model.themeNumber, context: context);
  }


  Future<void> _refreshConsentInfo() async {
    final AdUmpState newState = await _adUmpService.updateConsentInfo(_adUmpState);
    if (mounted) {
      setState(() { _adUmpState = newState; });
    }
  }

  Color _getRainbowAccentColor(int hue) {
    return HSVColor.fromAHSV(1.0, hue.toDouble(), 1.0, 1.0).toColor();
  }

  void _onApply() async {
    await Model.setItemName1(_nameControls[0].text.trim());
    await Model.setItemName2(_nameControls[1].text.trim());
    await Model.setItemName3(_nameControls[2].text.trim());
    await Model.setItemName4(_nameControls[3].text.trim());
    await Model.setItemName5(_nameControls[4].text.trim());
    await Model.setItemName6(_nameControls[5].text.trim());
    await Model.setItemName7(_nameControls[6].text.trim());
    await Model.setItemName8(_nameControls[7].text.trim());
    await Model.setItemQty1(int.tryParse(_qtyControls[0].text.trim()) ?? 0);
    await Model.setItemQty2(int.tryParse(_qtyControls[1].text.trim()) ?? 0);
    await Model.setItemQty3(int.tryParse(_qtyControls[2].text.trim()) ?? 0);
    await Model.setItemQty4(int.tryParse(_qtyControls[3].text.trim()) ?? 0);
    await Model.setItemQty5(int.tryParse(_qtyControls[4].text.trim()) ?? 0);
    await Model.setItemQty6(int.tryParse(_qtyControls[5].text.trim()) ?? 0);
    await Model.setItemQty7(int.tryParse(_qtyControls[6].text.trim()) ?? 0);
    await Model.setItemQty8(int.tryParse(_qtyControls[7].text.trim()) ?? 0);
    await Model.setPin(_pinControl.text.trim());
    await Model.setAnimationSpeed(int.tryParse(_animationSpeedControl.text.trim()) ?? 25);
    await Model.setAnimationQuick(_animationQuick);
    await Model.setMachineVolume(_machineVolume);
    await Model.setTtsEnabled(_ttsEnabled);
    await Model.setTtsVolume(_ttsVolume);
    await Model.setTtsVoiceId(_ttsVoiceId);
    await Model.setWakelockEnabled(_wakelockEnabled);
    await Model.setSchemeColor(_schemeColor);
    await Model.setThemeNumber(_themeNumber);
    await Model.setLanguageCode(_languageCode);
    if (!mounted) {
      return;
    }
    Navigator.of(context).pop(true);
  }

  @override
  Widget build(BuildContext context) {
    if (!_isReady) {
      return const LoadingScreen();
    }
    final l = AppLocalizations.of(context)!;
    final TextTheme t = Theme.of(context).textTheme;
    return Scaffold(
      backgroundColor: _themeColor.backColor,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        automaticallyImplyLeading: false,
        leading: IconButton(
          icon: const Icon(Icons.close),
          tooltip: l.cancel,
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: null,
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: 10),
            child: IconButton(
              onPressed: _onApply,
              tooltip: l.apply,
              icon: const Icon(Icons.check),
            ),
          ),
        ],
      ),
      body: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: SafeArea(
          child: Column(
            children: [
              Expanded(
                child: ListView(
                  padding: const EdgeInsets.only(left: 12, right: 12, top: 0, bottom: 100),
                  children: [
                    _buildItemsTable(l, t),
                    _buildPin(l, t),
                    _buildAnimationSpeed(l, t),
                    _buildAnimationQuick(l, t),
                    _buildMachineVolume(l, t),
                    _buildSpeech(l, t),
                    _buildWakelockEnabled(l, t),
                    _buildSchemeColor(l, t),
                    _buildTheme(l, t),
                    _buildLanguage(l, t),
                    _buildReview(l, t),
                    _buildCmp(l, t),
                    _buildAtt(l, t),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
      bottomNavigationBar: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(height: 10),
          AdBannerWidget(adManager: MainApp.of(context).adManager),
        ],
      ),
    );
  }

  Widget _buildItemsTable(AppLocalizations l, TextTheme t) {
    return SettingCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ListTile(
            contentPadding: const EdgeInsets.only(left: 16, right: 16, top: 8, bottom: 0),
            title: Text(l.resultsAndQuantity, style: t.bodyMedium),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 16, right: 16, top: 0, bottom: 16),
            child: Table(
              columnWidths: const {
                0: FixedColumnWidth(24),
                1: IntrinsicColumnWidth(),
                2: FlexColumnWidth(1),
                3: FixedColumnWidth(64),
              },
              defaultVerticalAlignment: TableCellVerticalAlignment.middle,
              children: List.generate(8, (i) {
                return TableRow(
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(4),
                      child: Image.asset(_ballAssets[i], width: 20, height: 20),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(4),
                      child: Text(_ballLabels[i]),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(4),
                      child: TextField(
                        controller: _nameControls[i],
                        decoration: const InputDecoration(
                          isDense: true,
                          hintText: 'Name',
                        ),
                        inputFormatters: [
                          LengthLimitingTextInputFormatter(50),
                        ],
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(4),
                      child: SizedBox(
                        width: 60,
                        child: TextField(
                          controller: _qtyControls[i],
                          keyboardType: TextInputType.number,
                          inputFormatters: [
                            FilteringTextInputFormatter.digitsOnly,
                          ],
                          decoration: const InputDecoration(isDense: true),
                        ),
                      ),
                    ),
                  ],
                );
              }),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPin(AppLocalizations l, TextTheme t) {
    return SettingCard(
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        title: Text(l.pin, style: t.bodyMedium),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              controller: _pinControl,
              obscureText: true,
              decoration: const InputDecoration(
                isDense: true,
              ),
              keyboardType: TextInputType.number,
              inputFormatters: [
                FilteringTextInputFormatter.digitsOnly,
              ],
            ),
            const SizedBox(height: 6),
            Text(
              l.pinNote,
              style: const TextStyle(fontSize: 12, color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildAnimationSpeed(AppLocalizations l, TextTheme t) {
    return SettingCard(
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        title: Row(
          children: [
            Text(l.animationSpeed, style: t.bodyMedium),
            const SizedBox(width: 12),
            Expanded(
              child: TextField(
                controller: _animationSpeedControl,
                keyboardType: TextInputType.number,
                textAlign: TextAlign.center,
                inputFormatters: [
                  FilteringTextInputFormatter.digitsOnly,
                ],
                decoration: const InputDecoration(
                  isDense: true,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }


  Widget _buildAnimationQuick(AppLocalizations l, TextTheme t) {
    return SettingCard(
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        title: Text(l.animationQuick, style: t.bodyMedium),
        subtitle: Row(
          children: [
            Text(_animationQuick.toString()),
            Expanded(
              child: Slider(
                value: _animationQuick.toDouble(),
                min: 0,
                max: 4,
                divisions: 4,
                label: _animationQuick.toString(),
                onChanged: (v) {
                  setState(() => _animationQuick = v.round());
                },
              ),
            ),
          ],
        ),
      ),
    );
  }


  Widget _buildMachineVolume(AppLocalizations l, TextTheme t) {
    return SettingCard(
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        title: Text(l.machineVolume, style: t.bodyMedium),
        subtitle: Row(
          children: [
            Text(_machineVolume.toStringAsFixed(1)),
            Expanded(
              child: Slider(
                value: _machineVolume,
                min: 0.0,
                max: 1.0,
                divisions: 10,
                label: _machineVolume.toStringAsFixed(1),
                onChanged: (v) {
                  setState(() => _machineVolume = v);
                },
              ),
            ),
          ],
        ),
      ),
    );
  }


  Widget _buildSpeech(AppLocalizations l, TextTheme t) {
    if (TextToSpeech.ttsVoices.isEmpty) {
      return const SizedBox.shrink();
    }
    return Column(
      children: [
        SettingCard.top(
          child: ListTile(
            contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            title: Text(l.ttsEnabled, style: t.bodyMedium),
            trailing: Switch(
              value: _ttsEnabled,
              onChanged: (value) {
                setState(() {
                  _ttsEnabled = value;
                });
              },
            ),
          ),
        ),
        SettingCard.flat(
          child: ListTile(
            contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            title: Text(l.ttsVolume, style: t.bodyMedium),
            subtitle: Row(
              children: [
                Text(_ttsVolume.toStringAsFixed(1)),
                Expanded(
                  child: Slider(
                    value: _ttsVolume,
                    min: 0.0,
                    max: 1.0,
                    divisions: 10,
                    label: _ttsVolume.toStringAsFixed(1),
                    onChanged: _ttsEnabled
                        ? (value) {
                      setState(() {
                        _ttsVolume = double.parse(value.toStringAsFixed(1));
                      });
                    }
                        : null,
                  ),
                ),
              ],
            ),
          ),
        ),
        SettingCard.bottom(
          child: ListTile(
            contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            title: null,
            subtitle: DropdownButtonFormField<String>(
              initialValue: () {
                if (_ttsVoiceId.isNotEmpty && TextToSpeech.ttsVoices.any((o) => o.id == _ttsVoiceId)) {
                  return _ttsVoiceId;
                }
                return TextToSpeech.ttsVoices.first.id;
              }(),
              items: TextToSpeech.buildGroupedItems(),
              onChanged: (v) {
                if (v == null) {
                  return;
                }
                setState(() => _ttsVoiceId = v);
              },
            ),
          ),
        )
      ],
    );
  }

  Widget _buildWakelockEnabled(AppLocalizations l, TextTheme t) {
    return SettingCard(
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        title: Text(l.wakelockEnabled, style: t.bodyMedium),
        trailing: Switch(
          value: _wakelockEnabled,
          onChanged: (value) => setState(() => _wakelockEnabled = value),
        ),
      ),
    );
  }

  Widget _buildSchemeColor(AppLocalizations l, TextTheme t) {
    return SettingCard(
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        title: Text(l.colorScheme, style: t.bodyMedium),
        subtitle: Row(
          children: <Widget>[
            Text(_schemeColor.toStringAsFixed(0), style: t.bodyMedium),
            Expanded(
              child: SliderTheme(
                data: SliderTheme.of(context).copyWith(
                  activeTrackColor: _accentColor,
                  inactiveTrackColor: _accentColor.withValues(alpha: 0.3),
                  thumbColor: _accentColor,
                  overlayColor: _accentColor.withValues(alpha: 0.2),
                  valueIndicatorColor: _accentColor,
                ),
                child: Slider(
                  value: _schemeColor.toDouble(),
                  min: 0,
                  max: 360,
                  divisions: 360,
                  label: _schemeColor.toString(),
                  onChanged: (double value) {
                    setState(() {
                      _schemeColor = value.toInt();
                      _accentColor = _getRainbowAccentColor(_schemeColor);
                    });
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTheme(AppLocalizations l, TextTheme t) {
    return SettingCard(
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        minVerticalPadding: 0,
        title: Text(l.theme, style: t.bodyMedium),
        trailing: DropdownButton<int>(
          value: _themeNumber,
          items: [
            DropdownMenuItem(value: 0, child: Text(l.systemSetting)),
            DropdownMenuItem(value: 1, child: Text(l.lightTheme)),
            DropdownMenuItem(value: 2, child: Text(l.darkTheme)),
          ],
          onChanged: (value) {
            if (value != null) {
              setState(() {
                _themeNumber = value;
              });
            }
          },
        ),
      ),
    );
  }

  Widget _buildLanguage(AppLocalizations l, TextTheme t) {
    final Map<String,String> languageNames = {
      'af': 'af: Afrikaans',
      'ar': 'ar: العربية',
      'bg': 'bg: Български',
      'bn': 'bn: বাংলা',
      'bs': 'bs: Bosanski',
      'ca': 'ca: Català',
      'cs': 'cs: Čeština',
      'da': 'da: Dansk',
      'de': 'de: Deutsch',
      'el': 'el: Ελληνικά',
      'en': 'en: English',
      'es': 'es: Español',
      'et': 'et: Eesti',
      'fa': 'fa: فارسی',
      'fi': 'fi: Suomi',
      'fil': 'fil: Filipino',
      'fr': 'fr: Français',
      'gu': 'gu: ગુજરાતી',
      'he': 'he: עברית',
      'hi': 'hi: हिन्दी',
      'hr': 'hr: Hrvatski',
      'hu': 'hu: Magyar',
      'id': 'id: Bahasa Indonesia',
      'it': 'it: Italiano',
      'ja': 'ja: 日本語',
      //'jv': 'jv: Basa Jawa',    //flutterのサポート外
      'km': 'km: ខ្មែរ',
      'kn': 'kn: ಕನ್ನಡ',
      'ko': 'ko: 한국어',
      'lt': 'lt: Lietuvių',
      'lv': 'lv: Latviešu',
      'ml': 'ml: മലയാളം',
      'mr': 'mr: मराठी',
      'ms': 'ms: Bahasa Melayu',
      'my': 'my: မြန်မာ',
      'ne': 'ne: नेपाली',
      'nl': 'nl: Nederlands',
      'or': 'or: ଓଡ଼ିଆ',
      'pa': 'pa: ਪੰਜਾਬੀ',
      'pl': 'pl: Polski',
      'pt': 'pt: Português',
      'ro': 'ro: Română',
      'ru': 'ru: Русский',
      'si': 'si: සිංහල',
      'sk': 'sk: Slovenčina',
      'sr': 'sr: Српски',
      'sv': 'sv: Svenska',
      'sw': 'sw: Kiswahili',
      'ta': 'ta: தமிழ்',
      'te': 'te: తెలుగు',
      'th': 'th: ไทย',
      'tl': 'tl: Tagalog',
      'tr': 'tr: Türkçe',
      'uk': 'uk: Українська',
      'ur': 'ur: اردو',
      'uz': 'uz: Oʻzbekcha',
      'vi': 'vi: Tiếng Việt',
      'zh': 'zh: 中文',
      'zu': 'zu: isiZulu',
    };
    return SettingCard(
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        minVerticalPadding: 0,
        title: Text(l.language, style: t.bodyMedium),
        trailing: DropdownButton<String?>(
          value: _languageCode,
          items: [
            DropdownMenuItem(value: '', child: Text('Default')),
            ...languageNames.entries.map((entry) => DropdownMenuItem<String?>(
              value: entry.key,
              child: Text(entry.value),
            )),
          ],
          onChanged: (String? value) {
            setState(() {
              _languageCode = value ?? '';
            });
          },
        ),
      ),
    );
  }

  Widget _buildReview(AppLocalizations l, TextTheme t) {
    return SettingCard(
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        title: Text(l.reviewApp, style: t.bodyMedium),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const SizedBox(height: 8),
            OutlinedButton.icon(
              icon: const Icon(Icons.open_in_new, size: 16),
              label: Text(l.reviewStore, style: t.bodySmall),
              onPressed: () async {
                await _inAppReview.openStoreListing(
                  appStoreId: Secrets.appStoreId,
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCmp(AppLocalizations l, TextTheme t) {
    final showButton = _adUmpState.privacyStatus == PrivacyOptionsRequirementStatus.required;
    String statusLabel = l.cmpCheckingRegion;
    IconData statusIcon = Icons.help_outline;
    switch (_adUmpState.privacyStatus) {
      case PrivacyOptionsRequirementStatus.required:
        statusLabel = l.cmpRegionRequiresSettings;
        statusIcon = Icons.privacy_tip_outlined;
        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 SettingCard(
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        title: Text(l.cmpSettingsTitle, style: t.bodyMedium),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 8),
            Text(l.cmpConsentDescription, style: t.bodySmall),
            const SizedBox(height: 16),
            Center(
              child: Column(
                children: [
                  Chip(
                    avatar: Icon(statusIcon, size: 18),
                    label: Text(statusLabel),
                  ),
                  const SizedBox(height: 6),
                  Text(
                    '${l.cmpConsentStatusLabel} ${_adUmpState.consentStatus.localized(context)}',
                    style: t.bodySmall,
                  ),
                  if (_adUmpState.consentStatus == ConsentStatus.obtained) ...[
                    const SizedBox(height: 6),
                    Text(l.cmpConsentStatusObtainedNote, style: t.bodySmall),
                  ],
                  if (showButton) ...[
                    const SizedBox(height: 8),
                    ElevatedButton.icon(
                      onPressed: _adUmpState.isChecking
                          ? null
                          : () async {
                        try {
                          await _adUmpService.showPrivacyOptions();
                        } catch (e) {
                          //debugPrint('Privacy options error ignored: $e');
                        }
                        await _refreshConsentInfo();
                      },
                      icon: const Icon(Icons.settings),
                      label: Text(
                        _adUmpState.isChecking
                            ? l.cmpConsentStatusChecking
                            : l.cmpOpenConsentSettings,
                      ),
                    ),
                    const SizedBox(height: 8),
                    OutlinedButton.icon(
                      onPressed: _adUmpState.isChecking ? null : _refreshConsentInfo,
                      icon: const Icon(Icons.refresh),
                      label: Text(l.cmpRefreshStatus),
                    ),
                    const SizedBox(height: 8),
                    OutlinedButton.icon(
                      onPressed: () async {
                        final messenger = ScaffoldMessenger.of(context);
                        final message = l.cmpResetStatusDone;
                        await ConsentInformation.instance.reset();
                        if (!mounted) {
                          return;
                        }
                        setState(() {
                          _adUmpState = _adUmpState.copyWith(
                            consentStatus: ConsentStatus.unknown,
                          );
                        });
                        messenger.showSnackBar(SnackBar(content: Text(message)));
                      },
                      icon: const Icon(Icons.delete_sweep_outlined),
                      label: Text(l.cmpResetStatus),
                    ),
                  ],
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildAtt(AppLocalizations l, TextTheme t) {
    if (kIsWeb || !Platform.isIOS) {
      return const SizedBox.shrink();
    }
    return SettingCard(
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        title: Text(l.attSettingsTitle, style: t.bodyMedium),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 8),
            Text(l.attDescription, style: t.bodySmall),
            const SizedBox(height: 8),
            FutureBuilder<AttStatus>(
              future: AttService().getTrackingStatus(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Center(
                    child: Column(
                      children: [
                        Chip(
                          avatar: const Icon(Icons.hourglass_empty),
                          label: Text(l.attStatusChecking),
                        ),
                        const SizedBox(height: 8),
                        OutlinedButton.icon(
                          onPressed: null,
                          icon: const Icon(Icons.open_in_new),
                          label: Text(l.attOpenSettings),
                        ),
                      ],
                    ),
                  );
                }
                final status = snapshot.data ?? AttStatus.unknown;
                final label = status.name;
                return Center(
                  child: Column(
                    children: [
                      Chip(
                        avatar: const Icon(Icons.track_changes),
                        label: Text('${l.attStatusLabel} $label'),
                      ),
                      const SizedBox(height: 8),
                      OutlinedButton.icon(
                        onPressed: () => AppSettings.openAppSettings(),
                        icon: const Icon(Icons.open_in_new, size: 16),
                        label: Text(l.attOpenSettings, style: t.bodySmall),
                      ),
                    ],
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

}
/// Copyright© ao-system, Inc.

/*
--- home_page.dart ---
import 'package:example/text_to_speech.dart';
class _MainHomePageState extends State<MainHomePage> {
  Future<void> _initState() async {
    await TextToSpeech.applyPreferences(Model.ttsVoiceId,Model.ttsVolume);
  }
  @override
  void dispose() {
    unawaited(TextToSpeech.stop());
  }
  void _ttsResult(String text) async {
    if (Model.ttsEnabled && Model.ttsVolume > 0.0) {
      await TextToSpeech.speak(text);
    }
  }
  Future<void> _openSetting() async {
      await TextToSpeech.applyPreferences(Model.ttsVoiceId,Model.ttsVolume);
  }
}
*/

/*
--- setting_page.dart ---
import 'package:example/text_to_speech.dart';
class _SettingPageState extends State<SettingPage> {
  bool _ttsEnabled = true;
  String _ttsVoiceId = '';
  double _ttsVolume = 1.0;
  Future<void> _initialize() async {
    //model
    _ttsEnabled = Model.ttsEnabled;
    _ttsVolume = Model.ttsVolume;
    _ttsVoiceId = Model.ttsVoiceId;
    //speech
    await TextToSpeech.applyPreferences(Model.ttsVoiceId,Model.ttsVolume);
  }
  @override
  void dispose() {
    unawaited(TextToSpeech.stop());
  }
  Future<void> _onApply() async {
    await Model.setTtsEnabled(_ttsEnabled);
    await Model.setTtsVoiceId(_ttsVoiceId);
    await Model.setTtsVolume(_ttsVolume);
  }
  Widget _buildSpeechSettings(AppLocalizations l, TextTheme t) {
    if (TextToSpeech.ttsVoices.isEmpty) {
      return SizedBox.shrink();
    }
    return Column(children:[
      SettingCard.bottom(
        child: ListTile(
          contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          title: null,
          subtitle: DropdownButtonFormField<String>(
            initialValue: () {
              if (_ttsVoiceId.isNotEmpty && TextToSpeech.ttsVoices.any((o) => o.id == _ttsVoiceId)) {
                return _ttsVoiceId;
              }
              return TextToSpeech.ttsVoices.first.id;
            }(),
            items: TextToSpeech.buildGroupedItems(),
            onChanged: (v) {
              if (v == null) {
                return;
              }
              setState(() => _ttsVoiceId = v);
            },
          ),
        ),
      )
    ]
  }
}
*/

import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_tts/flutter_tts.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';
}

class TextToSpeech {
  static final FlutterTts _tts = FlutterTts();
  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) {
      _initialized = true;
      await _instance!._initial();
    }
    return _instance!;
  }

  // 初期化:音声リスト作成
  Future<void> _initial() async {
    try {
      final vs = await _tts.getVoices;
      ttsVoices.clear();

      if (vs is List) {
        for (final v in vs) {
          if (v is Map && v['name'] is String && v['locale'] is String) {
            ttsVoices.add(TtsOption(v['locale']!, v['name']!));
          }
        }
      }

      // Default を定義(表示用)
      const defaultVoice = TtsOption("Default", "");

      if (ttsVoices.isEmpty) {
        // 取得できなかった → Default のみ
        ttsVoices.add(defaultVoice);
      } else {
        // Default を先頭に固定
        ttsVoices.removeWhere((v) => v.id == defaultVoice.id);
        ttsVoices.sort((a, b) => a.label.compareTo(b.label));
        ttsVoices.insert(0, defaultVoice);
      }
      // voiceId が存在しない場合は Default
      if (!ttsVoices.any((o) => o.id == ttsVoiceId)) {
        ttsVoiceId = ttsVoices.first.id;
      }
      await _setSpeechVoiceFromId();
    } catch (_) {}
  }

  // locale ごとにグループ化
  static Map<String, List<TtsOption>> _groupedVoices() {
    final Map<String, List<TtsOption>> grouped = {};
    for (final v in ttsVoices) {
      grouped.putIfAbsent(v.locale, () => []);
      grouped[v.locale]!.add(v);
    }
    return grouped;
  }

  //DropdownMenuItemを生成(Dividerで区切る)
  static List<DropdownMenuItem<String>> buildGroupedItems() {
    final grouped = _groupedVoicesDefaultFirst();
    final List<DropdownMenuItem<String>> items = [];
    bool first = true;
    grouped.forEach((locale, voices) {
      // 最初のグループの前には Divider を入れない
      if (!first) {
        items.add(
          const DropdownMenuItem<String>(
            enabled: false,
            value: null,
            child: Padding(
              padding: EdgeInsets.symmetric(vertical: 1),
              child: Divider(height: 1, thickness: 1),
            ),
          ),
        );
      }
      first = false;
      // グループ内の選択可能な項目
      for (final v in voices) {
        items.add(
          DropdownMenuItem<String>(
            value: v.id,
            child: Container(
              padding: const EdgeInsets.symmetric(vertical: 2),
              child: Text(v.label),
            ),
          ),
        );
      }
    });
    return items;
  }

  static Map<String, List<TtsOption>> _groupedVoicesSorted() {
    final grouped = _groupedVoices();
    // locale をアルファベット順にソート
    final sortedKeys = grouped.keys.toList()..sort();
    final Map<String, List<TtsOption>> sorted = {};
    for (final key in sortedKeys) {
      sorted[key] = grouped[key]!;
    }
    return sorted;
  }

  static Map<String, List<TtsOption>> _groupedVoicesDefaultFirst() {
    final grouped = _groupedVoices();
    // Default が存在しなければ通常のソート
    if (!grouped.containsKey("Default")) {
      return _groupedVoicesSorted();
    }
    // Default 以外の locale をソート
    final otherKeys = grouped.keys.where((k) => k != "Default").toList()..sort();
    final Map<String, List<TtsOption>> sorted = {};
    // Default を最上段に
    sorted["Default"] = grouped["Default"]!;
    // 残りをアルファベット順に追加
    for (final key in otherKeys) {
      sorted[key] = grouped[key]!;
    }
    return sorted;
  }

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

  // 選択された voiceId を TTS に反映
  static Future<void> _setSpeechVoiceFromId() async {
    if (ttsVoices.isEmpty || ttsVoiceId.isEmpty) {
      return;
    }
    final idx = ttsVoiceId.indexOf('|');
    final locale = idx >= 0 ? ttsVoiceId.substring(0, idx) : '';
    final name = idx >= 0 ? ttsVoiceId.substring(idx + 1) : ttsVoiceId;
    // Default の場合 → デバイスのデフォルトロケールを使う
    if (locale == "Default") {
      final deviceLocale = PlatformDispatcher.instance.locale.toString(); //e.g. ja_JP
      final ttsLocale = deviceLocale.replaceAll('_', '-'); //e.g. ja-JP
      try {
        await _tts.setLanguage(ttsLocale);
      } catch (_) {}
      return;
    }
    // 通常の処理
    try {
      if (locale.isNotEmpty) {
        await _tts.setLanguage(locale);
      }
      await _tts.setVoice({'name': name, 'locale': locale});
    } catch (_) {}
  }


  // 設定反映
  static Future<void> applyPreferences(String ttsVoiceId, double ttsVolume) async {
    await TextToSpeech._getInstance();
    await TextToSpeech._setTtsVoiceId(ttsVoiceId);
    await TextToSpeech._setVolume(ttsVolume);
  }

  // 音量
  static Future<void> _setVolume(double volume) async {
    try {
      await _tts.setVolume(volume);
    } catch (_) {}
  }

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

  // 停止
  static Future<void> stop() async {
    try {
      await _tts.stop();
    } 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 (_) {}
  }
}
/// Copyright© ao-system, Inc.

import 'package:flutter/material.dart';

import 'package:wheellotterymachine/model.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;
    }
  }

  Color _getRainbowAccentColor(int hue, double saturation, double value) {
    return HSVColor.fromAHSV(1.0, hue.toDouble(), saturation, value).toColor();
  }

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

  //main page
  Color get mainBackColor => _isLight ? _getRainbowAccentColor(Model.schemeColor,1,0.4) : _getRainbowAccentColor(Model.schemeColor,1,0.1);
  Color get mainBack2Color => _isLight ? _getRainbowAccentColor(Model.schemeColor,1,0.8) : _getRainbowAccentColor(Model.schemeColor,1,0.4);
  Color get mainForeColor => _isLight ? Color.fromRGBO(255, 255, 255, 1.0) : Color.fromRGBO(255, 255, 255, 1.0);
  //setting page
  Color get backColor => _isLight ? Colors.grey[200]! : 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]!;
}
/// Copyright© ao-system, Inc.

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;
    }
  }
}