import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:unturned_compass/pages/home.dart';
import 'package:unturned_compass/pages/welcome/sub_pages/page_one.dart';
import 'package:unturned_compass/pages/welcome/sub_pages/page_two.dart';
// ADDED IMPORT: Import the new page style
import 'package:unturned_compass/pages/welcome/sub_pages/page_three.dart';

// Assume PageOne, PageTwoStyle, and PageThreeStyle are StatelessWidget or StatefulWidget
// and they are the individual content pages for the welcome screen.
// class PageOne extends StatelessWidget { ... }
// class PageTwo extends StatelessWidget { ... }
// class PageThree extends StatelessWidget { ... }

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

  @override
  State<WelcomeScreen> createState() => _WelcomeScreenState();
}

class _WelcomeScreenState extends State<WelcomeScreen> {
  final PageController _pageController = PageController();
  int _currentPage = 0;

  // Updated list to include the new page
  // Removed 'const' from the list itself in case the widgets inside aren't const,
  // but kept 'const' on the widget instances assuming they are StatelessWidget/StatefulWidget
  // that can be const constructed for potential performance benefits.
  final List<Widget> _welcomePages = [
    const PageOne(),
    const PageTwo(),
    // Added the new PageThree instance here
    const PageThree(),
  ];

  // Get the total number of pages dynamically
  int get _totalPages => _welcomePages.length;

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

  void _goToNextPage() {
    // Check against the dynamically calculated _totalPages
    if (_currentPage < _totalPages - 1) {
      _pageController.nextPage(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  void _goToPrevPage() {
    if (_currentPage > 0) {
      _pageController.previousPage(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  /// Sets configuration info, marking the user as having completed setup.
  Future<void> _setConfiguration() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('isConfigured', true);
  }

  /// Builds a unified circular button container.
  Widget _buildCircularButton({
    required Widget icon, // Pass the icon Widget directly
    VoidCallback? onPressed,
    String? tooltip,
  }) {
    const double buttonSize = 48.0; // Define a consistent button size

    return Container(
      width: buttonSize,
      height: buttonSize,
      decoration: BoxDecoration(
        color: Colors.black,
        shape: BoxShape.circle,
      ),
      child: IconButton(
        onPressed: onPressed,
        icon: icon,
        tooltip: tooltip,
        color: Colors.white,
        iconSize: 24.0, // Optional: Adjust icon size if needed
      ),
    );
  }

  /// Builds the previous page button (left side).
  Widget _buildPrevButton() {
    // If it's the first page, use a placeholder to maintain layout symmetry
    return _currentPage > 0
        ? _buildCircularButton(
            onPressed: _goToPrevPage,
            icon: const Icon(Icons.arrow_back),
            tooltip: '上一页',
          )
        : const SizedBox(
            width: 48.0,
            height: 48.0); // Ensure placeholder matches button size
  }

  /// Builds the page indicator (dots in the middle).
  Widget _buildPageIndicator() {
    return Row(
      mainAxisSize: MainAxisSize.min, // Row takes minimum space needed
      children: List.generate(_totalPages, (index) {
        // Uses the dynamic _totalPages
        return AnimatedContainer(
          duration: const Duration(milliseconds: 300),
          margin: const EdgeInsets.symmetric(horizontal: 4.0),
          height: 8.0,
          width: _currentPage == index ? 16.0 : 8.0, // Active dot is wider
          decoration: BoxDecoration(
            color: _currentPage == index ? Colors.blueAccent : Colors.grey,
            borderRadius: BorderRadius.circular(4.0),
          ),
        );
      }),
    );
  }

  /// Builds the next or done button (right side).
  Widget _buildNextOrDoneButton(BuildContext context) {
    // Check if it's the last page using the dynamic _totalPages
    final bool isLastPage = _currentPage == _totalPages - 1;

    return _buildCircularButton(
      onPressed: () async {
        if (isLastPage) {
          // Last page: finish setup and navigate to the main screen
          await _setConfiguration();

          // *** Guard against using context after await ***
          if (!context.mounted) {
            return; // Exit if the widget is no longer mounted
          }

          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (ctx) => const HomePage()),
          );
        } else {
          // Not the last page: go to the next one
          _goToNextPage();
        }
      },
      icon: Icon(
        isLastPage ? Icons.check : Icons.arrow_forward_ios,
      ),
      tooltip: isLastPage ? '完成' : '下一页',
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // PageView for swipe effect
          PageView(
            controller: _pageController,
            onPageChanged: (int page) {
              setState(() {
                _currentPage = page;
              });
            },
            children: _welcomePages, // List of welcome page widgets
          ),
          // Bottom navigation controls: prev button, page indicator, next/done button
          Positioned(
            bottom: 30,
            left: 20,
            right: 20,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                _buildPrevButton(),
                _buildPageIndicator(),
                _buildNextOrDoneButton(context),
              ],
            ),
          ),
        ],
      ),
    );
  }
}


删除注释，优化透明度