import 'dart:async';

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

import '../../l10n/gen/app_localizations.dart';
import '../../state/providers.dart';
import '../widgets/season_background.dart';
import 'home_screen.dart';

/// Cold-start interstitial: "SEASON 1 · First Bloom". Tap anywhere or wait
/// ~1.6s. If content somehow fails to load we bail straight to home.
class SeasonTitleScreen extends ConsumerStatefulWidget {
  const SeasonTitleScreen({super.key});

  @override
  ConsumerState<SeasonTitleScreen> createState() =>
      _SeasonTitleScreenState();
}

class _SeasonTitleScreenState extends ConsumerState<SeasonTitleScreen> {
  Timer? _auto;
  bool _navigated = false;
  bool _dataTimerArmed = false;

  void _go() {
    if (_navigated || !mounted) return;
    _navigated = true;
    Navigator.of(context).pushReplacement(
      MaterialPageRoute(builder: (_) => const HomeScreen()),
    );
  }

  @override
  void dispose() {
    _auto?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final seasons = ref.watch(seasonsProvider);
    final l10n = AppLocalizations.of(context)!;
    return seasons.when(
      loading: () {
        _auto ??= Timer(const Duration(milliseconds: 2500), _go);
        return const Scaffold(
            backgroundColor: Color(0xFF0E1430), body: SizedBox());
      },
      error: (e, st) {
        WidgetsBinding.instance.addPostFrameCallback((_) => _go());
        return const Scaffold(
            backgroundColor: Color(0xFF0E1430), body: SizedBox());
      },
      data: (list) {
        if (list.isEmpty) {
          WidgetsBinding.instance.addPostFrameCallback((_) => _go());
          return const Scaffold(
              backgroundColor: Color(0xFF0E1430), body: SizedBox());
        }
        if (!_dataTimerArmed) {
          _dataTimerArmed = true;
          _auto?.cancel();
          _auto = Timer(const Duration(milliseconds: 1600), _go);
        }
        final pack = activeSeason(list);
        final locale = Localizations.localeOf(context).languageCode;
        final number = int.tryParse(pack.seasonId.split('_').last) ?? 1;
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: _go,
          child: Scaffold(
            body: Stack(
              fit: StackFit.expand,
              children: [
                SeasonBackground(theme: pack.theme),
                SafeArea(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        '${l10n.seasonLabel} $number',
                        style: TextStyle(
                          letterSpacing: 6,
                          fontSize: 14,
                          color: Colors.white.withValues(alpha: 0.7),
                        ),
                      ),
                      const SizedBox(height: 10),
                      Text(
                        pack.titleFor(locale),
                        style: const TextStyle(
                          fontSize: 38,
                          fontWeight: FontWeight.w900,
                          color: Colors.white,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Text(
                        l10n.seasonStages(pack.stages.length),
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.white.withValues(alpha: 0.6),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
