// SPDX-FileCopyrightText: 2026 FocusFlow contributors
// SPDX-License-Identifier: AGPL-3.0-only

/// Renders the Backlog board screen shell for the FocusFlow Flutter UI.
library;

import 'dart:async';

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

import '../../controllers/backlog_board_controller.dart';
import '../../models/backlog/backlog_board_screen_data.dart';
import '../../theme/focus_flow_tokens.dart';

/// Backlog board screen backed by a public scheduler read controller.
class BacklogBoardScreen extends StatelessWidget {
  /// Creates a Backlog board screen.
  const BacklogBoardScreen({required this.controller, super.key});

  /// Controller that owns Backlog board read and selection state.
  final BacklogBoardController controller;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: controller,
      builder: (context, _) {
        return switch (controller.state) {
          BacklogBoardLoading() => _BacklogFrame(
            taskCountLabel: '...',
            controller: controller,
            body: const _BacklogLoadingBody(),
          ),
          BacklogBoardFailure(:final message) => _BacklogFrame(
            taskCountLabel: '...',
            controller: controller,
            body: _BacklogFailureBody(
              message: message,
              onRetry: controller.retry,
            ),
          ),
          BacklogBoardEmpty(:final data) => _BacklogFrame(
            taskCountLabel: '${data.summary.totalTaskCount} tasks',
            controller: controller,
            body: _BacklogReadyBody(data: data, isEmpty: true),
          ),
          BacklogBoardReady(:final data) => _BacklogFrame(
            taskCountLabel: '${data.summary.totalTaskCount} tasks',
            controller: controller,
            body: _BacklogReadyBody(data: data),
          ),
        };
      },
    );
  }
}

/// Main Backlog frame containing header, controls, body, and overlay slot.
class _BacklogFrame extends StatelessWidget {
  /// Creates the Backlog frame.
  const _BacklogFrame({
    required this.taskCountLabel,
    required this.controller,
    required this.body,
  });

  /// Count label displayed beside the page title.
  final String taskCountLabel;

  /// Controller used by search and filter controls.
  final BacklogBoardController controller;

  /// Body rendered below the header controls.
  final Widget body;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(28, 26, 24, 28),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              _BacklogHeader(taskCountLabel: taskCountLabel),
              const SizedBox(height: 22),
              _BacklogControls(controller: controller),
              const SizedBox(height: 18),
              Expanded(child: body),
            ],
          ),
        ),
        const Positioned.fill(child: IgnorePointer(child: SizedBox.shrink())),
      ],
    );
  }
}

/// Header row for the Backlog board shell.
class _BacklogHeader extends StatelessWidget {
  /// Creates the Backlog header.
  const _BacklogHeader({required this.taskCountLabel});

  /// Count label displayed beside the page title.
  final String taskCountLabel;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Wrap(
                crossAxisAlignment: WrapCrossAlignment.center,
                spacing: 12,
                runSpacing: 8,
                children: [
                  Text(
                    'Backlog',
                    style: Theme.of(context).textTheme.displaySmall?.copyWith(
                      color: FocusFlowTokens.textPrimary,
                      fontSize: 34,
                      fontWeight: FontWeight.w800,
                    ),
                  ),
                  _CountPill(label: taskCountLabel),
                ],
              ),
              const SizedBox(height: 10),
              Text(
                'Choose work that fits your current energy.',
                style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                  color: FocusFlowTokens.textMuted,
                ),
              ),
            ],
          ),
        ),
        const SizedBox(width: 20),
        const _ModeAndSettingsControls(),
      ],
    );
  }
}

/// Header controls for Compact/Board mode and settings.
class _ModeAndSettingsControls extends StatelessWidget {
  /// Creates mode and settings controls.
  const _ModeAndSettingsControls();

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          height: 42,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            border: Border.all(color: FocusFlowTokens.subtleBorder),
          ),
          child: Row(
            children: const [
              _ModeSegment(label: 'Compact', active: false),
              _ModeSegment(label: 'Board', active: true),
            ],
          ),
        ),
        const SizedBox(width: 18),
        OutlinedButton.icon(
          onPressed: () {},
          icon: const Icon(Icons.wb_sunny_outlined, size: 18),
          label: const Text('Settings'),
          style: OutlinedButton.styleFrom(
            fixedSize: const Size(122, 42),
            foregroundColor: FocusFlowTokens.textPrimary,
            side: const BorderSide(color: FocusFlowTokens.subtleBorder),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
          ),
        ),
      ],
    );
  }
}

/// One segment in the Backlog mode toggle.
class _ModeSegment extends StatelessWidget {
  /// Creates a mode segment.
  const _ModeSegment({required this.label, required this.active});

  /// Segment label.
  final String label;

  /// Whether this segment is selected.
  final bool active;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 78,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: active ? FocusFlowTokens.glassPanelStrong : Colors.transparent,
        borderRadius: BorderRadius.circular(8),
        border: active
            ? Border.all(color: FocusFlowTokens.navBorder)
            : Border.all(color: Colors.transparent),
      ),
      child: Text(
        label,
        style: TextStyle(
          color: active
              ? FocusFlowTokens.accentMagenta
              : FocusFlowTokens.textPrimary,
          fontSize: 13,
          fontWeight: FontWeight.w700,
        ),
      ),
    );
  }
}

/// Search, filter, sort, group, and new-task controls.
class _BacklogControls extends StatelessWidget {
  /// Creates Backlog controls.
  const _BacklogControls({required this.controller});

  /// Controller updated by shell controls.
  final BacklogBoardController controller;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: SizedBox(
            height: 44,
            child: TextField(
              key: const ValueKey('backlog-search-field'),
              onSubmitted: (value) {
                unawaited(controller.updateSearchText(value));
              },
              style: const TextStyle(color: FocusFlowTokens.textPrimary),
              decoration: InputDecoration(
                prefixIcon: const Icon(
                  Icons.search,
                  color: FocusFlowTokens.textMuted,
                ),
                hintText: 'Search backlog...',
                hintStyle: const TextStyle(color: FocusFlowTokens.textFaint),
                filled: true,
                fillColor: FocusFlowTokens.panelBackground,
                contentPadding: EdgeInsets.zero,
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                  borderSide: const BorderSide(
                    color: FocusFlowTokens.subtleBorder,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                  borderSide: const BorderSide(
                    color: FocusFlowTokens.accentMagenta,
                  ),
                ),
              ),
            ),
          ),
        ),
        const SizedBox(width: 16),
        const _BacklogControlButton(
          icon: Icons.filter_alt_outlined,
          label: 'Filters',
        ),
        const SizedBox(width: 14),
        const _BacklogControlButton(icon: Icons.tune, label: 'Sort: Custom'),
        const SizedBox(width: 14),
        const _BacklogControlButton(
          icon: Icons.dashboard_customize_outlined,
          label: 'Group: None',
        ),
        const SizedBox(width: 18),
        FilledButton.icon(
          key: const ValueKey('backlog-new-task-button'),
          onPressed: () {},
          icon: const Icon(Icons.add),
          label: const Text('New Task'),
          style: FilledButton.styleFrom(
            fixedSize: const Size(146, 44),
            backgroundColor: FocusFlowTokens.accentMagenta,
            foregroundColor: FocusFlowTokens.textPrimary,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
          ),
        ),
      ],
    );
  }
}

/// Compact outlined control button used by the Backlog shell.
class _BacklogControlButton extends StatelessWidget {
  /// Creates a Backlog control button.
  const _BacklogControlButton({required this.icon, required this.label});

  /// Leading icon for the control.
  final IconData icon;

  /// Control label.
  final String label;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return OutlinedButton.icon(
      onPressed: () {},
      icon: Icon(icon, size: 18),
      label: Text(label),
      style: OutlinedButton.styleFrom(
        fixedSize: const Size(138, 44),
        foregroundColor: FocusFlowTokens.textPrimary,
        side: const BorderSide(color: FocusFlowTokens.subtleBorder),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      ),
    );
  }
}

/// Body shown while the Backlog board loads.
class _BacklogLoadingBody extends StatelessWidget {
  /// Creates a loading body.
  const _BacklogLoadingBody();

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return const _BacklogStatePanel(
      icon: Icons.hourglass_top,
      title: 'Loading backlog',
      message: 'Preparing your board.',
    );
  }
}

/// Body shown when the Backlog board fails to load.
class _BacklogFailureBody extends StatelessWidget {
  /// Creates a failure body.
  const _BacklogFailureBody({required this.message, required this.onRetry});

  /// Failure message or code.
  final String message;

  /// Retry callback.
  final Future<void> Function() onRetry;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return _BacklogStatePanel(
      icon: Icons.refresh,
      title: 'Could not load backlog',
      message: 'Status: $message',
      action: OutlinedButton.icon(
        onPressed: () {
          unawaited(onRetry());
        },
        icon: const Icon(Icons.refresh),
        label: const Text('Retry'),
      ),
    );
  }
}

/// Ready or empty Backlog board body.
class _BacklogReadyBody extends StatelessWidget {
  /// Creates a ready body.
  const _BacklogReadyBody({required this.data, this.isEmpty = false});

  /// Backlog board data.
  final BacklogBoardScreenData data;

  /// Whether the board has no tasks.
  final bool isEmpty;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Expanded(
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              for (final column in data.columns) ...[
                Expanded(child: _BacklogColumnShell(column: column)),
                if (column != data.columns.last) const SizedBox(width: 10),
              ],
            ],
          ),
        ),
        const SizedBox(width: 16),
        SizedBox(
          width: 292,
          child: isEmpty
              ? const _BacklogStatePanel(
                  icon: Icons.check_circle_outline,
                  title: 'Backlog is clear',
                  message: 'New tasks will appear here.',
                )
              : _BacklogSummaryShell(summary: data.summary),
        ),
      ],
    );
  }
}

/// One Backlog board column shell.
class _BacklogColumnShell extends StatelessWidget {
  /// Creates a column shell.
  const _BacklogColumnShell({required this.column});

  /// Column read model.
  final BacklogBoardColumnReadModel column;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    final accent = _accentColor(column.bucket);
    return DecoratedBox(
      decoration: BoxDecoration(
        color: FocusFlowTokens.panelBackground,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: accent.withValues(alpha: 0.62)),
      ),
      child: Padding(
        padding: const EdgeInsets.all(14),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Row(
              children: [
                Icon(_bucketIcon(column.bucket), color: accent, size: 22),
                const SizedBox(width: 10),
                Expanded(
                  child: Text(
                    column.title,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(
                      color: FocusFlowTokens.textPrimary,
                      fontSize: 15,
                      fontWeight: FontWeight.w800,
                    ),
                  ),
                ),
                _CountPill(label: '${column.count}', color: accent),
                IconButton(
                  onPressed: () {},
                  icon: const Icon(Icons.add),
                  color: FocusFlowTokens.textMuted,
                  tooltip: 'Add task',
                  iconSize: 18,
                  visualDensity: VisualDensity.compact,
                ),
              ],
            ),
            const SizedBox(height: 8),
            Text(
              column.subtitle,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(
                color: FocusFlowTokens.textMuted,
                fontSize: 12,
              ),
            ),
            const SizedBox(height: 16),
            Expanded(
              child: ListView.separated(
                physics: const NeverScrollableScrollPhysics(),
                itemCount: column.items.isEmpty
                    ? 2
                    : column.items.take(4).length,
                separatorBuilder: (context, index) =>
                    const SizedBox(height: 10),
                itemBuilder: (context, index) {
                  final hasItem = column.items.isNotEmpty;
                  return _ColumnSkeletonCard(
                    accent: accent,
                    active: hasItem,
                    title: hasItem ? column.items[index].title : null,
                  );
                },
              ),
            ),
            const SizedBox(height: 10),
            Align(
              alignment: Alignment.centerLeft,
              child: TextButton.icon(
                onPressed: () {},
                icon: Icon(Icons.add, color: accent),
                label: Text('Add task', style: TextStyle(color: accent)),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// Placeholder card used until Block 04 fills in card details.
class _ColumnSkeletonCard extends StatelessWidget {
  /// Creates a skeleton card.
  const _ColumnSkeletonCard({
    required this.accent,
    this.title,
    this.active = false,
  });

  /// Accent color inherited from the column.
  final Color accent;

  /// Optional task title for a loaded board item.
  final String? title;

  /// Whether this skeleton represents a loaded item.
  final bool active;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 86,
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: FocusFlowTokens.elevatedPanel.withValues(
          alpha: active ? 1 : 0.55,
        ),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: FocusFlowTokens.subtleBorder),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                width: 14,
                height: 14,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(3),
                  border: Border.all(color: FocusFlowTokens.textFaint),
                ),
              ),
              const SizedBox(width: 10),
              Expanded(
                child: title == null
                    ? _SkeletonLine(widthFactor: 0.7, color: accent)
                    : Text(
                        title!,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(
                          color: FocusFlowTokens.textPrimary,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
              ),
            ],
          ),
          const Spacer(),
          _SkeletonLine(widthFactor: active ? 0.55 : 0.42, color: accent),
          const SizedBox(height: 8),
          _SkeletonLine(widthFactor: active ? 0.78 : 0.58, color: accent),
        ],
      ),
    );
  }
}

/// Summary panel shell for loaded board data.
class _BacklogSummaryShell extends StatelessWidget {
  /// Creates a summary shell.
  const _BacklogSummaryShell({required this.summary});

  /// Summary read model.
  final BacklogBoardSummaryReadModel summary;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return DecoratedBox(
      decoration: BoxDecoration(
        color: FocusFlowTokens.panelBackground,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: FocusFlowTokens.subtleBorder),
      ),
      child: Padding(
        padding: const EdgeInsets.all(18),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Row(
              children: [
                Icon(Icons.auto_awesome, color: FocusFlowTokens.accentMagenta),
                SizedBox(width: 10),
                Expanded(
                  child: Text(
                    'Backlog summary',
                    style: TextStyle(
                      color: FocusFlowTokens.textPrimary,
                      fontSize: 18,
                      fontWeight: FontWeight.w800,
                    ),
                  ),
                ),
                Icon(Icons.expand_less, color: FocusFlowTokens.textMuted),
              ],
            ),
            const SizedBox(height: 24),
            Row(
              children: [
                Expanded(
                  child: _SummaryMetric(
                    value: '${summary.totalTaskCount}',
                    label: 'Total tasks',
                  ),
                ),
                Expanded(
                  child: _SummaryMetric(
                    value: _estimatedTimeText(summary.totalEstimatedMinutes),
                    label: 'Estimated time',
                  ),
                ),
              ],
            ),
            const SizedBox(height: 26),
            _SummaryDistribution(distribution: summary.priorityDistribution),
            const SizedBox(height: 20),
            _SummaryDistribution(distribution: summary.projectDistribution),
            const Spacer(),
            DecoratedBox(
              decoration: BoxDecoration(
                color: FocusFlowTokens.elevatedPanel,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Padding(
                padding: const EdgeInsets.all(14),
                child: Text(
                  summary.planningTip,
                  style: const TextStyle(
                    color: FocusFlowTokens.textMuted,
                    height: 1.4,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Formats [minutes] as compact hour/minute text.
  String _estimatedTimeText(int minutes) {
    final hours = minutes ~/ 60;
    final remainder = minutes % 60;
    if (hours == 0) {
      return '${remainder}m';
    }
    if (remainder == 0) {
      return '${hours}h';
    }
    return '${hours}h ${remainder}m';
  }
}

/// One numeric metric in the summary shell.
class _SummaryMetric extends StatelessWidget {
  /// Creates a summary metric.
  const _SummaryMetric({required this.value, required this.label});

  /// Metric value.
  final String value;

  /// Metric label.
  final String label;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          value,
          style: const TextStyle(
            color: FocusFlowTokens.textPrimary,
            fontSize: 24,
            fontWeight: FontWeight.w800,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          label,
          style: const TextStyle(
            color: FocusFlowTokens.textFaint,
            fontSize: 12,
          ),
        ),
      ],
    );
  }
}

/// Compact list form of a summary distribution.
class _SummaryDistribution extends StatelessWidget {
  /// Creates a summary distribution.
  const _SummaryDistribution({required this.distribution});

  /// Distribution read model.
  final BacklogDistributionReadModel distribution;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          distribution.title,
          style: const TextStyle(
            color: FocusFlowTokens.textPrimary,
            fontWeight: FontWeight.w700,
          ),
        ),
        const SizedBox(height: 10),
        for (final entry in distribution.entries.take(5))
          Padding(
            padding: const EdgeInsets.only(bottom: 8),
            child: Row(
              children: [
                Expanded(
                  child: Text(
                    entry.label,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(color: FocusFlowTokens.textMuted),
                  ),
                ),
                Text(
                  '${entry.count}',
                  style: const TextStyle(color: FocusFlowTokens.textPrimary),
                ),
              ],
            ),
          ),
      ],
    );
  }
}

/// Reusable centered state panel.
class _BacklogStatePanel extends StatelessWidget {
  /// Creates a state panel.
  const _BacklogStatePanel({
    required this.icon,
    required this.title,
    required this.message,
    this.action,
  });

  /// Leading icon.
  final IconData icon;

  /// Panel title.
  final String title;

  /// Panel message.
  final String message;

  /// Optional action widget.
  final Widget? action;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return Center(
      child: ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 360),
        child: DecoratedBox(
          decoration: BoxDecoration(
            color: FocusFlowTokens.panelBackground,
            borderRadius: BorderRadius.circular(8),
            border: Border.all(color: FocusFlowTokens.subtleBorder),
          ),
          child: Padding(
            padding: const EdgeInsets.all(24),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(icon, color: FocusFlowTokens.accentMagenta, size: 28),
                const SizedBox(height: 14),
                Text(
                  title,
                  textAlign: TextAlign.center,
                  style: const TextStyle(
                    color: FocusFlowTokens.textPrimary,
                    fontSize: 18,
                    fontWeight: FontWeight.w800,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  message,
                  textAlign: TextAlign.center,
                  style: const TextStyle(color: FocusFlowTokens.textMuted),
                ),
                if (action != null) ...[const SizedBox(height: 18), action!],
              ],
            ),
          ),
        ),
      ),
    );
  }
}

/// Small count pill used by headers.
class _CountPill extends StatelessWidget {
  /// Creates a count pill.
  const _CountPill({required this.label, this.color});

  /// Pill label.
  final String label;

  /// Optional accent color.
  final Color? color;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    final accent = color ?? FocusFlowTokens.textMuted;
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      decoration: BoxDecoration(
        color: accent.withValues(alpha: 0.16),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Text(
        label,
        style: TextStyle(
          color: color ?? FocusFlowTokens.textPrimary,
          fontSize: 12,
          fontWeight: FontWeight.w800,
        ),
      ),
    );
  }
}

/// Skeleton line used by placeholder cards.
class _SkeletonLine extends StatelessWidget {
  /// Creates a skeleton line.
  const _SkeletonLine({required this.widthFactor, required this.color});

  /// Fractional width for the line.
  final double widthFactor;

  /// Accent color for the line.
  final Color color;

  /// Builds the widget subtree for this component.
  /// The method translates the current widget configuration and state into Flutter UI without mutating scheduler domain data.
  @override
  Widget build(BuildContext context) {
    return FractionallySizedBox(
      widthFactor: widthFactor,
      alignment: Alignment.centerLeft,
      child: Container(
        height: 6,
        decoration: BoxDecoration(
          color: color.withValues(alpha: 0.22),
          borderRadius: BorderRadius.circular(999),
        ),
      ),
    );
  }
}

/// Resolves a display color for [bucket].
Color _accentColor(BacklogBoardBucket bucket) {
  return switch (bucket) {
    BacklogBoardBucket.doNext => FocusFlowTokens.flexibleGreen,
    BacklogBoardBucket.needTimeBlock => FocusFlowTokens.warningYellow,
    BacklogBoardBucket.breakUpFirst => FocusFlowTokens.restPurple,
    BacklogBoardBucket.notNow => FocusFlowTokens.appointmentBlue,
  };
}

/// Resolves a display icon for [bucket].
IconData _bucketIcon(BacklogBoardBucket bucket) {
  return switch (bucket) {
    BacklogBoardBucket.doNext => Icons.check_circle_outline,
    BacklogBoardBucket.needTimeBlock => Icons.schedule,
    BacklogBoardBucket.breakUpFirst => Icons.adjust,
    BacklogBoardBucket.notNow => Icons.cloud_outlined,
  };
}
