import 'dart:math' show min;

import 'package:bart/bart/bart_model.dart';
import 'package:bart/bart/widgets/side_bar/custom_sidebar.dart';
import 'package:flutter/foundation.dart' show TargetPlatform, defaultTargetPlatform;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:kasy_kit/components/components.dart';
import 'package:kasy_kit/core/data/models/user.dart';
import 'package:kasy_kit/core/states/user_state_notifier.dart';
import 'package:kasy_kit/core/theme/theme.dart';
import 'package:kasy_kit/core/widgets/kasy_hover.dart';
import 'package:kasy_kit/features/notifications/providers/notifications_provider.dart';
import 'package:kasy_kit/features/notifications/repositories/notifications_repository.dart';

const double _kWidth = 260.0;
const double _kItemHeight = 44.0;
const double _kItemRadius = 8.0;

/// Entry point — pass to [CustomSideBarOptions.sideBarBuilder].
Widget kasySidebarBuilder(
  List<BartMenuRoute> routes,
  OnTapItem onTapItem,
  ValueNotifier<int> currentItem,
) {
  return _KasySidebarRoot(
    routes: routes,
    onTapItem: onTapItem,
    currentItem: currentItem,
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Root — reacts to Bart's tab-index changes without recreating State
// ─────────────────────────────────────────────────────────────────────────────

class _KasySidebarRoot extends StatelessWidget {
  final List<BartMenuRoute> routes;
  final OnTapItem onTapItem;
  final ValueNotifier<int> currentItem;

  const _KasySidebarRoot({
    required this.routes,
    required this.onTapItem,
    required this.currentItem,
  });

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<int>(
      valueListenable: currentItem,
      builder: (_, currentIndex, child) => _KasySidebar(
        routes: routes,
        currentIndex: currentIndex,
        onTapItem: onTapItem,
      ),
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Sidebar — stateful: holds project expansion + keyboard shortcut ⌘K / Ctrl+K
// ─────────────────────────────────────────────────────────────────────────────

class _KasySidebar extends StatefulWidget {
  final List<BartMenuRoute> routes;
  final int currentIndex;
  final OnTapItem onTapItem;

  const _KasySidebar({
    required this.routes,
    required this.currentIndex,
    required this.onTapItem,
  });

  @override
  State<_KasySidebar> createState() => _KasySidebarState();
}

class _KasySidebarState extends State<_KasySidebar> {
  int? _expandedProject;
  bool _searchOpen = false;

  static const _projects = [
    (color: Color(0xFF34C759), name: 'Kasy Studio'),
    (color: Color(0xFF1E88E5), name: 'Design System'),
    (color: Color(0xFFF57F17), name: 'Components'),
  ];

  static const _placeholders = [
    (icon: KasyIcons.flash, label: 'Activity'),
    (icon: KasyIcons.note, label: 'Tasks'),
    (icon: KasyIcons.book, label: 'Reports'),
    (icon: KasyIcons.person, label: 'Team'),
  ];

  // ── Keyboard shortcut ────────────────────────────────────────────────────

  @override
  void initState() {
    super.initState();
    HardwareKeyboard.instance.addHandler(_onKeyEvent);
  }

  @override
  void dispose() {
    HardwareKeyboard.instance.removeHandler(_onKeyEvent);
    super.dispose();
  }

  bool _onKeyEvent(KeyEvent event) {
    if (!mounted || event is! KeyDownEvent) return false;
    if (event.logicalKey != LogicalKeyboardKey.keyK) return false;
    final bool trigger = HardwareKeyboard.instance.isMetaPressed ||
        HardwareKeyboard.instance.isControlPressed;
    if (trigger) {
      _openSearch();
      return true;
    }
    return false;
  }

  // ── Search modal ─────────────────────────────────────────────────────────

  void _openSearch() {
    if (_searchOpen || !mounted) return;
    setState(() => _searchOpen = true);
    showGeneralDialog<void>(
      context: context,
      barrierDismissible: true,
      barrierLabel: 'Dismiss',
      barrierColor: Colors.black.withValues(alpha: 0.32),
      transitionDuration: const Duration(milliseconds: 220),
      pageBuilder: (ctx, anim, secAnim) => Align(
        alignment: const Alignment(0, -0.18),
        child: _SearchModal(
          routes: widget.routes,
          onNavigate: (index) {
            Navigator.of(ctx, rootNavigator: true).pop();
            widget.onTapItem(index);
          },
        ),
      ),
      transitionBuilder: (ctx, anim, secAnim, child) {
        final curved =
            CurvedAnimation(parent: anim, curve: Curves.easeOutCubic);
        return FadeTransition(
          opacity: curved,
          child: ScaleTransition(
            scale: Tween<double>(begin: 0.95, end: 1.0).animate(curved),
            child: child,
          ),
        );
      },
    ).then((_) {
      if (mounted) setState(() => _searchOpen = false);
    });
  }

  // ── Projects expand/collapse ─────────────────────────────────────────────

  void _toggleProject(int index) {
    setState(() {
      _expandedProject = _expandedProject == index ? null : index;
    });
  }

  // ── Build ─────────────────────────────────────────────────────────────────

  @override
  Widget build(BuildContext context) {
    final colors = context.colors;

    return Container(
      width: _kWidth,
      decoration: BoxDecoration(
        color: colors.surface,
        border: Border(
          right: BorderSide(color: colors.outline.withValues(alpha: 0.4)),
        ),
      ),
      child: SafeArea(
        right: false,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // ── Scrollable content ──────────────────────────────────────────
            Expanded(
              child: ScrollConfiguration(
                // Hide scrollbar for a cleaner desktop/web look
                behavior: ScrollConfiguration.of(context)
                    .copyWith(scrollbars: false),
                child: SingleChildScrollView(
                  physics: const ClampingScrollPhysics(),
                  padding: const EdgeInsets.fromLTRB(12, 16, 12, 8),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // Brand header
                      const _Header(),
                      const SizedBox(height: 16),

                      // Search bar — opens modal on tap / ⌘K
                      _SearchBar(onTap: _openSearch),
                      const SizedBox(height: 20),

                      // ── MENU section ─────────────────────────────────────
                      const _SectionLabel('Menu'),
                      const SizedBox(height: 4),
                      ...widget.routes.asMap().entries.map(
                        (e) => _NavItem(
                          route: e.value,
                          isActive: widget.currentIndex == e.key,
                          onTap: () => widget.onTapItem(e.key),
                        ),
                      ),
                      const SizedBox(height: 8),

                      const _SidebarDivider(),
                      const SizedBox(height: 8),

                      // ── WORKSPACE section (placeholder items) ─────────────
                      const _SectionLabel('Workspace'),
                      const SizedBox(height: 4),
                      ..._placeholders.map(
                        (p) =>
                            _PlaceholderItem(icon: p.icon, label: p.label),
                      ),
                      const SizedBox(height: 16),

                      const _SidebarDivider(),
                      const SizedBox(height: 12),

                      // ── PROJECTS section ──────────────────────────────────
                      Row(
                        children: [
                          const Expanded(child: _SectionLabel('Projects')),
                          Icon(KasyIcons.add, size: 14, color: colors.muted),
                          const SizedBox(width: 4),
                        ],
                      ),
                      const SizedBox(height: 4),
                      ..._projects.asMap().entries.map(
                        (e) => _ProjectItem(
                          color: e.value.color,
                          name: e.value.name,
                          isExpanded: _expandedProject == e.key,
                          onToggle: () => _toggleProject(e.key),
                        ),
                      ),

                      // Add new project
                      _AddProjectButton(),
                      const SizedBox(height: 8),
                    ],
                  ),
                ),
              ),
            ),

            // ── Theme toggle + sticky footer ─────────────────────────────
            const _ThemeToggle(),
            const SizedBox(height: 8),
            const _SidebarDivider(),
            const _UserFooter(),
          ],
        ),
      ),
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Header — brand logo + workspace name + dropdown hint
// ─────────────────────────────────────────────────────────────────────────────

class _Header extends StatelessWidget {
  const _Header();

  @override
  Widget build(BuildContext context) {
    final colors = context.colors;
    return KasyHover(
      onTap: () {},
      hapticEnabled: false,
      borderRadius: BorderRadius.circular(10),
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 4),
        child: Row(
          children: [
            // Brand icon
            Container(
              width: 34,
              height: 34,
              decoration: BoxDecoration(
                color: colors.primary,
                borderRadius: BorderRadius.circular(8),
              ),
              child: const Icon(KasyIcons.assistant, size: 18, color: Colors.white),
            ),
            const SizedBox(width: 10),
            // Name + plan
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    'Kasy',
                    style: context.textTheme.titleMedium?.copyWith(
                      fontWeight: FontWeight.w700,
                      height: 1.15,
                    ),
                  ),
                  Text(
                    'Design System',
                    style: context.textTheme.labelSmall?.copyWith(
                      color: colors.muted,
                    ),
                  ),
                ],
              ),
            ),
            Icon(KasyIcons.chevronDown, size: 14, color: colors.muted),
          ],
        ),
      ),
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Search bar — tappable, opens command-palette modal
// ─────────────────────────────────────────────────────────────────────────────

class _SearchBar extends StatelessWidget {
  final VoidCallback onTap;
  const _SearchBar({required this.onTap});

  @override
  Widget build(BuildContext context) {
    final colors = context.colors;
    return KasyHover(
      onTap: onTap,
      semanticLabel: 'Search',
      borderRadius: BorderRadius.circular(8),
      child: Container(
        height: 36,
        decoration: BoxDecoration(
          color: colors.surfaceNeutralSoft,
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: colors.outline.withValues(alpha: 0.5),
            width: 0.6,
          ),
        ),
        child: Row(
          children: [
            const SizedBox(width: 10),
            Icon(KasyIcons.search, size: 15, color: colors.muted),
            const SizedBox(width: 8),
            Expanded(
              child: Text(
                'Search...',
                style: context.textTheme.bodySmall?.copyWith(
                  color: colors.muted,
                ),
              ),
            ),
            // Keyboard shortcut badge
            Container(
              margin: const EdgeInsets.only(right: 8),
              padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
              decoration: BoxDecoration(
                color: colors.outline.withValues(alpha: 0.35),
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(
                defaultTargetPlatform == TargetPlatform.macOS ? '⌘K' : 'Ctrl K',
                style: context.textTheme.labelSmall?.copyWith(
                  color: colors.muted,
                  fontSize: 10,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Section label — ALL CAPS, subtle
// ─────────────────────────────────────────────────────────────────────────────

class _SectionLabel extends StatelessWidget {
  final String text;
  const _SectionLabel(this.text);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(left: 4, bottom: 2),
      child: Text(
        text,
        style: context.textTheme.labelSmall?.copyWith(
          color: context.colors.muted,
          fontWeight: FontWeight.w600,
          letterSpacing: 0.4,
          fontSize: 11,
        ),
      ),
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Divider
// ─────────────────────────────────────────────────────────────────────────────

class _SidebarDivider extends StatelessWidget {
  const _SidebarDivider();

  @override
  Widget build(BuildContext context) {
    return Divider(
      height: 1,
      thickness: 0.8,
      color: context.colors.outline.withValues(alpha: 0.4),
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Nav item — real, tappable, animated active state
// ─────────────────────────────────────────────────────────────────────────────

class _NavItem extends StatelessWidget {
  final BartMenuRoute route;
  final bool isActive;
  final VoidCallback onTap;

  const _NavItem({
    required this.route,
    required this.isActive,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    final colors = context.colors;
    final Color iconColor =
        isActive ? colors.primary : colors.onSurface.withValues(alpha: 0.6);
    final Color textColor = isActive ? colors.primary : colors.onSurface;
    final bool hasIconBuilder = route.iconBuilder != null;
    final IconData icon = route.icon ?? KasyIcons.notification;

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 1.5),
      child: KasyHover(
        onTap: onTap,
        semanticLabel: route.label,
        borderRadius: BorderRadius.circular(_kItemRadius),
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 160),
          curve: Curves.easeOut,
          height: _kItemHeight,
          decoration: BoxDecoration(
            color: isActive
                ? colors.surfacePrimarySoft
                : Colors.transparent,
            borderRadius: BorderRadius.circular(_kItemRadius),
          ),
          child: Row(
            children: [
              // Active accent line on the left
              AnimatedContainer(
                duration: const Duration(milliseconds: 160),
                width: 3,
                height: 20,
                margin: const EdgeInsets.only(left: 4, right: 8),
                decoration: BoxDecoration(
                  color: isActive ? colors.primary : Colors.transparent,
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
              // Icon
              Icon(icon, size: 18, color: iconColor),
              const SizedBox(width: 10),
              // Label
              Expanded(
                child: Text(
                  route.label ?? '',
                  style: context.textTheme.bodyMedium?.copyWith(
                    color: textColor,
                    fontWeight:
                        isActive ? FontWeight.w600 : FontWeight.w500,
                  ),
                ),
              ),
              // Notification count badge (right side)
              if (hasIconBuilder) ...[
                const _NotificationCountBadge(),
                const SizedBox(width: 10),
              ],
            ],
          ),
        ),
      ),
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Notification count badge — right-aligned pill, reads live count
// ─────────────────────────────────────────────────────────────────────────────

class _NotificationCountBadge extends ConsumerWidget {
  const _NotificationCountBadge();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final String? userId = ref.watch(userStateNotifierProvider).user.idOrNull;
    if (userId == null) return const SizedBox.shrink();

    final int count = ref.watch(notificationsProvider).maybeWhen(
      data: (list) => list.data.where((n) => !n.seen).length,
      orElse: () => 0,
    );
    if (count == 0) return const SizedBox.shrink();

    return AnimatedSwitcher(
      duration: const Duration(milliseconds: 220),
      transitionBuilder: (child, anim) => ScaleTransition(
        scale: Tween<double>(begin: 0.55, end: 1.0).animate(
          CurvedAnimation(parent: anim, curve: Curves.easeOutBack),
        ),
        child: FadeTransition(opacity: anim, child: child),
      ),
      child: Container(
        key: ValueKey(count),
        padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
        decoration: BoxDecoration(
          color: context.colors.error,
          borderRadius: BorderRadius.circular(10),
        ),
        child: Text(
          count > 99 ? '99+' : '$count',
          style: context.textTheme.labelSmall?.copyWith(
            color: Colors.white,
            fontWeight: FontWeight.w700,
            fontSize: 10,
            height: 1.2,
          ),
        ),
      ),
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Placeholder item — hover feedback, no navigation (coming soon)
// ─────────────────────────────────────────────────────────────────────────────

class _PlaceholderItem extends StatelessWidget {
  final IconData icon;
  final String label;

  const _PlaceholderItem({required this.icon, required this.label});

  @override
  Widget build(BuildContext context) {
    final colors = context.colors;
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 1.5),
      child: KasyHover(
        onTap: () {
          showKasyToast(
            context,
            title: label,
            message: 'Coming soon',
            duration: const Duration(seconds: 2),
          );
        },
        hapticEnabled: false,
        borderRadius: BorderRadius.circular(_kItemRadius),
        child: SizedBox(
          height: _kItemHeight,
          child: Row(
            children: [
              const SizedBox(width: 15), // aligns with nav items (3+4+8)
              Icon(
                icon,
                size: 18,
                color: colors.onSurface.withValues(alpha: 0.35),
              ),
              const SizedBox(width: 10),
              Expanded(
                child: Text(
                  label,
                  style: context.textTheme.bodyMedium?.copyWith(
                    color: colors.muted,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Project item — expandable with animated chevron + sub-items
// ─────────────────────────────────────────────────────────────────────────────

class _ProjectItem extends StatelessWidget {
  final Color color;
  final String name;
  final bool isExpanded;
  final VoidCallback onToggle;

  const _ProjectItem({
    required this.color,
    required this.name,
    required this.isExpanded,
    required this.onToggle,
  });

  static const _subItems = [
    (icon: KasyIcons.home, label: 'Overview'),
    (icon: KasyIcons.person, label: 'Members'),
    (icon: KasyIcons.settings, label: 'Settings'),
  ];

  @override
  Widget build(BuildContext context) {
    final colors = context.colors;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        // ── Header row ────────────────────────────────────────────────────
        KasyHover(
          onTap: onToggle,
          borderRadius: BorderRadius.circular(_kItemRadius),
          child: SizedBox(
            height: 36,
            child: Row(
              children: [
                const SizedBox(width: 15),
                // Colored dot
                Container(
                  width: 10,
                  height: 10,
                  decoration: BoxDecoration(
                    color: color,
                    shape: BoxShape.circle,
                    boxShadow: [
                      BoxShadow(
                        color: color.withValues(alpha: 0.45),
                        blurRadius: 5,
                        offset: const Offset(0, 1),
                      ),
                    ],
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Text(
                    name,
                    style: context.textTheme.bodyMedium?.copyWith(
                      color: colors.onSurface.withValues(alpha: 0.8),
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                // Chevron rotates when expanded
                AnimatedRotation(
                  duration: const Duration(milliseconds: 200),
                  curve: Curves.easeInOut,
                  turns: isExpanded ? 0.25 : 0.0,
                  child: Icon(
                    KasyIcons.chevronRight,
                    size: 13,
                    color: colors.muted.withValues(alpha: 0.6),
                  ),
                ),
                const SizedBox(width: 10),
              ],
            ),
          ),
        ),

        // ── Sub-items — animated expand/collapse ──────────────────────────
        AnimatedSize(
          duration: const Duration(milliseconds: 200),
          curve: Curves.easeInOut,
          child: isExpanded
              ? Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: _subItems
                      .map((s) =>
                          _ProjectSubItem(icon: s.icon, label: s.label))
                      .toList(),
                )
              : const SizedBox.shrink(),
        ),
      ],
    );
  }
}

class _ProjectSubItem extends StatelessWidget {
  final IconData icon;
  final String label;

  const _ProjectSubItem({required this.icon, required this.label});

  @override
  Widget build(BuildContext context) {
    final colors = context.colors;
    return KasyHover(
      onTap: () {},
      hapticEnabled: false,
      borderRadius: BorderRadius.circular(6),
      child: SizedBox(
        height: 32,
        child: Row(
          children: [
            const SizedBox(width: 35), // deeper indent
            Icon(icon, size: 14, color: colors.muted),
            const SizedBox(width: 9),
            Text(
              label,
              style: context.textTheme.bodySmall?.copyWith(
                color: colors.onSurface.withValues(alpha: 0.6),
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// "Add New Project" button
// ─────────────────────────────────────────────────────────────────────────────

class _AddProjectButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final colors = context.colors;
    return KasyHover(
      onTap: () {},
      hapticEnabled: false,
      borderRadius: BorderRadius.circular(_kItemRadius),
      child: SizedBox(
        height: 34,
        child: Row(
          children: [
            const SizedBox(width: 15),
            Container(
              width: 20,
              height: 20,
              decoration: BoxDecoration(
                color: colors.surfacePrimarySoft,
                borderRadius: BorderRadius.circular(6),
              ),
              child: Icon(KasyIcons.add, size: 13, color: colors.primary),
            ),
            const SizedBox(width: 10),
            Text(
              'New Project',
              style: context.textTheme.bodySmall?.copyWith(
                color: colors.primary.withValues(alpha: 0.75),
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// User footer — real data via Riverpod, KasyAvatar initials
// Logout icon only visible on hover to avoid visual clutter.
// ─────────────────────────────────────────────────────────────────────────────

class _UserFooter extends ConsumerStatefulWidget {
  const _UserFooter();

  @override
  ConsumerState<_UserFooter> createState() => _UserFooterState();
}

class _UserFooterState extends ConsumerState<_UserFooter> {
  bool _hovered = false;

  @override
  Widget build(BuildContext context) {
    final user = ref.watch(userStateNotifierProvider).user;

    final String displayName;
    final String subtitle;

    if (user is AuthenticatedUserData) {
      displayName = user.name ?? user.email.split('@').first;
      subtitle = user.email;
    } else {
      displayName = 'Guest';
      subtitle = 'Not signed in';
    }

    final String initials =
        displayName.isNotEmpty ? displayName[0].toUpperCase() : 'G';

    return MouseRegion(
      onEnter: (_) => setState(() => _hovered = true),
      onExit: (_) => setState(() => _hovered = false),
      child: KasyHover(
        onTap: () {},
        hapticEnabled: false,
        child: Padding(
          padding: const EdgeInsets.fromLTRB(12, 10, 12, 10),
          child: Row(
            children: [
              // Avatar
              KasyAvatar(
                size: KasyAvatarSize.small,
                diameter: 32,
                initials: initials,
              ),
              const SizedBox(width: 10),
              // Name + email
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      displayName,
                      style: context.textTheme.labelMedium?.copyWith(
                        fontWeight: FontWeight.w600,
                      ),
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                    ),
                    Text(
                      subtitle,
                      style: context.textTheme.labelSmall?.copyWith(
                        color: context.colors.muted,
                      ),
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                    ),
                  ],
                ),
              ),
              // Logout icon — only visible on hover
              AnimatedOpacity(
                opacity: _hovered ? 1.0 : 0.0,
                duration: const Duration(milliseconds: 150),
                child: Padding(
                  padding: const EdgeInsets.only(left: 8),
                  child: Icon(
                    KasyIcons.logout,
                    size: 16,
                    color: context.colors.muted,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Search modal — centered command palette with KasyTextField + live filter
// ─────────────────────────────────────────────────────────────────────────────

class _SearchModal extends StatefulWidget {
  final List<BartMenuRoute> routes;
  final void Function(int index) onNavigate;

  const _SearchModal({required this.routes, required this.onNavigate});

  @override
  State<_SearchModal> createState() => _SearchModalState();
}

class _SearchModalState extends State<_SearchModal> {
  final _controller = TextEditingController();
  late final FocusNode _focusNode;
  final ScrollController _scrollController = ScrollController();
  String _query = '';
  int _selectedIndex = 0;

  // Approximate height of each result tile (34px icon + 12px vertical padding)
  static const double _kTileHeight = 47.0;

  static const _placeholders = [
    (icon: KasyIcons.flash, label: 'Activity'),
    (icon: KasyIcons.note, label: 'Tasks'),
    (icon: KasyIcons.book, label: 'Reports'),
    (icon: KasyIcons.person, label: 'Team'),
  ];

  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode(onKeyEvent: _onFocusKeyEvent);
  }

  @override
  void dispose() {
    _controller.dispose();
    _focusNode.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  KeyEventResult _onFocusKeyEvent(FocusNode node, KeyEvent event) {
    if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
      return KeyEventResult.ignored;
    }

    final results = _results;

    if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
      if (results.isNotEmpty) {
        setState(() {
          _selectedIndex = (_selectedIndex + 1).clamp(0, results.length - 1);
        });
        _scrollToSelected();
      }
      return KeyEventResult.handled;
    }

    if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
      if (results.isNotEmpty) {
        setState(() {
          _selectedIndex = (_selectedIndex - 1).clamp(0, results.length - 1);
        });
        _scrollToSelected();
      }
      return KeyEventResult.handled;
    }

    if (event.logicalKey == LogicalKeyboardKey.enter) {
      if (_selectedIndex < results.length) {
        final item = results[_selectedIndex];
        if (item.navIndex != null) {
          widget.onNavigate(item.navIndex!);
        }
      }
      return KeyEventResult.handled;
    }

    if (event.logicalKey == LogicalKeyboardKey.escape) {
      Navigator.of(context, rootNavigator: true).pop();
      return KeyEventResult.handled;
    }

    return KeyEventResult.ignored;
  }

  void _scrollToSelected() {
    if (!_scrollController.hasClients) return;
    final offset = (_selectedIndex * _kTileHeight)
        .clamp(0.0, _scrollController.position.maxScrollExtent);
    _scrollController.animateTo(
      offset,
      duration: const Duration(milliseconds: 120),
      curve: Curves.easeOut,
    );
  }

  List<({IconData icon, String label, int? navIndex})> get _results {
    final q = _query.trim().toLowerCase();
    final out = <({IconData icon, String label, int? navIndex})>[];

    // Real nav routes
    for (var i = 0; i < widget.routes.length; i++) {
      final r = widget.routes[i];
      final label = r.label ?? '';
      if (q.isEmpty || label.toLowerCase().contains(q)) {
        out.add((
          icon: r.icon ?? KasyIcons.notification,
          label: label,
          navIndex: i,
        ));
      }
    }

    // Placeholder workspace items
    for (final p in _placeholders) {
      if (q.isEmpty || p.label.toLowerCase().contains(q)) {
        out.add((icon: p.icon, label: p.label, navIndex: null));
      }
    }

    return out;
  }

  @override
  Widget build(BuildContext context) {
    final colors = context.colors;
    final results = _results;
    final double maxW = min(560.0, MediaQuery.of(context).size.width - 48);

    return Material(
      color: Colors.transparent,
      child: Container(
        width: maxW,
        constraints: BoxConstraints(
          maxHeight: MediaQuery.of(context).size.height * 0.62,
        ),
        decoration: BoxDecoration(
          color: colors.surface,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: colors.outline.withValues(alpha: 0.25)),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withValues(alpha: 0.18),
              blurRadius: 40,
              offset: const Offset(0, 12),
            ),
            BoxShadow(
              color: Colors.black.withValues(alpha: 0.06),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(16),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // ── Search input ──────────────────────────────────────────────
              Padding(
                padding: const EdgeInsets.fromLTRB(16, 16, 16, 12),
                child: KasyTextField(
                  controller: _controller,
                  focusNode: _focusNode,
                  hint: 'Search pages, settings, projects...',
                  autofocus: true,
                  onChanged: (v) => setState(() {
                    _query = v;
                    _selectedIndex = 0;
                  }),
                ),
              ),

              // ── Results ───────────────────────────────────────────────────
              if (results.isEmpty && _query.isNotEmpty)
                Padding(
                  padding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
                  child: Row(
                    children: [
                      Icon(KasyIcons.search, size: 16, color: colors.muted),
                      const SizedBox(width: 8),
                      Text(
                        'No results for "$_query"',
                        style: context.textTheme.bodyMedium
                            ?.copyWith(color: colors.muted),
                      ),
                    ],
                  ),
                )
              else ...[
                Divider(
                    height: 1,
                    color: colors.outline.withValues(alpha: 0.4)),
                Flexible(
                  child: ListView.separated(
                    controller: _scrollController,
                    shrinkWrap: true,
                    padding: const EdgeInsets.symmetric(vertical: 6),
                    itemCount: results.length,
                    separatorBuilder: (_, idx) => const SizedBox(height: 1),
                    itemBuilder: (_, i) {
                      final item = results[i];
                      return _SearchResultTile(
                        icon: item.icon,
                        label: item.label,
                        isNavigable: item.navIndex != null,
                        isSelected: i == _selectedIndex,
                        onTap: item.navIndex != null
                            ? () => widget.onNavigate(item.navIndex!)
                            : null,
                        onHover: () => setState(() => _selectedIndex = i),
                      );
                    },
                  ),
                ),
              ],

              // ── Footer hint ───────────────────────────────────────────────
              Container(
                decoration: BoxDecoration(
                  color: colors.surfaceNeutralSoft,
                  border: Border(
                    top: BorderSide(
                        color: colors.outline.withValues(alpha: 0.3)),
                  ),
                ),
                padding: const EdgeInsets.symmetric(
                    horizontal: 16, vertical: 8),
                child: const Row(
                  children: [
                    _KbdHint(label: '↑↓', tooltip: 'Navigate'),
                    SizedBox(width: 12),
                    _KbdHint(label: '↵', tooltip: 'Select'),
                    SizedBox(width: 12),
                    _KbdHint(label: 'Esc', tooltip: 'Close'),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

/// Keyboard shortcut hint chip shown in the modal footer.
class _KbdHint extends StatelessWidget {
  final String label;
  final String tooltip;

  const _KbdHint({required this.label, required this.tooltip});

  @override
  Widget build(BuildContext context) {
    final colors = context.colors;
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
          decoration: BoxDecoration(
            color: colors.surface,
            borderRadius: BorderRadius.circular(4),
            border:
                Border.all(color: colors.outline.withValues(alpha: 0.5)),
          ),
          child: Text(
            label,
            style: context.textTheme.labelSmall?.copyWith(
              fontSize: 10,
              color: colors.muted,
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
        const SizedBox(width: 4),
        Text(
          tooltip,
          style: context.textTheme.labelSmall?.copyWith(
            fontSize: 10,
            color: colors.muted,
          ),
        ),
      ],
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Search result tile
// ─────────────────────────────────────────────────────────────────────────────

class _SearchResultTile extends StatelessWidget {
  final IconData icon;
  final String label;
  final bool isNavigable;
  final bool isSelected;
  final VoidCallback? onTap;
  final VoidCallback? onHover;

  const _SearchResultTile({
    required this.icon,
    required this.label,
    required this.isNavigable,
    required this.isSelected,
    this.onTap,
    this.onHover,
  });

  @override
  Widget build(BuildContext context) {
    final colors = context.colors;

    final Widget content = AnimatedContainer(
      duration: const Duration(milliseconds: 100),
      color: isSelected
          ? colors.surfacePrimarySoft.withValues(alpha: 0.5)
          : Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        child: Row(
          children: [
            // Icon badge
            Container(
              width: 34,
              height: 34,
              decoration: BoxDecoration(
                color: isNavigable
                    ? colors.surfacePrimarySoft
                    : colors.surfaceNeutralSoft,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Icon(
                icon,
                size: 16,
                color: isNavigable ? colors.primary : colors.muted,
              ),
            ),
            const SizedBox(width: 12),
            // Label
            Expanded(
              child: Text(
                label,
                style: context.textTheme.bodyMedium?.copyWith(
                  color: isNavigable ? colors.onSurface : colors.muted,
                  fontWeight:
                      isNavigable ? FontWeight.w500 : FontWeight.w400,
                ),
              ),
            ),
            // Right indicator
            if (!isNavigable)
              Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 7, vertical: 3),
                decoration: BoxDecoration(
                  color: colors.surfaceNeutralSoft,
                  borderRadius: BorderRadius.circular(6),
                  border: Border.all(
                      color: colors.outline.withValues(alpha: 0.4)),
                ),
                child: Text(
                  'Soon',
                  style: context.textTheme.labelSmall?.copyWith(
                    color: colors.muted,
                    fontSize: 10,
                  ),
                ),
              )
            else
              Icon(KasyIcons.arrowForwardIos,
                  size: 13, color: colors.muted.withValues(alpha: 0.6)),
          ],
        ),
      ),
    );

    return MouseRegion(
      onEnter: (_) => onHover?.call(),
      child: onTap != null
          ? KasyHover(onTap: onTap!, child: content)
          : content,
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Theme toggle — pill switcher Light / Dark in the sidebar footer area
// ─────────────────────────────────────────────────────────────────────────────

class _ThemeToggle extends StatelessWidget {
  const _ThemeToggle();

  @override
  Widget build(BuildContext context) {
    final theme = ThemeProvider.of(context);
    final isDark = theme.mode == ThemeMode.dark;
    final colors = context.colors;

    return Padding(
      padding: const EdgeInsets.fromLTRB(12, 8, 12, 0),
      child: Container(
        height: 46,
        padding: const EdgeInsets.all(4),
        decoration: BoxDecoration(
          color: colors.surfaceNeutralSoft,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: colors.outline.withValues(alpha: 0.35)),
        ),
        child: Row(
          children: [
            Expanded(
              child: _ThemeOption(
                icon: KasyIcons.lightMode,
                label: 'Light',
                isActive: !isDark,
                isDarkMode: isDark,
                onTap: isDark ? theme.toggle : null,
              ),
            ),
            Expanded(
              child: _ThemeOption(
                icon: KasyIcons.darkMode,
                label: 'Dark',
                isActive: isDark,
                isDarkMode: isDark,
                onTap: isDark ? null : theme.toggle,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _ThemeOption extends StatelessWidget {
  final IconData icon;
  final String label;
  final bool isActive;
  final bool isDarkMode;
  final VoidCallback? onTap;

  const _ThemeOption({
    required this.icon,
    required this.label,
    required this.isActive,
    required this.isDarkMode,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    final colors = context.colors;

    // Active pill — white card on light, distinct dark surface on dark
    final Color activeBg =
        isDarkMode ? colors.onSurface.withValues(alpha: 0.18) : colors.surface;
    final Color activeContentColor =
        isDarkMode ? Colors.white : colors.onSurface;
    final Color inactiveColor = colors.muted;

    return KasyHover(
      onTap: onTap ?? () {},
      hapticEnabled: false,
      borderRadius: BorderRadius.circular(8),
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        curve: Curves.easeOut,
        decoration: BoxDecoration(
          color: isActive ? activeBg : Colors.transparent,
          borderRadius: BorderRadius.circular(8),
          boxShadow: isActive && !isDarkMode
              ? [
                  BoxShadow(
                    color: Colors.black.withValues(alpha: 0.12),
                    blurRadius: 8,
                    offset: const Offset(0, 2),
                  ),
                ]
              : null,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              icon,
              size: 15,
              color: isActive ? activeContentColor : inactiveColor,
            ),
            const SizedBox(width: 6),
            Text(
              label,
              style: context.textTheme.bodySmall?.copyWith(
                color: isActive ? activeContentColor : inactiveColor,
                fontWeight: isActive ? FontWeight.w700 : FontWeight.w400,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Rail theme toggle — single icon button in the collapsed rail
// ─────────────────────────────────────────────────────────────────────────────

class _RailThemeToggle extends StatelessWidget {
  const _RailThemeToggle();

  @override
  Widget build(BuildContext context) {
    final theme = ThemeProvider.of(context);
    final isDark = theme.mode == ThemeMode.dark;
    return _RailIconSlot(
      child: _RailIconBtn(
        icon: isDark ? KasyIcons.lightMode : KasyIcons.darkMode,
        tooltip: isDark ? 'Light mode' : 'Dark mode',
        onTap: theme.toggle,
        hapticEnabled: false,
      ),
    );
  }
}

// ═════════════════════════════════════════════════════════════════════════════
// COLLAPSED SIDEBAR — icon-only rail for medium breakpoint (768–1024 px)
// ═════════════════════════════════════════════════════════════════════════════

const double _kCollapsedWidth = 64.0;
const double _kRailIconSize = 40.0;

/// Entry point for the collapsed icon-only sidebar.
Widget kasySidebarCollapsedBuilder(
  List<BartMenuRoute> routes,
  OnTapItem onTapItem,
  ValueNotifier<int> currentItem,
) {
  return _KasySidebarCollapsedRoot(
    routes: routes,
    onTapItem: onTapItem,
    currentItem: currentItem,
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Root
// ─────────────────────────────────────────────────────────────────────────────

class _KasySidebarCollapsedRoot extends StatelessWidget {
  final List<BartMenuRoute> routes;
  final OnTapItem onTapItem;
  final ValueNotifier<int> currentItem;

  const _KasySidebarCollapsedRoot({
    required this.routes,
    required this.onTapItem,
    required this.currentItem,
  });

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<int>(
      valueListenable: currentItem,
      builder: (_, currentIndex, child) => _KasySidebarCollapsed(
        routes: routes,
        currentIndex: currentIndex,
        onTapItem: onTapItem,
      ),
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Collapsed sidebar — stateful for ⌘K shortcut
// ─────────────────────────────────────────────────────────────────────────────

class _KasySidebarCollapsed extends StatefulWidget {
  final List<BartMenuRoute> routes;
  final int currentIndex;
  final OnTapItem onTapItem;

  const _KasySidebarCollapsed({
    required this.routes,
    required this.currentIndex,
    required this.onTapItem,
  });

  @override
  State<_KasySidebarCollapsed> createState() => _KasySidebarCollapsedState();
}

class _KasySidebarCollapsedState extends State<_KasySidebarCollapsed> {
  bool _searchOpen = false;

  static const _projects = [
    (color: Color(0xFF34C759), name: 'Kasy Studio'),
    (color: Color(0xFF1E88E5), name: 'Design System'),
    (color: Color(0xFFF57F17), name: 'Components'),
  ];

  static const _placeholders = [
    (icon: KasyIcons.flash, label: 'Activity'),
    (icon: KasyIcons.note, label: 'Tasks'),
    (icon: KasyIcons.book, label: 'Reports'),
    (icon: KasyIcons.person, label: 'Team'),
  ];

  // ── Keyboard shortcut ────────────────────────────────────────────────────

  @override
  void initState() {
    super.initState();
    HardwareKeyboard.instance.addHandler(_onKeyEvent);
  }

  @override
  void dispose() {
    HardwareKeyboard.instance.removeHandler(_onKeyEvent);
    super.dispose();
  }

  bool _onKeyEvent(KeyEvent event) {
    if (!mounted || event is! KeyDownEvent) return false;
    if (event.logicalKey != LogicalKeyboardKey.keyK) return false;
    final bool trigger = HardwareKeyboard.instance.isMetaPressed ||
        HardwareKeyboard.instance.isControlPressed;
    if (trigger) {
      _openSearch();
      return true;
    }
    return false;
  }

  void _openSearch() {
    if (_searchOpen || !mounted) return;
    setState(() => _searchOpen = true);
    showGeneralDialog<void>(
      context: context,
      barrierDismissible: true,
      barrierLabel: 'Dismiss',
      barrierColor: Colors.black.withValues(alpha: 0.32),
      transitionDuration: const Duration(milliseconds: 220),
      pageBuilder: (ctx, anim, secAnim) => Align(
        alignment: const Alignment(0, -0.18),
        child: _SearchModal(
          routes: widget.routes,
          onNavigate: (index) {
            Navigator.of(ctx, rootNavigator: true).pop();
            widget.onTapItem(index);
          },
        ),
      ),
      transitionBuilder: (ctx, anim, secAnim, child) {
        final curved =
            CurvedAnimation(parent: anim, curve: Curves.easeOutCubic);
        return FadeTransition(
          opacity: curved,
          child: ScaleTransition(
            scale: Tween<double>(begin: 0.95, end: 1.0).animate(curved),
            child: child,
          ),
        );
      },
    ).then((_) {
      if (mounted) setState(() => _searchOpen = false);
    });
  }

  // ── Build ─────────────────────────────────────────────────────────────────

  @override
  Widget build(BuildContext context) {
    final colors = context.colors;

    return Container(
      width: _kCollapsedWidth,
      decoration: BoxDecoration(
        color: colors.surface,
        border: Border(
          right: BorderSide(color: colors.outline.withValues(alpha: 0.4)),
        ),
      ),
      child: SafeArea(
        right: false,
        child: Column(
          children: [
            // ── Scrollable area ────────────────────────────────────────────
            Expanded(
              child: ScrollConfiguration(
                behavior: ScrollConfiguration.of(context)
                    .copyWith(scrollbars: false),
                child: SingleChildScrollView(
                  physics: const ClampingScrollPhysics(),
                  child: Column(
                    children: [
                      const SizedBox(height: 16),

                      // Brand icon
                      _RailIconSlot(
                        child: Container(
                          width: 34,
                          height: 34,
                          decoration: BoxDecoration(
                            color: colors.primary,
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: const Icon(
                            KasyIcons.assistant,
                            size: 18,
                            color: Colors.white,
                          ),
                        ),
                      ),
                      const SizedBox(height: 12),

                      // Search
                      _RailIconSlot(
                        child: _RailIconBtn(
                          icon: KasyIcons.search,
                          tooltip: defaultTargetPlatform == TargetPlatform.macOS
                              ? 'Search  ⌘K'
                              : 'Search  Ctrl K',
                          onTap: _openSearch,
                        ),
                      ),
                      const SizedBox(height: 8),
                      const _SidebarDivider(),
                      const SizedBox(height: 8),

                      // ── Nav items ──────────────────────────────────────
                      ...widget.routes.asMap().entries.map((e) {
                        final hasBuilder = e.value.iconBuilder != null;
                        final icon = e.value.icon ?? KasyIcons.notification;
                        final label = e.value.label ?? '';
                        final isActive = widget.currentIndex == e.key;

                        if (hasBuilder) {
                          // Notification item — show dot badge
                          return Padding(
                            padding: const EdgeInsets.symmetric(vertical: 2),
                            child: _CollapsedNotificationBtn(
                              isActive: isActive,
                              label: label,
                              onTap: () => widget.onTapItem(e.key),
                            ),
                          );
                        }
                        return Padding(
                          padding: const EdgeInsets.symmetric(vertical: 2),
                          child: _RailNavBtn(
                            icon: icon,
                            tooltip: label,
                            isActive: isActive,
                            onTap: () => widget.onTapItem(e.key),
                          ),
                        );
                      }),
                      const SizedBox(height: 8),
                      const _SidebarDivider(),
                      const SizedBox(height: 8),

                      // ── Workspace icons ────────────────────────────────
                      ..._placeholders.map(
                        (p) => _RailIconSlot(
                          child: _RailIconBtn(
                            icon: p.icon,
                            tooltip: p.label,
                            onTap: () {},
                            hapticEnabled: false,
                          ),
                        ),
                      ),
                      const SizedBox(height: 12),
                      const _SidebarDivider(),
                      const SizedBox(height: 10),

                      // ── Project dots ───────────────────────────────────
                      ..._projects.map(
                        (p) => _RailProjectDot(
                          color: p.color,
                          name: p.name,
                        ),
                      ),
                      const SizedBox(height: 12),
                    ],
                  ),
                ),
              ),
            ),

            // ── Theme toggle + user avatar footer ─────────────────────────
            const _RailThemeToggle(),
            const SizedBox(height: 4),
            const _SidebarDivider(),
            const _CollapsedUserFooter(),
          ],
        ),
      ),
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Rail helpers
// ─────────────────────────────────────────────────────────────────────────────

/// Centers a child horizontally within the 64 px rail column.
class _RailIconSlot extends StatelessWidget {
  final Widget child;
  const _RailIconSlot({required this.child});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Center(child: child),
    );
  }
}

/// Generic icon-only button: tooltip + hover.
class _RailIconBtn extends StatelessWidget {
  final IconData icon;
  final String tooltip;
  final VoidCallback onTap;
  final bool hapticEnabled;

  const _RailIconBtn({
    required this.icon,
    required this.tooltip,
    required this.onTap,
    this.hapticEnabled = true,
  });

  @override
  Widget build(BuildContext context) {
    final colors = context.colors;
    return Tooltip(
      message: tooltip,
      preferBelow: false,
      waitDuration: const Duration(milliseconds: 400),
      child: KasyHover(
        onTap: onTap,
        hapticEnabled: hapticEnabled,
        borderRadius: BorderRadius.circular(_kItemRadius),
        child: SizedBox(
          width: _kRailIconSize,
          height: _kRailIconSize,
          child: Icon(
            icon,
            size: 19,
            color: colors.onSurface.withValues(alpha: 0.6),
          ),
        ),
      ),
    );
  }
}

/// Nav button with a left accent bar that appears when active.
class _RailNavBtn extends StatelessWidget {
  final IconData icon;
  final String tooltip;
  final bool isActive;
  final VoidCallback onTap;

  const _RailNavBtn({
    required this.icon,
    required this.tooltip,
    required this.isActive,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    final colors = context.colors;
    const double slotHeight = _kRailIconSize + 4;

    return Tooltip(
      message: tooltip,
      preferBelow: false,
      waitDuration: const Duration(milliseconds: 400),
      child: SizedBox(
        width: _kCollapsedWidth,
        height: slotHeight,
        child: Stack(
          alignment: Alignment.center,
          children: [
            // Left accent bar
            Positioned(
              left: 0,
              top: (slotHeight - 20) / 2,
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 160),
                width: 3,
                height: 20,
                decoration: BoxDecoration(
                  color: isActive ? colors.primary : Colors.transparent,
                  borderRadius: const BorderRadius.only(
                    topRight: Radius.circular(2),
                    bottomRight: Radius.circular(2),
                  ),
                ),
              ),
            ),
            // Icon with hover
            KasyHover(
              onTap: onTap,
              borderRadius: BorderRadius.circular(_kItemRadius),
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 160),
                curve: Curves.easeOut,
                width: _kRailIconSize,
                height: _kRailIconSize,
                decoration: BoxDecoration(
                  color: isActive
                      ? colors.surfacePrimarySoft
                      : Colors.transparent,
                  borderRadius: BorderRadius.circular(_kItemRadius),
                ),
                child: Icon(
                  icon,
                  size: 19,
                  color: isActive
                      ? colors.primary
                      : colors.onSurface.withValues(alpha: 0.6),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// Notification button with a live unread dot indicator.
class _CollapsedNotificationBtn extends ConsumerWidget {
  final bool isActive;
  final String label;
  final VoidCallback onTap;

  const _CollapsedNotificationBtn({
    required this.isActive,
    required this.label,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final colors = context.colors;
    final String? userId =
        ref.watch(userStateNotifierProvider).user.idOrNull;
    const double slotHeight = _kRailIconSize + 4;

    return Tooltip(
      message: label,
      preferBelow: false,
      waitDuration: const Duration(milliseconds: 400),
      child: SizedBox(
        width: _kCollapsedWidth,
        height: slotHeight,
        child: Stack(
          alignment: Alignment.center,
          children: [
            // Left accent bar
            Positioned(
              left: 0,
              top: (slotHeight - 20) / 2,
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 160),
                width: 3,
                height: 20,
                decoration: BoxDecoration(
                  color: isActive ? colors.primary : Colors.transparent,
                  borderRadius: const BorderRadius.only(
                    topRight: Radius.circular(2),
                    bottomRight: Radius.circular(2),
                  ),
                ),
              ),
            ),
            // Icon + dot badge
            KasyHover(
              onTap: onTap,
              borderRadius: BorderRadius.circular(_kItemRadius),
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 160),
                curve: Curves.easeOut,
                width: _kRailIconSize,
                height: _kRailIconSize,
                decoration: BoxDecoration(
                  color:
                      isActive ? colors.surfacePrimarySoft : Colors.transparent,
                  borderRadius: BorderRadius.circular(_kItemRadius),
                ),
                child: Stack(
                  clipBehavior: Clip.none,
                  alignment: Alignment.center,
                  children: [
                    Icon(
                      KasyIcons.notification,
                      size: 19,
                      color: isActive
                          ? colors.primary
                          : colors.onSurface.withValues(alpha: 0.6),
                    ),
                    if (userId != null)
                      StreamBuilder<int>(
                        stream: ref
                            .read(notificationRepositoryProvider)
                            .listenToUnreadNotificationsCount(userId),
                        builder: (_, snapshot) {
                          final int count = snapshot.data ?? 0;
                          if (count == 0) return const SizedBox.shrink();
                          return Positioned(
                            top: 7,
                            right: 7,
                            child: Container(
                              width: 7,
                              height: 7,
                              decoration: BoxDecoration(
                                color: colors.error,
                                shape: BoxShape.circle,
                                border: Border.all(
                                  color: colors.surface,
                                  width: 1.2,
                                ),
                              ),
                            ),
                          );
                        },
                      ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// Small colored dot for the projects section in collapsed mode.
class _RailProjectDot extends StatelessWidget {
  final Color color;
  final String name;

  const _RailProjectDot({required this.color, required this.name});

  @override
  Widget build(BuildContext context) {
    return _RailIconSlot(
      child: Tooltip(
        message: name,
        preferBelow: false,
        waitDuration: const Duration(milliseconds: 400),
        child: KasyHover(
          onTap: () {},
          hapticEnabled: false,
          borderRadius: BorderRadius.circular(_kItemRadius),
          child: SizedBox(
            width: _kRailIconSize,
            height: _kRailIconSize,
            child: Center(
              child: Container(
                width: 10,
                height: 10,
                decoration: BoxDecoration(
                  color: color,
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: color.withValues(alpha: 0.5),
                      blurRadius: 5,
                      offset: const Offset(0, 1),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

/// User avatar in the collapsed rail footer.
class _CollapsedUserFooter extends ConsumerWidget {
  const _CollapsedUserFooter();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final user = ref.watch(userStateNotifierProvider).user;
    final String displayName = user is AuthenticatedUserData
        ? (user.name ?? user.email.split('@').first)
        : 'Guest';
    final String initials =
        displayName.isNotEmpty ? displayName[0].toUpperCase() : 'G';

    return KasyHover(
      onTap: () {},
      hapticEnabled: false,
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 10),
        child: Center(
          child: Tooltip(
            message: displayName,
            preferBelow: false,
            waitDuration: const Duration(milliseconds: 400),
            child: KasyAvatar(
              size: KasyAvatarSize.small,
              diameter: 32,
              initials: initials,
            ),
          ),
        ),
      ),
    );
  }
}
