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-27

name: bingogame
description: "bingogame"

publish_to: 'none'

version: 1.5.1+20

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
  cupertino_icons: ^1.0.8
  shared_preferences: ^2.5.3
  google_mobile_ads: ^8.0.0
  just_audio: ^0.10.5
  audio_session: ^0.2.2
  collection: ^1.19.1
  video_player: ^2.10.1
  flutter_tts: ^4.2.3
  flutter_svg: ^2.2.3
  google_fonts: ^8.0.2
  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.4    # flutter pub run flutter_launcher_icons
  flutter_native_splash: ^2.4.7     # 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: '#ffd372'
  image: 'assets/image/splash.png'
  color_dark: '#ffd372'
  image_dark: 'assets/image/splash.png'
  fullscreen: true
  android_12:
    icon_background_color: '#ffd372'
    image: 'assets/image/splash.png'
    icon_background_color_dark: '#ffd372'
    image_dark: 'assets/image/splash.png'

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

  assets:
    - assets/image/
    - assets/audio/
    - assets/video/

/// Copyright© ao-system, Inc.

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

import 'package:bingogame/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:bingogame/_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:bingogame/l10n/app_localizations.dart';
import 'package:bingogame/_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.

class CardCell {
  CardCell({required this.number});
  int number;
  bool open = false;
}
/// Copyright© ao-system, Inc.

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

import 'package:bingogame/theme_color.dart';
import 'package:bingogame/card_cell.dart';
import 'package:bingogame/model.dart';
import 'package:bingogame/card_grid_cell.dart';

class CardGrid extends StatefulWidget {
  final int cardNumber;
  final int cardGridUpdateSign;

  const CardGrid({
    super.key,
    required this.cardNumber, //1|2|3|4|5|6
    required this.cardGridUpdateSign, //状態が変化したら新しい数値になる
  });

  @override
  State<CardGrid> createState() => _CardGridState();
}

class _CardGridState extends State<CardGrid> {
  static const int _gridSize = 5;
  static final Random _random = Random();
  late List<List<CardCell>> _grid;
  final Set<int> _highlighted = <int>{};
  late int _cardNumber;
  late ThemeColor _themeColor;
  late String _subject;
  late String _cardState;

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

  void _initState() async {
    _themeColor = ThemeColor(context: context);
    _cardNumber = widget.cardNumber;
    _updateSubject();
    await _restoreCardState();
    _loadBallHistory(); //ballHistoryの読み込みと該当数字を開ける
    _updateBingoHighlight();
    if (mounted) {
      setState(() {});
    }
  }

  @override
  void didUpdateWidget(covariant CardGrid oldWidget) {
    super.didUpdateWidget(oldWidget);
    _didUpdateWidget(oldWidget);
  }

  void _didUpdateWidget(covariant CardGrid oldWidget) async {
    if (widget.cardGridUpdateSign == -1) { //何も変更されていない場合
      //何もしない
    } else if (widget.cardGridUpdateSign == 0) { //設定からapplyで戻った場合
      _updateSubject();
      await _restoreCardState();
      _loadBallHistory(); //ballHistoryの読み込みと該当数字を開ける
      _updateBingoHighlight();
      if (mounted) {
        setState(() {});
      }
    } else {  //1以上の整数
      if (oldWidget.cardGridUpdateSign != widget.cardGridUpdateSign) {
        _loadBallHistory(); //ballHistoryの読み込みと該当数字を開ける
        _updateBingoHighlight();
        if (mounted) {
          setState(() {});
        }
      }
    }
  }

  int _indexOf(int row, int col) => col * _gridSize + row;

  void _updateSubject() {
    if (_cardNumber == 1) {
      _subject = Model.cardSubject1;
    } else if (_cardNumber == 2) {
      _subject = Model.cardSubject2;
    } else if (_cardNumber == 3) {
      _subject = Model.cardSubject3;
    } else if (_cardNumber == 4) {
      _subject = Model.cardSubject4;
    } else if (_cardNumber == 5) {
      _subject = Model.cardSubject5;
    } else if (_cardNumber == 6) {
      _subject = Model.cardSubject6;
    }
  }

  Future<void> _restoreCardState() async {
    if (_cardNumber == 1) {
      _cardState = Model.cardState1;
    } else if (_cardNumber == 2) {
      _cardState = Model.cardState2;
    } else if (_cardNumber == 3) {
      _cardState = Model.cardState3;
    } else if (_cardNumber == 4) {
      _cardState = Model.cardState4;
    } else if (_cardNumber == 5) {
      _cardState = Model.cardState5;
    } else if (_cardNumber == 6) {
      _cardState = Model.cardState6;
    }
    _grid = List.generate(
      _gridSize,
          (_) => List.generate(_gridSize, (_) => CardCell(number: 0)),
    );
    final bool restored = _loadStoredCardState(_cardState);
    if (!restored) {
      _generateNewCard();
      await _saveCardState();
    }
  }
  
  bool _loadStoredCardState(String stored) {
    //データが無かったらfalseを返して新しいカードを作る
    if (stored.isEmpty) {
      return false;
    }
    //データをカンマ区切りからint配列に変換
    final List<int> entries = stored
      .split(',')
      .where((element) => element.isNotEmpty)
      .map((e) => int.tryParse(e))  //失敗するとnullを返す
      .where((e) => e != null)      //nullを除外
      .map((e) => e!)               //nullではないことを保証
      .toList();
    //データの数が不一致だったらfalseを返して新しいカードを作る
    if (entries.length != _gridSize * _gridSize) {
      return false;
    }
    //データに0が含まれる不整合な場合はfalseを返して新しいカードを作る
    for (int i = 0; i < _gridSize * _gridSize; i++) {
      if (entries[i] == 0) {
        return false;
      }
    }
    //保存されていたデータを復元
    int index = 0;
    for (int col = 0; col < _gridSize; col++) {
      for (int row = 0; row < _gridSize; row++) {
        _grid[row][col]
          ..number = entries[index]
          ..open = false;
        index++;
      }
    }
    _grid[2][2].open = true;  //中央のFree
    return true;  //カード復元完了
  }

  void _generateNewCard() {
    for (int col = 0; col < _gridSize; col++) {
      final int base = col * 15;
      final numbers = List<int>.generate(15, (index) => base + index + 1);
      numbers.shuffle(_random);
      for (int row = 0; row < _gridSize; row++) {
        _grid[row][col]
          ..number = numbers[row]
          ..open = false;
      }
    }
    _grid[2][2].open = true;
  }

  Future<void> _saveCardState() async {
    final buffer = StringBuffer();
    for (int col = 0; col < _gridSize; col++) {
      for (int row = 0; row < _gridSize; row++) {
        final cellNumber = _grid[row][col].number;
        buffer..write(cellNumber.toString())..write(',');
      }
    }
    await Model.setCardState(_cardNumber, buffer.toString());
  }

  void _loadBallHistory() {
    final String ballHistory = Model.ballHistory;
    if (ballHistory.isEmpty) {
      return;
    }
    final List<int> ballHistoryNumbers = ballHistory
        .split(',')
        .map((e) => int.tryParse(e))        //変換できない場合はnull
        .where((e) => e != null)            //nullを除外
        .map((e) => e!)                     //nullではないことを保証
        .where((e) => e >= 0 && e < 75)     //0は残し、負数と75以上を除外
        .toList();
    if (ballHistoryNumbers.isEmpty) {
      return;
    }
    for (int col = 0; col < _gridSize; col++) {
      for (int row = 0; row < _gridSize; row++) {
        if (ballHistoryNumbers.contains(_grid[row][col].number - 1)) {
          _grid[row][col].open = true;
        }
      }
    }
  }

  void _updateBingoHighlight() {
    _highlighted.clear();
    for (int row = 0; row < _gridSize; row++) {
      bool allOpen = true;
      for (int col = 0; col < _gridSize; col++) {
        if (!_grid[row][col].open && !(row == 2 && col == 2)) {
          allOpen = false;
          break;
        }
      }
      if (allOpen) {
        for (int col = 0; col < _gridSize; col++) {
          _highlighted.add(_indexOf(row, col));
        }
      }
    }
    for (int col = 0; col < _gridSize; col++) {
      bool allOpen = true;
      for (int row = 0; row < _gridSize; row++) {
        if (!_grid[row][col].open && !(row == 2 && col == 2)) {
          allOpen = false;
          break;
        }
      }
      if (allOpen) {
        for (int row = 0; row < _gridSize; row++) {
          _highlighted.add(_indexOf(row, col));
        }
      }
    }
    bool diagonal1 = true;
    for (int i = 0; i < _gridSize; i++) {
      if (!_grid[i][i].open && !(i == 2 && i == 2)) {
        diagonal1 = false;
        break;
      }
    }
    if (diagonal1) {
      for (int i = 0; i < _gridSize; i++) {
        _highlighted.add(_indexOf(i, i));
      }
    }
    bool diagonal2 = true;
    for (int i = 0; i < _gridSize; i++) {
      final int row = i;
      final int col = _gridSize - 1 - i;
      if (!_grid[row][col].open && !(row == 2 && col == 2)) {
        diagonal2 = false;
        break;
      }
    }
    if (diagonal2) {
      for (int i = 0; i < _gridSize; i++) {
        _highlighted.add(_indexOf(i, _gridSize - 1 - i));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      color: _themeColor.mainCardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 5),
        child: Column(children:[
          Text(_subject),
          GridView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: _gridSize * _gridSize,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: _gridSize,
              crossAxisSpacing: 3,
              mainAxisSpacing: 3,
              childAspectRatio: 1,
            ),
            itemBuilder: (context, index) {
              final row = index ~/ _gridSize;
              final col = index % _gridSize;
              return _buildCardCell(row, col);
            },
          )
        ]),
      )
    );
  }

  Widget _buildCardCell(int row, int col) {
    final cell = _grid[row][col];
    final bool isCenter = row == 2 && col == 2;
    final bool isOpen = cell.open || isCenter;
    final int index = _indexOf(row, col);
    final bool highlighted = _highlighted.contains(index);
    final Color background = isOpen ? _themeColor.cardTableOpenBackColor : _themeColor.cardTableCloseBackColor;
    final Color baseTextColor = isOpen ? _themeColor.cardTableOpenForeColor : _themeColor.cardTableCloseForeColor;
    final Color textColor = highlighted ? _themeColor.cardTableBingoForeColor : baseTextColor;
    final String label = isCenter ? 'F' : cell.number.toString();
    return CardGridCell(
      isOpen: isOpen,
      label: label,
      background: background,
      textColor: textColor,
    );
  }

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

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

import 'package:bingogame/model.dart';

class CardGridCell extends StatefulWidget {
  final bool isOpen;
  final String label;
  final Color background;
  final Color textColor;

  const CardGridCell({
    super.key,
    required this.isOpen,
    required this.label,
    required this.background,
    required this.textColor,
  });

  @override
  State<CardGridCell> createState() => _CardGridCellState();
}

class _CardGridCellState extends State<CardGridCell> {
  double _scale = 1.0;

  @override
  void didUpdateWidget(CardGridCell oldWidget) {
    super.didUpdateWidget(oldWidget);

    // isOpen が false → true に変化したとき
    if (!oldWidget.isOpen && widget.isOpen) {
      setState(() => _scale = 3); // 拡大
      Future.delayed(const Duration(milliseconds: 500), () {
        if (mounted) {
          setState(() => _scale = 1.0); // 0.5秒後に元に戻す
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedScale(
      scale: _scale,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeOut,
      child: Container(
        decoration: BoxDecoration(
          color: widget.background,
          borderRadius: BorderRadius.circular(6),
        ),
        alignment: Alignment.center,
        child: Text(
          widget.label,
          style: TextStyle(
            fontSize: Model.textSizeCard.toDouble(),
            fontWeight: FontWeight.bold,
            color: widget.textColor,
          ),
        ),
      ),
    );
  }
}
/// Copyright© ao-system, Inc.


class ConstValue {
  ConstValue._();

  static const int ballCount = 75;

  static const int minQuickDraw = 0;
  static const int maxQuickDraw = 9;
  static const int defaultQuickDraw = 0;

  static const int minAutomaticDrawInterval = 1;
  static const int maxAutomaticDrawInterval = 60;
  static const int defaultAutomaticDrawInterval = 10;

  static const double minTextSizeRatioBall = 0.1;
  static const double maxTextSizeRatioBall = 2.0;
  static const double defaultTextSizeRatioBall = 1.0;

  static const int minTextSizeTable = 8;
  static const int maxTextSizeTable = 100;
  static const int defaultTextSizeTable = 32;

  static const int minTextSizeCard = 8;
  static const int maxTextSizeCard = 100;
  static const int defaultTextSizeCard = 16;

  static const ballImage = '''
    <svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1024 1024">
      <defs>
      <radialGradient id="gradation" cx="4207.03" cy="-2361.28" fx="4207.03" fy="-2361.28" r="759.39" gradientTransform="translate(-4275.84 -2532.86) scale(1.14 -1.14)" gradientUnits="userSpaceOnUse">
        <stop offset="0" stop-color="#e7e7e7"/>
        <stop offset=".5" stop-color="#dcdcdc"/>
        <stop offset=".75" stop-color="#d5d5d5"/>
        <stop offset="1" stop-color="#e1e1e1"/>
      </radialGradient>
      <linearGradient id="gradation2" x1="512" y1="402.03" x2="512" y2="965.65" gradientTransform="translate(0 845.89) scale(1 -1)" gradientUnits="userSpaceOnUse">
        <stop offset="0" stop-color="#eee"/>
        <stop offset=".5" stop-color="#f3f3f3"/>
        <stop offset="1" stop-color="#fff"/>
      </linearGradient>
      <linearGradient id="gradation3" x1="-2985.24" y1="2118.12" x2="-2985.24" y2="1929.06" gradientTransform="translate(-2473.24 -1171.35) rotate(-180) scale(1 -1)" gradientUnits="userSpaceOnUse">
        <stop offset="0" stop-color="#e8e8e8"/>
        <stop offset="1" stop-color="#e1e1e1"/>
      </linearGradient>
      </defs>
      <path d="M1024,512c0,282.62-229.38,512-512,512S0,794.62,0,512,229.38,0,512,0s512,229.38,512,512Z" fill="url(#gradation)"/>
      <path d="M887.81,324.61c0,145.92-155.14,257.54-375.81,257.54s-375.81-111.62-375.81-257.54S291.84,25.6,512,25.6s375.81,152.58,375.81,299.01Z" fill="url(#gradation2)"/>
      <path d="M245.25,878.59c0-56.83,119.3-102.91,266.75-102.91s266.75,46.08,266.75,102.91-119.3,119.81-266.75,119.81-266.75-62.98-266.75-119.81Z" fill="url(#gradation3)"/>
    </svg>
  ''';

  static const ballImage2 = '''
    <svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1024 1024">
      <defs>
      <radialGradient id="gradation" cx="4207.03" cy="-2361.28" fx="4207.03" fy="-2361.28" r="759.39" gradientTransform="translate(-4275.84 -2532.86) scale(1.14 -1.14)" gradientUnits="userSpaceOnUse">
        <stop offset="0" stop-color="#fd0"/>
        <stop offset=".5" stop-color="#f6d600"/>
        <stop offset=".75" stop-color="#f6d600"/>
        <stop offset="1" stop-color="#fe0"/>
      </radialGradient>
      <linearGradient id="gradation2" x1="512" y1="402.03" x2="512" y2="965.65" gradientTransform="translate(0 845.89) scale(1 -1)" gradientUnits="userSpaceOnUse">
        <stop offset="0" stop-color="#fe0"/>
        <stop offset=".5" stop-color="#fea"/>
        <stop offset="1" stop-color="#fe0"/>
      </linearGradient>
      <linearGradient id="gradation3" x1="-2985.24" y1="2118.12" x2="-2985.24" y2="1929.06" gradientTransform="translate(-2473.24 -1171.35) rotate(-180) scale(1 -1)" gradientUnits="userSpaceOnUse">
        <stop offset="0" stop-color="#fea"/>
        <stop offset="1" stop-color="#fe0"/>
      </linearGradient>
      </defs>
      <path d="M1024,512c0,282.62-229.38,512-512,512S0,794.62,0,512,229.38,0,512,0s512,229.38,512,512Z" fill="url(#gradation)"/>
      <path d="M887.81,324.61c0,145.92-155.14,257.54-375.81,257.54s-375.81-111.62-375.81-257.54S291.84,25.6,512,25.6s375.81,152.58,375.81,299.01Z" fill="url(#gradation2)"/>
      <path d="M245.25,878.59c0-56.83,119.3-102.91,266.75-102.91s266.75,46.08,266.75,102.91-119.3,119.81-266.75,119.81-266.75-62.98-266.75-119.81Z" fill="url(#gradation3)"/>
    </svg>
  ''';

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

import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:video_player/video_player.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:wakelock_plus/wakelock_plus.dart';

import 'package:bingogame/l10n/app_localizations.dart';
import 'package:bingogame/ad_banner_widget.dart';
import 'package:bingogame/const_value.dart';
import 'package:bingogame/loading_screen.dart';
import 'package:bingogame/model.dart';
import 'package:bingogame/text_to_speech.dart';
import 'package:bingogame/sound_player.dart';
import 'package:bingogame/theme_color.dart';
import 'package:bingogame/setting_page.dart';
import 'package:bingogame/main.dart';
import 'package:bingogame/card_grid.dart';

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

class _MainHomePageState extends State<MainHomePage> with TickerProviderStateMixin, WidgetsBindingObserver {
  static const Alignment _ballStartAlignment = Alignment(-0.51, 0.56);
  late ThemeColor _themeColor;
  late SoundPlayer _soundPlayer;
  VideoPlayerController? _videoController;
  bool _videoReady = false;
  int? _pendingBallIndex;
  AnimationController? _resultController;
  late final AnimationController _ballController;
  late final Animation<double> _ballScale;
  late final Animation<Alignment> _ballAlignment;
  bool _isSpinning = false;
  bool _videoCompleted = false;
  bool _videoStarted = false;
  bool _secondImageVisible = true;
  List<int> _ballHistory = <int>[];
  Set<int> _ballHistorySet = <int>{};
  int? _currentBall;
  //
  bool _isAutomaticDraw = false;
  Timer? _automaticDrawTimer;
  int _automaticDrawTimeCount = 0;
  double _automaticDrawProgress = 0.0;
  //
  bool _isReady = false;
  //
  //状態が変化する毎に番号を変更してCardGrid()へ知らせる
  //設定ページからapplyで戻ったときは0をセット
  //何も変更されていない時は-1をセット
  //抽選後は結果の数字をセット(1以上ならいい)
  int _cardGridUpdateSign = 0;
  //

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

  Future<void> _initState() async {
    _themeColor = ThemeColor(themeNumber: Model.themeNumber, context: context);
    _soundPlayer = SoundPlayer();
    _wakelock();
    //
    _resultController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 500),
    );
    _ballController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 3),
    );
    final CurvedAnimation ballCurve = CurvedAnimation(
      parent: _ballController,
      curve: Curves.easeOut,
    );
    _ballScale = ballCurve;
    _ballAlignment = AlignmentTween(
      begin: _ballStartAlignment,
      end: Alignment.topLeft,
    ).animate(ballCurve);
    _ballController.addListener(_onBallAnimationTick);
    //
    await _setupVideoController();
    _applyBallHistory();
    await TextToSpeech.applyPreferences(Model.ttsVoiceId,Model.ttsVolume);
    //
    if (mounted) {
      setState(() {
        _isReady = true;
      });
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    WakelockPlus.disable();
    _videoController
      ?..removeListener(_onVideoFrame)
      ..dispose();
    _resultController?.dispose();
    _ballController.removeListener(_onBallAnimationTick);
    _ballController.dispose();
    _soundPlayer.dispose();
    _automaticDrawTimer?.cancel();
    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();
    }
  }

  void _applyBallHistory() {
    _ballHistory = _parseHistory(Model.ballHistory);
    _ballHistorySet = _ballHistory.toSet();
    if (_ballHistory.isNotEmpty) {
      _currentBall = _ballHistory.last;
      _resultController?.forward(from: 1);
    } else {
      _currentBall = null;
    }
  }

  void _ttsResult(String text) async {
    if (Model.ttsEnabled && Model.ttsVolume > 0.0) {
      await TextToSpeech.speak(text);
    }
  }

  Future<void> _setupVideoController() async {
    late VideoPlayerController videoController;
    if (Model.colorScheme == 0) {
      videoController = VideoPlayerController.asset(
        'assets/video/bingo.mp4',
        videoPlayerOptions: VideoPlayerOptions(mixWithOthers: true),
      );
    } else if (Model.colorScheme == 1) {
      videoController = VideoPlayerController.asset(
        'assets/video/bingo2.mp4',
        videoPlayerOptions: VideoPlayerOptions(mixWithOthers: true),
      );
    }
    _videoController = videoController;
    await videoController.initialize();
    await videoController.setLooping(false);
    await videoController.setPlaybackSpeed((Model.quickDraw / 2.0) + 1.0);
    videoController.addListener(_onVideoFrame);
    if (mounted) {
      setState(() {
        _videoReady = true;
      });
    }
  }

  void _onVideoFrame() {
    final videoController = _videoController;
    if (videoController == null ||
        !_isSpinning ||
        _pendingBallIndex == null ||
        _videoCompleted) {
      return;
    }
    final value = videoController.value;
    if (!value.isInitialized) {
      return;
    }
    if (value.isPlaying) {
      _videoStarted = true;
      return;
    }
    if (!_videoStarted) {
      return;
    }
    final bool finished =
        value.duration > Duration.zero &&
        value.position >= value.duration - const Duration(milliseconds: 100);
    if (finished) {
      _onSpinCompleted(_pendingBallIndex!);
    }
  }

  void _onBallAnimationTick() {
    if (!mounted) {
      return;
    }
    setState(() {});
  }

  List<int> _parseHistory(String stored) {
    if (stored.isEmpty) {
      return <int>[];
    }
    final List<int> result = <int>[];
    for (final piece in stored.split(',')) {
      if (piece.isEmpty) continue;
      final value = int.tryParse(piece);
      if (value != null && value >= 0 && value < ConstValue.ballCount) {
        result.add(value);
      }
    }
    return result;
  }

  Future<void> _handleStart() async {
    if (_isSpinning || !_videoReady) {
      return;
    }
    final nextBall = _pickNextBall();
    if (nextBall == null) {
      _automaticDrawCancel();
      _notifyFinished();
      return;
    }
    HapticFeedback.selectionClick();
    _resultController?.reset();
    _ballController.reset();
    setState(() {
      _isSpinning = true;
      _pendingBallIndex = nextBall;
      _videoCompleted = false;
      _currentBall = null;
      _videoStarted = false;
    });
    await _soundPlayer.setSpeed((Model.quickDraw / 2.0) + 1.0);
    unawaited(_soundPlayer.play(Model.machineVolume));
    //毎回動画を作り直さないと再生されなくなる
    _videoController?.dispose();
    await _setupVideoController();
    await _videoController?.play();
    //0.1秒後に動画に重ねている画像をフェードアウト
    Future.delayed(Duration(milliseconds: 100), () {
      if (mounted) {
        setState(() {
          _secondImageVisible = false;
        });
      }
    });
  }

  void _automaticDrawStart() {
    _cardGridUpdateSign = -1;  //何も変更されていない設定
    _automaticDrawTimeCount = 0;
    _automaticDrawTimer = Timer.periodic(Duration(milliseconds: 100), (timer) async {
      if (_isSpinning || !_videoReady) {
        return;
      }
      _automaticDrawTimeCount += 1;
      setState(() {
        _automaticDrawProgress = (_automaticDrawTimeCount / (Model.automaticDrawInterval * 10)).clamp(0.0,1.0);
      });
      if (_automaticDrawTimeCount >= Model.automaticDrawInterval * 10) {
        _automaticDrawTimeCount = 0;
        await _handleStart();
      }
    });
  }

  void _automaticDrawStop() {
    _automaticDrawTimer?.cancel();
    _automaticDrawTimer = null;
    setState(() {
      _automaticDrawProgress = 0.0;
    });
  }

  void _automaticDrawCancel() {
    _automaticDrawStop();
    setState(() {
      _isAutomaticDraw = false;
    });
  }

  int? _pickNextBall() {
    if (_ballHistory.length >= ConstValue.ballCount) {
      return null;
    }
    final remaining = <int>[];
    for (var i = 0; i < ConstValue.ballCount; i++) {
      if (!_ballHistorySet.contains(i)) {
        remaining.add(i);
      }
    }
    if (remaining.isEmpty) {
      return null;
    }
    remaining.shuffle(Random());
    return remaining.first;
  }

  void _onSpinCompleted(int ballIndex) async {
    _videoCompleted = true;
    _pendingBallIndex = null;
    _videoController?.pause();
    _soundPlayer.stop();
    final updated = List<int>.from(_ballHistory)..add(ballIndex);
    _ballHistory = updated;
    _ballHistorySet = updated.toSet();
    _currentBall = ballIndex;
    Model.setBallHistory(updated.join(','));
    _resultController?.forward(from: 0);
    _ttsResult((ballIndex + 1).toString());
    if (mounted) {
      setState(() {
        _isSpinning = false;
      });
    }
    _ballController.forward(from: 0);
    _secondImageVisible = true;
    Future.delayed(Duration(milliseconds: 2000), () {
      _cardGridUpdateSign = ballIndex + 1;  //状態が変更されたことを知らせる。1以上の整数
    });
  }

  void _notifyFinished() {
    final l = AppLocalizations.of(context);
    if (l == null) {
      return;
    }
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(SnackBar(content: Text(l.finished)));
  }

  Future<void> _openSetting() async {
    _automaticDrawCancel();
    //
    final updated = await Navigator.push<bool>(
      context,
      MaterialPageRoute(builder: (_) => const SettingPage()),
    );
    if (!mounted) {
      return;
    }
    if (updated == true) {
      MainApp.of(context).rebuildApp();
      _themeColor = ThemeColor(themeNumber: Model.themeNumber, context: context);
      _wakelock();
      _applyBallHistory();
      await TextToSpeech.applyPreferences(Model.ttsVoiceId,Model.ttsVolume);
      _cardGridUpdateSign = 0;  //状態が変更されたことを知らせる
    } else {
      _cardGridUpdateSign = -1;  //何も変更されていないことを知らせる
    }
    if (mounted) {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isReady == false) {
      return const LoadingScreen();
    }
    final l = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: _themeColor.mainBackColor,
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: LayoutBuilder(
                builder: (context, constraints) {
                  final bool wideLayout = constraints.maxWidth >= 720;
                  return SingleChildScrollView(
                    padding: const EdgeInsets.only(left: 4, right: 4, top: 0, bottom: 100),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        Table(
                          columnWidths: const {
                            0: FlexColumnWidth(1),
                            1: FlexColumnWidth(1),
                          },
                          children: [
                            TableRow(
                              children: [
                                _buildVideoSection(l),
                                Column(
                                  children: [
                                    _buildControlButtons(l),
                                    _buildAutomaticDraw(l),
                                  ],
                                ), // 右のセル
                              ],
                            ),
                          ],
                        ),
                        Row(children:[
                          Expanded(child: CardGrid(cardNumber: 1, cardGridUpdateSign: _cardGridUpdateSign)),
                          Expanded(child: CardGrid(cardNumber: 2, cardGridUpdateSign: _cardGridUpdateSign)),
                        ]),
                        Row(children:[
                          Expanded(child: CardGrid(cardNumber: 3, cardGridUpdateSign: _cardGridUpdateSign)),
                          Expanded(child: CardGrid(cardNumber: 4, cardGridUpdateSign: _cardGridUpdateSign)),
                        ]),
                        Row(children:[
                          Expanded(child: CardGrid(cardNumber: 5, cardGridUpdateSign: _cardGridUpdateSign)),
                          Expanded(child: CardGrid(cardNumber: 6, cardGridUpdateSign: _cardGridUpdateSign)),
                        ]),
                        if (wideLayout)
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Expanded(
                                child: _buildProgressCard(l),
                              ),
                              Expanded(child: _buildHistoryCard(l)),
                            ],
                          )
                        else ...[
                          _buildProgressCard(l),
                          _buildHistoryCard(l),
                        ],
                      ],
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
      bottomNavigationBar: AdBannerWidget(adManager: MainApp.of(context).adManager),
    );
  }

  Widget _buildControlButtons(AppLocalizations l) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 4),
      child: SizedBox(
        width: double.infinity,
        child: OutlinedButton.icon(
          onPressed: _isSpinning ? null : _openSetting,
          icon: const Icon(Icons.settings_rounded),
          label: Text(l.setting),
          style: OutlinedButton.styleFrom(
            foregroundColor: _themeColor.mainButtonColor,
            side: BorderSide(color: _themeColor.mainButtonColor),
            padding: EdgeInsets.zero,
            visualDensity: VisualDensity.compact,
          ),
        ),
      ),
    );
  }

  Widget _buildVideoSection(AppLocalizations l) {
    final videoController = _videoController;
    final videoValue = videoController?.value;
    final bool hasVideo = videoValue?.isInitialized ?? false;
    return Card(
      color: _themeColor.cardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(12),
            child: AspectRatio(
              aspectRatio: 1,
              child: LayoutBuilder(
                builder: (context, boxConstraints) {
                  final double videoWidth = boxConstraints.maxWidth;
                  final double ballSize = (videoWidth * 0.5 * _ballScale.value)
                      .clamp(0.0, videoWidth);
                  final bool showBall =
                      _currentBall != null &&
                      (_ballController.value > 0 ||
                          _ballController.isAnimating);
                  return Stack(
                    fit: StackFit.expand,
                    children: [
                      _buildLastFrame(),
                      if (hasVideo && videoController != null)
                        AnimatedOpacity(
                          opacity: 1.0,
                          duration: Duration(milliseconds: 200),
                          child: VideoPlayer(videoController),
                        ),
                      AnimatedOpacity(
                        opacity: _secondImageVisible ? 1.0 : 0.0,
                        duration: Duration(milliseconds: 400),
                        child: _buildLastFrame(),
                      ),
                      if (showBall && ballSize > 0)
                        Padding(
                          padding: const EdgeInsets.only(left: 4, top: 4),
                          child: Align(
                            alignment: _ballAlignment.value,
                            child: SizedBox(
                              width: ballSize,
                              height: ballSize,
                              child: Stack(
                                alignment: Alignment.center,
                                children: [
                                  _buildBallImage(ballSize),
                                  Text(
                                    ((_currentBall ?? 0) + 1).toString(),
                                    style: GoogleFonts.ubuntu(
                                      fontSize: ballSize * 0.7 * Model.textSizeRatioBall,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.black,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      Align(
                        alignment: Alignment.bottomRight,
                        child: Padding(
                          padding: const EdgeInsets.only(right: 8, bottom: 3),
                          child: ElevatedButton(
                            onPressed: (_isSpinning || !_videoReady)
                                ? null
                                : _handleStart,
                            style: ElevatedButton.styleFrom(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 12,
                                vertical: 4,
                              ),
                              elevation: 0,
                              backgroundColor: _isSpinning
                                  ? Theme.of(context).disabledColor
                                  : _themeColor.mainStartBackColor,
                              foregroundColor: _themeColor.mainStartForeColor,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10),
                              ),
                            ),
                            child: Padding(
                              padding: const EdgeInsets.symmetric(vertical: 1),
                              child: Text(
                                l.start,
                                style: const TextStyle(
                                  fontSize: 20,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  Image _buildLastFrame() {
    if (Model.colorScheme == 1) {
      return Image.asset('assets/image/last_frame2.webp', fit: BoxFit.contain);
    }
    //Model.colorScheme == 0
    return Image.asset('assets/image/last_frame.webp', fit: BoxFit.contain);
  }

  SvgPicture _buildBallImage(double ballSize) {
    if (Model.colorScheme == 1) {
      return SvgPicture.string(
        ConstValue.ballImage2,
        width: ballSize,
        height: ballSize,
      );
    }
    //Model.colorScheme == 0
    return SvgPicture.string(
      ConstValue.ballImage,
      width: ballSize,
      height: ballSize,
    );
  }

  Widget _buildAutomaticDraw(AppLocalizations l) {
    return Card(
      color: _themeColor.mainCardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.only(left: 8, right: 8, top: 4, bottom: 0),
        child: Column(
          children: [
            Text(l.automaticDraw, textAlign: TextAlign.center),
            Row(children:[
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 8.0),
                  child: LinearProgressIndicator(
                    value: _automaticDrawProgress,
                    minHeight: 3,
                  ),
                )
              ),
              Switch(
                value: _isAutomaticDraw,
                onChanged: (value) {
                  setState(() {
                    _isAutomaticDraw = value;
                    if (value) {
                      _automaticDrawStart();
                    } else {
                      _automaticDrawStop();
                    }
                  });
                },
              ),
            ])
          ],
        ),
      ),
    );
  }

  Widget _buildProgressCard(AppLocalizations l) {
    return Card(
      color: _themeColor.mainCardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.all(8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(l.progress, textAlign: TextAlign.center),
            const SizedBox(height: 8),
            _buildProgressGrid(),
          ],
        ),
      ),
    );
  }

  Widget _buildHistoryCard(AppLocalizations l) {
    return Card(
      color: _themeColor.mainCardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.all(8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(l.history, textAlign: TextAlign.center),
            const SizedBox(height: 8),
            _buildHistoryGrid(),
          ],
        ),
      ),
    );
  }

  Widget _buildProgressGrid() {
    const int columns = 5;
    final int rows = (ConstValue.ballCount / columns).ceil();
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: columns,
        mainAxisSpacing: 3,
        crossAxisSpacing: 3,
        childAspectRatio: 1.6,
      ),
      itemCount: ConstValue.ballCount,
      itemBuilder: (context, index) {
        final int col = index % columns;
        final int row = index ~/ columns;
        final int verticalIndex = row + col * rows;
        final isDrawn = _ballHistorySet.contains(verticalIndex);
        final isLast = _ballHistory.isNotEmpty && _ballHistory.last == verticalIndex;
        final background = isLast
            ? _themeColor.mainTableLastColor
            : (isDrawn ? _themeColor.mainTableOpenColor : _themeColor.mainTableCloseColor);
        return Container(
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: background,
            borderRadius: BorderRadius.circular(6),
          ),
          child: Text(
            (verticalIndex + 1).toString(),
            style: TextStyle(
              fontSize: Model.textSizeTable.toDouble(),
              fontWeight: FontWeight.bold,
              color: _themeColor.mainTableTextColor,
            ),
          ),
        );
      },
    );
  }

  Widget _buildHistoryGrid() {
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 5,
        mainAxisSpacing: 3,
        crossAxisSpacing: 3,
        childAspectRatio: 1.6,
      ),
      itemCount: ConstValue.ballCount,
      itemBuilder: (context, index) {
        if (index >= _ballHistory.length) {
          return Container(
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: _themeColor.mainTableCloseColor,
              borderRadius: BorderRadius.circular(6),
            ),
          );
        }
        final ballIndex = _ballHistory[index];
        final isLast = index == _ballHistory.length - 1;
        final background = isLast ? _themeColor.mainTableLastColor : _themeColor.mainTableOpenColor;
        return Container(
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: background,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Text(
            (ballIndex + 1).toString(),
            style: TextStyle(
              fontSize: Model.textSizeTable.toDouble(),
              fontWeight: FontWeight.bold,
              color: _themeColor.mainTableTextColor,
            ),
          ),
        );
      },
    );
  }

}
/// 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: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:bingogame/l10n/app_localizations.dart';
import 'package:bingogame/model.dart';
import 'package:bingogame/home_page.dart';
import 'package:bingogame/theme_mode_number.dart';
import 'package:bingogame/loading_screen.dart';
import 'package:bingogame/parse_locale_tag.dart';
import 'package:bingogame/ad_ump_status.dart';
import 'package:bingogame/att_service.dart';
import 'package:bingogame/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);
    });
  }

  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 = Model.colorScheme == 1 ? Colors.blue : Colors.green;
    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 'dart:io';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:bingogame/const_value.dart';
import 'package:bingogame/l10n/app_localizations.dart';

class Model {
  Model._();

  static const String _prefBallHistory = 'ballHistory';
  static const String _prefCardState1 = 'cardState1';
  static const String _prefCardState2 = 'cardState2';
  static const String _prefCardState3 = 'cardState3';
  static const String _prefCardState4 = 'cardState4';
  static const String _prefCardState5 = 'cardState5';
  static const String _prefCardState6 = 'cardState6';
  static const String _prefCardSubject1 = 'cardSubject1';
  static const String _prefCardSubject2 = 'cardSubject2';
  static const String _prefCardSubject3 = 'cardSubject3';
  static const String _prefCardSubject4 = 'cardSubject4';
  static const String _prefCardSubject5 = 'cardSubject5';
  static const String _prefCardSubject6 = 'cardSubject6';
  static const String _prefTtsEnabled = 'ttsEnabled';
  static const String _prefTtsVolume = 'ttsVolume';
  static const String _prefTtsVoiceId = 'ttsVoiceId';
  static const String _prefMachineVolume = 'machineVolume';
  static const String _prefQuickDraw = 'quickDraw';
  static const String _prefAutomaticDrawInterval = 'automaticDrawInterval';
  static const String _prefTextSizeRatioBall = 'textSizeRatioBall';
  static const String _prefTextSizeTable = 'textSizeTable';
  static const String _prefTextSizeCard = 'textSizeCard';
  static const String _prefWakelockEnabled = 'wakelockEnabled';
  static const String _prefColorScheme = 'colorScheme';
  static const String _prefThemeNumber = 'themeNumber';
  static const String _prefLanguageCode = 'languageCode';

  static bool _ready = false;
  static String _ballHistory = '';  //0から数える数字のカンマ区切り文字列 e.g. "2,5,74,0,32"
  static String _cardState1 = '';  //列×行の数字。0は使用しない e.g. "12,1,11,10,3,25,24,29,22,30,41,35,31,38,44,56,48,47,51,53,75,67,65,68,69,"
  static String _cardState2 = '';
  static String _cardState3 = '';
  static String _cardState4 = '';
  static String _cardState5 = '';
  static String _cardState6 = '';
  static String _cardSubject1 = 'A';
  static String _cardSubject2 = 'B';
  static String _cardSubject3 = 'C';
  static String _cardSubject4 = 'D';
  static String _cardSubject5 = 'E';
  static String _cardSubject6 = 'F';
  static bool _ttsEnabled = true;
  static String _ttsVoiceId = '';
  static double _ttsVolume = 1.0;
  static double _machineVolume = 1.0;
  static int _quickDraw = ConstValue.defaultQuickDraw;
  static int _automaticDrawInterval = ConstValue.defaultAutomaticDrawInterval;
  static double _textSizeRatioBall = ConstValue.defaultTextSizeRatioBall;
  static int _textSizeTable = ConstValue.defaultTextSizeTable;
  static int _textSizeCard = ConstValue.defaultTextSizeCard;
  static bool _wakelockEnabled = false;
  static int _colorScheme = 0;
  static int _themeNumber = 0;
  static String _languageCode = '';

  static String get ballHistory => _ballHistory;
  static String get cardState1 => _cardState1;
  static String get cardState2 => _cardState2;
  static String get cardState3 => _cardState3;
  static String get cardState4 => _cardState4;
  static String get cardState5 => _cardState5;
  static String get cardState6 => _cardState6;
  static String get cardSubject1 => _cardSubject1;
  static String get cardSubject2 => _cardSubject2;
  static String get cardSubject3 => _cardSubject3;
  static String get cardSubject4 => _cardSubject4;
  static String get cardSubject5 => _cardSubject5;
  static String get cardSubject6 => _cardSubject6;
  static bool get ttsEnabled => _ttsEnabled;
  static String get ttsVoiceId => _ttsVoiceId;
  static double get ttsVolume => _ttsVolume;
  static double get machineVolume => _machineVolume;
  static int get quickDraw => _quickDraw;
  static int get automaticDrawInterval => _automaticDrawInterval;
  static double get textSizeRatioBall => _textSizeRatioBall;
  static int get textSizeTable => _textSizeTable;
  static int get textSizeCard => _textSizeCard;
  static bool get wakelockEnabled => _wakelockEnabled;
  static int get colorScheme => _colorScheme;
  static int get themeNumber => _themeNumber;
  static String get languageCode => _languageCode;

  static Future<void> ensureReady() async {
    if (_ready) {
      return;
    }
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    //
    _ballHistory = prefs.getString(_prefBallHistory) ?? '';
    _cardState1 = prefs.getString(_prefCardState1) ?? '';
    _cardState2 = prefs.getString(_prefCardState2) ?? '';
    _cardState3 = prefs.getString(_prefCardState3) ?? '';
    _cardState4 = prefs.getString(_prefCardState4) ?? '';
    _cardState5 = prefs.getString(_prefCardState5) ?? '';
    _cardState6 = prefs.getString(_prefCardState6) ?? '';
    _cardSubject1 = prefs.getString(_prefCardSubject1) ?? 'A';
    _cardSubject2 = prefs.getString(_prefCardSubject2) ?? 'B';
    _cardSubject3 = prefs.getString(_prefCardSubject3) ?? 'C';
    _cardSubject4 = prefs.getString(_prefCardSubject4) ?? 'D';
    _cardSubject5 = prefs.getString(_prefCardSubject5) ?? 'E';
    _cardSubject6 = prefs.getString(_prefCardSubject6) ?? 'F';
    _ttsEnabled = prefs.getBool(_prefTtsEnabled) ?? true;
    _ttsVoiceId = prefs.getString(_prefTtsVoiceId) ?? '';
    _ttsVolume = (prefs.getDouble(_prefTtsVolume) ?? 1.0).clamp(0.0,1.0);
    _machineVolume = (prefs.getDouble(_prefMachineVolume) ?? 1.0).clamp(0.0,1.0);
    _quickDraw = (prefs.getInt(_prefQuickDraw) ?? ConstValue.defaultQuickDraw).clamp(
      ConstValue.minQuickDraw,
      ConstValue.maxQuickDraw,
    );
    _automaticDrawInterval = (prefs.getInt(_prefAutomaticDrawInterval) ?? ConstValue.defaultAutomaticDrawInterval).clamp(
      ConstValue.minAutomaticDrawInterval,
      ConstValue.maxAutomaticDrawInterval,
    );
    _textSizeRatioBall = (prefs.getDouble(_prefTextSizeRatioBall) ?? ConstValue.defaultTextSizeRatioBall).clamp(
      ConstValue.minTextSizeRatioBall,
      ConstValue.maxTextSizeRatioBall,
    );
    _textSizeTable = (prefs.getInt(_prefTextSizeTable) ?? ConstValue.defaultTextSizeTable).clamp(
      ConstValue.minTextSizeTable,
      ConstValue.maxTextSizeTable,
    );
    _textSizeCard = (prefs.getInt(_prefTextSizeCard) ?? ConstValue.defaultTextSizeCard).clamp(
      ConstValue.minTextSizeCard,
      ConstValue.maxTextSizeCard,
    );
    final int initialColorScheme = (Platform.isIOS) ? 1 : 0;  //iosの場合は初期色を変える
    _wakelockEnabled = prefs.getBool(_prefWakelockEnabled) ?? false;
    _colorScheme = (prefs.getInt(_prefColorScheme) ?? initialColorScheme).clamp(0, 1);
    _themeNumber = (prefs.getInt(_prefThemeNumber) ?? 0).clamp(0, 2);
    _languageCode = prefs.getString(_prefLanguageCode) ?? ui.PlatformDispatcher.instance.locale.languageCode;
    _languageCode = _resolveLanguageCode(_languageCode);
    _ready = true;
  }

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

  static Future<void> resetMachine() async {
    _ballHistory = '';
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_prefBallHistory);
  }

  static Future<void> resetCard(int number) async {
    final prefs = await SharedPreferences.getInstance();
    if (number == 1) {
      _cardState1 = '';
      await prefs.remove(_prefCardState1);
    } else if (number == 2) {
      _cardState2 = '';
      await prefs.remove(_prefCardState2);
    } else if (number == 3) {
      _cardState3 = '';
      await prefs.remove(_prefCardState3);
    } else if (number == 4) {
      _cardState4 = '';
      await prefs.remove(_prefCardState4);
    } else if (number == 5) {
      _cardState5 = '';
      await prefs.remove(_prefCardState5);
    } else if (number == 6) {
      _cardState6 = '';
      await prefs.remove(_prefCardState6);
    }
  }

  static Future<void> setCardSubject1(String value) async {
    _cardSubject1 = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefCardSubject1, value);
  }

  static Future<void> setCardSubject2(String value) async {
    _cardSubject2 = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefCardSubject2, value);
  }

  static Future<void> setCardSubject3(String value) async {
    _cardSubject3 = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefCardSubject3, value);
  }

  static Future<void> setCardSubject4(String value) async {
    _cardSubject4 = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefCardSubject4, value);
  }

  static Future<void> setCardSubject5(String value) async {
    _cardSubject5 = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefCardSubject5, value);
  }

  static Future<void> setCardSubject6(String value) async {
    _cardSubject6 = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefCardSubject6, value);
  }

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

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

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

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

  static Future<void> setQuickDraw(int value) async {
    _quickDraw = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefQuickDraw, value);
  }

  static Future<void> setAutomaticDrawInterval(int value) async {
    _automaticDrawInterval = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefAutomaticDrawInterval, value);
  }

  static Future<void> setTextSizeRatioBall(double value) async {
    _textSizeRatioBall = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setDouble(_prefTextSizeRatioBall, value);
  }

  static Future<void> setTextSizeTable(int value) async {
    _textSizeTable = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefTextSizeTable, value);
  }

  static Future<void> setTextSizeCard(int value) async {
    _textSizeCard = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefTextSizeCard, value);
  }

  static Future<void> setBallHistory(String value) async {
    _ballHistory = value;  //0から数える数字のカンマ区切り文字列 e.g. "2,5,74,0,32"
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefBallHistory, value);
  }

  static Future<void> setCardState(int number, String value) async {
    final prefs = await SharedPreferences.getInstance();
    if (number == 1) {
      _cardState1 = value;
      if (value.isEmpty) {
        await prefs.remove(_prefCardState1);
      } else {
        await prefs.setString(_prefCardState1, value);
      }
    } else if (number == 2) {
      _cardState2 = value;
      if (value.isEmpty) {
        await prefs.remove(_prefCardState2);
      } else {
        await prefs.setString(_prefCardState2, value);
      }
    } else if (number == 3) {
      _cardState3 = value;
      if (value.isEmpty) {
        await prefs.remove(_prefCardState3);
      } else {
        await prefs.setString(_prefCardState3, value);
      }
    } else if (number == 4) {
      _cardState4 = value;
      if (value.isEmpty) {
        await prefs.remove(_prefCardState4);
      } else {
        await prefs.setString(_prefCardState4, value);
      }
    } else if (number == 5) {
      _cardState5 = value;
      if (value.isEmpty) {
        await prefs.remove(_prefCardState5);
      } else {
        await prefs.setString(_prefCardState5, value);
      }
    } else if (number == 6) {
      _cardState6 = value;
      if (value.isEmpty) {
        await prefs.remove(_prefCardState6);
      } else {
        await prefs.setString(_prefCardState6, value);
      }
    }
  }

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

  static Future<void> setColorScheme(int value) async {
    _colorScheme = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefColorScheme, 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';

import 'package:bingogame/theme_color.dart';
import 'package:bingogame/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/foundation.dart";
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:in_app_review/in_app_review.dart';

import "package:bingogame/setting_card.dart";
import 'package:bingogame/l10n/app_localizations.dart';
import 'package:bingogame/ad_banner_widget.dart';
import 'package:bingogame/ad_ump_status.dart';
import 'package:bingogame/const_value.dart';
import 'package:bingogame/loading_screen.dart';
import 'package:bingogame/model.dart';
import 'package:bingogame/text_to_speech.dart';
import 'package:bingogame/theme_color.dart';
import 'package:bingogame/_secrets.dart';
import 'package:bingogame/main.dart';
import 'package:bingogame/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;
  final _inAppReview = InAppReview.instance;
  bool _wakelockEnabled = true;
  int _colorScheme = 0;
  int _themeNumber = 0;
  String _languageCode = '';
  bool _isReady = false;
  //
  TextEditingController _cardSubjectController1 = TextEditingController();
  TextEditingController _cardSubjectController2 = TextEditingController();
  TextEditingController _cardSubjectController3 = TextEditingController();
  TextEditingController _cardSubjectController4 = TextEditingController();
  TextEditingController _cardSubjectController5 = TextEditingController();
  TextEditingController _cardSubjectController6 = TextEditingController();
  bool _resetMachine = false;
  bool _resetCard = false;
  int _quickDraw = ConstValue.defaultQuickDraw;
  int _automaticDrawInterval = ConstValue.defaultAutomaticDrawInterval;
  double _textSizeRatioBall = ConstValue.defaultTextSizeRatioBall;
  int _textSizeTable = ConstValue.defaultTextSizeTable;
  int _textSizeCard = ConstValue.defaultTextSizeCard;
  bool _ttsEnabled = true;
  String _ttsVoiceId = '';
  double _ttsVolume = 1.0;
  double _machineVolume = 1.0;
  //
  @override
  void initState() {
    super.initState();
    _initState();
  }

  void _initState() async {
    //ump
    _adUmpService = AdUmpService();
    await _refreshConsentInfo();
    //model
    _cardSubjectController1 = TextEditingController(text: Model.cardSubject1);
    _cardSubjectController2 = TextEditingController(text: Model.cardSubject2);
    _cardSubjectController3 = TextEditingController(text: Model.cardSubject3);
    _cardSubjectController4 = TextEditingController(text: Model.cardSubject4);
    _cardSubjectController5 = TextEditingController(text: Model.cardSubject5);
    _cardSubjectController6 = TextEditingController(text: Model.cardSubject6);
    _ttsEnabled = Model.ttsEnabled;
    _ttsVolume = Model.ttsVolume;
    _ttsVoiceId = Model.ttsVoiceId;
    _machineVolume = Model.machineVolume;
    _quickDraw = Model.quickDraw;
    _automaticDrawInterval = Model.automaticDrawInterval;
    _textSizeRatioBall = Model.textSizeRatioBall;
    _textSizeTable = Model.textSizeTable;
    _textSizeCard = Model.textSizeCard;
    _wakelockEnabled = Model.wakelockEnabled;
    _colorScheme = Model.colorScheme;
    _themeNumber = Model.themeNumber;
    _languageCode = Model.languageCode;
    //speech
    await TextToSpeech.applyPreferences(Model.ttsVoiceId,Model.ttsVolume);
    setState(() {
      _isReady = true;
    });
  }

  @override
  void 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; });
    }
  }

  Future<void> _onApply() async {
    FocusScope.of(context).unfocus();
    if (_resetMachine) {
      await Model.resetMachine();
    }
    if (_resetCard) {
      await Model.resetCard(1);
      await Model.resetCard(2);
      await Model.resetCard(3);
      await Model.resetCard(4);
      await Model.resetCard(5);
      await Model.resetCard(6);
    }
    await Model.setCardSubject1(_cardSubjectController1.text);
    await Model.setCardSubject2(_cardSubjectController2.text);
    await Model.setCardSubject3(_cardSubjectController3.text);
    await Model.setCardSubject4(_cardSubjectController4.text);
    await Model.setCardSubject5(_cardSubjectController5.text);
    await Model.setCardSubject6(_cardSubjectController6.text);
    await Model.setMachineVolume(_machineVolume);
    await Model.setQuickDraw(_quickDraw);
    await Model.setAutomaticDrawInterval(_automaticDrawInterval);
    await Model.setTextSizeRatioBall(_textSizeRatioBall);
    await Model.setTextSizeTable(_textSizeTable);
    await Model.setTextSizeCard(_textSizeCard);
    await Model.setTtsEnabled(_ttsEnabled);
    await Model.setTtsVoiceId(_ttsVoiceId);
    await Model.setTtsVolume(_ttsVolume);
    await Model.setWakelockEnabled(_wakelockEnabled);
    await Model.setColorScheme(_colorScheme);
    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(
        centerTitle: true,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.close),
          onPressed: () => Navigator.of(context).pop(false),
        ),
        title: Text(l.setting),
        foregroundColor: _themeColor.appBarForegroundColor,
        backgroundColor: Colors.transparent,
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: 10),
            child: IconButton(
              onPressed: _onApply,
              tooltip: l.apply,
              icon: const Icon(Icons.check),
            ),
          ),
        ],
      ),
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: GestureDetector(
                onTap: () => FocusScope.of(context).unfocus(),
                child: SingleChildScrollView(
                  padding: const EdgeInsets.only(left: 12, right: 12, top: 0, bottom: 100),
                  child: Column(
                    children: [
                      _buildCardSubject(l, t),
                      _buildReset(l, t),
                      _buildTextSize(l, t),
                      _buildQuickDraw(l, t),
                      _buildAutomaticDrawInterval(l, t),
                      _buildVolumeSection(l, t),
                      _buildSpeechSettings(l, t),
                      _buildWakelockEnabled(l, t),
                      _buildColorScheme(l, t),
                      _buildTheme(l, t),
                      _buildLanguage(l, t),
                      _buildReview(l, t),
                      _buildCmp(l, t),
                      _buildAtt(l, t),
                      _buildUsage(l, t),
                    ],
                  ),
                ),
              ),
            ),
          ],
        )
      ),
      bottomNavigationBar: AdBannerWidget(adManager: MainApp.of(context).adManager),
    );
  }

  InputDecoration _inputDecoration() {
    final radius = BorderRadius.circular(8);
    return InputDecoration(
      isDense: true,
      filled: true,
      fillColor: _themeColor.cardColor,
      contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
      border: OutlineInputBorder(
        borderRadius: radius,
        borderSide: BorderSide(color: _themeColor.backColor, width: 1),
      ),
    );
  }

  Widget _buildCardSubject(AppLocalizations l, TextTheme t) {
    final controllers = [
      _cardSubjectController1,
      _cardSubjectController2,
      _cardSubjectController3,
      _cardSubjectController4,
      _cardSubjectController5,
      _cardSubjectController6,
    ];
    return SettingCard(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(l.cardSubject),
            const SizedBox(height: 6),

            Table(
              columnWidths: const {
                0: FlexColumnWidth(0.2),
                1: FlexColumnWidth(2),
              },
              children: List.generate(6, (i) {
                return TableRow(
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(top: 16),
                      child: Text('${i + 1}'),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 6),
                      child: TextField(
                        controller: controllers[i],
                        keyboardType: TextInputType.text,
                        decoration: _inputDecoration(),
                      ),
                    ),
                  ],
                );
              }),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildReset(AppLocalizations l, TextTheme t) {
    return Column(
      children: [
        SettingCard.top(
          child: ListTile(
            contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            title: Text(
              l.resetMachine,
              style: t.bodyMedium,
            ),
            subtitle: Text(
              l.resetMachineNote,
              style: t.bodySmall,
            ),
            trailing: Switch(
              value: _resetMachine,
              onChanged: (value) {
                setState(() {
                  _resetMachine = value;
                });
              },
            ),
          ),
        ),
        SettingCard.bottom(
          child: ListTile(
            contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            title: Text(
              l.resetCard,
              style: t.bodyMedium,
            ),
            subtitle: Text(
              l.resetCardNote,
              style: t.bodySmall,
            ),
            trailing: Switch(
              value: _resetCard,
              onChanged: (value) {
                setState(() {
                  _resetCard = value;
                });
              },
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildTextSize(AppLocalizations l, TextTheme t) {
    return Column(
      children: [
        SettingCard.top(
          child: ListTile(
            contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            title: Text(l.textSizeRatioBall, style: t.bodyMedium),
            subtitle: Row(
              children: [
                SizedBox(
                  width: 30,
                  child: Text(
                    _textSizeRatioBall.toStringAsFixed(1),
                    textAlign: TextAlign.right,
                  ),
                ),
                Expanded(
                  child: Slider(
                    value: _textSizeRatioBall,
                    min: ConstValue.minTextSizeRatioBall.toDouble(),
                    max: ConstValue.maxTextSizeRatioBall.toDouble(),
                    divisions: 19,
                    label: _textSizeRatioBall.toStringAsFixed(1),
                    onChanged: (value) {
                      setState(() {
                        _textSizeRatioBall = value;
                      });
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
        SettingCard.flat(
          child: ListTile(
            contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            title: Text(l.textSizeCard, style: t.bodyMedium),
            subtitle: Row(
              children: [
                SizedBox(
                  width: 30,
                  child: Text(
                    _textSizeCard.toStringAsFixed(0),
                    textAlign: TextAlign.right,
                  ),
                ),
                Expanded(
                  child: Slider(
                    value: _textSizeCard.toDouble(),
                    min: ConstValue.minTextSizeCard.toDouble(),
                    max: ConstValue.maxTextSizeCard.toDouble(),
                    divisions: 46,
                    label: _textSizeCard.toStringAsFixed(0),
                    onChanged: (value) {
                      setState(() {
                        _textSizeCard = value.toInt();
                      });
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
        SettingCard.bottom(
          child: ListTile(
            contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            title: Text(l.textSizeTable, style: t.bodyMedium),
            subtitle: Row(
              children: [
                SizedBox(
                  width: 30,
                  child: Text(
                    _textSizeTable.toStringAsFixed(0),
                    textAlign: TextAlign.right,
                  ),
                ),
                Expanded(
                  child: Slider(
                    value: _textSizeTable.toDouble(),
                    min: ConstValue.minTextSizeTable.toDouble(),
                    max: ConstValue.maxTextSizeTable.toDouble(),
                    divisions: 46,
                    label: _textSizeTable.toStringAsFixed(0),
                    onChanged: (value) {
                      setState(() {
                        _textSizeTable = value.toInt();
                      });
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildQuickDraw(AppLocalizations l, TextTheme t) {
    return SettingCard(
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        title: Text(l.quickDraw, style: t.bodyMedium),
        subtitle: Row(
          children: [
            Text(
              _quickDraw.toString(),
              textAlign: TextAlign.right,
            ),
            Expanded(
              child: Slider(
                value: _quickDraw.toDouble(),
                min: ConstValue.minQuickDraw.toDouble(),
                max: ConstValue.maxQuickDraw.toDouble(),
                divisions: 10,
                label: _quickDraw.toString(),
                onChanged: (value) {
                  setState(() {
                    _quickDraw = value.toInt();
                  });
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildAutomaticDrawInterval(AppLocalizations l, TextTheme t) {
    return SettingCard(
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        title: Text(l.automaticDrawInterval, style: t.bodyMedium),
        subtitle: Row(
          children: [
            Text(
              _automaticDrawInterval.toString(),
              textAlign: TextAlign.right,
            ),
            Expanded(
              child: Slider(
                value: _automaticDrawInterval.toDouble(),
                min: ConstValue.minAutomaticDrawInterval.toDouble(),
                max: ConstValue.maxAutomaticDrawInterval.toDouble(),
                divisions: ConstValue.maxAutomaticDrawInterval -
                    ConstValue.minAutomaticDrawInterval,
                label: _automaticDrawInterval.toString(),
                onChanged: (value) {
                  setState(() {
                    _automaticDrawInterval = value.toInt();
                  });
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

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

  Widget _buildSpeechSettings(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 _buildColorScheme(AppLocalizations l, TextTheme t) {
    return SettingCard(
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        title: Text(l.colorScheme, style: t.bodyMedium),
        trailing: DropdownButton<int>(
          value: _colorScheme,
          items: const [
            DropdownMenuItem(value: 0, child: Text('Green')),
            DropdownMenuItem(value: 1, child: Text('Blue')),
          ],
          onChanged: (value) {
            if (value != null) {
              setState(() {
                _colorScheme = value;
              });
            }
          },
        ),
      ),
    );
  }

  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),
                      ),
                    ],
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildUsage(AppLocalizations l, TextTheme t) {
    return SettingCard(
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(l.usage1, style: t.bodySmall),
            const SizedBox(height: 8),
            Text(l.usage2, style: t.bodySmall),
          ],
        ),
      ),
    );
  }

}

/// Copyright© ao-system, Inc.

import 'package:audio_session/audio_session.dart';
import 'package:just_audio/just_audio.dart';

/// Lightweight wrapper around [AudioPlayer] for the bingo spin sound.
class SoundPlayer {
  SoundPlayer() {
    _load();
  }

  final AudioPlayer _player = AudioPlayer();
  bool _loaded = false;

  Future<void> _load() async {
    final session = await AudioSession.instance;
    await session.configure(AudioSessionConfiguration.speech().copyWith(
      androidAudioFocusGainType: AndroidAudioFocusGainType.gainTransient,
      androidWillPauseWhenDucked: false,
      avAudioSessionCategoryOptions: AVAudioSessionCategoryOptions.mixWithOthers,
    ));
    try {
      await _player.setAsset('assets/audio/karakara.wav');
      await _player.load();
      _loaded = true;
    } catch (_) {
      _loaded = false;
    }
  }

  Future<void> play(double volume) async {
    if (!_loaded) {
      await _load();
    }
    await _player.setVolume(volume.clamp(0.0, 1.0));
    await _player.seek(Duration.zero);
    await _player.play();
  }

  Future<void> setSpeed(double speed) async {
    await _player.setSpeed(speed);
  }

  Future<void> stop() async {
    if (_player.playing) {
      await _player.stop();
    }
  }

  Future<void> dispose() async {
    await _player.dispose();
  }
}
/// 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:bingogame/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;
    }
  }

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

  Color get mainBackColor => Model.colorScheme == 1
      ? (_isLight ? Color.fromRGBO(140, 188, 255, 1.0) : Color.fromRGBO(35, 66, 99, 1.0))
      : (_isLight ? Color.fromRGBO(46,255,146,1) : Color.fromRGBO(0,90,10,1));
  Color get mainButtonColor => _isLight ? Color.fromRGBO(0,0,0,0.3) : Color.fromRGBO(255,255,255,0.3);
  Color get mainStartBackColor => _isLight ? Color.fromRGBO(255,255,255,0.3) : Color.fromRGBO(255,255,255,0.3);
  Color get mainStartForeColor => _isLight ? Color.fromRGBO(0,0,0,0.6) : Color.fromRGBO(255,255,255,0.8);
  Color get mainCardColor => _isLight ? Color.fromRGBO(255,255,255,0.5) : Color.fromRGBO(255,255,255,0.2);
  Color get mainTableCloseColor => _isLight ? Color.fromRGBO(255,255,255,0.5) : Color.fromRGBO(0,0,0,0.5);
  Color get mainTableOpenColor => _isLight ? Color.fromRGBO(255,225,0,0.9) : Color.fromRGBO(255,183,0,0.5);
  Color get mainTableLastColor => _isLight ? Color.fromRGBO(255,100,0,0.9) : Color.fromRGBO(255,110,0,0.8);
  Color get mainTableTextColor => _isLight ? Color.fromRGBO(0,0,0,1) : Color.fromRGBO(255,255,255,0.7);
  //
  Color get cardBackColor => _isLight ? Color.fromRGBO(255, 244, 204, 1.0) : Color.fromRGBO(62, 42, 0, 1.0);
  Color get cardTitleColor => _isLight ? Color.fromRGBO(0,0,0,0.8) : Color.fromRGBO(255,255,255,0.9);
  Color get cardTableCloseBackColor => _isLight ? Color.fromRGBO(0, 180, 0, 0.3) : Color.fromRGBO(0,0,0,0.3);
  Color get cardTableOpenBackColor => _isLight ? Color.fromRGBO(255, 212, 0, 1.0) : Color.fromRGBO(214, 148, 0, 0.6);
  Color get cardTableCloseForeColor => _isLight ? Color.fromRGBO(0,0,0,1) : Color.fromRGBO(255,255,255,0.9);
  Color get cardTableOpenForeColor => _isLight ? Color.fromRGBO(0,0,0,1) : Color.fromRGBO(255,255,255,1);
  Color get cardTableBingoForeColor => _isLight ? Color.fromRGBO(255, 77, 0, 1.0) : Color.fromRGBO(255, 221, 0, 1.0);
  //
  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 backColorMono => _isLight ? Colors.white : Colors.black;
  Color get foreColorMono => _isLight ? Colors.black : Colors.white;

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

}