import 'package:flutter/material.dart';

import '../auth_gate.dart';
import '../screens/hello_splash_screen.dart';

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

  @override
  State<DebugLaunchGate> createState() => _DebugLaunchGateState();
}

class _DebugLaunchGateState extends State<DebugLaunchGate> {
  bool _showHello = true;
  bool _shouldLaunchQuiz = false;
  bool _quizLaunched = false;

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

  Future<void> _loadQuizFlag() async {
    // O quiz NÃO deve iniciar automaticamente na primeira abertura.
    // Ele deve iniciar apenas quando o usuário clicar no botão "Iniciar Quiz"
    // ou quando houver um registro novo (fluxo tratado no LoggedHome).
    if (!mounted) return;
    setState(() => _shouldLaunchQuiz = false);
  }

  @override
  Widget build(BuildContext context) {
    final Widget child;
    if (_showHello) {
      child = HelloSplashScreen(
        key: const ValueKey('hello_splash'),
        onFinished: () {
          if (!mounted) return;
          setState(() => _showHello = false);
        },
      );
    } else {
      child = const AuthGate(key: ValueKey('auth_gate'));
    }

    if (!_showHello && _shouldLaunchQuiz && !_quizLaunched) {
      _quizLaunched = true;
    }

    return AnimatedSwitcher(
      duration: const Duration(milliseconds: 420),
      reverseDuration: const Duration(milliseconds: 260),
      switchInCurve: Curves.easeOutCubic,
      switchOutCurve: Curves.easeInCubic,
      transitionBuilder: (child, animation) {
        final fade = CurvedAnimation(parent: animation, curve: Curves.easeOut);
        return FadeTransition(
          opacity: fade,
          child: ScaleTransition(
            scale: Tween<double>(begin: 0.995, end: 1.0).animate(fade),
            child: child,
          ),
        );
      },
      child: child,
    );
  }
}
