import 'dart:async';

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:qr_flutter/qr_flutter.dart';

import '../../../../../../core/services/leave_service.dart';

const _leaveGreen = Color.fromARGB(255, 2, 105, 48);
const _leaveGold = Color.fromARGB(255, 204, 117, 4);
const _leaveInk = Color(0xFF1E2A24);
const _leaveMuted = Color(0xFF6E7973);
const _leaveBorder = Color(0xFFDDE5E0);
const _leaveSurface = Color(0xFFF6F8F7);
const _sheetGreen = Color(0xFF70AD47);
const _sheetDarkGreen = Color(0xFF548235);
const _sheetBand = Color(0xFFE2F0D9);
const _sheetBandSoft = Color(0xFFF3F8EF);

bool _truthyValue(dynamic value) {
  if (value is bool) return value;
  if (value is num) return value != 0;
  final text = '${value ?? ''}'.trim().toLowerCase();
  return text == '1' || text == 'true' || text == 't' || text == 'yes';
}

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

  @override
  State<LeaveMainTab> createState() => _LeaveMainTabState();
}

class _LeaveMainTabState extends State<LeaveMainTab> {
  int _index = 0;
  bool _loading = true;
  String? _error;
  Map<String, dynamic> _setup = const {};
  List<Map<String, dynamic>> _my = const [];
  List<Map<String, dynamic>> _action = const [];
  List<Map<String, dynamic>> _completed = const [];
  Map<String, dynamic> _myLedger = const {};
  int _unread = 0;
  bool _offlineCache = false;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _load();
    _timer = Timer.periodic(const Duration(seconds: 10), (_) => _silentRefresh());
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  Future<void> _silentRefresh() async {
    if (!mounted) return;
    try {
      final results = await Future.wait([
        LeaveService.list(scope: 'my'),
        LeaveService.list(scope: 'action'),
        LeaveService.list(scope: 'completed'),
        LeaveService.myLedger(),
        LeaveService.unreadCount(),
      ]);
      if (!mounted) return;
      setState(() {
        _my = _rows(results[0]);
        _action = _rows(results[1]);
        _completed = _rows(results[2]);
        _myLedger = Map<String, dynamic>.from(results[3] as Map);
        _unread = results[4] as int;
        _offlineCache = results.take(4).whereType<Map>().any((e) => e['_offline_cache'] == true);
      });
    } catch (_) {}
  }

  List<Map<String, dynamic>> _rows(dynamic data) {
    if (data is! Map) return [];
    final raw = data['data'];
    if (raw is! List) return [];
    return raw
        .whereType<Map>()
        .map((e) => e.map((k, v) => MapEntry(k.toString(), v)))
        .toList();
  }

  Future<void> _load() async {
    if (!mounted) return;
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final results = await Future.wait([
        LeaveService.getSetup(),
        LeaveService.list(scope: 'my'),
        LeaveService.list(scope: 'action'),
        LeaveService.list(scope: 'completed'),
        LeaveService.myLedger(),
        LeaveService.unreadCount(),
      ]);
      if (!mounted) return;
      setState(() {
        _setup = Map<String, dynamic>.from(results[0] as Map);
        _my = _rows(results[1]);
        _action = _rows(results[2]);
        _completed = _rows(results[3]);
        _myLedger = Map<String, dynamic>.from(results[4] as Map);
        _unread = results[5] as int;
        _offlineCache = results.take(5).whereType<Map>().any((e) => e['_offline_cache'] == true);
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = LeaveService.cleanError(e);
      });
    }
  }

  Future<void> _openNew() async {
    final saved = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => LeaveApplicationDialog(setup: _setup),
    );
    if (saved == true) await _load();
  }

  Future<void> _openLeave(Map<String, dynamic> row) async {
    final id = int.tryParse('${row['id'] ?? 0}') ?? 0;
    if (id <= 0) return;
    try {
      final leave = await LeaveService.getLeave(id);
      if (!mounted) return;
      final changed = await showDialog<bool>(
        context: context,
        barrierDismissible: false,
        builder: (_) => LeaveDetailDialog(leave: leave),
      );
      if (changed == true) await _load();
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(LeaveService.cleanError(e)),
          backgroundColor: Colors.red.shade700,
        ),
      );
    }
  }

  Future<void> _openNotifications() async {
    await showDialog<void>(
      context: context,
      builder: (_) => _LeaveNotificationsDialog(
        onOpenLeave: (id) async {
          Navigator.of(context).pop();
          try {
            final leave = await LeaveService.getLeave(id);
            if (!mounted) return;
            final changed = await showDialog<bool>(
              context: context,
              barrierDismissible: false,
              builder: (_) => LeaveDetailDialog(leave: leave),
            );
            if (changed == true) await _load();
          } catch (_) {}
        },
      ),
    );
    await _silentRefresh();
  }

  Map<String, dynamic> get _hrAccess {
    final raw = _setup['hr_access'];
    return raw is Map ? raw.map((k, v) => MapEntry(k.toString(), v)) : const <String, dynamic>{};
  }

  bool get _isHr => _truthyValue(_hrAccess['enabled']);

  List<Map<String, dynamic>> get _currentRows =>
      _index == 1 ? _action : (_index == 2 ? _completed : _my);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF3F6F4),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: (_loading || _offlineCache) ? null : _openNew,
        backgroundColor: _leaveGold,
        foregroundColor: Colors.white,
        icon: const Icon(Icons.add_rounded),
        label: const Text('NEW LEAVE', style: TextStyle(fontWeight: FontWeight.w900)),
      ),
      body: SafeArea(
        child: Column(
          children: [
            _LeaveHeader(
              unread: _unread,
              offline: _offlineCache,
              onNotifications: _openNotifications,
              onRefresh: _load,
            ),
            _LeaveTabs(
              index: _index,
              myCount: _my.length,
              actionCount: _action.length,
              completedCount: _completed.length,
              showHr: _isHr,
              onChanged: (value) => setState(() => _index = value),
            ),
            Expanded(
              child: _loading
                  ? const Center(child: CircularProgressIndicator(color: _leaveGreen))
                  : _error != null
                      ? _ErrorPanel(message: _error!, onRetry: _load)
                      : _index == 3
                          ? _MyLeaveDaysPanel(
                              data: _myLedger,
                              onOpenLeave: _openLeave,
                            )
                          : (_index == 4 && _isHr)
                              ? _HrLeaveControlCentre(
                                  access: _hrAccess,
                                  onOpenLeaveId: (id) async {
                                    try {
                                      final leave = await LeaveService.getLeave(id);
                                      if (!mounted) return;
                                      final changed = await showDialog<bool>(
                                        context: context,
                                        barrierDismissible: false,
                                        builder: (_) => LeaveDetailDialog(leave: leave),
                                      );
                                      if (changed == true) await _load();
                                    } catch (e) {
                                      if (!mounted) return;
                                      ScaffoldMessenger.of(context).showSnackBar(
                                        SnackBar(content: Text(LeaveService.cleanError(e)), backgroundColor: Colors.red.shade700),
                                      );
                                    }
                                  },
                                )
                              : _index == 1 || _index == 2
                                  ? _CampusLeaveSections(
                                      rows: _currentRows,
                                      section: _index == 1 ? 'Action Required' : 'Completed',
                                      onOpen: _openLeave,
                                    )
                                  : _LeaveGrid(rows: _currentRows, onOpen: _openLeave),
            ),
          ],
        ),
      ),
    );
  }
}

class _LeaveHeader extends StatelessWidget {
  final int unread;
  final bool offline;
  final VoidCallback onNotifications;
  final VoidCallback onRefresh;

  const _LeaveHeader({
    required this.unread,
    required this.offline,
    required this.onNotifications,
    required this.onRefresh,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      constraints: const BoxConstraints(minHeight: 54),
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
      decoration: const BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(color: _leaveBorder)),
      ),
      child: Row(
        children: [
          Container(
            width: 34,
            height: 34,
            decoration: BoxDecoration(
              color: _leaveGreen.withOpacity(.08),
              borderRadius: BorderRadius.circular(9),
              border: Border.all(color: _leaveGreen.withOpacity(.14)),
            ),
            child: const Icon(Icons.event_note_rounded, color: _leaveGreen, size: 19),
          ),
          const SizedBox(width: 10),
          const Expanded(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('LEAVE MANAGEMENT', style: TextStyle(color: _leaveInk, fontSize: 13.2, fontWeight: FontWeight.w900, letterSpacing: .35)),
                SizedBox(height: 1),
                Text('Applications • balances • approvals', style: TextStyle(color: _leaveMuted, fontSize: 9.2)),
              ],
            ),
          ),
          if (offline)
            Container(
              margin: const EdgeInsets.only(right: 6),
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
              decoration: BoxDecoration(
                color: _leaveGold.withOpacity(.08),
                borderRadius: BorderRadius.circular(99),
                border: Border.all(color: _leaveGold.withOpacity(.25)),
              ),
              child: const Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(Icons.cloud_off_rounded, size: 13, color: _leaveGold),
                  SizedBox(width: 4),
                  Text('OFFLINE CACHE', style: TextStyle(color: _leaveGold, fontSize: 7.8, fontWeight: FontWeight.w900)),
                ],
              ),
            ),
          IconButton(
            tooltip: 'Refresh',
            visualDensity: VisualDensity.compact,
            onPressed: onRefresh,
            icon: const Icon(Icons.refresh_rounded, color: _leaveGreen, size: 20),
          ),
          Stack(
            clipBehavior: Clip.none,
            children: [
              IconButton(
                tooltip: 'Leave notifications',
                visualDensity: VisualDensity.compact,
                onPressed: onNotifications,
                icon: const Icon(Icons.notifications_none_rounded, color: _leaveGreen, size: 20),
              ),
              if (unread > 0)
                Positioned(top: -1, right: -1, child: _CountBadge(unread, small: true)),
            ],
          ),
        ],
      ),
    );
  }
}

class _LeaveTabs extends StatelessWidget {
  final int index;
  final int myCount;
  final int actionCount;
  final int completedCount;
  final bool showHr;
  final ValueChanged<int> onChanged;

  const _LeaveTabs({
    required this.index,
    required this.myCount,
    required this.actionCount,
    required this.completedCount,
    required this.showHr,
    required this.onChanged,
  });

  @override
  Widget build(BuildContext context) {
    final tabs = <(String, IconData, int)>[
      ('My Leave', Icons.description_outlined, myCount),
      ('Action Required', Icons.approval_outlined, actionCount),
      ('Completed', Icons.task_alt_rounded, completedCount),
      ('My Leave Days', Icons.calendar_view_month_rounded, 0),
      if (showHr) ('HR Leave Ledger', Icons.people_alt_outlined, 0),
    ];
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.fromLTRB(12, 8, 12, 10),
      child: LayoutBuilder(
        builder: (_, c) {
          final compact = c.maxWidth < 620;
          return Row(
            children: List.generate(tabs.length, (i) {
              final tab = tabs[i];
              final selected = index == i;
              return Expanded(
                child: InkWell(
                  borderRadius: BorderRadius.circular(12),
                  onTap: () => onChanged(i),
                  child: AnimatedContainer(
                    duration: const Duration(milliseconds: 180),
                    margin: const EdgeInsets.symmetric(horizontal: 3),
                    padding: EdgeInsets.symmetric(
                      horizontal: compact ? 5 : 10,
                      vertical: 10,
                    ),
                    decoration: BoxDecoration(
                      color: selected ? _leaveGreen.withOpacity(.08) : Colors.transparent,
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(
                        color: selected ? _leaveGreen.withOpacity(.25) : Colors.transparent,
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(tab.$2, size: compact ? 18 : 20, color: selected ? _leaveGreen : _leaveMuted),
                        if (!compact) ...[
                          const SizedBox(width: 7),
                          Flexible(
                            child: Text(
                              tab.$1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                color: selected ? _leaveGreen : _leaveInk,
                                fontWeight: FontWeight.w800,
                                fontSize: 11.5,
                              ),
                            ),
                          ),
                        ],
                        if (tab.$3 > 0) ...[
                          const SizedBox(width: 6),
                          _CountBadge(tab.$3, small: true),
                        ],
                      ],
                    ),
                  ),
                ),
              );
            }),
          );
        },
      ),
    );
  }
}

class _CountBadge extends StatelessWidget {
  final int count;
  final bool small;
  const _CountBadge(this.count, {this.small = false});

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: BoxConstraints(minWidth: small ? 18 : 20, minHeight: small ? 18 : 20),
      padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
      decoration: BoxDecoration(
        color: Colors.redAccent,
        borderRadius: BorderRadius.circular(99),
        border: Border.all(color: Colors.white, width: 1.2),
      ),
      alignment: Alignment.center,
      child: Text(
        count > 99 ? '99+' : '$count',
        style: TextStyle(
          color: Colors.white,
          fontSize: small ? 8 : 9,
          fontWeight: FontWeight.w900,
          height: 1,
        ),
      ),
    );
  }
}


class _MyLeaveDaysPanel extends StatefulWidget {
  final Map<String, dynamic> data;
  final ValueChanged<Map<String, dynamic>> onOpenLeave;

  const _MyLeaveDaysPanel({
    required this.data,
    required this.onOpenLeave,
  });

  @override
  State<_MyLeaveDaysPanel> createState() => _MyLeaveDaysPanelState();
}

class _MyLeaveDaysPanelState extends State<_MyLeaveDaysPanel> {
  final _historyScroll = ScrollController();

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

  String _t(dynamic value, [String fallback = '—']) {
    final text = value?.toString().trim() ?? '';
    return text.isEmpty || text.toLowerCase() == 'null' ? fallback : text;
  }

  double _n(dynamic value) => double.tryParse('${value ?? 0}') ?? 0;

  String _date(dynamic value, [String fallback = '—']) {
    final raw = _t(value, '');
    if (raw.isEmpty) return fallback;
    try {
      return DateFormat('dd MMM yyyy').format(DateTime.parse(raw).toLocal());
    } catch (_) {
      return raw;
    }
  }

  @override
  Widget build(BuildContext context) {
    final balanceRaw = widget.data['balance'];
    final balance = balanceRaw is Map
        ? balanceRaw.map((k, v) => MapEntry(k.toString(), v))
        : <String, dynamic>{};
    final summaryRaw = widget.data['summary'];
    final summary = summaryRaw is Map
        ? summaryRaw.map((k, v) => MapEntry(k.toString(), v))
        : <String, dynamic>{};
    final historyRaw = widget.data['leave_history'];
    final history = historyRaw is List
        ? historyRaw
            .whereType<Map>()
            .map((e) => e.map((k, v) => MapEntry(k.toString(), v)))
            .toList()
        : <Map<String, dynamic>>[];
    final adjustmentRaw = widget.data['adjustments'];
    final adjustments = adjustmentRaw is List
        ? adjustmentRaw
            .whereType<Map>()
            .map((e) => e.map((k, v) => MapEntry(k.toString(), v)))
            .toList()
        : <Map<String, dynamic>>[];
    final offline = widget.data['_offline_cache'] == true;
    final cachedAt = _t(widget.data['_cache_updated_at'], '');
    final year = int.tryParse('${widget.data['year'] ?? DateTime.now().year}') ?? DateTime.now().year;

    return LayoutBuilder(
      builder: (_, c) {
        final compact = c.maxWidth < 720;
        return ListView(
          padding: EdgeInsets.fromLTRB(compact ? 10 : 16, 10, compact ? 10 : 16, 100),
          children: [
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 10),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
                border: Border.all(color: _leaveBorder),
              ),
              child: Row(
                children: [
                  Container(
                    width: 34,
                    height: 34,
                    decoration: BoxDecoration(
                      color: _leaveGreen.withOpacity(.08),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: const Icon(Icons.calendar_view_month_rounded, color: _leaveGreen, size: 19),
                  ),
                  const SizedBox(width: 9),
                  const Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('MY LEAVE DAYS', style: TextStyle(color: _leaveInk, fontSize: 12.4, fontWeight: FontWeight.w900, letterSpacing: .3)),
                        SizedBox(height: 1),
                        Text('Your current balance, approved leave periods and HR adjustments are available offline after the first sync.', style: TextStyle(color: _leaveMuted, fontSize: 9.1)),
                      ],
                    ),
                  ),
                  if (offline)
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
                      decoration: BoxDecoration(
                        color: _leaveGold.withOpacity(.08),
                        borderRadius: BorderRadius.circular(99),
                        border: Border.all(color: _leaveGold.withOpacity(.25)),
                      ),
                      child: Text(
                        'OFFLINE${cachedAt.isEmpty ? '' : ' • CACHED'}',
                        style: const TextStyle(color: _leaveGold, fontSize: 7.5, fontWeight: FontWeight.w900),
                      ),
                    ),
                ],
              ),
            ),
            const SizedBox(height: 9),
            LayoutBuilder(
              builder: (_, metrics) {
                final width = metrics.maxWidth < 620
                    ? metrics.maxWidth
                    : metrics.maxWidth < 1050
                        ? (metrics.maxWidth - 8) / 2
                        : (metrics.maxWidth - 32) / 5;
                final cards = [
                  _HrMetricCard(icon: Icons.event_available_outlined, label: 'AVAILABLE', value: _n(balance['available_days']).toStringAsFixed(2), note: 'Days available now'),
                  _HrMetricCard(icon: Icons.add_chart_rounded, label: 'ACCRUED', value: _n(balance['entitlement_days']).toStringAsFixed(2), note: '$year entitlement'),
                  _HrMetricCard(icon: Icons.beach_access_outlined, label: 'USED', value: _n(balance['used_days']).toStringAsFixed(2), note: 'Approved leave used'),
                  _HrMetricCard(icon: Icons.sync_alt_rounded, label: 'ADJUSTMENTS', value: _n(balance['adjustment_days']).toStringAsFixed(2), note: 'HR additions / reductions'),
                  _HrMetricCard(icon: Icons.calendar_month_outlined, label: 'MONTHLY RATE', value: _n(balance['accrual_rate_month']).toStringAsFixed(2), note: 'Days added each month'),
                ];
                return Wrap(
                  spacing: 8,
                  runSpacing: 8,
                  children: cards.map((e) => SizedBox(width: width, child: e)).toList(),
                );
              },
            ),
            const SizedBox(height: 9),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 9),
              decoration: BoxDecoration(
                color: _sheetBandSoft,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: _sheetGreen.withOpacity(.8), width: .8),
              ),
              child: Wrap(
                spacing: 18,
                runSpacing: 7,
                children: [
                  _MiniLedgerFact(label: 'BALANCE YEAR', value: '$year'),
                  _MiniLedgerFact(label: 'APPROVED RECORDS', value: '${summary['approved_leave_records'] ?? 0}'),
                  _MiniLedgerFact(label: 'PENDING', value: '${summary['pending_leave_records'] ?? 0}'),
                  _MiniLedgerFact(label: 'DAYS TAKEN', value: _n(summary['days_taken_history'] ?? summary['days_taken_this_year']).toStringAsFixed(2)),
                ],
              ),
            ),
            const SizedBox(height: 9),
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: _sheetGreen, width: .8),
              ),
              clipBehavior: Clip.antiAlias,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 9),
                    decoration: BoxDecoration(
                      color: _sheetBand,
                      border: Border(bottom: BorderSide(color: _sheetGreen.withOpacity(.9), width: .8)),
                    ),
                    child: const Row(
                      children: [
                        Icon(Icons.table_chart_outlined, color: _sheetDarkGreen, size: 17),
                        SizedBox(width: 7),
                        Expanded(child: Text('MY LEAVE HISTORY', style: TextStyle(color: _sheetDarkGreen, fontWeight: FontWeight.w900, fontSize: 11.5, letterSpacing: .25))),
                        Text('Tap a record to open the full application', style: TextStyle(color: _leaveMuted, fontSize: 8.8)),
                      ],
                    ),
                  ),
                  if (history.isEmpty)
                    const Padding(
                      padding: EdgeInsets.all(24),
                      child: Center(child: Text('No leave records are available for this year.', style: TextStyle(color: _leaveMuted))),
                    )
                  else if (compact)
                    ...List.generate(history.length, (i) {
                      final row = history[i];
                      final status = _t(row['status'], 'pending').toUpperCase();
                      return InkWell(
                        onTap: () => widget.onOpenLeave(row),
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 9),
                          decoration: BoxDecoration(
                            color: i.isOdd ? _sheetBandSoft : Colors.white,
                            border: const Border(bottom: BorderSide(color: _sheetGreen, width: .55)),
                          ),
                          child: Row(
                            children: [
                              Container(width: 5, height: 42, decoration: BoxDecoration(color: status == 'APPROVED' ? _leaveGreen : _leaveGold, borderRadius: BorderRadius.circular(99))),
                              const SizedBox(width: 9),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text('${_t(row['leave_type'], 'leave').toUpperCase()} • ${_n(row['requested_days']).toStringAsFixed(2)} day(s)', style: const TextStyle(color: _leaveInk, fontSize: 10.8, fontWeight: FontWeight.w900)),
                                    const SizedBox(height: 3),
                                    Text('${_date(row['start_date'])} → ${_date(row['end_date'])}', style: const TextStyle(color: _leaveMuted, fontSize: 9.5, fontWeight: FontWeight.w700)),
                                    const SizedBox(height: 2),
                                    Text('Approved/decided: ${_date(row['final_decision_at'], 'Pending')} • Return: ${_date(row['expected_return_date'])}', style: const TextStyle(color: _leaveMuted, fontSize: 8.8)),
                                  ],
                                ),
                              ),
                              Container(
                                padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 4),
                                decoration: BoxDecoration(color: (status == 'APPROVED' ? _leaveGreen : _leaveGold).withOpacity(.09), borderRadius: BorderRadius.circular(99)),
                                child: Text(status, style: TextStyle(color: status == 'APPROVED' ? _leaveGreen : _leaveGold, fontSize: 7.5, fontWeight: FontWeight.w900)),
                              ),
                              const SizedBox(width: 4),
                              const Icon(Icons.chevron_right_rounded, color: _leaveGreen, size: 18),
                            ],
                          ),
                        ),
                      );
                    })
                  else
                    Scrollbar(
                      controller: _historyScroll,
                      thumbVisibility: true,
                      trackVisibility: true,
                      scrollbarOrientation: ScrollbarOrientation.bottom,
                      child: SingleChildScrollView(
                        controller: _historyScroll,
                        scrollDirection: Axis.horizontal,
                        padding: const EdgeInsets.only(bottom: 13),
                        child: SizedBox(
                          width: 1330,
                          child: Column(
                            children: [
                              const _MyLeaveHistoryHeader(),
                              ...List.generate(history.length, (i) => _MyLeaveHistoryRow(
                                    row: history[i],
                                    shaded: i.isOdd,
                                    onTap: () => widget.onOpenLeave(history[i]),
                                  )),
                            ],
                          ),
                        ),
                      ),
                    ),
                ],
              ),
            ),
            if (adjustments.isNotEmpty) ...[
              const SizedBox(height: 9),
              Container(
                decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(8), border: Border.all(color: _sheetGreen, width: .8)),
                clipBehavior: Clip.antiAlias,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 9),
                      color: _sheetBand,
                      child: const Text('HR BALANCE CHANGES', style: TextStyle(color: _sheetDarkGreen, fontSize: 10.8, fontWeight: FontWeight.w900)),
                    ),
                    ...List.generate(adjustments.length, (i) {
                      final item = adjustments[i];
                      final amount = _n(item['amount']);
                      return Container(
                        padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 8),
                        color: i.isOdd ? _sheetBandSoft : Colors.white,
                        child: Row(
                          children: [
                            SizedBox(width: 78, child: Text('${amount >= 0 ? '+' : ''}${amount.toStringAsFixed(2)}', style: TextStyle(color: amount >= 0 ? _leaveGreen : Colors.red.shade700, fontWeight: FontWeight.w900, fontSize: 10.5))),
                            Expanded(child: Text(_t(item['reason']), style: const TextStyle(color: _leaveInk, fontSize: 9.6))),
                            const SizedBox(width: 8),
                            Text(_date(item['created_at']), style: const TextStyle(color: _leaveMuted, fontSize: 8.6)),
                          ],
                        ),
                      );
                    }),
                  ],
                ),
              ),
            ],
          ],
        );
      },
    );
  }
}

class _MiniLedgerFact extends StatelessWidget {
  final String label;
  final String value;
  const _MiniLedgerFact({required this.label, required this.value});

  @override
  Widget build(BuildContext context) => Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text('$label: ', style: const TextStyle(color: _leaveMuted, fontSize: 8.4, fontWeight: FontWeight.w900)),
          Text(value, style: const TextStyle(color: _leaveInk, fontSize: 9.5, fontWeight: FontWeight.w900)),
        ],
      );
}

class _MyLeaveHistoryHeader extends StatelessWidget {
  const _MyLeaveHistoryHeader();
  @override
  Widget build(BuildContext context) => const SizedBox(
        height: 38,
        child: Row(
          children: [
            _MyLeaveHistoryCell(width: 62, text: 'REF', header: true),
            _MyLeaveHistoryCell(width: 70, text: 'YEAR', header: true, center: true),
            _MyLeaveHistoryCell(width: 118, text: 'DECISION DATE', header: true),
            _MyLeaveHistoryCell(width: 120, text: 'LEAVE TYPE', header: true),
            _MyLeaveHistoryCell(width: 118, text: 'START DATE', header: true),
            _MyLeaveHistoryCell(width: 118, text: 'END DATE', header: true),
            _MyLeaveHistoryCell(width: 78, text: 'DAYS', header: true, center: true),
            _MyLeaveHistoryCell(width: 118, text: 'RETURN DATE', header: true),
            _MyLeaveHistoryCell(width: 105, text: 'STATUS', header: true, center: true),
            _MyLeaveHistoryCell(width: 105, text: 'CLOSING BAL.', header: true, center: true),
            _MyLeaveHistoryCell(width: 318, text: 'OPEN RECORD', header: true),
          ],
        ),
      );
}

class _MyLeaveHistoryRow extends StatelessWidget {
  final Map<String, dynamic> row;
  final bool shaded;
  final VoidCallback onTap;
  const _MyLeaveHistoryRow({required this.row, required this.shaded, required this.onTap});

  String _t(dynamic value, [String fallback = '—']) {
    final text = value?.toString().trim() ?? '';
    return text.isEmpty || text.toLowerCase() == 'null' ? fallback : text;
  }

  double _n(dynamic value) => double.tryParse('${value ?? 0}') ?? 0;

  String _date(dynamic value, [String fallback = '—']) {
    final raw = _t(value, '');
    if (raw.isEmpty) return fallback;
    try {
      return DateFormat('dd MMM yyyy').format(DateTime.parse(raw).toLocal());
    } catch (_) {
      return raw;
    }
  }

  @override
  Widget build(BuildContext context) {
    final status = _t(row['status'], 'pending').toUpperCase();
    final closing = row['closing_balance'] == null ? '—' : _n(row['closing_balance']).toStringAsFixed(2);
    return InkWell(
      onTap: onTap,
      child: Container(
        height: 38,
        color: shaded ? _sheetBandSoft : Colors.white,
        child: Row(
          children: [
            _MyLeaveHistoryCell(width: 62, text: '#${row['id'] ?? ''}'),
            _MyLeaveHistoryCell(width: 70, text: _t(row['leave_year'], _date(row['start_date']).split(' ').last), center: true),
            _MyLeaveHistoryCell(width: 118, text: _date(row['final_decision_at'], 'Pending')),
            _MyLeaveHistoryCell(width: 120, text: _t(row['leave_type']).toUpperCase()),
            _MyLeaveHistoryCell(width: 118, text: _date(row['start_date'])),
            _MyLeaveHistoryCell(width: 118, text: _date(row['end_date'])),
            _MyLeaveHistoryCell(width: 78, text: _n(row['requested_days']).toStringAsFixed(2), center: true, strong: true),
            _MyLeaveHistoryCell(width: 118, text: _date(row['expected_return_date'])),
            _MyLeaveHistoryCell(width: 105, text: status, center: true, strong: status == 'APPROVED'),
            _MyLeaveHistoryCell(width: 105, text: closing, center: true),
            SizedBox(
              width: 318,
              height: double.infinity,
              child: Container(
                alignment: Alignment.centerLeft,
                padding: const EdgeInsets.symmetric(horizontal: 9),
                decoration: const BoxDecoration(border: Border(right: BorderSide(color: _sheetGreen, width: .55), bottom: BorderSide(color: _sheetGreen, width: .55))),
                child: Row(
                  children: [
                    const Icon(Icons.open_in_new_rounded, color: _sheetDarkGreen, size: 14),
                    const SizedBox(width: 6),
                    Text('Open full ${_t(row['leave_type'], 'leave')} application', style: const TextStyle(color: _sheetDarkGreen, fontSize: 9.2, fontWeight: FontWeight.w800)),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _MyLeaveHistoryCell extends StatelessWidget {
  final double width;
  final String text;
  final bool header;
  final bool center;
  final bool strong;

  const _MyLeaveHistoryCell({
    required this.width,
    required this.text,
    this.header = false,
    this.center = false,
    this.strong = false,
  });

  @override
  Widget build(BuildContext context) => Container(
        width: width,
        height: double.infinity,
        alignment: center ? Alignment.center : Alignment.centerLeft,
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
        decoration: BoxDecoration(
          color: header ? _sheetBand : Colors.transparent,
          border: const Border(
            right: BorderSide(color: _sheetGreen, width: .55),
            bottom: BorderSide(color: _sheetGreen, width: .55),
          ),
        ),
        child: Text(
          text,
          maxLines: 2,
          overflow: TextOverflow.ellipsis,
          textAlign: center ? TextAlign.center : TextAlign.left,
          style: TextStyle(
            color: header ? _sheetDarkGreen : _leaveInk,
            fontSize: header ? 8.2 : 9.2,
            fontWeight: header || strong ? FontWeight.w900 : FontWeight.w600,
            height: 1.15,
          ),
        ),
      );
}


class _CampusLeaveSections extends StatefulWidget {
  final List<Map<String, dynamic>> rows;
  final String section;
  final ValueChanged<Map<String, dynamic>> onOpen;
  const _CampusLeaveSections({required this.rows, required this.section, required this.onOpen});

  @override
  State<_CampusLeaveSections> createState() => _CampusLeaveSectionsState();
}

class _CampusLeaveSectionsState extends State<_CampusLeaveSections> {
  final Map<String, TextEditingController> _searches = {};

  TextEditingController _search(String campus) => _searches.putIfAbsent(
    '${widget.section}:$campus', () => TextEditingController());

  String _normalise(dynamic value) => '${value ?? ''}'.trim().replaceAll(RegExp(r'\s+'), ' ').toLowerCase();

  @override
  void dispose() {
    for (final controller in _searches.values) {
      controller.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final groups = <String, List<Map<String, dynamic>>>{};
    for (final row in widget.rows) {
      var campus = _normalise(row['campus']).replaceFirst(RegExp(r'\s+campus$'), '').trim();
      if (campus.isEmpty || campus == 'null') campus = 'campus not specified';
      groups.putIfAbsent(campus, () => []).add(row);
    }
    final campuses = groups.keys.toList()..sort();
    final cards = _LeaveGrid(rows: widget.rows, onOpen: widget.onOpen);
    return LayoutBuilder(builder: (context, constraints) {
      final columns = constraints.maxWidth >= 1450 ? 4 : constraints.maxWidth >= 980 ? 3 : constraints.maxWidth >= 620 ? 2 : 1;
      return CustomScrollView(
        key: PageStorageKey<String>('campus-leave-${widget.section}'),
        slivers: [
          SliverToBoxAdapter(child: Padding(
            padding: const EdgeInsets.fromLTRB(16, 20, 16, 8),
            child: Text('${widget.section} • ${widget.rows.length} requests',
              style: const TextStyle(color: _leaveInk, fontSize: 17, fontWeight: FontWeight.w800)),
          )),
          if (campuses.isEmpty)
            const SliverToBoxAdapter(child: Padding(
              padding: EdgeInsets.all(24),
              child: Text('No leave applications here yet.', style: TextStyle(color: _leaveMuted)),
            )),
          for (final campus in campuses) ..._campusSlivers(campus, groups[campus]!, columns, cards),
          const SliverToBoxAdapter(child: SizedBox(height: 96)),
        ],
      );
    });
  }

  List<Widget> _campusSlivers(String campus, List<Map<String, dynamic>> rows, int columns, _LeaveGrid cards) {
    final controller = _search(campus);
    final query = _normalise(controller.text);
    final visible = rows.where((row) => _normalise(row['applicant_name']).contains(query)).toList();
    final label = campus == 'campus not specified' ? 'CAMPUS NOT SPECIFIED' : '${campus.toUpperCase()} CAMPUS';
    return [
      SliverToBoxAdapter(child: Container(
        margin: const EdgeInsets.fromLTRB(16, 20, 16, 12),
        padding: const EdgeInsets.only(top: 16),
        decoration: const BoxDecoration(border: Border(top: BorderSide(color: _leaveGreen, width: 2))),
        child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
          Row(children: [
            const Icon(Icons.location_city_outlined, color: _leaveGreen, size: 22),
            const SizedBox(width: 10),
            Expanded(child: Text(label, style: const TextStyle(color: _leaveGreen, fontSize: 13, fontWeight: FontWeight.w900, letterSpacing: .5))),
            const SizedBox(width: 8),
            Text('${visible.length} / ${rows.length}', style: const TextStyle(color: _leaveMuted, fontSize: 12)),
          ]),
          const SizedBox(height: 12),
          TextField(
            controller: controller,
            onChanged: (_) => setState(() {}),
            decoration: _input('Search employee name', Icons.search_rounded).copyWith(
              hintText: 'Name within this campus',
              suffixIcon: query.isEmpty ? null : IconButton(
                tooltip: 'Clear name search',
                onPressed: () { controller.clear(); setState(() {}); },
                icon: const Icon(Icons.close_rounded),
              ),
            ),
          ),
        ]),
      )),
      if (visible.isEmpty)
        const SliverToBoxAdapter(child: Padding(
          padding: EdgeInsets.fromLTRB(16, 8, 16, 20),
          child: Text('No employee names match this search.', style: TextStyle(color: _leaveMuted)),
        ))
      else
        SliverPadding(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          sliver: SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: columns, crossAxisSpacing: 12, mainAxisSpacing: 12, mainAxisExtent: 158),
            delegate: SliverChildBuilderDelegate((context, index) => cards.buildCard(visible[index]), childCount: visible.length),
          ),
        ),
    ];
  }
}

// One scrollable page: the full-width form followed by its routing history.
class _LeaveFormLayout extends StatelessWidget {
  final Widget form;
  final Widget routing;
  const _LeaveFormLayout({required this.form, required this.routing});

  @override
  Widget build(BuildContext context) => SingleChildScrollView(
    child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
      form,
      const Divider(height: 1, color: _leaveBorder),
      routing,
    ]),
  );
}

class _LeaveGrid extends StatelessWidget {
  final List<Map<String, dynamic>> rows;
  final ValueChanged<Map<String, dynamic>> onOpen;

  const _LeaveGrid({required this.rows, required this.onOpen});

  String _text(dynamic value, [String fallback = '']) {
    final text = value?.toString().trim() ?? '';
    return text.isEmpty || text.toLowerCase() == 'null' ? fallback : text;
  }

  Widget buildCard(Map<String, dynamic> row) {
            final status = _text(row['status'], 'pending').toUpperCase();
            final type = _text(row['leave_type'], 'leave').toUpperCase();
            final stage = _text(row['current_recipient_label'], _text(row['current_stage'], ''));
            final applicant = _text(row['applicant_name'], 'Staff');
            final campus = _text(row['campus']);
            final department = _text(row['department']);
            final action = _truthyValue(row['action_required']);
            final statusColor = status == 'APPROVED'
                ? _leaveGreen
                : status == 'REJECTED'
                    ? Colors.red.shade700
                    : _leaveGold;

            return Material(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
              child: InkWell(
                borderRadius: BorderRadius.circular(12),
                onTap: () => onOpen(row),
                child: Container(
                  padding: const EdgeInsets.fromLTRB(11, 10, 10, 9),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(color: action ? _leaveGold.withOpacity(.55) : _leaveBorder),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(.018),
                        blurRadius: 7,
                        offset: const Offset(0, 3),
                      ),
                    ],
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Container(
                            width: 30,
                            height: 30,
                            decoration: BoxDecoration(
                              color: _leaveGreen.withOpacity(.075),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: const Icon(Icons.beach_access_outlined, color: _leaveGreen, size: 16),
                          ),
                          const SizedBox(width: 8),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(type, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _leaveInk, fontWeight: FontWeight.w900, fontSize: 10.7)),
                                const SizedBox(height: 1),
                                Text('#${row['id']} • $status', style: TextStyle(color: statusColor, fontSize: 8.4, fontWeight: FontWeight.w800)),
                              ],
                            ),
                          ),
                          if (action)
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
                              decoration: BoxDecoration(color: _leaveGold.withOpacity(.1), borderRadius: BorderRadius.circular(99)),
                              child: const Text('ACTION', style: TextStyle(color: _leaveGold, fontSize: 7.1, fontWeight: FontWeight.w900)),
                            ),
                        ],
                      ),
                      const SizedBox(height: 8),
                      Text(applicant, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _leaveInk, fontSize: 11.2, fontWeight: FontWeight.w900)),
                      const SizedBox(height: 2),
                      Text('$department • $campus', maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _leaveMuted, fontSize: 8.8)),
                      const Spacer(),
                      Row(
                        children: [
                          const Icon(Icons.date_range_outlined, size: 12, color: _leaveMuted),
                          const SizedBox(width: 4),
                          Expanded(
                            child: Text(
                              '${row['start_date']} → ${row['end_date']}',
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: const TextStyle(color: _leaveInk, fontSize: 8.7, fontWeight: FontWeight.w700),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 5),
                      Row(
                        children: [
                          const Icon(Icons.route_outlined, size: 12, color: _leaveMuted),
                          const SizedBox(width: 4),
                          Expanded(
                            child: Text(
                              stage.isEmpty ? 'Finalised' : stage,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: const TextStyle(color: _leaveInk, fontSize: 8.7, fontWeight: FontWeight.w800),
                            ),
                          ),
                          const Icon(Icons.chevron_right_rounded, color: _leaveGreen, size: 16),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            );
  }

  @override
  Widget build(BuildContext context) {
    if (rows.isEmpty) {
      return const Center(
        child: Padding(
          padding: EdgeInsets.all(22),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.event_available_outlined, size: 44, color: Color(0xFF9AA79F)),
              SizedBox(height: 8),
              Text('No leave applications here yet.', style: TextStyle(color: _leaveMuted, fontSize: 11)),
            ],
          ),
        ),
      );
    }

    return LayoutBuilder(
      builder: (_, c) {
        final cols = c.maxWidth >= 1450
            ? 4
            : c.maxWidth >= 980
                ? 3
                : c.maxWidth >= 620
                    ? 2
                    : 1;
        return GridView.builder(
          padding: const EdgeInsets.fromLTRB(12, 12, 12, 88),
          itemCount: rows.length,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: cols,
            crossAxisSpacing: 9,
            mainAxisSpacing: 9,
            mainAxisExtent: 158,
          ),
          itemBuilder: (_, i) {
            return buildCard(rows[i]);
          },
        );
      },
    );
  }
}

class _HrLeaveControlCentre extends StatefulWidget {
  final Map<String, dynamic> access;
  final ValueChanged<int> onOpenLeaveId;

  const _HrLeaveControlCentre({
    required this.access,
    required this.onOpenLeaveId,
  });

  @override
  State<_HrLeaveControlCentre> createState() => _HrLeaveControlCentreState();
}

class _HrLeaveControlCentreState extends State<_HrLeaveControlCentre> {
  final _search = TextEditingController();
  final _horizontal = ScrollController();
  bool _loading = true;
  bool _accruing = false;
  bool _offline = false;
  String _cachedAt = '';
  String? _error;
  String _campusFilter = 'ALL';
  String _departmentFilter = 'ALL';
  String _statusFilter = 'ALL';
  List<Map<String, dynamic>> _employees = const [];
  Map<String, dynamic> _summary = const {};
  List<String> _campuses = const [];
  List<String> _departments = const [];

  @override
  void initState() {
    super.initState();
    _search.addListener(_refreshFilter);
    _load();
  }

  @override
  void dispose() {
    _search.removeListener(_refreshFilter);
    _search.dispose();
    _horizontal.dispose();
    super.dispose();
  }

  void _refreshFilter() {
    if (mounted) setState(() {});
  }

  String _t(dynamic value, [String fallback = '']) {
    final text = value?.toString().trim() ?? '';
    return text.isEmpty || text.toLowerCase() == 'null' ? fallback : text;
  }

  double _n(dynamic value) => double.tryParse('${value ?? 0}') ?? 0;
  int _i(dynamic value) => int.tryParse('${value ?? 0}') ?? 0;
  String _days(dynamic value) => _n(value).toStringAsFixed(2);
  bool get _canSuspend => _truthyValue(widget.access['can_suspend']);

  Future<void> _load({bool silent = false}) async {
    if (!mounted) return;
    if (!silent) {
      setState(() {
        _loading = true;
        _error = null;
      });
    }
    try {
      final data = await LeaveService.hrLedger();
      final rawRows = data['data'];
      final rows = rawRows is List
          ? rawRows.whereType<Map>().map((e) => e.map((k, v) => MapEntry(k.toString(), v))).toList()
          : <Map<String, dynamic>>[];
      final rawSummary = data['summary'];
      final summary = rawSummary is Map ? rawSummary.map((k, v) => MapEntry(k.toString(), v)) : <String, dynamic>{};
      final rawCampuses = data['campuses'];
      final campuses = rawCampuses is List
          ? rawCampuses.map((e) => e.toString().trim()).where((e) => e.isNotEmpty).toSet().toList()
          : <String>[];
      campuses.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
      final departments = rows
          .map((e) => _t(e['department']))
          .where((e) => e.isNotEmpty)
          .toSet()
          .toList()
        ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
      if (!mounted) return;
      setState(() {
        _employees = rows;
        _summary = summary;
        _campuses = campuses;
        _departments = departments;
        _offline = data['_offline_cache'] == true;
        _cachedAt = _t(data['_cache_updated_at']);
        if (_campusFilter != 'ALL' && !_campuses.contains(_campusFilter)) _campusFilter = 'ALL';
        if (_departmentFilter != 'ALL' && !_departments.contains(_departmentFilter)) _departmentFilter = 'ALL';
        _loading = false;
        _error = null;
      });
    } catch (e) {
      if (!mounted) return;
      if (!silent) {
        setState(() {
          _loading = false;
          _error = LeaveService.cleanError(e);
        });
      }
    }
  }

  List<Map<String, dynamic>> get _visibleEmployees {
    final query = _search.text.trim().toLowerCase();
    return _employees.where((row) {
      final campus = _t(row['campus']);
      final department = _t(row['department']);
      final status = _t(row['account_status'], 'active').toUpperCase();
      if (_campusFilter != 'ALL' && campus != _campusFilter) return false;
      if (_departmentFilter != 'ALL' && department != _departmentFilter) return false;
      if (_statusFilter != 'ALL' && status != _statusFilter) return false;
      if (query.isEmpty) return true;
      final haystack = [
        row['full_name'], row['email'], row['nrc'], row['phone'], row['campus'],
        row['department'], row['school'], row['role'], row['account_status'],
      ].map((e) => _t(e).toLowerCase()).join(' ');
      return haystack.contains(query);
    }).toList();
  }

  Future<void> _runAccrual() async {
    if (_accruing || _offline) return;
    setState(() => _accruing = true);
    try {
      final result = await LeaveService.runAccrual();
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(_t(result['message'], 'Monthly leave accrual synchronized.')),
        backgroundColor: _leaveGreen,
        behavior: SnackBarBehavior.floating,
      ));
      await _load();
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(LeaveService.cleanError(e)),
        backgroundColor: Colors.red.shade700,
        behavior: SnackBarBehavior.floating,
      ));
    } finally {
      if (mounted) setState(() => _accruing = false);
    }
  }

  Future<void> _adjust(Map<String, dynamic> employee, String direction) async {
    if (_offline) {
      _offlineWriteWarning();
      return;
    }
    final result = await showDialog<Map<String, dynamic>>(
      context: context,
      barrierDismissible: false,
      builder: (_) => _HrAdjustmentDialog(employee: employee, direction: direction),
    );
    if (result == null || !mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text(_t(result['message'], 'Leave balance updated successfully.')),
      backgroundColor: _leaveGreen,
      behavior: SnackBarBehavior.floating,
    ));
    await _load();
  }

  void _offlineWriteWarning() {
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Text('You are viewing cached leave data. Reconnect before changing balances or account status.'),
      backgroundColor: _leaveGold,
      behavior: SnackBarBehavior.floating,
    ));
  }

  Future<void> _history(Map<String, dynamic> employee) async {
    final userId = _i(employee['user_id']);
    if (userId <= 0) return;
    await showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (_) => _HrEmployeeHistoryDialog(userId: userId, onOpenLeaveId: widget.onOpenLeaveId),
    );
  }

  Future<void> _changeAccountStatus(Map<String, dynamic> employee) async {
    if (!_canSuspend) return;
    if (_offline) {
      _offlineWriteWarning();
      return;
    }
    final status = _t(employee['account_status'], 'active').toLowerCase();
    final operation = status == 'suspended' ? 'restore' : 'suspend';
    final result = await showDialog<Map<String, dynamic>>(
      context: context,
      barrierDismissible: false,
      builder: (_) => _AccountStatusDialog(employee: employee, operation: operation),
    );
    if (result == null || !mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text(_t(result['message'], 'Account status updated.')),
      backgroundColor: operation == 'suspend' ? Colors.red.shade700 : _leaveGreen,
      behavior: SnackBarBehavior.floating,
    ));
    await _load();
  }

  @override
  Widget build(BuildContext context) {
    if (_loading) return const Center(child: CircularProgressIndicator(color: _leaveGreen));
    if (_error != null) return _ErrorPanel(message: _error!, onRetry: _load);

    final accessLabel = _t(widget.access['label'], 'Human Resources');
    final accessScope = _t(widget.access['scope']) == 'all_campuses'
        ? 'All campuses'
        : _t(widget.access['campus'], 'Assigned campus');
    final rows = _visibleEmployees;

    return LayoutBuilder(builder: (_, c) {
      final compact = c.maxWidth < 760;
      return RefreshIndicator(
        color: _leaveGreen,
        onRefresh: _load,
        child: ListView(
          padding: EdgeInsets.fromLTRB(compact ? 10 : 16, 10, compact ? 10 : 16, 100),
          children: [
            // Small, clean control header instead of a large banner.
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 10),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
                border: Border.all(color: _leaveBorder),
              ),
              child: Wrap(
                alignment: WrapAlignment.spaceBetween,
                crossAxisAlignment: WrapCrossAlignment.center,
                spacing: 10,
                runSpacing: 8,
                children: [
                  Row(mainAxisSize: MainAxisSize.min, children: [
                    Container(width: 32, height: 32, decoration: BoxDecoration(color: _leaveGreen.withOpacity(.08), borderRadius: BorderRadius.circular(8)), child: const Icon(Icons.table_view_rounded, color: _leaveGreen, size: 18)),
                    const SizedBox(width: 9),
                    Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                      const Text('LEAVE CONTROL LEDGER', style: TextStyle(color: _leaveInk, fontSize: 12.2, fontWeight: FontWeight.w900, letterSpacing: .35)),
                      Text('$accessLabel • $accessScope', style: const TextStyle(color: _leaveMuted, fontSize: 8.9, fontWeight: FontWeight.w700)),
                    ]),
                  ]),
                  Wrap(spacing: 6, runSpacing: 6, children: [
                    if (_offline) Container(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
                      decoration: BoxDecoration(color: _leaveGold.withOpacity(.08), borderRadius: BorderRadius.circular(99), border: Border.all(color: _leaveGold.withOpacity(.25))),
                      child: Text('OFFLINE CACHE${_cachedAt.isEmpty ? '' : ' • $_cachedAt'}', style: const TextStyle(color: _leaveGold, fontSize: 7.5, fontWeight: FontWeight.w900)),
                    ),
                    OutlinedButton.icon(onPressed: () => _load(), icon: const Icon(Icons.refresh_rounded, size: 15), label: const Text('REFRESH'), style: OutlinedButton.styleFrom(foregroundColor: _leaveGreen, visualDensity: VisualDensity.compact)),
                    ElevatedButton.icon(onPressed: (_accruing || _offline) ? null : _runAccrual, icon: _accruing ? const SizedBox(width: 13,height:13,child:CircularProgressIndicator(strokeWidth:2,color:Colors.white)) : const Icon(Icons.autorenew_rounded, size: 15), label: Text(_accruing ? 'SYNCING' : 'SYNC 2 DAYS / MONTH'), style: ElevatedButton.styleFrom(backgroundColor:_leaveGreen,foregroundColor:Colors.white,elevation:0,visualDensity:VisualDensity.compact)),
                  ]),
                ],
              ),
            ),
            const SizedBox(height: 9),
            LayoutBuilder(builder: (_, metrics) {
              final cardWidth = metrics.maxWidth < 620 ? metrics.maxWidth : metrics.maxWidth < 1050 ? (metrics.maxWidth - 8) / 2 : (metrics.maxWidth - 32) / 5;
              final cards = [
                _HrMetricCard(icon: Icons.people_alt_outlined,label:'EMPLOYEES',value:'${_i(_summary['employees'])}',note:'Visible records'),
                _HrMetricCard(icon: Icons.event_available_outlined,label:'AVAILABLE DAYS',value:_days(_summary['total_available_days']),note:'Combined balance'),
                _HrMetricCard(icon: Icons.pending_actions_outlined,label:'PENDING LEAVE',value:'${_i(_summary['pending_leave_requests'])}',note:'Current requests'),
                _HrMetricCard(icon: Icons.warning_amber_rounded,label:'LOW BALANCE',value:'${_i(_summary['low_balance_employees'])}',note:'Below 4 days'),
                _HrMetricCard(icon: Icons.calendar_month_outlined,label:'MONTHLY RATE',value:'${_days(_summary['monthly_accrual_days'])}',note:'Days per month'),
              ];
              return Wrap(spacing:8,runSpacing:8,children:cards.map((e)=>SizedBox(width:cardWidth,child:e)).toList());
            }),
            const SizedBox(height: 9),
            Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(color: Colors.white,borderRadius:BorderRadius.circular(10),border:Border.all(color:_leaveBorder)),
              child: LayoutBuilder(builder: (_, filters) {
                final allCampuses = _t(widget.access['scope']) == 'all_campuses';
                final search = TextField(
                  controller:_search,
                  decoration:_input('Search employee, NRC, department, email or status',Icons.search_rounded),
                );
                final campus = DropdownButtonFormField<String>(
                  value:_campusFilter,
                  isExpanded:true,
                  decoration:_input('Campus',Icons.domain_outlined),
                  items:[const DropdownMenuItem(value:'ALL',child:Text('ALL CAMPUSES')),..._campuses.map((e)=>DropdownMenuItem(value:e,child:Text(e,overflow:TextOverflow.ellipsis)))],
                  onChanged:(v)=>setState(()=>_campusFilter=v??'ALL'),
                );
                final department = DropdownButtonFormField<String>(
                  value:_departmentFilter,
                  isExpanded:true,
                  decoration:_input('Department',Icons.account_tree_outlined),
                  items:[const DropdownMenuItem(value:'ALL',child:Text('ALL DEPARTMENTS')),..._departments.map((e)=>DropdownMenuItem(value:e,child:Text(e,overflow:TextOverflow.ellipsis)))],
                  onChanged:(v)=>setState(()=>_departmentFilter=v??'ALL'),
                );
                final status = DropdownButtonFormField<String>(
                  value:_statusFilter,
                  isExpanded:true,
                  decoration:_input('Account',Icons.verified_user_outlined),
                  items:const [
                    DropdownMenuItem(value:'ALL',child:Text('ALL ACCOUNTS')),
                    DropdownMenuItem(value:'ACTIVE',child:Text('ACTIVE')),
                    DropdownMenuItem(value:'SUSPENDED',child:Text('SUSPENDED')),
                  ],
                  onChanged:(v)=>setState(()=>_statusFilter=v??'ALL'),
                );

                if (filters.maxWidth < 760) {
                  return Column(children:[
                    search,
                    const SizedBox(height:8),
                    if (allCampuses) ...[campus,const SizedBox(height:8)]
                    else Container(
                      width:double.infinity,
                      padding:const EdgeInsets.symmetric(horizontal:12,vertical:10),
                      decoration:BoxDecoration(color:_leaveGreen.withOpacity(.05),borderRadius:BorderRadius.circular(10),border:Border.all(color:_leaveGreen.withOpacity(.16))),
                      child:Text('Campus: ${_t(widget.access['campus'], 'Assigned campus')}',style:const TextStyle(color:_leaveGreen,fontSize:9.5,fontWeight:FontWeight.w900)),
                    ),
                    if (!allCampuses) const SizedBox(height:8),
                    department,
                    const SizedBox(height:8),
                    status,
                  ]);
                }
                final campusOrScope = allCampuses
                    ? campus
                    : Container(
                        alignment:Alignment.centerLeft,
                        padding:const EdgeInsets.symmetric(horizontal:12),
                        decoration:BoxDecoration(color:_leaveGreen.withOpacity(.05),borderRadius:BorderRadius.circular(10),border:Border.all(color:_leaveGreen.withOpacity(.16))),
                        child:Text('CAMPUS: ${_t(widget.access['campus'], 'Assigned campus')}',maxLines:1,overflow:TextOverflow.ellipsis,style:const TextStyle(color:_leaveGreen,fontSize:9,fontWeight:FontWeight.w900)),
                      );
                return Row(children:[
                  Expanded(flex:3,child:search),
                  const SizedBox(width:8),
                  Expanded(flex:2,child:campusOrScope),
                  const SizedBox(width:8),
                  Expanded(flex:2,child:department),
                  const SizedBox(width:8),
                  Expanded(flex:2,child:status),
                ]);
              }),
            ),
            const SizedBox(height: 9),
            if (rows.isEmpty)
              Container(padding:const EdgeInsets.all(28),decoration:BoxDecoration(color:Colors.white,borderRadius:BorderRadius.circular(10),border:Border.all(color:_leaveBorder)),child:const Center(child:Text('No employees match the current filter.',style:TextStyle(color:_leaveMuted))))
            else if (c.maxWidth < 900)
              ...List.generate(rows.length,(i)=>Padding(padding:const EdgeInsets.only(bottom:7),child:_HrEmployeeCard(
                employee:rows[i],
                shaded:i.isOdd,
                canSuspend:_canSuspend,
                onAdd:()=>_adjust(rows[i],'add'),
                onReduce:()=>_adjust(rows[i],'reduce'),
                onHistory:()=>_history(rows[i]),
                onAccountStatus:()=>_changeAccountStatus(rows[i]),
              )))
            else
              _desktopLedger(rows),
          ],
        ),
      );
    });
  }

  Widget _desktopLedger(List<Map<String, dynamic>> rows) {
    const width = 1680.0;
    return Container(
      decoration: BoxDecoration(color: Colors.white,borderRadius:BorderRadius.circular(8),border:Border.all(color:_sheetGreen,width:.8)),
      clipBehavior: Clip.antiAlias,
      child: Scrollbar(
        controller: _horizontal,
        thumbVisibility: true,
        trackVisibility: true,
        scrollbarOrientation: ScrollbarOrientation.bottom,
        child: SingleChildScrollView(
          controller:_horizontal,
          scrollDirection:Axis.horizontal,
          padding:const EdgeInsets.only(bottom:13),
          child:SizedBox(
            width:width,
            child:Column(children:[
              const _HrLedgerHeader(),
              ...List.generate(rows.length,(index)=>_HrLedgerRow(
                employee:rows[index],
                shaded:index.isOdd,
                canSuspend:_canSuspend,
                onAdd:()=>_adjust(rows[index],'add'),
                onReduce:()=>_adjust(rows[index],'reduce'),
                onHistory:()=>_history(rows[index]),
                onAccountStatus:()=>_changeAccountStatus(rows[index]),
              )),
            ]),
          ),
        ),
      ),
    );
  }
}

class _HrMetricCard extends StatelessWidget {
  final IconData icon;
  final String label;
  final String value;
  final String note;

  const _HrMetricCard({required this.icon, required this.label, required this.value, required this.note});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(15),
        border: Border.all(color: _leaveBorder),
      ),
      child: Row(
        children: [
          Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(color: _leaveGreen.withOpacity(.08), borderRadius: BorderRadius.circular(12)),
            child: Icon(icon, color: _leaveGreen, size: 20),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(label, style: const TextStyle(color: _leaveMuted, fontSize: 8.3, fontWeight: FontWeight.w900, letterSpacing: .5)),
                const SizedBox(height: 3),
                Text(value, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _leaveInk, fontSize: 16, fontWeight: FontWeight.w900)),
                const SizedBox(height: 2),
                Text(note, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _leaveMuted, fontSize: 8.7)),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class _HrEmployeeCard extends StatelessWidget {
  final Map<String, dynamic> employee;
  final bool shaded;
  final bool canSuspend;
  final VoidCallback onAdd;
  final VoidCallback onReduce;
  final VoidCallback onHistory;
  final VoidCallback onAccountStatus;

  const _HrEmployeeCard({
    required this.employee,
    required this.shaded,
    required this.canSuspend,
    required this.onAdd,
    required this.onReduce,
    required this.onHistory,
    required this.onAccountStatus,
  });

  String _t(dynamic v, [String f = '—']) {
    final s = v?.toString().trim() ?? '';
    return s.isEmpty || s.toLowerCase() == 'null' ? f : s;
  }
  double _n(dynamic v) => double.tryParse('${v ?? 0}') ?? 0;
  Map<String, dynamic> get balance {
    final raw = employee['balance'];
    return raw is Map ? raw.map((k,v)=>MapEntry(k.toString(),v)) : const {};
  }

  @override
  Widget build(BuildContext context) {
    final available = _n(balance['available_days']);
    final status = _t(employee['account_status'],'active').toLowerCase();
    final suspended = status == 'suspended';
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: shaded ? _sheetBandSoft : Colors.white,
        border: Border.all(color: _sheetGreen.withOpacity(.75), width: .8),
      ),
      child: Column(crossAxisAlignment:CrossAxisAlignment.start,children:[
        Row(children:[
          Expanded(child:Column(crossAxisAlignment:CrossAxisAlignment.start,children:[
            Text(_t(employee['full_name']),style:const TextStyle(color:_leaveInk,fontWeight:FontWeight.w900,fontSize:12.5)),
            const SizedBox(height:2),
            Text('${_t(employee['department'])} • ${_t(employee['campus'])}',style:const TextStyle(color:_leaveMuted,fontSize:9.5)),
          ])),
          Container(padding:const EdgeInsets.symmetric(horizontal:8,vertical:4),decoration:BoxDecoration(color:suspended?Colors.red.withOpacity(.08):_leaveGreen.withOpacity(.08),borderRadius:BorderRadius.circular(99)),child:Text(suspended?'SUSPENDED':'ACTIVE',style:TextStyle(color:suspended?Colors.red.shade700:_leaveGreen,fontSize:7.8,fontWeight:FontWeight.w900))),
        ]),
        const SizedBox(height:9),
        Wrap(spacing:6,runSpacing:6,children:[
          _MiniStat(label:'ACCRUED',value:_n(balance['entitlement_days']).toStringAsFixed(2)),
          _MiniStat(label:'USED',value:_n(balance['used_days']).toStringAsFixed(2)),
          _MiniStat(label:'AVAILABLE',value:available.toStringAsFixed(2)),
          _MiniStat(label:'ADJUST.',value:_n(balance['adjustment_days']).toStringAsFixed(2)),
        ]),
        const SizedBox(height:9),
        Wrap(spacing:6,runSpacing:6,children:[
          _HrSmallAction(label:'ADD DAYS',icon:Icons.add_rounded,color:_leaveGreen,onTap:onAdd),
          _HrSmallAction(label:'REDUCE',icon:Icons.remove_rounded,color:Colors.red.shade700,onTap:onReduce),
          _HrSmallAction(label:'HISTORY',icon:Icons.history_rounded,color:_leaveGold,onTap:onHistory),
          if(canSuspend)_HrSmallAction(label:suspended?'RESTORE':'SUSPEND',icon:suspended?Icons.lock_open_rounded:Icons.block_rounded,color:suspended?_leaveGreen:Colors.red.shade800,onTap:onAccountStatus),
        ]),
      ]),
    );
  }
}

class _MiniStat extends StatelessWidget {
  final String label;
  final String value;
  const _MiniStat({required this.label, required this.value});
  @override
  Widget build(BuildContext context) => Container(
        padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 7),
        decoration: BoxDecoration(color: _leaveSurface, borderRadius: BorderRadius.circular(9), border: Border.all(color: _leaveBorder)),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(label, style: const TextStyle(color: _leaveMuted, fontSize: 7.8, fontWeight: FontWeight.w900)),
            const SizedBox(width: 6),
            Text(value, style: const TextStyle(color: _leaveInk, fontSize: 9.5, fontWeight: FontWeight.w900)),
          ],
        ),
      );
}

class _HrSmallAction extends StatelessWidget {
  final String label;
  final IconData icon;
  final Color color;
  final VoidCallback onTap;
  const _HrSmallAction({required this.label, required this.icon, required this.color, required this.onTap});
  @override
  Widget build(BuildContext context) => OutlinedButton.icon(
        onPressed: onTap,
        icon: Icon(icon, size: 15),
        label: Text(label, style: const TextStyle(fontSize: 8.8, fontWeight: FontWeight.w900)),
        style: OutlinedButton.styleFrom(
          foregroundColor: color,
          side: BorderSide(color: color.withOpacity(.35)),
          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 9),
        ),
      );
}

class _HrLedgerHeader extends StatelessWidget {
  const _HrLedgerHeader();
  @override
  Widget build(BuildContext context) => Container(
    height: 42,
    color: _sheetDarkGreen,
    child: const Row(children:[
      _LedgerCell(width:245,text:'EMPLOYEE',header:true),
      _LedgerCell(width:135,text:'CAMPUS',header:true),
      _LedgerCell(width:190,text:'DEPARTMENT',header:true),
      _LedgerCell(width:92,text:'ACCRUED',header:true,center:true),
      _LedgerCell(width:82,text:'USED',header:true,center:true),
      _LedgerCell(width:100,text:'ADJUSTMENT',header:true,center:true),
      _LedgerCell(width:100,text:'AVAILABLE',header:true,center:true),
      _LedgerCell(width:116,text:'LAST ACCRUAL',header:true,center:true),
      _LedgerCell(width:105,text:'ACCOUNT',header:true,center:true),
      _LedgerCell(width:515,text:'ACTIONS',header:true,center:true),
    ]),
  );
}

class _HrLedgerRow extends StatelessWidget {
  final Map<String,dynamic> employee;
  final bool shaded;
  final bool canSuspend;
  final VoidCallback onAdd;
  final VoidCallback onReduce;
  final VoidCallback onHistory;
  final VoidCallback onAccountStatus;
  const _HrLedgerRow({required this.employee,required this.shaded,required this.canSuspend,required this.onAdd,required this.onReduce,required this.onHistory,required this.onAccountStatus});
  String _t(dynamic v,[String f='—']){final s=v?.toString().trim()??'';return s.isEmpty||s.toLowerCase()=='null'?f:s;}
  double _n(dynamic v)=>double.tryParse('${v??0}')??0;
  @override
  Widget build(BuildContext context){
    final raw=employee['balance'];
    final balance=raw is Map?raw.map((k,v)=>MapEntry(k.toString(),v)):<String,dynamic>{};
    final status=_t(employee['account_status'],'active').toLowerCase();
    final suspended=status=='suspended';
    final last=_t(balance['last_accrual_month']);
    final lastShort=last=='—'?last:last.split(' ').first;
    return Container(
      height:58,
      color:shaded?_sheetBand:Colors.white,
      child:Row(children:[
        _LedgerCell(width:245,text:'${_t(employee['full_name'])}\n${_t(employee['email'],'')}',twoLine:true),
        _LedgerCell(width:135,text:_t(employee['campus'])),
        _LedgerCell(width:190,text:_t(employee['department'])),
        _LedgerCell(width:92,text:_n(balance['entitlement_days']).toStringAsFixed(2),center:true),
        _LedgerCell(width:82,text:_n(balance['used_days']).toStringAsFixed(2),center:true),
        _LedgerCell(width:100,text:_n(balance['adjustment_days']).toStringAsFixed(2),center:true),
        _LedgerCell(width:100,text:_n(balance['available_days']).toStringAsFixed(2),center:true,strong:true),
        _LedgerCell(width:116,text:lastShort,center:true),
        SizedBox(width:105,height:double.infinity,child:Container(alignment:Alignment.center,decoration:const BoxDecoration(border:Border(right:BorderSide(color:_sheetGreen,width:.7),bottom:BorderSide(color:_sheetGreen,width:.7))),child:Container(padding:const EdgeInsets.symmetric(horizontal:7,vertical:4),decoration:BoxDecoration(color:suspended?Colors.red.withOpacity(.09):_leaveGreen.withOpacity(.08),borderRadius:BorderRadius.circular(99)),child:Text(suspended?'SUSPENDED':'ACTIVE',style:TextStyle(color:suspended?Colors.red.shade800:_leaveGreen,fontSize:7.4,fontWeight:FontWeight.w900))))),
        SizedBox(width:515,height:double.infinity,child:Container(alignment:Alignment.center,decoration:const BoxDecoration(border:Border(right:BorderSide(color:_sheetGreen,width:.7),bottom:BorderSide(color:_sheetGreen,width:.7))),child:Wrap(alignment:WrapAlignment.center,spacing:4,runSpacing:3,children:[
          _GridAction(label:'ADD',icon:Icons.add_rounded,color:_leaveGreen,onTap:onAdd),
          _GridAction(label:'REDUCE',icon:Icons.remove_rounded,color:Colors.red.shade700,onTap:onReduce),
          _GridAction(label:'HISTORY',icon:Icons.history_rounded,color:_leaveGold,onTap:onHistory),
          if(canSuspend)_GridAction(label:suspended?'RESTORE':'SUSPEND',icon:suspended?Icons.lock_open_rounded:Icons.block_rounded,color:suspended?_leaveGreen:Colors.red.shade800,onTap:onAccountStatus),
        ]))),
      ]),
    );
  }
}

class _GridAction extends StatelessWidget{
  final String label;final IconData icon;final Color color;final VoidCallback onTap;
  const _GridAction({required this.label,required this.icon,required this.color,required this.onTap});
  @override Widget build(BuildContext context)=>TextButton.icon(onPressed:onTap,icon:Icon(icon,size:12),label:Text(label,style:const TextStyle(fontSize:7.6,fontWeight:FontWeight.w900)),style:TextButton.styleFrom(foregroundColor:color,padding:const EdgeInsets.symmetric(horizontal:7,vertical:5),minimumSize:Size.zero,tapTargetSize:MaterialTapTargetSize.shrinkWrap));
}

class _LedgerCell extends StatelessWidget {
  final double width;
  final String text;
  final bool header;
  final bool center;
  final bool twoLine;
  final bool strong;

  const _LedgerCell({
    required this.width,
    required this.text,
    this.header = false,
    this.center = false,
    this.twoLine = false,
    this.strong = false,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      height: double.infinity,
      alignment: center ? Alignment.center : Alignment.centerLeft,
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
      decoration: const BoxDecoration(
        border: Border(
          right: BorderSide(color: _sheetGreen, width: .7),
          bottom: BorderSide(color: _sheetGreen, width: .7),
        ),
      ),
      child: Text(
        text,
        maxLines: twoLine ? 2 : (header ? 2 : 1),
        overflow: TextOverflow.ellipsis,
        textAlign: center ? TextAlign.center : TextAlign.left,
        style: TextStyle(
          color: header ? Colors.white : _leaveInk,
          fontSize: header ? 8.1 : 9.1,
          fontWeight: (header || strong) ? FontWeight.w900 : FontWeight.w600,
          height: twoLine ? 1.25 : 1.1,
          letterSpacing: header ? 0.25 : 0,
        ),
      ),
    );
  }
}

class _AccountStatusDialog extends StatefulWidget{
  final Map<String,dynamic> employee;final String operation;
  const _AccountStatusDialog({required this.employee,required this.operation});
  @override State<_AccountStatusDialog> createState()=>_AccountStatusDialogState();
}
class _AccountStatusDialogState extends State<_AccountStatusDialog>{
  final _reason=TextEditingController();bool _busy=false;String? _error;
  @override void dispose(){_reason.dispose();super.dispose();}
  String _t(dynamic v,[String f='']){final s=v?.toString().trim()??'';return s.isEmpty||s.toLowerCase()=='null'?f:s;}
  Future<void> _save()async{
    if(_busy)return;final reason=_reason.text.trim();if(reason.isEmpty){setState(()=>_error='An official reason is required.');return;}
    final id=int.tryParse('${widget.employee['user_id']??0}')??0;if(id<=0)return;
    setState((){_busy=true;_error=null;});
    try{final result=await LeaveService.setAccountStatus(userId:id,operation:widget.operation,reason:reason);if(mounted)Navigator.pop(context,result);}catch(e){if(mounted)setState(()=>_error=LeaveService.cleanError(e));}finally{if(mounted)setState(()=>_busy=false);}
  }
  @override Widget build(BuildContext context){final suspend=widget.operation=='suspend';return Dialog(shape:RoundedRectangleBorder(borderRadius:BorderRadius.circular(12)),child:ConstrainedBox(constraints:const BoxConstraints(maxWidth:520),child:Column(mainAxisSize:MainAxisSize.min,children:[
    _DialogHeader(title:suspend?'SUSPEND ACCOUNT':'RESTORE ACCOUNT',subtitle:'DVC1 executive account control • fully audited',onClose:_busy?null:()=>Navigator.pop(context)),
    Padding(padding:const EdgeInsets.all(16),child:Column(crossAxisAlignment:CrossAxisAlignment.stretch,children:[
      Text(_t(widget.employee['full_name'],'Employee'),style:const TextStyle(color:_leaveInk,fontWeight:FontWeight.w900,fontSize:13)),const SizedBox(height:4),
      Text('${_t(widget.employee['department'])} • ${_t(widget.employee['campus'])}',style:const TextStyle(color:_leaveMuted,fontSize:10)),const SizedBox(height:14),
      if(_error!=null)_InlineError(_error!),
      TextField(controller:_reason,minLines:3,maxLines:5,decoration:_input('Official reason',Icons.gavel_rounded)),const SizedBox(height:12),
      Container(padding:const EdgeInsets.all(10),decoration:BoxDecoration(color:(suspend?Colors.red:_leaveGreen).withOpacity(.06),border:Border.all(color:(suspend?Colors.red:_leaveGreen).withOpacity(.2))),child:Text(suspend?'Suspension revokes active sessions immediately. The user will be unable to sign in until DVC1 restores the account.':'Restoring the account allows the user to sign in again with their normal credentials.',style:const TextStyle(color:_leaveMuted,fontSize:9.5,height:1.4))),
    ])),
    Container(padding:const EdgeInsets.all(10),decoration:const BoxDecoration(border:Border(top:BorderSide(color:_leaveBorder))),child:Row(mainAxisAlignment:MainAxisAlignment.end,children:[TextButton(onPressed:_busy?null:()=>Navigator.pop(context),child:const Text('CANCEL')),const SizedBox(width:7),ElevatedButton.icon(onPressed:_busy?null:_save,icon:Icon(suspend?Icons.block_rounded:Icons.lock_open_rounded),label:Text(suspend?'SUSPEND':'RESTORE'),style:ElevatedButton.styleFrom(backgroundColor:suspend?Colors.red.shade700:_leaveGreen,foregroundColor:Colors.white,elevation:0))]))
  ])));}
}

class _HrAdjustmentDialog extends StatefulWidget {
  final Map<String, dynamic> employee;
  final String direction;
  const _HrAdjustmentDialog({required this.employee, required this.direction});

  @override
  State<_HrAdjustmentDialog> createState() => _HrAdjustmentDialogState();
}

class _HrAdjustmentDialogState extends State<_HrAdjustmentDialog> {
  final _days = TextEditingController();
  final _reason = TextEditingController();
  bool _busy = false;
  String? _error;

  @override
  void dispose() {
    _days.dispose();
    _reason.dispose();
    super.dispose();
  }

  String _t(dynamic v, [String f = '']) {
    final s = v?.toString().trim() ?? '';
    return s.isEmpty || s.toLowerCase() == 'null' ? f : s;
  }

  Future<void> _save() async {
    if (_busy) return;
    final days = double.tryParse(_days.text.trim());
    final reason = _reason.text.trim();
    if (days == null || days <= 0) {
      setState(() => _error = 'Enter a valid number of leave days greater than zero.');
      return;
    }
    if (reason.isEmpty) {
      setState(() => _error = 'An official reason is required for every HR adjustment.');
      return;
    }
    final userId = int.tryParse('${widget.employee['user_id'] ?? 0}') ?? 0;
    if (userId <= 0) return;
    setState(() {
      _busy = true;
      _error = null;
    });
    try {
      final result = await LeaveService.adjustBalance(
        userId: userId,
        direction: widget.direction,
        days: days,
        reason: reason,
      );
      if (mounted) Navigator.pop(context, result);
    } catch (e) {
      if (mounted) setState(() => _error = LeaveService.cleanError(e));
    } finally {
      if (mounted) setState(() => _busy = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final add = widget.direction == 'add';
    final raw = widget.employee['balance'];
    final balance = raw is Map ? raw : const {};
    final available = double.tryParse('${balance['available_days'] ?? 0}') ?? 0;
    final size = MediaQuery.sizeOf(context);
    return Dialog(
      insetPadding: EdgeInsets.all(size.width < 600 ? 10 : 28),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
      child: ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 560),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _DialogHeader(
              title: add ? 'ADD LEAVE DAYS' : 'REDUCE LEAVE DAYS',
              subtitle: 'Audited HR balance adjustment • employee notification will be sent',
              onClose: _busy ? null : () => Navigator.pop(context),
            ),
            Padding(
              padding: const EdgeInsets.all(18),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Container(
                    padding: const EdgeInsets.all(13),
                    decoration: BoxDecoration(color: _leaveSurface, borderRadius: BorderRadius.circular(12), border: Border.all(color: _leaveBorder)),
                    child: Row(
                      children: [
                        const Icon(Icons.person_outline_rounded, color: _leaveGreen),
                        const SizedBox(width: 10),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(_t(widget.employee['full_name'], 'Employee'), style: const TextStyle(color: _leaveInk, fontWeight: FontWeight.w900)),
                              const SizedBox(height: 2),
                              Text('${_t(widget.employee['department'])} • ${_t(widget.employee['campus'])}', style: const TextStyle(color: _leaveMuted, fontSize: 10.2)),
                            ],
                          ),
                        ),
                        Text('${available.toStringAsFixed(2)} days', style: const TextStyle(color: _leaveGreen, fontWeight: FontWeight.w900)),
                      ],
                    ),
                  ),
                  if (_error != null) ...[const SizedBox(height: 12), _InlineError(_error!)],
                  const SizedBox(height: 13),
                  TextField(
                    controller: _days,
                    enabled: !_busy,
                    keyboardType: const TextInputType.numberWithOptions(decimal: true),
                    decoration: _input(add ? 'Days to Add' : 'Days to Reduce', add ? Icons.add_circle_outline : Icons.remove_circle_outline),
                  ),
                  const SizedBox(height: 12),
                  TextField(
                    controller: _reason,
                    enabled: !_busy,
                    minLines: 3,
                    maxLines: 5,
                    decoration: _input('Official Reason / HR Note', Icons.edit_note_rounded),
                  ),
                  const SizedBox(height: 11),
                  Container(
                    padding: const EdgeInsets.all(11),
                    decoration: BoxDecoration(color: _leaveGold.withOpacity(.07), borderRadius: BorderRadius.circular(10), border: Border.all(color: _leaveGold.withOpacity(.2))),
                    child: const Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Icon(Icons.notifications_active_outlined, color: _leaveGold, size: 18),
                        SizedBox(width: 8),
                        Expanded(child: Text('This adjustment will be recorded in the permanent HR audit history and the employee will receive a leave notification showing the change and reason.', style: TextStyle(color: _leaveMuted, fontSize: 9.8, height: 1.4))),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: const BoxDecoration(border: Border(top: BorderSide(color: _leaveBorder))),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(onPressed: _busy ? null : () => Navigator.pop(context), child: const Text('CANCEL')),
                  const SizedBox(width: 8),
                  ElevatedButton.icon(
                    onPressed: _busy ? null : _save,
                    icon: _busy
                        ? const SizedBox(width: 15, height: 15, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
                        : Icon(add ? Icons.add_rounded : Icons.remove_rounded),
                    label: Text(add ? 'ADD DAYS' : 'REDUCE DAYS'),
                    style: ElevatedButton.styleFrom(backgroundColor: add ? _leaveGreen : Colors.red.shade700, foregroundColor: Colors.white),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _HrEmployeeHistoryDialog extends StatefulWidget {
  final int userId;
  final ValueChanged<int> onOpenLeaveId;
  const _HrEmployeeHistoryDialog({required this.userId, required this.onOpenLeaveId});

  @override
  State<_HrEmployeeHistoryDialog> createState() => _HrEmployeeHistoryDialogState();
}

class _HrEmployeeHistoryDialogState extends State<_HrEmployeeHistoryDialog> {
  bool _loading = true;
  String? _error;
  Map<String, dynamic> _data = const {};

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

  String _t(dynamic v, [String f = '—']) {
    final s = v?.toString().trim() ?? '';
    return s.isEmpty || s.toLowerCase() == 'null' ? f : s;
  }

  double _n(dynamic v) => double.tryParse('${v ?? 0}') ?? 0;

  Future<void> _load() async {
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final data = await LeaveService.hrHistory(widget.userId);
      if (!mounted) return;
      setState(() {
        _data = data;
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = LeaveService.cleanError(e);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);
    final employeeRaw = _data['employee'];
    final employee = employeeRaw is Map ? employeeRaw.map((k, v) => MapEntry(k.toString(), v)) : <String, dynamic>{};
    final balanceRaw = _data['balance'];
    final balance = balanceRaw is Map ? balanceRaw.map((k, v) => MapEntry(k.toString(), v)) : <String, dynamic>{};
    final adjustments = _data['adjustments'] is List
        ? (_data['adjustments'] as List).whereType<Map>().map((e) => e.map((k, v) => MapEntry(k.toString(), v))).toList()
        : <Map<String, dynamic>>[];
    final leaves = _data['leave_history'] is List
        ? (_data['leave_history'] as List).whereType<Map>().map((e) => e.map((k, v) => MapEntry(k.toString(), v))).toList()
        : <Map<String, dynamic>>[];

    return Dialog(
      insetPadding: EdgeInsets.all(size.width < 700 ? 8 : 24),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: 900, maxHeight: size.height * .92),
        child: Column(
          children: [
            _DialogHeader(
              title: 'EMPLOYEE LEAVE AUDIT',
              subtitle: _loading ? 'Loading employee leave history...' : '${_t(employee['full_name'], 'Employee')} • ${_t(employee['campus'])}',
              onClose: () => Navigator.pop(context),
            ),
            Expanded(
              child: _loading
                  ? const Center(child: CircularProgressIndicator(color: _leaveGreen))
                  : _error != null
                      ? _ErrorPanel(message: _error!, onRetry: _load)
                      : ListView(
                          padding: const EdgeInsets.all(18),
                          children: [
                            _Section(
                              icon: Icons.account_balance_wallet_outlined,
                              title: 'Current Annual Leave Position',
                              subtitle: 'Balance is calculated from monthly accrual, approved leave, carry-forward and audited HR adjustments.',
                              child: Wrap(
                                spacing: 10,
                                runSpacing: 10,
                                children: [
                                  _HistoryMetric(label: 'ACCRUED', value: _n(balance['entitlement_days']).toStringAsFixed(2)),
                                  _HistoryMetric(label: 'USED', value: _n(balance['used_days']).toStringAsFixed(2)),
                                  _HistoryMetric(label: 'CARRY FORWARD', value: _n(balance['carried_forward_days']).toStringAsFixed(2)),
                                  _HistoryMetric(label: 'ADJUSTMENTS', value: _n(balance['adjustment_days']).toStringAsFixed(2)),
                                  _HistoryMetric(label: 'AVAILABLE', value: _n(balance['available_days']).toStringAsFixed(2), strong: true),
                                  _HistoryMetric(label: 'MONTHLY RATE', value: '${_n(balance['accrual_rate_month']).toStringAsFixed(2)} days'),
                                ],
                              ),
                            ),
                            const SizedBox(height: 14),
                            _Section(
                              icon: Icons.manage_history_rounded,
                              title: 'HR Adjustment Audit Trail',
                              subtitle: 'Every manual addition or reduction records who made the change, when it happened and the official reason.',
                              child: adjustments.isEmpty
                                  ? const Text('No manual HR adjustments have been recorded for this employee.', style: TextStyle(color: _leaveMuted, fontSize: 10.5))
                                  : Column(
                                      children: adjustments.map((item) {
                                        final amount = _n(item['amount']);
                                        final positive = amount >= 0;
                                        return Container(
                                          margin: const EdgeInsets.only(bottom: 8),
                                          padding: const EdgeInsets.all(12),
                                          decoration: BoxDecoration(color: _leaveSurface, borderRadius: BorderRadius.circular(11), border: Border.all(color: _leaveBorder)),
                                          child: Row(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              Container(
                                                width: 36,
                                                height: 36,
                                                decoration: BoxDecoration(color: (positive ? _leaveGreen : Colors.red).withOpacity(.08), borderRadius: BorderRadius.circular(10)),
                                                child: Icon(positive ? Icons.add_rounded : Icons.remove_rounded, color: positive ? _leaveGreen : Colors.red.shade700),
                                              ),
                                              const SizedBox(width: 10),
                                              Expanded(
                                                child: Column(
                                                  crossAxisAlignment: CrossAxisAlignment.start,
                                                  children: [
                                                    Text('${positive ? '+' : ''}${amount.toStringAsFixed(2)} day(s) • ${_t(item['actor_name'])}', style: const TextStyle(color: _leaveInk, fontSize: 10.8, fontWeight: FontWeight.w900)),
                                                    const SizedBox(height: 3),
                                                    Text('${_t(item['actor_position'])} • ${_t(item['actor_campus'])} • ${_t(item['created_at'])}', style: const TextStyle(color: _leaveMuted, fontSize: 9.1)),
                                                    const SizedBox(height: 5),
                                                    Text(_t(item['reason']), style: const TextStyle(color: _leaveMuted, fontSize: 10, height: 1.35)),
                                                    const SizedBox(height: 4),
                                                    Text('Balance: ${_n(item['before_balance']).toStringAsFixed(2)} → ${_n(item['after_balance']).toStringAsFixed(2)}', style: const TextStyle(color: _leaveGreen, fontSize: 9.5, fontWeight: FontWeight.w800)),
                                                  ],
                                                ),
                                              ),
                                            ],
                                          ),
                                        );
                                      }).toList(),
                                    ),
                            ),
                            const SizedBox(height: 14),
                            _Section(
                              icon: Icons.description_outlined,
                              title: 'Leave Application History',
                              subtitle: 'Open any leave record to view the official form, QR verification and complete routing history.',
                              child: leaves.isEmpty
                                  ? const Text('No leave applications are recorded for this employee in the selected year.', style: TextStyle(color: _leaveMuted, fontSize: 10.5))
                                  : Column(
                                      children: leaves.map((leave) {
                                        final id = int.tryParse('${leave['id'] ?? 0}') ?? 0;
                                        return InkWell(
                                          onTap: id <= 0
                                              ? null
                                              : () {
                                                  Navigator.pop(context);
                                                  widget.onOpenLeaveId(id);
                                                },
                                          borderRadius: BorderRadius.circular(11),
                                          child: Container(
                                            margin: const EdgeInsets.only(bottom: 7),
                                            padding: const EdgeInsets.all(11),
                                            decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(11), border: Border.all(color: _leaveBorder)),
                                            child: Row(
                                              children: [
                                                const Icon(Icons.event_note_outlined, color: _leaveGreen, size: 19),
                                                const SizedBox(width: 9),
                                                Expanded(
                                                  child: Column(
                                                    crossAxisAlignment: CrossAxisAlignment.start,
                                                    children: [
                                                      Text('#$id • ${_t(leave['leave_type']).toUpperCase()} • ${_n(leave['requested_days']).toStringAsFixed(2)} day(s)', style: const TextStyle(color: _leaveInk, fontSize: 10.5, fontWeight: FontWeight.w900)),
                                                      const SizedBox(height: 2),
                                                      Text('${_t(leave['start_date'])} → ${_t(leave['end_date'])} • ${_t(leave['status']).toUpperCase()}', style: const TextStyle(color: _leaveMuted, fontSize: 9.3)),
                                                    ],
                                                  ),
                                                ),
                                                const Icon(Icons.chevron_right_rounded, color: _leaveGreen),
                                              ],
                                            ),
                                          ),
                                        );
                                      }).toList(),
                                    ),
                            ),
                          ],
                        ),
            ),
          ],
        ),
      ),
    );
  }
}

class _HistoryMetric extends StatelessWidget {
  final String label;
  final String value;
  final bool strong;
  const _HistoryMetric({required this.label, required this.value, this.strong = false});
  @override
  Widget build(BuildContext context) => Container(
        width: 132,
        padding: const EdgeInsets.all(11),
        decoration: BoxDecoration(
          color: strong ? _leaveGreen.withOpacity(.07) : _leaveSurface,
          borderRadius: BorderRadius.circular(11),
          border: Border.all(color: strong ? _leaveGreen.withOpacity(.25) : _leaveBorder),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(label, style: const TextStyle(color: _leaveMuted, fontSize: 7.8, fontWeight: FontWeight.w900, letterSpacing: .35)),
            const SizedBox(height: 4),
            Text(value, style: TextStyle(color: strong ? _leaveGreen : _leaveInk, fontSize: 12.5, fontWeight: FontWeight.w900)),
          ],
        ),
      );
}


class LeaveApplicationDialog extends StatefulWidget {
  final Map<String, dynamic> setup;
  const LeaveApplicationDialog({super.key, required this.setup});

  @override
  State<LeaveApplicationDialog> createState() => _LeaveApplicationDialogState();
}

class _LeaveApplicationDialogState extends State<LeaveApplicationDialog> {
  final _formKey = GlobalKey<FormState>();
  final _personnel = TextEditingController();
  final _position = TextEditingController();
  final _reason = TextEditingController();
  final _otherType = TextEditingController();
  final _address = TextEditingController();
  final _contactName = TextEditingController();
  final _contactPhone = TextEditingController();
  final _contactRelationship = TextEditingController();
  final _contactAddress = TextEditingController();
  bool _busy = false;
  String? _error;
  String _leaveType = 'annual';
  DateTime? _start;
  DateTime? _end;
  DateTime? _return;

  Map<String, dynamic> get _user {
    final raw = widget.setup['current_user'];
    return raw is Map ? raw.map((k, v) => MapEntry(k.toString(), v)) : const {};
  }

  @override
  void initState() {
    super.initState();
    final position = '${_user['position'] ?? ''}'.trim();
    if (!['staff', 'admin', 'administrator'].contains(position.toLowerCase())) {
      _position.text = position;
    }
  }

  @override
  void dispose() {
    for (final c in [_personnel,_position,_reason,_otherType,_address,_contactName,_contactPhone,_contactRelationship,_contactAddress]) {
      c.dispose();
    }
    super.dispose();
  }

  int get _days {
    if (_start == null || _end == null || _end!.isBefore(_start!)) return 0;
    return _end!.difference(DateTime(_start!.year,_start!.month,_start!.day)).inDays + 1;
  }

  String _fmt(DateTime? value) => value == null ? 'Select date' : DateFormat('dd MMM yyyy').format(value);
  String _iso(DateTime value) => DateFormat('yyyy-MM-dd').format(value);

  Future<void> _pick(String field) async {
    final now = DateTime.now();
    final initial = field == 'start' ? (_start ?? now) : field == 'end' ? (_end ?? _start ?? now) : (_return ?? _end ?? now);
    final picked = await showDatePicker(
      context: context,
      initialDate: initial,
      firstDate: DateTime(now.year - 1),
      lastDate: DateTime(now.year + 3),
      helpText: field == 'start' ? 'START DATE' : field == 'end' ? 'END DATE' : 'EXPECTED RETURN TO DUTY',
    );
    if (picked == null) return;
    setState(() {
      if (field == 'start') {
        _start = picked;
        if (_end != null && _end!.isBefore(picked)) _end = picked;
      } else if (field == 'end') {
        _end = picked;
        _return ??= picked.add(const Duration(days: 1));
      } else {
        _return = picked;
      }
    });
  }

  Future<void> _submit() async {
    if (_busy || !(_formKey.currentState?.validate() ?? false)) return;
    if (_start == null || _end == null || _return == null) {
      setState(() => _error = 'Start date, end date and expected return-to-duty date are required.');
      return;
    }
    if (_end!.isBefore(_start!)) {
      setState(() => _error = 'End date cannot be before start date.');
      return;
    }
    setState(() {
      _busy = true;
      _error = null;
    });
    try {
      await LeaveService.create({
        'personnel_no': _personnel.text.trim(),
        'position_title': _position.text.trim(),
        'leave_type': _leaveType,
        'other_leave_type': _otherType.text.trim(),
        'reason': _reason.text.trim(),
        'start_date': _iso(_start!),
        'end_date': _iso(_end!),
        'expected_return_date': _iso(_return!),
        'address_while_on_leave': _address.text.trim(),
        'emergency_contact_name': _contactName.text.trim(),
        'emergency_contact_phone': _contactPhone.text.trim(),
        'emergency_contact_relationship': _contactRelationship.text.trim(),
        'emergency_contact_address': _contactAddress.text.trim(),
      });
      if (mounted) Navigator.pop(context, true);
    } catch (e) {
      if (mounted) setState(() => _error = LeaveService.cleanError(e));
    } finally {
      if (mounted) setState(() => _busy = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);
    final narrow = size.width < 700;
    final annualRaw = widget.setup['annual_balance'];
    final annualBalance = annualRaw is Map ? annualRaw.map((k, v) => MapEntry(k.toString(), v)) : const <String, dynamic>{};
    final annualAvailable = double.tryParse('${annualBalance['available_days'] ?? 0}') ?? 0;
    final department = '${_user['department'] ?? ''}'.trim();
    final campus = '${_user['campus'] ?? ''}'.trim();

    return PopScope(
      canPop: !_busy,
      child: Dialog(
        insetPadding: EdgeInsets.all(narrow ? 8 : 24),
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(narrow ? 14 : 20)),
        child: ConstrainedBox(
          constraints: BoxConstraints(maxWidth: 1240, maxHeight: size.height * .94),
          child: Column(
            children: [
              _DialogHeader(
                title: 'LEAVE APPLICATION',
                subtitle: 'Rockview University • $campus • Staff leave application',
                onClose: _busy ? null : () => Navigator.pop(context, false),
              ),
              Expanded(
                child: _LeaveFormLayout(
                  routing: const _LeaveWorkflowPanel(row: <String, dynamic>{}),
                  form: Padding(
                  padding: EdgeInsets.all(narrow ? 16 : 26),
                  child: Form(
                    key: _formKey,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        if (_error != null) _InlineError(_error!),
                        _Section(
                          icon: Icons.badge_outlined,
                          title: '01  Employee information',
                          subtitle: 'Campus and department are taken from the authenticated staff profile.',
                          child: Column(
                            children: [
                              _InfoGrid(items: [
                                ('Employee', '${_user['name'] ?? ''}'),
                                ('Department', department),
                                ('Campus / workstation', campus),
                                ('Phone', '${_user['phone'] ?? ''}'),
                                ('Annual leave available', '${annualAvailable.toStringAsFixed(2)} days'),
                                ('Monthly accrual', '2.00 days / month'),
                              ]),
                              const SizedBox(height: 14),
                              _ResponsiveFields(children: [
                                _Field(controller: _personnel, label: 'MAN / Personnel No.', icon: Icons.numbers_rounded, isRequired: false),
                                _Field(controller: _position, label: 'Position / Job Title', icon: Icons.work_outline_rounded),
                              ]),
                            ],
                          ),
                        ),
                        const SizedBox(height: 16),
                        _Section(
                          icon: Icons.calendar_month_outlined,
                          title: '02  Leave details',
                          subtitle: 'Select the type and dates. Requested days are calculated automatically as calendar days.',
                          child: Column(
                            children: [
                              _ResponsiveFields(children: [
                                DropdownButtonFormField<String>(
                                  value: _leaveType,
                                  isExpanded: true,
                                  decoration: _input('Leave Type', Icons.category_outlined),
                                  items: const [
                                    'annual','compassionate','sick','maternity','paternity','study','unpaid','other'
                                  ].map((e) => DropdownMenuItem(value: e, child: Text(e.toUpperCase()))).toList(),
                                  onChanged: _busy ? null : (v) => setState(() => _leaveType = v ?? 'annual'),
                                ),
                                if (_leaveType == 'other')
                                  _Field(controller: _otherType, label: 'Specify Other Leave', icon: Icons.edit_note_rounded),
                              ]),
                              const SizedBox(height: 12),
                              _DateGrid(
                                start: _fmt(_start),
                                end: _fmt(_end),
                                back: _fmt(_return),
                                days: _days,
                                onStart: () => _pick('start'),
                                onEnd: () => _pick('end'),
                                onReturn: () => _pick('return'),
                              ),
                              const SizedBox(height: 12),
                              _Field(controller: _reason, label: 'Reason for Taking Leave', icon: Icons.subject_rounded, maxLines: 4),
                            ],
                          ),
                        ),
                        const SizedBox(height: 16),
                        _Section(
                          icon: Icons.contact_phone_outlined,
                          title: '03  Contact while on leave',
                          subtitle: 'Emergency and contact details help the university reach the staff member when necessary.',
                          child: Column(
                            children: [
                              _Field(controller: _address, label: 'Physical Address / Contact Location While on Leave', icon: Icons.home_work_outlined, maxLines: 2, isRequired: false),
                              const SizedBox(height: 12),
                              _ResponsiveFields(children: [
                                _Field(controller: _contactName, label: 'Alternative Contact Person', icon: Icons.person_outline_rounded, isRequired: false),
                                _Field(controller: _contactPhone, label: 'Alternative Contact Phone', icon: Icons.phone_outlined, isRequired: false),
                                _Field(controller: _contactRelationship, label: 'Relationship', icon: Icons.family_restroom_outlined, isRequired: false),
                              ]),
                              const SizedBox(height: 12),
                              _Field(controller: _contactAddress, label: 'Alternative Contact Physical Address', icon: Icons.location_on_outlined, maxLines: 2, isRequired: false),
                            ],
                          ),
                        ),
                        const SizedBox(height: 16),
                        _Section(
                          icon: Icons.qr_code_2_rounded,
                          title: 'Official QR verification',
                          subtitle: 'Each action receives a self-contained QR audit record with organized verification data.',
                          child: Container(
                            padding: const EdgeInsets.all(14),
                            decoration: BoxDecoration(
                              color: _leaveGreen.withOpacity(.045),
                              borderRadius: BorderRadius.circular(13),
                              border: Border.all(color: _leaveGreen.withOpacity(.18)),
                            ),
                            child: const Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Icon(Icons.verified_user_outlined, color: _leaveGreen, size: 24),
                                SizedBox(width: 12),
                                Expanded(
                                  child: Text(
                                    'When you submit, the system creates a unique QR audit record. Every HOD, HR, Registrar and DVC1 action receives its own QR containing the leave reference, authenticated person, office, campus, action, timestamp and verification code — not a web link.',
                                    style: TextStyle(color: _leaveMuted, fontSize: 11.2, height: 1.5),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                        const SizedBox(height: 20),
                      ],
                    ),
                  ),
                ),
                ),
              ),
              _DialogFooter(
                busy: _busy,
                cancelLabel: 'CANCEL',
                actionLabel: 'SUBMIT TO HOD',
                onCancel: () => Navigator.pop(context, false),
                onAction: _submit,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class LeaveDetailDialog extends StatefulWidget {
  final Map<String, dynamic> leave;
  const LeaveDetailDialog({super.key, required this.leave});

  @override
  State<LeaveDetailDialog> createState() => _LeaveDetailDialogState();
}

class _LeaveDetailDialogState extends State<LeaveDetailDialog> {
  bool _busy = false;
  final _remarks = TextEditingController();

  Map<String, dynamic> get row => widget.leave;
  bool _truthy(dynamic v) => v == true || v == 1 || v == '1' || v == 'true' || v == 't';
  String _t(dynamic v, [String f = '']) {
    final s = v?.toString().trim() ?? '';
    return s.isEmpty || s.toLowerCase() == 'null' ? f : s;
  }

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

  Future<void> _do(String action) async {
    if (_busy) return;
    setState(() => _busy = true);
    try {
      await LeaveService.action(
        int.parse('${row['id']}'),
        action,
        remarks: _remarks.text.trim(),
      );
      if (mounted) Navigator.pop(context, true);
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(LeaveService.cleanError(e)), backgroundColor: Colors.red.shade700),
      );
    } finally {
      if (mounted) setState(() => _busy = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);
    final actionRequired = _truthy(row['action_required']);
    final owner = _truthy(row['is_owner']);
    final status = _t(row['status'], 'pending');
    final stage = _t(row['current_stage']);

    final document = _LeaveDocumentView(row: row);
    final workflow = _LeaveWorkflowPanel(row: row);

    return Dialog(
      insetPadding: EdgeInsets.all(size.width < 700 ? 8 : 22),
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: 1180, maxHeight: size.height * .94),
        child: Column(
          children: [
            _DialogHeader(
              title: 'LEAVE APPLICATION #${row['id']}',
              subtitle: '${_t(row['leave_type']).toUpperCase()} • ${status.toUpperCase()} • ${_t(row['current_recipient_label'], 'Finalised')}',
              onClose: _busy ? null : () => Navigator.pop(context, false),
            ),
            Expanded(
              child: _LeaveFormLayout(form: document, routing: workflow),
            ),
            if (actionRequired || (owner && (status == 'pending' || status == 'returned')))
              _LeaveActionBar(
                busy: _busy,
                stage: stage,
                status: status,
                isOwner: owner,
                remarks: _remarks,
                onAction: _do,
              ),
          ],
        ),
      ),
    );
  }
}

class _LeaveActionBar extends StatelessWidget {
  final bool busy;
  final String stage;
  final String status;
  final bool isOwner;
  final TextEditingController remarks;
  final ValueChanged<String> onAction;

  const _LeaveActionBar({
    required this.busy,
    required this.stage,
    required this.status,
    required this.isOwner,
    required this.remarks,
    required this.onAction,
  });

  @override
  Widget build(BuildContext context) {
    final buttons = <Widget>[];
    if (isOwner && status == 'pending') {
      buttons.add(_ActionButton(label: 'WITHDRAW', icon: Icons.undo_rounded, color: Colors.redAccent, onTap: busy ? null : () => onAction('withdraw')));
    } else if (isOwner && status == 'returned') {
      buttons.add(_ActionButton(label: 'RESUBMIT TO HOD', icon: Icons.send_rounded, color: _leaveGreen, onTap: busy ? null : () => onAction('resubmit')));
    } else {
      if (stage == 'junior_hr') {
        buttons.add(_ActionButton(label: 'VERIFY & ROUTE TO REGISTRAR', icon: Icons.verified_rounded, color: _leaveGreen, onTap: busy ? null : () => onAction('verify')));
      } else if (stage == 'dvc1') {
        buttons.add(_ActionButton(label: 'FINAL APPROVE', icon: Icons.verified_user_rounded, color: _leaveGreen, onTap: busy ? null : () => onAction('approve')));
      } else {
        buttons.add(_ActionButton(label: stage == 'hod' ? 'RECOMMEND & ROUTE' : 'APPROVE & FORWARD', icon: Icons.route_rounded, color: _leaveGreen, onTap: busy ? null : () => onAction('recommend')));
      }
      buttons.add(_ActionButton(label: 'RETURN', icon: Icons.keyboard_return_rounded, color: _leaveGold, onTap: busy ? null : () => onAction('return')));
      buttons.add(_ActionButton(label: 'REJECT', icon: Icons.cancel_outlined, color: Colors.redAccent, onTap: busy ? null : () => onAction('reject')));
    }

    return Container(
      padding: const EdgeInsets.fromLTRB(14, 10, 14, 14),
      decoration: const BoxDecoration(color: Colors.white, border: Border(top: BorderSide(color: _leaveBorder))),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (!isOwner && stage == 'junior_hr') ...[
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(11),
              decoration: BoxDecoration(
                color: _leaveGreen.withOpacity(.045),
                borderRadius: BorderRadius.circular(11),
                border: Border.all(color: _leaveGreen.withOpacity(.18)),
              ),
              child: const Row(
                children: [
                  Icon(Icons.auto_graph_rounded, color: _leaveGreen, size: 19),
                  SizedBox(width: 9),
                  Expanded(
                    child: Text(
                      'The employee annual leave balance is taken directly from the HR ledger and is accrued automatically at 2.00 days per month. Use the HR Leave Ledger tab for audited add/reduce adjustments.',
                      style: TextStyle(color: _leaveMuted, fontSize: 10.5, height: 1.4),
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 8),
          ],
          TextField(
            controller: remarks,
            enabled: !busy,
            minLines: 1,
            maxLines: 3,
            decoration: _input('Official Remarks / Recommendation', Icons.edit_note_rounded),
          ),
          const SizedBox(height: 9),
          Wrap(spacing: 8, runSpacing: 8, alignment: WrapAlignment.end, children: buttons),
        ],
      ),
    );
  }
}

class _SmallNumberField extends StatelessWidget {
  final TextEditingController controller;
  final String label;
  const _SmallNumberField({required this.controller, required this.label});
  @override
  Widget build(BuildContext context) => TextField(
        controller: controller,
        keyboardType: const TextInputType.numberWithOptions(decimal: true),
        decoration: _input(label, Icons.calculate_outlined),
      );
}

class _ActionButton extends StatelessWidget {
  final String label;
  final IconData icon;
  final Color color;
  final VoidCallback? onTap;
  const _ActionButton({required this.label, required this.icon, required this.color, required this.onTap});
  @override
  Widget build(BuildContext context) => ElevatedButton.icon(
        onPressed: onTap,
        icon: Icon(icon, size: 17),
        label: Text(label, style: const TextStyle(fontSize: 10.5, fontWeight: FontWeight.w900)),
        style: ElevatedButton.styleFrom(
          backgroundColor: color,
          foregroundColor: Colors.white,
          elevation: 0,
          padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 13),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        ),
      );
}

class _LeaveDocumentView extends StatelessWidget {
  final Map<String, dynamic> row;
  const _LeaveDocumentView({required this.row});
  String _t(dynamic v, [String f = '']) {
    final s = v?.toString().trim() ?? '';
    return s.isEmpty || s.toLowerCase() == 'null' ? f : s;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color(0xFFF2F5F3),
      padding: const EdgeInsets.all(14),
      child: Align(
        alignment: Alignment.topLeft,
        child: Container(
            constraints: const BoxConstraints(maxWidth: 1100),
            padding: const EdgeInsets.fromLTRB(34, 28, 34, 38),
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border.all(color: _leaveBorder),
              boxShadow: [BoxShadow(color: Colors.black.withOpacity(.05), blurRadius: 14, offset: const Offset(0, 6))],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                const Text('ROCKVIEW UNIVERSITY LTD', textAlign: TextAlign.center, style: TextStyle(fontFamily: 'Georgia', color: _leaveGreen, fontSize: 22, fontWeight: FontWeight.w900, letterSpacing: .6)),
                const SizedBox(height: 6),
                const Text('DIGITAL LEAVE APPLICATION FORM', textAlign: TextAlign.center, style: TextStyle(color: _leaveInk, fontSize: 12.5, fontWeight: FontWeight.w900, decoration: TextDecoration.underline)),
                const SizedBox(height: 8),
                Text(_t(row['campus'], 'Campus not specified').toUpperCase(), textAlign: TextAlign.center, style: const TextStyle(color: _leaveMuted, fontSize: 11, fontWeight: FontWeight.w700)),
                const SizedBox(height: 16),
                const Divider(color: _leaveGreen, thickness: 2),
                const SizedBox(height: 16),
                _DocHeading('EMPLOYEE AND LEAVE PARTICULARS'),
                const SizedBox(height: 12),
                _DocumentGrid(items: [
                  ('EMPLOYEE NAME', _t(row['applicant_name'])),
                  ('MAN / PERSONNEL NO.', _t(row['personnel_no'], '—')),
                  ('POSITION', _t(row['position_title'])),
                  ('DEPARTMENT', _t(row['department'])),
                  ('WORKSTATION / CAMPUS', _t(row['campus'])),
                  ('PHONE NUMBER', _t(row['applicant_phone'], '—')),
                  ('START DATE', _t(row['start_date'])),
                  ('END DATE', _t(row['end_date'])),
                  ('EXPECTED RETURN', _t(row['expected_return_date'])),
                  ('DAYS APPLIED FOR', _t(row['requested_days'])),
                ]),
                const SizedBox(height: 18),
                _DocHeading('REASON FOR TAKING LEAVE'),
                const SizedBox(height: 7),
                Text('${_t(row['leave_type']).toUpperCase()}${_t(row['other_leave_type']).isNotEmpty ? ' — ${_t(row['other_leave_type'])}' : ''}', style: const TextStyle(color: _leaveGreen, fontWeight: FontWeight.w900, fontSize: 11.5)),
                const SizedBox(height: 7),
                Text(_t(row['reason']), style: const TextStyle(color: _leaveInk, fontSize: 11.5, height: 1.5)),
                const SizedBox(height: 18),
                _DocHeading('CONTACT WHILE ON LEAVE'),
                const SizedBox(height: 8),
                _DocumentGrid(items: [
                  ('PHYSICAL ADDRESS', _t(row['address_while_on_leave'], '—')),
                  ('ALTERNATIVE CONTACT', _t(row['emergency_contact_name'], '—')),
                  ('CONTACT PHONE', _t(row['emergency_contact_phone'], '—')),
                  ('RELATIONSHIP', _t(row['emergency_contact_relationship'], '—')),
                  ('CONTACT ADDRESS', _t(row['emergency_contact_address'], '—')),
                ]),
                const SizedBox(height: 18),
                _DocHeading('LEAVE DAYS / HR CONFIRMATION'),
                const SizedBox(height: 8),
                _BalanceTable(row: row),
              ],
            ),
        ),
      ),
    );
  }
}

class _LeaveWorkflowPanel extends StatelessWidget {
  final Map<String, dynamic> row;
  const _LeaveWorkflowPanel({required this.row});

  @override
  Widget build(BuildContext context) {
    final historyRaw = row['history'];
    final history = historyRaw is List
        ? historyRaw
            .whereType<Map>()
            .map((e) => e.map((k, v) => MapEntry(k.toString(), v)))
            .toList()
        : <Map<String, dynamic>>[];

    DateTime? eventTime(Map<String, dynamic> event) => DateTime.tryParse('${event['signed_at'] ?? event['created_at'] ?? ''}');
    if (history.every((event) => eventTime(event) != null)) {
      final originalOrder = {for (var i = 0; i < history.length; i++) history[i]: i};
      history.sort((a, b) {
        final order = eventTime(a)!.compareTo(eventTime(b)!);
        return order == 0 ? originalOrder[a]!.compareTo(originalOrder[b]!) : order;
      });
    }

    return Container(
      color: Colors.white,
      padding: const EdgeInsets.all(16),
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('REQUEST ROUTING', style: TextStyle(color: _leaveInk, fontSize: 13.5, fontWeight: FontWeight.w900, letterSpacing: .3)),
            const SizedBox(height: 3),
            const Text('The standard route is shown first; the actual movement below records every forward route, return loop and final decision in sequence.', style: TextStyle(color: _leaveMuted, fontSize: 9.8, height: 1.35)),
            const SizedBox(height: 12),
            Container(
              padding: const EdgeInsets.fromLTRB(10, 9, 10, 7),
              decoration: BoxDecoration(
                color: _leaveSurface,
                borderRadius: BorderRadius.circular(10),
                border: Border.all(color: _leaveBorder),
              ),
              child: const Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('STANDARD CONTROLLED ROUTE', style: TextStyle(color: _leaveMuted, fontSize: 8.7, fontWeight: FontWeight.w900)),
                  SizedBox(height: 7),
                  _LeaveRouteStrip(),
                ],
              ),
            ),
            const SizedBox(height: 14),
            const Row(
              children: [
                Icon(Icons.account_tree_rounded, color: _leaveGreen, size: 17),
                SizedBox(width: 7),
                Text('ACTUAL REQUEST MOVEMENT', style: TextStyle(color: _leaveInk, fontSize: 10.8, fontWeight: FontWeight.w900, letterSpacing: .3)),
              ],
            ),
            const SizedBox(height: 3),
            const Text('Start at record 1 and follow the orange arrows down to each next action. Returns to an earlier office are labelled clearly.', style: TextStyle(color: _leaveMuted, fontSize: 9.2, height: 1.35)),
            const SizedBox(height: 10),
            if (history.isEmpty)
              Container(
                width: double.infinity,
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(color: _leaveSurface, borderRadius: BorderRadius.circular(10), border: Border.all(color: _leaveBorder)),
                child: const Text('No routing history has been recorded yet.', style: TextStyle(color: _leaveMuted, fontSize: 10)),
              )
            else
              _ActualLeaveJourney(
                history: history,
                leaveRef: '#${row['id'] ?? '—'}',
                applicantName: '${row['applicant_name'] ?? 'Employee'}',
              ),
          ],
      ),
    );
  }
}

class _ActualLeaveJourney extends StatelessWidget {
  final List<Map<String, dynamic>> history;
  final String leaveRef;
  final String applicantName;

  const _ActualLeaveJourney({
    required this.history,
    required this.leaveRef,
    required this.applicantName,
  });

  String _t(dynamic value, [String fallback = '']) {
    final text = value?.toString().trim() ?? '';
    return text.isEmpty || text.toLowerCase() == 'null' ? fallback : text;
  }

  String _stageLabel(String raw) {
    final clean = raw.trim().toLowerCase();
    const labels = {
      'staff': 'STAFF',
      'hod': 'HOD',
      'junior_hr': 'JUNIOR HR',
      'registrar': 'REGISTRAR',
      'senior_hr': 'SENIOR HR',
      'dvc1': 'DVC1',
    };
    return labels[clean] ?? clean.replaceAll('_', ' ').toUpperCase();
  }

  int _stageIndex(String stage) {
    const order = ['staff', 'hod', 'junior_hr', 'registrar', 'senior_hr', 'dvc1'];
    return order.indexOf(stage.trim().toLowerCase());
  }

  bool _isReturn(Map<String, dynamic> event) {
    final action = _t(event['action']).toLowerCase();
    if (action.contains('return')) return true;
    final from = _stageIndex(_t(event['from_stage']));
    final to = _stageIndex(_t(event['to_stage']));
    return from >= 0 && to >= 0 && to < from;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: List.generate(history.length, (index) {
        final event = history[index];
        final fromStage = _t(event['from_stage'], index == 0 ? 'staff' : '');
        final toStage = _t(event['to_stage']);
        final action = _t(event['action'], 'recorded').toUpperCase();
        final returning = _isReturn(event);
        final remarks = _t(event['remarks']);
        final routeText = toStage.isEmpty
            ? _stageLabel(fromStage)
            : '${_stageLabel(fromStage)} → ${_stageLabel(toStage)}';

        return Padding(
          padding: const EdgeInsets.only(bottom: 12),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(width: 54, child: index == 0
                ? const Padding(padding: EdgeInsets.only(top: 18), child: Icon(Icons.play_circle_fill_rounded, color: _leaveGreen, size: 26))
                : const _RouteJourneyConnector()),
              Expanded(child: Container(
                width: double.infinity,
                decoration: BoxDecoration(
                  color: returning ? _leaveGold.withOpacity(.045) : Colors.white,
                  borderRadius: BorderRadius.circular(11),
                  border: Border.all(color: returning ? _leaveGold.withOpacity(.45) : _leaveBorder),
                ),
                child: IntrinsicHeight(
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Container(
                        width: 4,
                        decoration: BoxDecoration(
                          color: returning ? _leaveGold : _leaveGreen,
                          borderRadius: const BorderRadius.only(topLeft: Radius.circular(10), bottomLeft: Radius.circular(10)),
                        ),
                      ),
                      const SizedBox(width: 9),
                      Padding(
                        padding: const EdgeInsets.symmetric(vertical: 10),
                        child: _OfficialVerificationQr(
                          verificationCode: _t(event['qr_token']),
                          leaveRef: leaveRef,
                          applicantName: applicantName,
                          action: action,
                          name: _t(event['actor_name'], 'Authorised Officer'),
                          subtitle: _t(event['actor_position'], fromStage),
                          campus: _t(event['actor_campus']),
                          timestamp: _t(event['signed_at']),
                          compact: true,
                        ),
                      ),
                      const SizedBox(width: 9),
                      Expanded(
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(0, 9, 10, 9),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Wrap(
                                spacing: 6,
                                runSpacing: 4,
                                crossAxisAlignment: WrapCrossAlignment.center,
                                children: [
                                  Container(
                                    padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 4),
                                    decoration: BoxDecoration(
                                      color: returning ? _leaveGold.withOpacity(.10) : _leaveGreen.withOpacity(.08),
                                      borderRadius: BorderRadius.circular(99),
                                    ),
                                    child: Text(
                                      index == 0 ? '1 • FIRST RECORDED ACTION' : '${index + 1} • ${returning ? 'RETURN TO EARLIER OFFICE' : 'NEXT ACTION'}',
                                      style: TextStyle(color: returning ? _leaveGold : _leaveGreen, fontSize: 7.4, fontWeight: FontWeight.w900),
                                    ),
                                  ),
                                  Text(routeText, style: const TextStyle(color: _leaveInk, fontSize: 9.8, fontWeight: FontWeight.w900)),
                                ],
                              ),
                              const SizedBox(height: 5),
                              Text(
                                '${_t(event['actor_name'], 'Authorised Officer')} • ${_t(event['actor_position'], _stageLabel(fromStage))}',
                                style: const TextStyle(color: _leaveInk, fontSize: 10.4, fontWeight: FontWeight.w800),
                              ),
                              const SizedBox(height: 2),
                              Text(
                                '${returning ? '↩' : '→'} $action${_t(event['to_label']).isNotEmpty ? ' • ${_t(event['to_label'])}' : ''}',
                                style: TextStyle(color: returning ? _leaveGold : _leaveGreen, fontSize: 9.2, fontWeight: FontWeight.w800),
                              ),
                              if (remarks.isNotEmpty) ...[
                                const SizedBox(height: 5),
                                Text(remarks, style: const TextStyle(color: _leaveMuted, fontSize: 9.5, height: 1.35)),
                              ],
                              const SizedBox(height: 4),
                              Text(_t(event['signed_at']), style: const TextStyle(color: _leaveMuted, fontSize: 8.5)),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              )),
            ],
          ),
        );
      }),
    );
  }
}

class _RouteJourneyConnector extends StatelessWidget {
  const _RouteJourneyConnector();
  @override
  Widget build(BuildContext context) => const Padding(
    padding: EdgeInsets.only(right: 6),
    child: SizedBox(width: 48, height: 52, child: CustomPaint(painter: _ElbowArrowPainter())),
  );
}

// Solid down-then-right arrow, matching the supplied orange reference.
class _ElbowArrowPainter extends CustomPainter {
  const _ElbowArrowPainter();
  @override
  void paint(Canvas canvas, Size size) {
    final path = Path()
      ..moveTo(size.width * .20, 0)
      ..lineTo(size.width * .38, 0)
      ..lineTo(size.width * .38, size.height * .66)
      ..lineTo(size.width * .72, size.height * .66)
      ..lineTo(size.width * .72, size.height * .49)
      ..lineTo(size.width, size.height * .75)
      ..lineTo(size.width * .72, size.height)
      ..lineTo(size.width * .72, size.height * .83)
      ..lineTo(size.width * .20, size.height * .83)
      ..close();
    canvas.drawPath(path, Paint()..color = const Color(0xFFEF6C00));
  }
  @override
  bool shouldRepaint(covariant _ElbowArrowPainter oldDelegate) => false;
}

class _LeaveRouteStrip extends StatefulWidget {
  const _LeaveRouteStrip();
  @override
  State<_LeaveRouteStrip> createState() => _LeaveRouteStripState();
}

class _LeaveRouteStripState extends State<_LeaveRouteStrip> {
  final _controller = ScrollController();
  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    const steps = [
      ('STAFF','ORIGIN'),
      ('HOD','DEPT + CAMPUS'),
      ('JUNIOR HR','CAMPUS'),
      ('REGISTRAR','CAMPUS'),
      ('SENIOR HR','HQ'),
      ('DVC1','HQ'),
    ];
    return Container(
      padding: const EdgeInsets.fromLTRB(10, 10, 10, 5),
      decoration: BoxDecoration(color: _leaveSurface, borderRadius: BorderRadius.circular(12), border: Border.all(color: _leaveBorder)),
      child: Scrollbar(
        controller: _controller,
        thumbVisibility: true,
        trackVisibility: true,
        scrollbarOrientation: ScrollbarOrientation.bottom,
        child: SingleChildScrollView(
          controller: _controller,
          scrollDirection: Axis.horizontal,
          padding: const EdgeInsets.only(bottom: 12),
          child: Row(
            children: List.generate(steps.length, (i) {
              final s = steps[i];
              return Row(
                children: [
                  Container(
                    width: 100,
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 9),
                    decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(10), border: Border.all(color: _leaveBorder)),
                    child: Column(
                      children: [
                        Text(s.$1, textAlign: TextAlign.center, style: const TextStyle(color: _leaveInk, fontSize: 9.5, fontWeight: FontWeight.w900)),
                        const SizedBox(height: 2),
                        Text(s.$2, textAlign: TextAlign.center, style: const TextStyle(color: _leaveMuted, fontSize: 7.5, fontWeight: FontWeight.w800)),
                      ],
                    ),
                  ),
                  if (i < steps.length - 1)
                    const Padding(padding: EdgeInsets.symmetric(horizontal: 5), child: SizedBox(width: 32, height: 34, child: CustomPaint(painter: _ElbowArrowPainter()))),
                ],
              );
            }),
          ),
        ),
      ),
    );
  }
}

class _BalanceTable extends StatelessWidget {
  final Map<String, dynamic> row;
  const _BalanceTable({required this.row});
  String _t(dynamic v, [String f = '—']) {
    final s = v?.toString().trim() ?? '';
    return s.isEmpty || s.toLowerCase() == 'null' ? f : s;
  }
  @override
  Widget build(BuildContext context) {
    final values = [
      ('AVAILABLE DAYS', _t(row['available_days'])),
      ('PREVIOUSLY TAKEN', _t(row['previously_taken_days'])),
      ('ACCRUAL / MONTH', _t(row['accrual_rate_month'], '2.00')),
      ('DAYS APPLIED FOR', _t(row['requested_days'])),
      ('CLOSING BALANCE', _t(row['closing_balance'])),
    ];
    return LayoutBuilder(
      builder: (_, c) {
        if (c.maxWidth < 540) {
          return Column(children: values.map((e) => Container(width: double.infinity, padding: const EdgeInsets.all(10), decoration: const BoxDecoration(border: Border(bottom: BorderSide(color: _leaveBorder))), child: Row(children:[Expanded(child: Text(e.$1, style: const TextStyle(fontSize:9.5,fontWeight:FontWeight.w900))),Text(e.$2, style: const TextStyle(fontWeight:FontWeight.w900))]))).toList());
        }
        return Table(
          border: TableBorder.all(color: _leaveBorder),
          children: [
            TableRow(
              children: values
                  .map(
                    (e) => Container(
                      color: _leaveSurface,
                      padding: const EdgeInsets.all(9),
                      child: Text(
                        e.$1,
                        style: const TextStyle(
                          fontSize: 8.8,
                          fontWeight: FontWeight.w900,
                        ),
                      ),
                    ),
                  )
                  .toList(),
            ),
            TableRow(
              children: values
                  .map(
                    (e) => Padding(
                      padding: const EdgeInsets.all(10),
                      child: Text(
                        e.$2,
                        textAlign: TextAlign.center,
                        style: const TextStyle(
                          color: _leaveInk,
                          fontWeight: FontWeight.w900,
                        ),
                      ),
                    ),
                  )
                  .toList(),
            ),
          ],
        );
      },
    );
  }
}

class _OfficialVerificationQr extends StatelessWidget {
  final String verificationCode;
  final String leaveRef;
  final String applicantName;
  final String action;
  final String name;
  final String subtitle;
  final String campus;
  final String timestamp;
  final bool compact;

  const _OfficialVerificationQr({
    required this.verificationCode,
    required this.leaveRef,
    required this.applicantName,
    required this.action,
    required this.name,
    required this.subtitle,
    required this.campus,
    required this.timestamp,
    this.compact = false,
  });

  String _oneLine(String value) => value
      .replaceAll(RegExp(r'[\r\n]+'), ' ')
      .replaceAll(RegExp(r'\s{2,}'), ' ')
      .trim();

  String _buildQrPayload() {
    final code = _oneLine(verificationCode);
    final lines = <String>[
      'ROCKVIEW UNIVERSITY',
      'OFFICIAL LEAVE WORKFLOW RECORD',
      'LEAVE REFERENCE: ${_oneLine(leaveRef)}',
      'EMPLOYEE: ${_oneLine(applicantName)}',
      'ACTION: ${_oneLine(action)}',
      'AUTHENTICATED PERSON: ${_oneLine(name)}',
      'POSITION: ${_oneLine(subtitle)}',
      if (_oneLine(campus).isNotEmpty) 'CAMPUS: ${_oneLine(campus)}',
      'DATE / TIME: ${_oneLine(timestamp)}',
      'VERIFICATION CODE: ${code.isEmpty ? 'PENDING' : code}',
    ];
    return lines.join('\n');
  }

  void _open(BuildContext context) {
    if (verificationCode.trim().isEmpty) return;
    final payload = _buildQrPayload();
    showDialog<void>(
      context: context,
      barrierDismissible: true,
      builder: (_) => _QrRevealDialog(
        payload: payload,
        verificationCode: verificationCode,
        leaveRef: leaveRef,
        applicantName: applicantName,
        action: action,
        name: name,
        subtitle: subtitle,
        campus: campus,
        timestamp: timestamp,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final valid = verificationCode.trim().isNotEmpty;
    final label = valid ? 'CLICK TO SCAN' : 'QR PENDING';

    if (compact) {
      return Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: valid ? () => _open(context) : null,
          borderRadius: BorderRadius.circular(10),
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
            decoration: BoxDecoration(
              color: valid ? _leaveGreen.withOpacity(.06) : _leaveSurface,
              borderRadius: BorderRadius.circular(10),
              border: Border.all(
                color: valid ? _leaveGreen.withOpacity(.28) : _leaveBorder,
              ),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(
                  Icons.qr_code_scanner_rounded,
                  size: 18,
                  color: valid ? _leaveGreen : _leaveMuted,
                ),
                const SizedBox(width: 7),
                Text(
                  label,
                  style: TextStyle(
                    color: valid ? _leaveGreen : _leaveMuted,
                    fontSize: 10.8,
                    fontWeight: FontWeight.w900,
                    letterSpacing: .35,
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    }

    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: valid ? () => _open(context) : null,
        borderRadius: BorderRadius.circular(12),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 12),
          decoration: BoxDecoration(
            color: _leaveGreen.withOpacity(.04),
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: _leaveGreen.withOpacity(.22)),
          ),
          child: Row(
            children: [
              Container(
                width: 38,
                height: 38,
                decoration: BoxDecoration(
                  color: _leaveGreen.withOpacity(.09),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: const Icon(
                  Icons.qr_code_scanner_rounded,
                  color: _leaveGreen,
                  size: 22,
                ),
              ),
              const SizedBox(width: 11),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      name,
                      style: const TextStyle(
                        color: _leaveInk,
                        fontSize: 12.2,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                    const SizedBox(height: 3),
                    Text(
                      '$subtitle${campus.trim().isEmpty ? '' : ' • $campus'} • $timestamp',
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(
                        color: _leaveMuted,
                        fontSize: 10.2,
                        height: 1.3,
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 9),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
                decoration: BoxDecoration(
                  color: valid ? _leaveGreen : _leaveMuted.withOpacity(.16),
                  borderRadius: BorderRadius.circular(9),
                ),
                child: Text(
                  label,
                  style: TextStyle(
                    color: valid ? Colors.white : _leaveMuted,
                    fontSize: 10.6,
                    fontWeight: FontWeight.w900,
                    letterSpacing: .25,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _QrRevealDialog extends StatefulWidget {
  final String payload;
  final String verificationCode;
  final String leaveRef;
  final String applicantName;
  final String action;
  final String name;
  final String subtitle;
  final String campus;
  final String timestamp;

  const _QrRevealDialog({
    required this.payload,
    required this.verificationCode,
    required this.leaveRef,
    required this.applicantName,
    required this.action,
    required this.name,
    required this.subtitle,
    required this.campus,
    required this.timestamp,
  });

  @override
  State<_QrRevealDialog> createState() => _QrRevealDialogState();
}

class _QrRevealDialogState extends State<_QrRevealDialog> {
  Widget _detailRow(String label, String value) => Padding(
    padding: const EdgeInsets.symmetric(vertical: 4),
    child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Text(label, style: const TextStyle(color: _leaveMuted, fontSize: 10)),
      const SizedBox(height: 2),
      SelectableText(value.trim().isEmpty ? '—' : value.trim(),
        style: const TextStyle(color: _leaveInk, fontSize: 11, height: 1.3)),
    ]),
  );

  @override
  Widget build(BuildContext context) {
    final screen = MediaQuery.sizeOf(context);
    return Dialog(
      backgroundColor: Colors.white,
      insetPadding: const EdgeInsets.all(16),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: 340, maxHeight: screen.height * .85),
        child: SingleChildScrollView(
          padding: const EdgeInsets.fromLTRB(18, 10, 18, 16),
          child: Column(mainAxisSize: MainAxisSize.min, children: [
            Row(children: [
              const Icon(Icons.verified_outlined, color: _leaveGreen, size: 20),
              const SizedBox(width: 8),
              const Expanded(child: Text('LEAVE VERIFICATION',
                style: TextStyle(color: _leaveGreen, fontSize: 12, fontWeight: FontWeight.w800))),
              IconButton(tooltip: 'Close', visualDensity: VisualDensity.compact,
                onPressed: () => Navigator.pop(context),
                icon: const Icon(Icons.close_rounded, size: 20)),
            ]),
            const Divider(height: 12, color: _leaveBorder),
            const SizedBox(height: 8),
            LayoutBuilder(builder: (context, constraints) => QrImageView(
              data: widget.payload,
              version: QrVersions.auto,
              size: constraints.maxWidth < 220 ? constraints.maxWidth : 220,
              padding: const EdgeInsets.all(12),
              gapless: true,
              backgroundColor: Colors.white,
              errorCorrectionLevel: QrErrorCorrectLevel.M,
              eyeStyle: const QrEyeStyle(eyeShape: QrEyeShape.square, color: Colors.black),
              dataModuleStyle: const QrDataModuleStyle(dataModuleShape: QrDataModuleShape.square, color: Colors.black),
            )),
            const SizedBox(height: 8),
            Text(widget.applicantName, textAlign: TextAlign.center,
              style: const TextStyle(color: _leaveInk, fontSize: 13, fontWeight: FontWeight.w800)),
            const SizedBox(height: 4),
            Text('${widget.leaveRef} • ${widget.action}', textAlign: TextAlign.center,
              style: const TextStyle(color: _leaveGreen, fontSize: 11, fontWeight: FontWeight.w700)),
            const SizedBox(height: 6),
            const Text('Scan to view the official verification record.', textAlign: TextAlign.center,
              style: TextStyle(color: _leaveMuted, fontSize: 10, height: 1.4)),
            const SizedBox(height: 8),
            ExpansionTile(
              tilePadding: EdgeInsets.zero,
              childrenPadding: const EdgeInsets.only(bottom: 4),
              title: const Text('Record details', style: TextStyle(fontSize: 11, color: _leaveInk, fontWeight: FontWeight.w700)),
              children: [
                Align(alignment: Alignment.centerLeft, child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    _detailRow('Processed by', widget.name),
                    _detailRow('Position', widget.subtitle),
                    _detailRow('Campus', widget.campus),
                    _detailRow('Date / time', widget.timestamp),
                    _detailRow('Verification code', widget.verificationCode),
                  ],
                )),
              ],
            ),
          ]),
        ),
      ),
    );
  }
}

class _DialogHeader extends StatelessWidget {
  final String title;
  final String subtitle;
  final VoidCallback? onClose;
  const _DialogHeader({required this.title,required this.subtitle,required this.onClose});
  @override Widget build(BuildContext context)=>Container(
    padding:const EdgeInsets.fromLTRB(12,9,8,9),
    decoration:const BoxDecoration(color:Colors.white,border:Border(top:BorderSide(color:_leaveGreen,width:3),bottom:BorderSide(color:_leaveBorder))),
    child:Row(children:[
      Container(width:31,height:31,decoration:BoxDecoration(color:_leaveGreen.withOpacity(.08),borderRadius:BorderRadius.circular(8)),child:const Icon(Icons.event_note_rounded,color:_leaveGreen,size:18)),
      const SizedBox(width:9),
      Expanded(child:Column(crossAxisAlignment:CrossAxisAlignment.start,children:[Text(title,style:const TextStyle(color:_leaveInk,fontSize:12.3,fontWeight:FontWeight.w900,letterSpacing:.25)),const SizedBox(height:1),Text(subtitle,maxLines:1,overflow:TextOverflow.ellipsis,style:const TextStyle(color:_leaveMuted,fontSize:8.8))])),
      IconButton(visualDensity:VisualDensity.compact,onPressed:onClose,icon:const Icon(Icons.close_rounded,color:_leaveMuted,size:19)),
    ]),
  );
}

class _DialogFooter extends StatelessWidget {
  final bool busy;
  final String cancelLabel;
  final String actionLabel;
  final VoidCallback onCancel;
  final VoidCallback onAction;
  const _DialogFooter({required this.busy, required this.cancelLabel, required this.actionLabel, required this.onCancel, required this.onAction});
  @override
  Widget build(BuildContext context) => Container(
        padding: const EdgeInsets.all(12),
        decoration: const BoxDecoration(color: Colors.white, border: Border(top: BorderSide(color: _leaveBorder))),
        child: Wrap(
          alignment: WrapAlignment.end,
          spacing: 8,
          runSpacing: 8,
          children: [
            OutlinedButton(onPressed: busy ? null : onCancel, child: Text(cancelLabel)),
            ElevatedButton.icon(
              onPressed: busy ? null : onAction,
              icon: busy ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white)) : const Icon(Icons.send_rounded),
              label: Text(busy ? 'SUBMITTING...' : actionLabel, style: const TextStyle(fontWeight: FontWeight.w900)),
              style: ElevatedButton.styleFrom(backgroundColor: _leaveGold, foregroundColor: Colors.white, elevation: 0),
            ),
          ],
        ),
      );
}

class _Section extends StatelessWidget {
  final IconData icon;
  final String title;
  final String subtitle;
  final Widget child;
  const _Section({required this.icon, required this.title, required this.subtitle, required this.child});
  @override
  Widget build(BuildContext context) => Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(16), border: Border.all(color: _leaveBorder)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(children: [Container(width: 38,height:38,decoration:BoxDecoration(color:_leaveGreen.withOpacity(.08),borderRadius:BorderRadius.circular(11)),child:Icon(icon,color:_leaveGreen,size:20)),const SizedBox(width:10),Expanded(child:Column(crossAxisAlignment:CrossAxisAlignment.start,children:[Text(title,style:const TextStyle(color:_leaveInk,fontSize:13,fontWeight:FontWeight.w900)),const SizedBox(height:2),Text(subtitle,style:const TextStyle(color:_leaveMuted,fontSize:10.5,height:1.3))]))]),
            const SizedBox(height: 14),
            child,
          ],
        ),
      );
}

class _Field extends StatelessWidget {
  final TextEditingController controller;
  final String label;
  final IconData icon;
  final int maxLines;
  final bool isRequired;
  const _Field({required this.controller, required this.label, required this.icon, this.maxLines = 1, this.isRequired = true});
  @override
  Widget build(BuildContext context) => TextFormField(
        controller: controller,
        maxLines: maxLines,
        validator: isRequired ? (v) => (v == null || v.trim().isEmpty) ? '$label is required' : null : null,
        decoration: _input(label, icon),
      );
}

InputDecoration _input(String label, IconData icon) => InputDecoration(
      labelText: label,
      prefixIcon: Icon(icon, color: _leaveGreen, size: 19),
      filled: true,
      fillColor: _leaveSurface,
      contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 13),
      border: OutlineInputBorder(borderRadius: BorderRadius.circular(11), borderSide: const BorderSide(color: _leaveBorder)),
      enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(11), borderSide: const BorderSide(color: _leaveBorder)),
      focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(11), borderSide: const BorderSide(color: _leaveGreen, width: 1.5)),
    );

class _ResponsiveFields extends StatelessWidget {
  final List<Widget> children;
  const _ResponsiveFields({required this.children});
  @override
  Widget build(BuildContext context) => LayoutBuilder(
        builder: (_, c) {
          if (c.maxWidth < 620) return Column(children: [for (int i=0;i<children.length;i++) Padding(padding: EdgeInsets.only(bottom: i == children.length-1 ? 0 : 10), child: children[i])]);
          return Wrap(
            spacing: 10,
            runSpacing: 10,
            children: [for (final child in children) SizedBox(width: (c.maxWidth - 10) / 2, child: child)],
          );
        },
      );
}

class _InfoGrid extends StatelessWidget {
  final List<(String,String)> items;
  const _InfoGrid({required this.items});
  @override
  Widget build(BuildContext context) => LayoutBuilder(builder: (_, c) {
        final width = c.maxWidth < 620 ? c.maxWidth : (c.maxWidth - 10) / 2;
        return Wrap(spacing: 10, runSpacing: 10, children: items.map((e) => SizedBox(width: width, child: Container(padding: const EdgeInsets.all(12), decoration: BoxDecoration(color:_leaveSurface,borderRadius:BorderRadius.circular(11),border:Border.all(color:_leaveBorder)), child: Column(crossAxisAlignment:CrossAxisAlignment.start,children:[Text(e.$1,style:const TextStyle(color:_leaveMuted,fontSize:8.8,fontWeight:FontWeight.w900)),const SizedBox(height:4),Text(e.$2.isEmpty?'Not assigned':e.$2,style:const TextStyle(color:_leaveInk,fontSize:11.5,fontWeight:FontWeight.w800))])))).toList());
      });
}

class _DateGrid extends StatelessWidget {
  final String start;
  final String end;
  final String back;
  final int days;
  final VoidCallback onStart;
  final VoidCallback onEnd;
  final VoidCallback onReturn;
  const _DateGrid({required this.start,required this.end,required this.back,required this.days,required this.onStart,required this.onEnd,required this.onReturn});
  @override
  Widget build(BuildContext context) {
    final cards = [
      _DateCard(label:'START DATE',value:start,onTap:onStart),
      _DateCard(label:'END DATE',value:end,onTap:onEnd),
      _DateCard(label:'RETURN TO DUTY',value:back,onTap:onReturn),
      _DateCard(label:'DAYS APPLIED',value:'$days',onTap:null),
    ];
    return LayoutBuilder(builder:(_,c){final w=c.maxWidth<620?c.maxWidth:(c.maxWidth-10)/2;return Wrap(spacing:10,runSpacing:10,children:cards.map((e)=>SizedBox(width:w,child:e)).toList());});
  }
}

class _DateCard extends StatelessWidget {
  final String label;
  final String value;
  final VoidCallback? onTap;
  const _DateCard({required this.label,required this.value,required this.onTap});
  @override
  Widget build(BuildContext context) => InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(11),
        child: Container(padding:const EdgeInsets.all(12),decoration:BoxDecoration(color:_leaveSurface,borderRadius:BorderRadius.circular(11),border:Border.all(color:_leaveBorder)),child:Row(children:[const Icon(Icons.calendar_today_outlined,color:_leaveGreen,size:18),const SizedBox(width:10),Expanded(child:Column(crossAxisAlignment:CrossAxisAlignment.start,children:[Text(label,style:const TextStyle(color:_leaveMuted,fontSize:8.8,fontWeight:FontWeight.w900)),const SizedBox(height:3),Text(value,style:const TextStyle(color:_leaveInk,fontSize:11.5,fontWeight:FontWeight.w800))]))])),
      );
}

class _DocumentGrid extends StatelessWidget {
  final List<(String, String)> items;
  const _DocumentGrid({required this.items});
  @override
  Widget build(BuildContext context) => LayoutBuilder(builder: (context, constraints) {
    final columns = constraints.maxWidth >= 480 ? 2 : 1;
    final width = (constraints.maxWidth - (columns - 1) * 12) / columns;
    return Wrap(spacing: 12, runSpacing: 12, children: [
      for (final item in items)
        SizedBox(width: width, child: Container(
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(color: _leaveSurface, border: Border.all(color: _leaveBorder), borderRadius: BorderRadius.circular(6)),
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Text(item.$1, style: const TextStyle(color: _leaveMuted, fontSize: 9, fontWeight: FontWeight.w800, letterSpacing: .3)),
            const SizedBox(height: 6),
            Text(item.$2.isEmpty ? '—' : item.$2, style: const TextStyle(color: _leaveInk, fontSize: 12, height: 1.4, fontWeight: FontWeight.w600)),
          ]),
        )),
    ]);
  });
}

class _DocHeading extends StatelessWidget {
  final String text;
  const _DocHeading(this.text);
  @override
  Widget build(BuildContext context) => Container(
    width: double.infinity,
    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
    decoration: const BoxDecoration(color: _sheetBandSoft, border: Border(left: BorderSide(color: _leaveGreen, width: 3))),
    child: Text(text, style: const TextStyle(color: _leaveGreen, fontSize: 10.5, fontWeight: FontWeight.w900, letterSpacing: .4)),
  );
}

class _InlineError extends StatelessWidget {
  final String message;
  const _InlineError(this.message);
  @override
  Widget build(BuildContext context) => Container(margin:const EdgeInsets.only(bottom:14),padding:const EdgeInsets.all(12),decoration:BoxDecoration(color:const Color(0xFFFFF1F0),borderRadius:BorderRadius.circular(11),border:Border.all(color:const Color(0xFFF1B9B3))),child:Text(message,style:const TextStyle(color:Color(0xFFA7352C),fontSize:11.2,height:1.4)));
}

class _ErrorPanel extends StatelessWidget {
  final String message;
  final VoidCallback onRetry;
  const _ErrorPanel({required this.message, required this.onRetry});
  @override
  Widget build(BuildContext context) => Center(child:Container(constraints:const BoxConstraints(maxWidth:560),margin:const EdgeInsets.all(20),padding:const EdgeInsets.all(24),decoration:BoxDecoration(color:Colors.white,borderRadius:BorderRadius.circular(16),border:Border.all(color:_leaveBorder)),child:Column(mainAxisSize:MainAxisSize.min,children:[const Icon(Icons.error_outline_rounded,color:Colors.redAccent,size:42),const SizedBox(height:10),const Text('Unable to load leave management',style:TextStyle(color:_leaveInk,fontWeight:FontWeight.w900)),const SizedBox(height:8),Text(message,textAlign:TextAlign.center,style:const TextStyle(color:_leaveMuted,height:1.4)),const SizedBox(height:14),ElevatedButton.icon(onPressed:onRetry,icon:const Icon(Icons.refresh_rounded),label:const Text('RETRY'),style:ElevatedButton.styleFrom(backgroundColor:_leaveGreen,foregroundColor:Colors.white))])));
}

class _LeaveNotificationsDialog extends StatefulWidget {
  final ValueChanged<int> onOpenLeave;
  const _LeaveNotificationsDialog({required this.onOpenLeave});
  @override
  State<_LeaveNotificationsDialog> createState() => _LeaveNotificationsDialogState();
}

class _LeaveNotificationsDialogState extends State<_LeaveNotificationsDialog> {
  bool _loading = true;
  List<Map<String, dynamic>> _items = [];
  String? _error;

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

  Future<void> _load() async {
    try {
      final rows = await LeaveService.notifications();
      if (!mounted) return;
      setState(() {
        _items = rows;
        _loading = false;
        _error = null;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _error = LeaveService.cleanError(e);
        _loading = false;
      });
    }
  }

  bool _read(dynamic value) =>
      value == true || value == 1 || value == '1' || value == 'true' || value == 't';

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
      child: ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 620, maxHeight: 680),
        child: Column(
          children: [
            _DialogHeader(
              title: 'LEAVE NOTIFICATIONS',
              subtitle: 'Routing, returns and final decisions',
              onClose: () => Navigator.pop(context),
            ),
            Expanded(
              child: _loading
                  ? const Center(
                      child: CircularProgressIndicator(color: _leaveGreen),
                    )
                  : _error != null
                      ? Center(child: Text(_error!))
                      : _items.isEmpty
                          ? const Center(
                              child: Text(
                                'No leave notifications yet.',
                                style: TextStyle(color: _leaveMuted),
                              ),
                            )
                          : ListView.separated(
                              padding: const EdgeInsets.all(12),
                              itemCount: _items.length,
                              separatorBuilder: (_, __) => const SizedBox(height: 8),
                              itemBuilder: (_, i) {
                                final item = _items[i];
                                final read = _read(item['is_read']);
                                return ListTile(
                                  tileColor: read
                                      ? Colors.white
                                      : _leaveGreen.withOpacity(.05),
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(12),
                                    side: const BorderSide(color: _leaveBorder),
                                  ),
                                  leading: Icon(
                                    read
                                        ? Icons.notifications_none
                                        : Icons.notifications_active,
                                    color: read ? _leaveMuted : _leaveGold,
                                  ),
                                  title: Text(
                                    '${item['title'] ?? ''}',
                                    style: const TextStyle(
                                      fontWeight: FontWeight.w900,
                                      fontSize: 11.5,
                                    ),
                                  ),
                                  subtitle: Text(
                                    '${item['body'] ?? ''}',
                                    maxLines: 3,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                  onTap: () async {
                                    final notificationId =
                                        int.tryParse('${item['id'] ?? 0}') ?? 0;
                                    final leaveId =
                                        int.tryParse('${item['leave_id'] ?? 0}') ?? 0;
                                    if (!read && notificationId > 0) {
                                      await LeaveService.markNotificationRead(
                                        notificationId,
                                      );
                                    }
                                    if (leaveId > 0) widget.onOpenLeave(leaveId);
                                  },
                                );
                              },
                            ),
            ),
            Container(
              padding: const EdgeInsets.all(10),
              child: Align(
                alignment: Alignment.centerRight,
                child: TextButton(
                  onPressed: () async {
                    await LeaveService.markAllNotificationsRead();
                    await _load();
                  },
                  child: const Text('MARK ALL READ'),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
