// lib/presentation/pages/splash_screen.dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:proxibuy/presentation/pages/onboarding_page.dart';
import 'package:proxibuy/presentation/pages/offers_page.dart';
import 'package:proxibuy/core/gen/assets.gen.dart';
import 'package:proxibuy/services/mqtt_service.dart';

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

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {

  @override
  void initState() {
    super.initState();
    // با کمی تاخیر برای نمایش لوگو، فرآیند را شروع می‌کنیم
    Timer(const Duration(seconds: 2), _checkAuthAndNavigate);
  }

  Future<void> _checkAuthAndNavigate() async {
    final storage = const FlutterSecureStorage();
    final token = await storage.read(key: 'accessToken');

    if (token != null && token.isNotEmpty) {
      // کاربر احراز هویت شده است
      debugPrint("--- SplashScreen: User is authenticated. Connecting to MQTT...");
      try {
        final mqttService = context.read<MqttService>();
        
        // ۱. منتظر می‌مانیم تا اتصال کامل برقرار شود
        await mqttService.connect(token);
        
        // ۲. پس از اطمینان از اتصال، به صفحه بعد می‌رویم
        if (mounted && mqttService.isConnected) {
          debugPrint("--- SplashScreen: MQTT Connected. Navigating to OffersPage.");
          Navigator.of(context).pushReplacement(
            MaterialPageRoute(builder: (_) => const OffersPage()),
          );
        } else if (mounted) {
           // اگر به هر دلیلی پس از اتمام متد، اتصال برقرار نبود
           debugPrint("--- SplashScreen: MQTT connection failed after attempt. Navigating to Onboarding.");
           Navigator.of(context).pushReplacement(
            MaterialPageRoute(builder: (_) => const OnboardingPage()),
          );
        }
      } catch (e) {
        debugPrint("❌ SplashScreen: Critical error during MQTT connection: $e");
         if (mounted) {
           Navigator.of(context).pushReplacement(
            MaterialPageRoute(builder: (_) => const OnboardingPage()),
          );
        }
      }
    } else {
      // کاربر احراز هویت نشده است
      debugPrint("--- SplashScreen: User not authenticated. Navigating to Onboarding.");
       if (mounted) {
        Navigator.of(context).pushReplacement(
          MaterialPageRoute(builder: (_) => const OnboardingPage()),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: Assets.icons.logo.svg(height: 160),
      ),
    );
  }
}