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

import '../core/constants.dart';
import 'desktop_sidebar.dart';
import 'desktop_topbar.dart';

class ResponsiveShell extends StatefulWidget {
  final int currentIndex;
  final ValueChanged<int> onIndexChanged;
  final Widget child;
  final bool showTopBar;

  const ResponsiveShell({
    Key? key,
    required this.currentIndex,
    required this.onIndexChanged,
    required this.child,
    this.showTopBar = true,
  }) : super(key: key);

  @override
  State<ResponsiveShell> createState() => _ResponsiveShellState();
}

class _ResponsiveShellState extends State<ResponsiveShell> {
  String _username = 'Guest';
  String? _profileImage;

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

  Future<void> _loadPreferences() async {
    final prefs = await SharedPreferences.getInstance();
    if (!mounted) return;
    setState(() {
      _username = prefs.getString('display_name') ??
          prefs.getString('username') ??
          'Guest';
      _profileImage = prefs.getString('profileImage');
    });
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      final width = constraints.maxWidth;

      // Mobile — no shell
      if (width < AppConstants.desktopBreakpoint) {
        return widget.child;
      }

      return Scaffold(
        body: Row(
          children: [
            DesktopSidebar(
              selectedIndex: widget.currentIndex,
              onIndexChanged: widget.onIndexChanged,
            ),
            Expanded(
              child: Column(
                children: [
                  if (widget.showTopBar)
                    DesktopTopBar(
                      username: _username,
                      profileImage: _profileImage,
                      onAvatarTap: () => widget.onIndexChanged(2),
                    ),
                  Expanded(
                    child: RepaintBoundary(child: widget.child),
                  ),
                ],
              ),
            ),
          ],
        ),
      );
    });
  }
}
