import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../api_client.dart';
import '../auth_storage.dart';
import 'addresses_screen.dart';
import 'privacy_screen.dart';
import 'support_screen.dart';
import 'terms_screen.dart';

// ── Brand tokens ──────────────────────────────────────────────────────────────
class _Brand {
  static const bg = Color(0xFF0F1114);
  static const surface = Color(0xFF1A1D22);
  static const card = Color(0xFF21252D);
  static const amber = Color(0xFFFF9500);
  static const amberGlow = Color(0x33FF9500);
  static const textPrimary = Color(0xFFF2F2F2);
  static const textMuted = Color(0xFF8A8F99);
  static const divider = Color(0xFF2C3040);
  static const error = Color(0xFFFF4545);
  static const green = Color(0xFF34C759);
}

// ─────────────────────────────────────────────────────────────────────────────

class SettingsScreen extends StatefulWidget {
  const SettingsScreen({super.key, required this.onUnauthorized});

  final VoidCallback onUnauthorized;

  @override
  State<SettingsScreen> createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen> {
  late Dio _dio;
  Map? _user;
  bool _loading = true;
  String? _error;

  @override
  void initState() {
    super.initState();
    _dio = createApiClient(() => widget.onUnauthorized());
    _load();
  }

  Future<void> _load() async {
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final r = await _dio.get('/api/auth/me');
      if (!mounted) return;
      setState(() {
        _user = (r.data is Map && r.data['data'] != null)
            ? r.data['data'] as Map
            : null;
        _loading = false;
      });
    } catch (e) {
      if (e is DioException && e.response?.statusCode == 401) {
        widget.onUnauthorized();
        return;
      }
      if (mounted) {
        setState(() {
          _loading = false;
          _error = 'Failed to load profile';
        });
      }
    }
  }

  String _formatPhone(String? phone) {
    if (phone == null || phone.isEmpty) return '—';
    final digits = phone.replaceAll(RegExp(r'\D'), '');
    if (digits.length >= 9 && digits.startsWith('256')) {
      return '+${digits.substring(0, 3)} ${digits.substring(3)}';
    }
    if (digits.length >= 9 && digits.startsWith('7')) {
      return '+256 $digits';
    }
    return phone;
  }

  void _showChangePhone() {
    final newPhoneC = TextEditingController();
    final currentPinC = TextEditingController();
    String? dialogError;
    bool loading = false;

    showDialog(
      context: context,
      builder: (ctx) => StatefulBuilder(
        builder: (context, setDialogState) {
          return AlertDialog(
            backgroundColor: _Brand.card,
            title: const Text(
              'Change login number',
              style: TextStyle(color: _Brand.textPrimary),
            ),
            content: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  if (dialogError != null) ...[
                    Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: _Brand.error.withOpacity(0.15),
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(color: _Brand.error.withOpacity(0.4)),
                      ),
                      child: Text(
                        dialogError!,
                        style: const TextStyle(
                          color: _Brand.error,
                          fontSize: 13,
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),
                  ],
                  const Text(
                    'New phone number (9 digits, e.g. 712345678)',
                    style: TextStyle(
                      color: _Brand.textMuted,
                      fontSize: 12,
                    ),
                  ),
                  const SizedBox(height: 6),
                  TextField(
                    controller: newPhoneC,
                    keyboardType: TextInputType.phone,
                    style: const TextStyle(color: _Brand.textPrimary),
                    decoration: InputDecoration(
                      hintText: '712345678',
                      hintStyle: TextStyle(color: _Brand.textMuted.withOpacity(0.6)),
                      filled: true,
                      fillColor: _Brand.surface,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: const BorderSide(color: _Brand.divider),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: const BorderSide(color: _Brand.divider),
                      ),
                    ),
                    inputFormatters: [
                      FilteringTextInputFormatter.allow(RegExp(r'\d')),
                      LengthLimitingTextInputFormatter(9),
                    ],
                  ),
                  const SizedBox(height: 16),
                  const Text(
                    'Current PIN (to confirm)',
                    style: TextStyle(
                      color: _Brand.textMuted,
                      fontSize: 12,
                    ),
                  ),
                  const SizedBox(height: 6),
                  TextField(
                    controller: currentPinC,
                    obscureText: true,
                    keyboardType: TextInputType.number,
                    style: const TextStyle(color: _Brand.textPrimary),
                    decoration: InputDecoration(
                      hintText: '••••••',
                      hintStyle: TextStyle(color: _Brand.textMuted.withOpacity(0.6)),
                      filled: true,
                      fillColor: _Brand.surface,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: const BorderSide(color: _Brand.divider),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: const BorderSide(color: _Brand.divider),
                      ),
                    ),
                    inputFormatters: [
                      FilteringTextInputFormatter.digitsOnly,
                      LengthLimitingTextInputFormatter(6),
                    ],
                  ),
                ],
              ),
            ),
            actions: [
              TextButton(
                onPressed: loading ? null : () => Navigator.of(ctx).pop(),
                child: Text('Cancel', style: TextStyle(color: _Brand.textMuted)),
              ),
              FilledButton(
                onPressed: loading
                    ? null
                    : () async {
                        final raw = newPhoneC.text.trim().replaceAll(RegExp(r'\D'), '');
                        final newPhone = raw.length == 9 && raw.startsWith('7')
                            ? '256$raw'
                            : raw;
                        final currentPin = currentPinC.text.trim();
                        if (newPhone.length != 12) {
                          setDialogState(() => dialogError = 'Enter a valid 9-digit number starting with 7');
                          return;
                        }
                        if (currentPin.length != 6) {
                          setDialogState(() => dialogError = 'PIN must be 6 digits');
                          return;
                        }
                        setDialogState(() {
                          loading = true;
                          dialogError = null;
                        });
                        try {
                          final r = await _dio.patch(
                            '/api/auth/change-phone',
                            data: {
                              'new_phone': newPhone,
                              'current_pin': currentPin,
                            },
                          );
                          if (!context.mounted) return;
                          final data = r.data is Map ? r.data['data'] as Map? : null;
                          final token = data?['token']?.toString();
                          if (token != null && token.isNotEmpty) {
                            await AuthStorage.setToken(token);
                          }
                          if (context.mounted) {
                            Navigator.of(ctx).pop();
                            _load();
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(
                                content: Text('Login number updated.'),
                                backgroundColor: _Brand.green,
                              ),
                            );
                          }
                        } catch (e) {
                          if (e is DioException && e.response?.data is Map) {
                            final msg = e.response!.data['error']?['message'] ?? 'Failed to update number';
                            setDialogState(() {
                              dialogError = msg.toString();
                              loading = false;
                            });
                          } else {
                            setDialogState(() {
                              dialogError = 'Something went wrong';
                              loading = false;
                            });
                          }
                        }
                      },
                style: FilledButton.styleFrom(backgroundColor: _Brand.amber),
                child: loading
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(strokeWidth: 2, color: Colors.black),
                      )
                    : const Text('Update'),
              ),
            ],
          );
        },
      ),
    );
  }

  void _showChangePin() {
    final currentPinC = TextEditingController();
    final newPinC = TextEditingController();
    final confirmPinC = TextEditingController();
    String? dialogError;
    bool loading = false;

    showDialog(
      context: context,
      builder: (ctx) => StatefulBuilder(
        builder: (context, setDialogState) {
          return AlertDialog(
            backgroundColor: _Brand.card,
            title: const Text(
              'Change PIN',
              style: TextStyle(color: _Brand.textPrimary),
            ),
            content: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  if (dialogError != null) ...[
                    Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: _Brand.error.withOpacity(0.15),
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(color: _Brand.error.withOpacity(0.4)),
                      ),
                      child: Text(
                        dialogError!,
                        style: const TextStyle(
                          color: _Brand.error,
                          fontSize: 13,
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),
                  ],
                  const Text(
                    'Current PIN',
                    style: TextStyle(color: _Brand.textMuted, fontSize: 12),
                  ),
                  const SizedBox(height: 6),
                  TextField(
                    controller: currentPinC,
                    obscureText: true,
                    keyboardType: TextInputType.number,
                    style: const TextStyle(color: _Brand.textPrimary),
                    decoration: _inputDecoration('••••••'),
                    inputFormatters: [
                      FilteringTextInputFormatter.digitsOnly,
                      LengthLimitingTextInputFormatter(6),
                    ],
                  ),
                  const SizedBox(height: 16),
                  const Text(
                    'New PIN (6 digits)',
                    style: TextStyle(color: _Brand.textMuted, fontSize: 12),
                  ),
                  const SizedBox(height: 6),
                  TextField(
                    controller: newPinC,
                    obscureText: true,
                    keyboardType: TextInputType.number,
                    style: const TextStyle(color: _Brand.textPrimary),
                    decoration: _inputDecoration('••••••'),
                    inputFormatters: [
                      FilteringTextInputFormatter.digitsOnly,
                      LengthLimitingTextInputFormatter(6),
                    ],
                  ),
                  const SizedBox(height: 16),
                  const Text(
                    'Confirm new PIN',
                    style: TextStyle(color: _Brand.textMuted, fontSize: 12),
                  ),
                  const SizedBox(height: 6),
                  TextField(
                    controller: confirmPinC,
                    obscureText: true,
                    keyboardType: TextInputType.number,
                    style: const TextStyle(color: _Brand.textPrimary),
                    decoration: _inputDecoration('••••••'),
                    inputFormatters: [
                      FilteringTextInputFormatter.digitsOnly,
                      LengthLimitingTextInputFormatter(6),
                    ],
                  ),
                ],
              ),
            ),
            actions: [
              TextButton(
                onPressed: loading ? null : () => Navigator.of(ctx).pop(),
                child: Text('Cancel', style: TextStyle(color: _Brand.textMuted)),
              ),
              FilledButton(
                onPressed: loading
                    ? null
                    : () async {
                        final currentPin = currentPinC.text.trim();
                        final newPin = newPinC.text.trim();
                        final confirmPin = confirmPinC.text.trim();
                        if (currentPin.length != 6) {
                          setDialogState(() => dialogError = 'Current PIN must be 6 digits');
                          return;
                        }
                        if (newPin.length != 6) {
                          setDialogState(() => dialogError = 'New PIN must be 6 digits');
                          return;
                        }
                        if (newPin != confirmPin) {
                          setDialogState(() => dialogError = 'New PIN and confirm do not match');
                          return;
                        }
                        setDialogState(() {
                          loading = true;
                          dialogError = null;
                        });
                        try {
                          await _dio.patch(
                            '/api/auth/change-pin',
                            data: {
                              'current_pin': currentPin,
                              'new_pin': newPin,
                            },
                          );
                          if (!context.mounted) return;
                          Navigator.of(ctx).pop();
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(
                              content: Text('PIN updated. Use it next time you log in.'),
                              backgroundColor: _Brand.green,
                            ),
                          );
                        } catch (e) {
                          if (e is DioException && e.response?.data is Map) {
                            final msg = e.response!.data['error']?['message'] ?? 'Failed to update PIN';
                            setDialogState(() {
                              dialogError = msg.toString();
                              loading = false;
                            });
                          } else {
                            setDialogState(() {
                              dialogError = 'Something went wrong';
                              loading = false;
                            });
                          }
                        }
                      },
                style: FilledButton.styleFrom(backgroundColor: _Brand.amber),
                child: loading
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(strokeWidth: 2, color: Colors.black),
                      )
                    : const Text('Update PIN'),
              ),
            ],
          );
        },
      ),
    );
  }

  void _showDeleteAccount() {
    showDialog<void>(
      context: context,
      builder: (ctx) => AlertDialog(
        backgroundColor: _Brand.card,
        title: const Text(
          'Delete account?',
          style: TextStyle(color: _Brand.textPrimary),
        ),
        content: const Text(
          'This permanently deletes your Jambo account. You will lose access, saved addresses, and in-app notifications. '
          'Order history may be kept for business records without being linked to you. '
          'You cannot undo this. If you have an order in progress, finish or cancel it first.',
          style: TextStyle(color: _Brand.textMuted, fontSize: 14, height: 1.4),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(),
            child: Text('Cancel', style: TextStyle(color: _Brand.textMuted)),
          ),
          FilledButton(
            onPressed: () {
              Navigator.of(ctx).pop();
              _showDeleteAccountPinDialog();
            },
            style: FilledButton.styleFrom(backgroundColor: _Brand.error),
            child: const Text('Continue'),
          ),
        ],
      ),
    );
  }

  void _showDeleteAccountPinDialog() {
    final pinC = TextEditingController();
    String? dialogError;
    bool loading = false;

    showDialog<void>(
      context: context,
      builder: (ctx) => StatefulBuilder(
        builder: (context, setDialogState) {
          return AlertDialog(
            backgroundColor: _Brand.card,
            title: const Text(
              'Confirm deletion',
              style: TextStyle(color: _Brand.textPrimary),
            ),
            content: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  const Text(
                    'Enter your 6-digit PIN to permanently delete your account.',
                    style: TextStyle(color: _Brand.textMuted, fontSize: 14, height: 1.4),
                  ),
                  const SizedBox(height: 16),
                  if (dialogError != null) ...[
                    Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: _Brand.error.withOpacity(0.15),
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(color: _Brand.error.withOpacity(0.4)),
                      ),
                      child: Text(
                        dialogError!,
                        style: const TextStyle(color: _Brand.error, fontSize: 13),
                      ),
                    ),
                    const SizedBox(height: 16),
                  ],
                  const Text(
                    'PIN',
                    style: TextStyle(color: _Brand.textMuted, fontSize: 12),
                  ),
                  const SizedBox(height: 6),
                  TextField(
                    controller: pinC,
                    obscureText: true,
                    keyboardType: TextInputType.number,
                    style: const TextStyle(color: _Brand.textPrimary),
                    decoration: _inputDecoration('••••••'),
                    inputFormatters: [
                      FilteringTextInputFormatter.digitsOnly,
                      LengthLimitingTextInputFormatter(6),
                    ],
                  ),
                ],
              ),
            ),
            actions: [
              TextButton(
                onPressed: loading ? null : () => Navigator.of(ctx).pop(),
                child: Text('Cancel', style: TextStyle(color: _Brand.textMuted)),
              ),
              FilledButton(
                onPressed: loading
                    ? null
                    : () async {
                        final pin = pinC.text.trim();
                        if (pin.length != 6) {
                          setDialogState(() => dialogError = 'PIN must be 6 digits');
                          return;
                        }
                        setDialogState(() {
                          loading = true;
                          dialogError = null;
                        });
                        try {
                          await _dio.post('/api/auth/delete-account', data: {'pin': pin});
                          if (!context.mounted) return;
                          Navigator.of(ctx).pop();
                          await AuthStorage.clearToken();
                          if (!context.mounted) return;
                          widget.onUnauthorized();
                        } catch (e) {
                          if (e is DioException && e.response?.data is Map) {
                            final msg = e.response!.data['error']?['message'] ?? 'Could not delete account';
                            setDialogState(() {
                              dialogError = msg.toString();
                              loading = false;
                            });
                          } else {
                            setDialogState(() {
                              dialogError = 'Something went wrong';
                              loading = false;
                            });
                          }
                        }
                      },
                style: FilledButton.styleFrom(backgroundColor: _Brand.error),
                child: loading
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
                      )
                    : const Text('Delete account'),
              ),
            ],
          );
        },
      ),
    );
  }

  InputDecoration _inputDecoration(String hint) {
    return InputDecoration(
      hintText: hint,
      hintStyle: TextStyle(color: _Brand.textMuted.withOpacity(0.6)),
      filled: true,
      fillColor: _Brand.surface,
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(10),
        borderSide: const BorderSide(color: _Brand.divider),
      ),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(10),
        borderSide: const BorderSide(color: _Brand.divider),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_loading && _user == null) {
      return const Scaffold(
        backgroundColor: _Brand.bg,
        body: Center(
          child: SizedBox(
            width: 36,
            height: 36,
            child: CircularProgressIndicator(
              strokeWidth: 2.5,
              valueColor: AlwaysStoppedAnimation(_Brand.amber),
            ),
          ),
        ),
      );
    }

    return Scaffold(
      backgroundColor: _Brand.bg,
      body: RefreshIndicator(
        onRefresh: _load,
        color: _Brand.amber,
        backgroundColor: _Brand.card,
        child: ListView(
          padding: const EdgeInsets.all(20),
          children: [
            // Profile card
            Container(
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: _Brand.card,
                borderRadius: BorderRadius.circular(16),
                border: Border.all(color: _Brand.divider),
              ),
              child: Column(
                children: [
                  Container(
                    width: 64,
                    height: 64,
                    decoration: BoxDecoration(
                      color: _Brand.amberGlow,
                      shape: BoxShape.circle,
                      border: Border.all(color: _Brand.amber.withOpacity(0.4), width: 1.5),
                    ),
                    child: const Icon(Icons.person_rounded, color: _Brand.amber, size: 32),
                  ),
                  const SizedBox(height: 14),
                  Text(
                    _formatPhone(_user?['phone']?.toString()),
                    style: const TextStyle(
                      color: _Brand.textPrimary,
                      fontSize: 18,
                      fontWeight: FontWeight.w700,
                      letterSpacing: 0.5,
                    ),
                  ),
                  if (_user?['role'] != null) ...[
                    const SizedBox(height: 4),
                    Text(
                      (_user!['role'] as String).toUpperCase(),
                      style: TextStyle(
                        color: _Brand.textMuted,
                        fontSize: 11,
                        letterSpacing: 1.5,
                      ),
                    ),
                  ],
                ],
              ),
            ),

            if (_error != null) ...[
              const SizedBox(height: 16),
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: _Brand.error.withOpacity(0.12),
                  borderRadius: BorderRadius.circular(10),
                  border: Border.all(color: _Brand.error.withOpacity(0.4)),
                ),
                child: Row(
                  children: [
                    const Icon(Icons.warning_amber_rounded, color: _Brand.error, size: 20),
                    const SizedBox(width: 10),
                    Expanded(child: Text(_error!, style: const TextStyle(color: _Brand.error, fontSize: 13))),
                  ],
                ),
              ),
            ],

            const SizedBox(height: 24),
            const Text(
              'PROFILE',
              style: TextStyle(
                color: _Brand.textMuted,
                fontSize: 10,
                letterSpacing: 2.5,
                fontWeight: FontWeight.w600,
              ),
            ),
            const SizedBox(height: 10),
            _SettingsTile(
              icon: Icons.phone_android_rounded,
              title: 'Change login number',
              subtitle: 'Update the phone number you use to sign in',
              onTap: _showChangePhone,
            ),
            const SizedBox(height: 8),
            _SettingsTile(
              icon: Icons.lock_rounded,
              title: 'Change PIN',
              subtitle: 'Set a new 6-digit PIN',
              onTap: _showChangePin,
            ),

            const SizedBox(height: 24),
            const Text(
              'ACCOUNT',
              style: TextStyle(
                color: _Brand.textMuted,
                fontSize: 10,
                letterSpacing: 2.5,
                fontWeight: FontWeight.w600,
              ),
            ),
            const SizedBox(height: 10),
            _SettingsTile(
              icon: Icons.location_on_rounded,
              title: 'Addresses',
              subtitle: 'Delivery addresses',
              onTap: () => Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (_) => AddressesScreen(onUnauthorized: widget.onUnauthorized),
                ),
              ),
            ),

            if ((_user?['role'] as String?) == 'user') ...[
              const SizedBox(height: 8),
              ListTile(
                contentPadding: EdgeInsets.zero,
                leading: Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: _Brand.error.withOpacity(0.15),
                    borderRadius: BorderRadius.circular(10),
                    border: Border.all(color: _Brand.error.withOpacity(0.4)),
                  ),
                  child: const Icon(Icons.delete_forever_rounded, color: _Brand.error, size: 20),
                ),
                title: const Text(
                  'Delete account',
                  style: TextStyle(
                    color: _Brand.error,
                    fontWeight: FontWeight.w600,
                    fontSize: 15,
                  ),
                ),
                subtitle: const Text(
                  'Permanently remove your account, addresses, and notifications',
                  style: TextStyle(color: _Brand.textMuted, fontSize: 12),
                ),
                onTap: _showDeleteAccount,
              ),
            ],

            const SizedBox(height: 24),
            const Text(
              'SUPPORT',
              style: TextStyle(
                color: _Brand.textMuted,
                fontSize: 10,
                letterSpacing: 2.5,
                fontWeight: FontWeight.w600,
              ),
            ),
            const SizedBox(height: 10),
            _SettingsTile(
              icon: Icons.support_agent_rounded,
              title: 'Support',
              subtitle: 'Phone and WhatsApp contact',
              onTap: () => Navigator.push(
                context,
                MaterialPageRoute(builder: (_) => const SupportScreen()),
              ),
            ),

            const SizedBox(height: 24),
            const Text(
              'LEGAL',
              style: TextStyle(
                color: _Brand.textMuted,
                fontSize: 10,
                letterSpacing: 2.5,
                fontWeight: FontWeight.w600,
              ),
            ),
            const SizedBox(height: 10),
            _SettingsTile(
              icon: Icons.privacy_tip_rounded,
              title: 'Privacy Policy',
              subtitle: 'How we handle your data',
              onTap: () => Navigator.push(
                context,
                MaterialPageRoute(builder: (_) => const PrivacyScreen()),
              ),
            ),
            const SizedBox(height: 8),
            _SettingsTile(
              icon: Icons.description_rounded,
              title: 'Terms of Service',
              subtitle: 'Terms and conditions',
              onTap: () => Navigator.push(
                context,
                MaterialPageRoute(builder: (_) => const TermsScreen()),
              ),
            ),

            const SizedBox(height: 24),
            const Divider(color: _Brand.divider, height: 1),
            const SizedBox(height: 16),
            ListTile(
              contentPadding: EdgeInsets.zero,
              leading: Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: _Brand.error.withOpacity(0.15),
                  borderRadius: BorderRadius.circular(10),
                  border: Border.all(color: _Brand.error.withOpacity(0.4)),
                ),
                child: const Icon(Icons.logout_rounded, color: _Brand.error, size: 20),
              ),
              title: const Text(
                'Log out',
                style: TextStyle(
                  color: _Brand.error,
                  fontWeight: FontWeight.w600,
                  fontSize: 15,
                ),
              ),
              onTap: () async {
                await AuthStorage.clearToken();
                if (context.mounted) widget.onUnauthorized();
              },
            ),
            const SizedBox(height: 24),
          ],
        ),
      ),
    );
  }
}

class _SettingsTile extends StatelessWidget {
  final IconData icon;
  final String title;
  final String subtitle;
  final VoidCallback onTap;

  const _SettingsTile({
    required this.icon,
    required this.title,
    required this.subtitle,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return Material(
      color: _Brand.card,
      borderRadius: BorderRadius.circular(12),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
          child: Row(
            children: [
              Container(
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: _Brand.amberGlow,
                  borderRadius: BorderRadius.circular(10),
                  border: Border.all(color: _Brand.amber.withOpacity(0.3)),
                ),
                child: Icon(icon, color: _Brand.amber, size: 20),
              ),
              const SizedBox(width: 14),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title,
                      style: const TextStyle(
                        color: _Brand.textPrimary,
                        fontSize: 15,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const SizedBox(height: 2),
                    Text(
                      subtitle,
                      style: const TextStyle(
                        color: _Brand.textMuted,
                        fontSize: 12,
                      ),
                    ),
                  ],
                ),
              ),
              const Icon(Icons.chevron_right_rounded, color: _Brand.textMuted, size: 22),
            ],
          ),
        ),
      ),
    );
  }
}
