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

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

const _green = Color(0xFF026930);
const _gold = Color(0xFFCC7504);
const _ink = Color(0xFF1E2A24);
const _muted = Color(0xFF6E7973);
const _line = Color(0xFFDDE5E0);
const _page = Color(0xFFF3F6F4);

const _sections = <String, String>{
  'education': 'Education',
  'experience': 'Employment & Experience',
  'certification': 'Certifications',
  'project': 'Selected Projects',
  'skill': 'Skills & Competencies',
  'referee': 'Professional Referees',
};
const _fields = <String, Map<String, String>>{
  'education': {'qualification':'Qualification / award','institution':'Institution','start_year':'From year','end_year':'To year','details':'Focus or achievement'},
  'experience': {'position':'Position / job title','employer':'Employer / organization','start_date':'From','end_date':'To','responsibilities':'Responsibilities and achievements'},
  'certification': {'name':'Certificate / professional membership','issuer':'Issuing organization','date':'Date / year','details':'Description'},
  'project': {'title':'Project title','role':'Your role','year':'Year','description':'Summary and outcome'},
  'skill': {'name':'Skill or competency','level':'Proficiency (optional)','category':'Area (optional)'},
  'referee': {'name':'Full name','title':'Title / relationship','organization':'Organization','email':'Email','phone':'Phone'},
};

class CvMainTab extends StatefulWidget {
  const CvMainTab({super.key});
  @override
  State<CvMainTab> createState() => _CvMainTabState();
}

class _CvMainTabState extends State<CvMainTab> {
  bool _loading = true;
  bool _admin = false;
  String? _error;
  int _tab = 0;
  Map<String, dynamic> _mine = {};
  List<Map<String, dynamic>> _directory = [];
  String _search = '';
  final _searchController = TextEditingController();

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

  Future<void> _load() async {
    setState(() { _loading = true; _error = null; });
    try {
      final mine = await CvService.mine();
      final admin = '${mine['role'] ?? ''}'.toLowerCase() == 'admin';
      final directory = admin ? await CvService.directory(search: _search) : <Map<String, dynamic>>[];
      if (!mounted) return;
      setState(() { _mine = mine; _admin = admin; _directory = directory; _loading = false; });
    } catch (e) {
      if (!mounted) return;
      setState(() { _error = CvService.cleanError(e); _loading = false; });
    }
  }

  Future<void> _searchDirectory(String value) async {
    _search = value;
    try {
      final rows = await CvService.directory(search: value);
      if (mounted) setState(() => _directory = rows);
    } catch (_) {}
  }

  Future<void> _editMine() async {
    final saved = await showDialog<bool>(
      context: context, barrierDismissible: false,
      builder: (_) => CvEditorDialog(cv: _mine),
    );
    if (saved == true) await _load();
  }

  Future<void> _openPerson(Map<String, dynamic> row) async {
    final id = int.tryParse('${row['user_id'] ?? 0}') ?? 0;
    try {
      final cv = id == int.tryParse('${_mine['user_id'] ?? 0}') ? _mine : await CvService.getCv(id);
      if (!mounted) return;
      await showDialog<void>(context: context, builder: (_) => CvPreviewDialog(cv: cv));
    } catch (e) {
      if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(CvService.cleanError(e))));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: _page,
      body: SafeArea(child: _loading
          ? const Center(child: CircularProgressIndicator(color: _green))
          : _error != null
              ? _ErrorBox(message: _error!, retry: _load)
              : Column(children: [
                  _CvHeader(onRefresh: _load),
                  if (_admin) _TopTabs(index: _tab, onSelect: (v) => setState(() => _tab = v)),
                  Expanded(child: _admin && _tab == 1 ? _directoryView() : _myView()),
                ])),
    );
  }

  Widget _myView() => LayoutBuilder(builder: (context, box) {
    final wide = box.maxWidth > 900;
    return SingleChildScrollView(padding: const EdgeInsets.all(22), child: Center(
      child: ConstrainedBox(constraints: const BoxConstraints(maxWidth: 1180), child: Column(
        crossAxisAlignment: CrossAxisAlignment.start, children: [
          Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Text(_admin ? 'My professional CV' : 'My professional CV', style: const TextStyle(color: _ink, fontSize: 26, fontWeight: FontWeight.w900)),
              const SizedBox(height: 6), const Text('Keep your experience and qualifications current. Changes are saved securely to your account.', style: TextStyle(color: _muted, height: 1.45)),
            ])),
            const SizedBox(width: 12),
            FilledButton.icon(onPressed: _editMine, icon: const Icon(Icons.edit_rounded), label: const Text('Edit my CV'), style: FilledButton.styleFrom(backgroundColor: _green, padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 15))),
          ]),
          const SizedBox(height: 20),
          if (wide) Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Expanded(flex: 7, child: CvPaper(cv: _mine)),
            const SizedBox(width: 18), Expanded(flex: 3, child: _CompletenessCard(cv: _mine)),
          ]) else Column(children: [CvPaper(cv: _mine), const SizedBox(height: 16), _CompletenessCard(cv: _mine)]),
        ],
      )),
    ));
  });

  Widget _directoryView() => Column(children: [
    Padding(padding: const EdgeInsets.fromLTRB(20, 18, 20, 12), child: LayoutBuilder(builder: (context, constraints) {
      final search = TextField(controller: _searchController, onChanged: _searchDirectory, decoration: InputDecoration(hintText: 'Search name, email or campus', prefixIcon: const Icon(Icons.search), filled: true, fillColor: Colors.white, border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _line)), enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _line))));
      final title = Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        const Text('Staff CV directory', style: TextStyle(color: _ink, fontSize: 24, fontWeight: FontWeight.w900)),
        const SizedBox(height: 4), Text('${_directory.length} staff and administrator profiles', style: const TextStyle(color: _muted)),
      ]);
      if (constraints.maxWidth < 700) return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [title, const SizedBox(height: 12), search]);
      return Row(children: [Expanded(child: title), const SizedBox(width: 18), SizedBox(width: 320, child: search)]);
    })),
    Expanded(child: _directory.isEmpty ? const Center(child: Text('No matching staff CVs found.', style: TextStyle(color: _muted))) : LayoutBuilder(builder: (context, box) {
      final columns = box.maxWidth > 1080 ? 3 : (box.maxWidth > 680 ? 2 : 1);
      return GridView.builder(padding: const EdgeInsets.fromLTRB(20, 0, 20, 24), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: columns, crossAxisSpacing: 14, mainAxisSpacing: 14, mainAxisExtent: 178), itemCount: _directory.length, itemBuilder: (context, i) {
        final row = _directory[i];
        return _DirectoryCard(row: row, onTap: () => _openPerson(row));
      });
    })),
  ]);
}

class CvEditorDialog extends StatefulWidget {
  final Map<String, dynamic> cv;
  const CvEditorDialog({super.key, required this.cv});
  @override
  State<CvEditorDialog> createState() => _CvEditorDialogState();
}

class _CvEditorDialogState extends State<CvEditorDialog> {
  final _formKey = GlobalKey<FormState>();
  final Map<String, TextEditingController> _profile = {};
  final Map<String, List<Map<String, dynamic>>> _entries = {};
  bool _saving = false;
  static const _profileFields = <String, String>{
    'professional_title':'Professional title / position','career_objective':'Career objective','professional_summary':'Professional profile / summary','phone':'Phone','contact_email':'Professional email','address':'City / postal address','photo_url':'Professional photograph URL (optional)','website':'Portfolio / website (optional)','linkedin_url':'LinkedIn profile (optional)','nationality':'Nationality (optional)','languages':'Languages',
  };

  @override
  void initState() {
    super.initState();
    for (final key in _profileFields.keys) {
      final existing = widget.cv[key];
      final fallback = key == 'contact_email' ? widget.cv['account_email'] : (key == 'photo_url' ? widget.cv['account_photo'] : null);
      _profile[key] = TextEditingController(text: '${existing ?? fallback ?? ''}');
    }
    final raw = widget.cv['entries'];
    for (final section in _sections.keys) {
      final list = raw is Map && raw[section] is List ? (raw[section] as List) : const [];
      _entries[section] = list.whereType<Map>().map((e) => e.map((k,v)=>MapEntry(k.toString(),v))).toList();
    }
  }

  @override
  void dispose() { for (final field in _profile.values) { field.dispose(); } super.dispose(); }

  Future<void> _addEntry(String section, {int? index}) async {
    final result = await showDialog<Map<String, String>>(
      context: context, builder: (_) => _EntryDialog(section: section, initial: index == null ? null : _entries[section]![index]),
    );
    if (result == null) return;
    setState(() {
      if (index == null) _entries[section]!.add(result); else _entries[section]![index] = result;
    });
  }

  Future<void> _save() async {
    if (!_formKey.currentState!.validate()) return;
    setState(() => _saving = true);
    try {
      await CvService.save({
        'profile': _profile.map((key, value) => MapEntry(key, value.text.trim())),
        'entries': _entries,
      });
      if (mounted) Navigator.pop(context, true);
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(CvService.cleanError(e)), backgroundColor: Colors.red.shade700));
      setState(() => _saving = false);
    }
  }

  @override
  Widget build(BuildContext context) => Dialog.fullscreen(child: Scaffold(
    backgroundColor: _page,
    appBar: AppBar(backgroundColor: _green, foregroundColor: Colors.white, title: const Text('Update my CV', style: TextStyle(fontWeight: FontWeight.w800)), actions: [TextButton.icon(onPressed: _saving ? null : _save, icon: const Icon(Icons.save_rounded, color: Colors.white), label: Text(_saving ? 'Saving…' : 'Save CV', style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w800))), const SizedBox(width: 8)]),
    body: Form(key: _formKey, child: ListView(padding: const EdgeInsets.all(18), children: [
      const _InfoBanner(text: 'Your CV can be edited whenever your role or experience changes. Only your account and authorized administrators can access it.'),
      const SizedBox(height: 14),
      _EditorPanel(title: 'Professional profile', subtitle: 'Use current contact details. Sensitive identity details are not required.', icon: Icons.badge_outlined, child: LayoutBuilder(builder: (context, box) {
        final cols = box.maxWidth > 740 ? 2 : 1;
        return Wrap(spacing: 14, runSpacing: 4, children: _profileFields.entries.map((entry) {
          final multiline = ['career_objective','professional_summary','address'].contains(entry.key);
          final w = cols == 2 && !multiline ? (box.maxWidth - 14) / 2 : box.maxWidth;
          return SizedBox(width: w, child: Padding(padding: const EdgeInsets.only(bottom: 8), child: TextFormField(
            controller: _profile[entry.key], maxLines: multiline ? 4 : 1,
            keyboardType: entry.key == 'contact_email' ? TextInputType.emailAddress : TextInputType.text,
            decoration: _inputDecoration(entry.value),
            validator: entry.key == 'professional_title' ? (v) => (v ?? '').trim().isEmpty ? 'Add your professional title.' : null : null,
          )));
        }).toList());
      })),
      for (final section in _sections.keys) ...[
        const SizedBox(height: 14),
        _EntrySectionEditor(title: _sections[section]!, section: section, rows: _entries[section]!, onAdd: () => _addEntry(section), onEdit: (i) => _addEntry(section, index: i), onDelete: (i) => setState(() => _entries[section]!.removeAt(i))),
      ],
      const SizedBox(height: 20),
      Align(alignment: Alignment.centerRight, child: FilledButton.icon(onPressed: _saving ? null : _save, icon: const Icon(Icons.save_rounded), label: Text(_saving ? 'Saving CV…' : 'Save all CV details'), style: FilledButton.styleFrom(backgroundColor: _green, padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16)))),
    ])),
  ));
}

class _EntryDialog extends StatefulWidget {
  final String section;
  final Map<String, dynamic>? initial;
  const _EntryDialog({required this.section, this.initial});
  @override
  State<_EntryDialog> createState() => _EntryDialogState();
}
class _EntryDialogState extends State<_EntryDialog> {
  final _key = GlobalKey<FormState>();
  final Map<String, TextEditingController> _controllers = {};
  @override
  void initState() { super.initState(); for (final field in _fields[widget.section]!.keys) { _controllers[field] = TextEditingController(text: '${widget.initial?[field] ?? ''}'); } }
  @override
  void dispose() { for (final c in _controllers.values) { c.dispose(); } super.dispose(); }
  @override
  Widget build(BuildContext context) => AlertDialog(
    title: Text(
      "${widget.initial == null ? 'Add' : 'Edit'} ${_sections[widget.section]}",
      style: const TextStyle(color: _ink, fontWeight: FontWeight.w800),
    ),
    content: SizedBox(
      width: 520,
      child: SingleChildScrollView(
        child: Form(
          key: _key,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: _fields[widget.section]!.entries.map((field) {
              final requiredField = ['name', 'qualification', 'position', 'title'].contains(field.key);
              final multiline = ['details', 'responsibilities', 'description'].contains(field.key);
              return Padding(
                padding: const EdgeInsets.only(bottom: 12),
                child: TextFormField(
                  controller: _controllers[field.key],
                  maxLines: multiline ? 3 : 1,
                  decoration: _inputDecoration(field.value),
                  validator: requiredField
                      ? (value) => (value ?? '').trim().isEmpty ? 'This field is required.' : null
                      : null,
                ),
              );
            }).toList(),
          ),
        ),
      ),
    ),
    actions: [
      TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancel')),
      FilledButton(
        onPressed: () {
          if (!_key.currentState!.validate()) return;
          Navigator.pop(context, _controllers.map((key, value) => MapEntry(key, value.text.trim())));
        },
        style: FilledButton.styleFrom(backgroundColor: _green),
        child: const Text('Save entry'),
      ),
    ],
  );
}

class _EntrySectionEditor extends StatelessWidget {
  final String title, section;
  final List<Map<String, dynamic>> rows;
  final VoidCallback onAdd;
  final ValueChanged<int> onEdit, onDelete;
  const _EntrySectionEditor({required this.title, required this.section, required this.rows, required this.onAdd, required this.onEdit, required this.onDelete});
  String _label(Map<String, dynamic> row) => '${row['qualification'] ?? row['position'] ?? row['name'] ?? row['title'] ?? 'Entry'}';
  String _sub(Map<String, dynamic> row) => '${row['institution'] ?? row['employer'] ?? row['issuer'] ?? row['organization'] ?? row['category'] ?? ''}';
  @override
  Widget build(BuildContext context) => _EditorPanel(
    title: title,
    subtitle: '${rows.length} ${rows.length == 1 ? 'entry' : 'entries'}',
    icon: _sectionIcon(section),
    trailing: TextButton.icon(onPressed: onAdd, icon: const Icon(Icons.add_rounded), label: const Text('Add')),
    child: rows.isEmpty
        ? const Text('No entries added yet.', style: TextStyle(color: _muted))
        : Column(
            children: List.generate(rows.length, (i) => ListTile(
              contentPadding: EdgeInsets.zero,
              leading: CircleAvatar(
                backgroundColor: const Color(0xFFE8F3ED),
                child: Icon(_sectionIcon(section), color: _green, size: 19),
              ),
              title: Text(_label(rows[i]), style: const TextStyle(fontWeight: FontWeight.w700)),
              subtitle: _sub(rows[i]).isEmpty ? null : Text(_sub(rows[i])),
              trailing: Wrap(children: [
                IconButton(onPressed: () => onEdit(i), icon: const Icon(Icons.edit_outlined)),
                IconButton(onPressed: () => onDelete(i), icon: const Icon(Icons.delete_outline_rounded, color: Colors.redAccent)),
              ]),
            )),
          ),
  );
}

class CvPaper extends StatelessWidget {
  final Map<String, dynamic> cv;
  const CvPaper({super.key, required this.cv});
  String _s(String key) => '${cv[key] ?? (key == 'photo_url' ? cv['account_photo'] : '') ?? ''}'.trim();
  Map<String, List<Map<String, dynamic>>> _entries() {
    final raw = cv['entries'];
    final result = <String, List<Map<String, dynamic>>>{};
    for (final section in _sections.keys) {
      final rows = raw is Map && raw[section] is List ? raw[section] as List : const [];
      result[section] = rows.whereType<Map>().map((e) => e.map((k,v)=>MapEntry(k.toString(),v))).toList();
    }
    return result;
  }
  @override
  Widget build(BuildContext context) {
    final name = _s('full_name').isNotEmpty ? _s('full_name') : 'Your name';
    final entries = _entries();
    return Container(width: double.infinity, padding: const EdgeInsets.all(26), decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(18), border: Border.all(color: _line), boxShadow: const [BoxShadow(color: Color(0x0B17221A), blurRadius: 18, offset: Offset(0, 6))]), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
        _Photo(url: _s('photo_url'), size: 90), const SizedBox(width: 18), Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text(name, style: const TextStyle(color: _ink, fontSize: 28, fontWeight: FontWeight.w900)),
          if (_s('professional_title').isNotEmpty) Padding(padding: const EdgeInsets.only(top: 5), child: Text(_s('professional_title'), style: const TextStyle(color: _green, fontSize: 16, fontWeight: FontWeight.w700))),
          const SizedBox(height: 10), Wrap(spacing: 14, runSpacing: 6, children: [if (_s('contact_email').isNotEmpty) _Contact(Icons.email_outlined, _s('contact_email')), if (_s('phone').isNotEmpty) _Contact(Icons.phone_outlined, _s('phone')), if (_s('address').isNotEmpty) _Contact(Icons.location_on_outlined, _s('address')), if (_s('website').isNotEmpty) _Contact(Icons.language_rounded, _s('website'))]),
        ])),
      ]),
      const SizedBox(height: 22),
      if (_s('professional_summary').isNotEmpty) _CvSection(title: 'PROFESSIONAL PROFILE', child: Text(_s('professional_summary'), style: const TextStyle(color: _ink, height: 1.6))),
      if (_s('career_objective').isNotEmpty) _CvSection(title: 'CAREER OBJECTIVE', child: Text(_s('career_objective'), style: const TextStyle(color: _ink, height: 1.6))),
      for (final section in _sections.keys) if (entries[section]!.isNotEmpty) _CvSection(title: _sections[section]!.toUpperCase(), child: Column(children: entries[section]!.map((row) => _CvEntry(section: section, row: row)).toList())),
      if (_s('languages').isNotEmpty) _CvSection(title: 'LANGUAGES', child: Text(_s('languages'), style: const TextStyle(color: _ink))),
      if (_s('nationality').isNotEmpty) _CvSection(title: 'ADDITIONAL INFORMATION', child: Text('Nationality: ${_s('nationality')}', style: const TextStyle(color: _ink))),
      const SizedBox(height: 8), const Divider(color: _line), const Text('ROCKVIEW UNIVERSITY  •  PROFESSIONAL PROFILE', style: TextStyle(color: _muted, fontSize: 10, letterSpacing: 1.1, fontWeight: FontWeight.w700)),
    ]));
  }
}

class CvPreviewDialog extends StatelessWidget {
  final Map<String, dynamic> cv;
  const CvPreviewDialog({super.key, required this.cv});
  @override
  Widget build(BuildContext context) => Dialog.fullscreen(child: Scaffold(backgroundColor: _page, appBar: AppBar(backgroundColor: _green, foregroundColor: Colors.white, title: Text('${cv['full_name'] ?? 'Staff'} — CV')), body: Center(child: ConstrainedBox(constraints: const BoxConstraints(maxWidth: 1180), child: SingleChildScrollView(padding: const EdgeInsets.all(18), child: CvPaper(cv: cv))))));
}

class _CvEntry extends StatelessWidget {
  final String section;
  final Map<String, dynamic> row;
  const _CvEntry({required this.section, required this.row});
  @override
  Widget build(BuildContext context) {
    final heading = row['qualification'] ?? row['position'] ?? row['name'] ?? row['title'] ?? '';
    final sub = row['institution'] ?? row['employer'] ?? row['issuer'] ?? row['organization'] ?? '';
    final date = [row['start_year'] ?? row['start_date'], row['end_year'] ?? row['end_date'] ?? row['date'] ?? row['year']].where((v) => v != null && '$v'.isNotEmpty).join(' — ');
    final details = row['details'] ?? row['responsibilities'] ?? row['description'] ?? row['level'] ?? '';
    return Padding(padding: const EdgeInsets.only(bottom: 13), child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [const Padding(padding: EdgeInsets.only(top: 6), child: Icon(Icons.circle, size: 7, color: _gold)), const SizedBox(width: 10), Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Row(children: [Expanded(child: Text('$heading', style: const TextStyle(color: _ink, fontWeight: FontWeight.w800))), if (date.isNotEmpty) Text(date, style: const TextStyle(color: _muted, fontSize: 12, fontWeight: FontWeight.w600))]), if ('$sub'.isNotEmpty) Padding(padding: const EdgeInsets.only(top: 3), child: Text('$sub', style: const TextStyle(color: _green, fontWeight: FontWeight.w600))), if ('$details'.isNotEmpty) Padding(padding: const EdgeInsets.only(top: 5), child: Text('$details', style: const TextStyle(color: _ink, height: 1.45)))]))]));
  }
}

class _CvHeader extends StatelessWidget {
  final VoidCallback onRefresh;
  const _CvHeader({required this.onRefresh});
  @override
  Widget build(BuildContext context) => Container(padding: const EdgeInsets.fromLTRB(22, 18, 18, 18), decoration: const BoxDecoration(color: _green, boxShadow: [BoxShadow(color: Color(0x22000000), blurRadius: 10, offset: Offset(0, 4))]), child: Row(children: [Container(width: 44, height: 44, decoration: BoxDecoration(color: Colors.white.withOpacity(.14), borderRadius: BorderRadius.circular(12)), child: const Icon(Icons.description_rounded, color: Colors.white)), const SizedBox(width: 12), const Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text('Curriculum Vitae', style: TextStyle(color: Colors.white, fontSize: 21, fontWeight: FontWeight.w900)), SizedBox(height: 3), Text('Professional profile management', style: TextStyle(color: Color(0xFFD9EEE1), fontSize: 12))])), IconButton(onPressed: onRefresh, tooltip: 'Refresh CV', icon: const Icon(Icons.refresh_rounded, color: Colors.white))]));
}

class _TopTabs extends StatelessWidget {
  final int index;
  final ValueChanged<int> onSelect;
  const _TopTabs({required this.index, required this.onSelect});
  @override
  Widget build(BuildContext context) => Container(color: Colors.white, child: Row(children: [for (var i = 0; i < 2; i++) Expanded(child: InkWell(onTap: () => onSelect(i), child: Container(padding: const EdgeInsets.symmetric(vertical: 14), decoration: BoxDecoration(border: Border(bottom: BorderSide(color: index == i ? _gold : Colors.transparent, width: 3))), child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [Icon(i == 0 ? Icons.person_outline : Icons.groups_outlined, size: 18, color: index == i ? _green : _muted), const SizedBox(width: 8), Text(i == 0 ? 'My CV' : 'Staff CV directory', style: TextStyle(color: index == i ? _green : _muted, fontWeight: FontWeight.w800))]))))]));
}

class _DirectoryCard extends StatelessWidget {
  final Map<String, dynamic> row;
  final VoidCallback onTap;
  const _DirectoryCard({required this.row, required this.onTap});
  @override
  Widget build(BuildContext context) {
    final name = '${row['full_name'] ?? 'Staff member'}';
    final title = '${row['professional_title'] ?? (row['role'] ?? '')}';
    final updated = row['updated_at'] == null ? 'CV not created yet' : 'Updated ${_date(row['updated_at'])}';
    return InkWell(onTap: onTap, borderRadius: BorderRadius.circular(16), child: Container(padding: const EdgeInsets.all(17), decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(16), border: Border.all(color: _line)), child: Row(children: [CircleAvatar(radius: 27, backgroundColor: const Color(0xFFE8F3ED), child: Text(name.isEmpty ? '?' : name[0].toUpperCase(), style: const TextStyle(color: _green, fontWeight: FontWeight.w900, fontSize: 20))), const SizedBox(width: 13), Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [Text(name, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _ink, fontSize: 16, fontWeight: FontWeight.w800)), const SizedBox(height: 4), Text(title, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _green, fontWeight: FontWeight.w600)), const SizedBox(height: 5), Text('${row['campus'] ?? 'Campus not set'}  •  $updated', maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _muted, fontSize: 11))])), const Icon(Icons.arrow_forward_ios_rounded, size: 15, color: _muted)])));
  }
}

class _CompletenessCard extends StatelessWidget {
  final Map<String, dynamic> cv;
  const _CompletenessCard({required this.cv});
  @override
  Widget build(BuildContext context) {
    final profile = cv['entries'] is Map ? cv['entries'] as Map : const {};
    final filled = ['professional_title','professional_summary','phone','contact_email'].where((key) => '${cv[key] ?? ''}'.trim().isNotEmpty).length;
    final sections = ['education','experience','certification','skill'].where((key) => profile[key] is List && (profile[key] as List).isNotEmpty).length;
    final score = ((filled + sections) / 8 * 100).round();
    return Container(padding: const EdgeInsets.all(20), decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(16), border: Border.all(color: _line)), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [const Text('CV readiness', style: TextStyle(color: _ink, fontSize: 17, fontWeight: FontWeight.w900)), const SizedBox(height: 13), LinearProgressIndicator(value: score / 100, minHeight: 9, borderRadius: BorderRadius.circular(8), color: _green, backgroundColor: const Color(0xFFE8EDE9)), const SizedBox(height: 9), Text('$score% complete', style: const TextStyle(color: _green, fontWeight: FontWeight.w800)), const SizedBox(height: 11), const Text('For a strong professional CV, add a profile summary, work history, education, and relevant skills. References are optional.', style: TextStyle(color: _muted, height: 1.45))]));
  }
}

class _EditorPanel extends StatelessWidget {
  final String title, subtitle;
  final IconData icon;
  final Widget child;
  final Widget? trailing;
  const _EditorPanel({required this.title, required this.subtitle, required this.icon, required this.child, this.trailing});
  @override
  Widget build(BuildContext context) => Container(width: double.infinity, padding: const EdgeInsets.all(18), decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(15), border: Border.all(color: _line)), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Row(children: [Container(width: 38, height: 38, decoration: BoxDecoration(color: const Color(0xFFE8F3ED), borderRadius: BorderRadius.circular(11)), child: Icon(icon, color: _green)), const SizedBox(width: 11), Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text(title, style: const TextStyle(color: _ink, fontWeight: FontWeight.w900, fontSize: 16)), const SizedBox(height: 2), Text(subtitle, style: const TextStyle(color: _muted, fontSize: 12))])), if (trailing != null) trailing!]), const SizedBox(height: 15), child]));
}

class _CvSection extends StatelessWidget {
  final String title;
  final Widget child;
  const _CvSection({required this.title, required this.child});
  @override
  Widget build(BuildContext context) => Padding(padding: const EdgeInsets.only(bottom: 15), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Row(children: [Expanded(child: Text(title, style: const TextStyle(color: _green, fontWeight: FontWeight.w900, fontSize: 12, letterSpacing: 1.15))), const SizedBox(width: 12), Container(width: 42, height: 2, color: _gold)]), const SizedBox(height: 11), child]));
}

class _Contact extends StatelessWidget {
  final IconData icon;
  final String text;
  const _Contact(this.icon, this.text);
  @override
  Widget build(BuildContext context) => Row(mainAxisSize: MainAxisSize.min, children: [Icon(icon, size: 14, color: _gold), const SizedBox(width: 5), ConstrainedBox(constraints: const BoxConstraints(maxWidth: 240), child: Text(text, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _muted, fontSize: 12)))]);
}

class _Photo extends StatelessWidget {
  final String url;
  final double size;
  const _Photo({required this.url, required this.size});
  @override
  Widget build(BuildContext context) => ClipRRect(borderRadius: BorderRadius.circular(15), child: Container(width: size, height: size, color: const Color(0xFFE8F3ED), child: url.isEmpty ? const Icon(Icons.person_rounded, color: _green, size: 42) : Image.network(url, fit: BoxFit.cover, errorBuilder: (_, __, ___) => const Icon(Icons.person_rounded, color: _green, size: 42))));
}

class _InfoBanner extends StatelessWidget {
  final String text;
  const _InfoBanner({required this.text});
  @override
  Widget build(BuildContext context) => Container(padding: const EdgeInsets.all(14), decoration: BoxDecoration(color: const Color(0xFFE8F3ED), borderRadius: BorderRadius.circular(12)), child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [const Icon(Icons.verified_user_outlined, color: _green), const SizedBox(width: 10), Expanded(child: Text(text, style: const TextStyle(color: _ink, height: 1.45)))]));
}

class _ErrorBox extends StatelessWidget {
  final String message;
  final VoidCallback retry;
  const _ErrorBox({required this.message, required this.retry});
  @override
  Widget build(BuildContext context) => Center(child: Container(margin: const EdgeInsets.all(24), padding: const EdgeInsets.all(24), decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(16)), child: Column(mainAxisSize: MainAxisSize.min, children: [const Icon(Icons.cloud_off_rounded, color: _gold, size: 36), const SizedBox(height: 12), Text(message, textAlign: TextAlign.center, style: const TextStyle(color: _ink)), const SizedBox(height: 14), FilledButton(onPressed: retry, style: FilledButton.styleFrom(backgroundColor: _green), child: const Text('Try again'))])));
}

InputDecoration _inputDecoration(String label) => InputDecoration(labelText: label, filled: true, fillColor: const Color(0xFFFAFBFA), contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14), border: OutlineInputBorder(borderRadius: BorderRadius.circular(11), borderSide: const BorderSide(color: _line)), enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(11), borderSide: const BorderSide(color: _line)), focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(11), borderSide: const BorderSide(color: _green, width: 1.5)));

IconData _sectionIcon(String section) => switch (section) {
  'education' => Icons.school_outlined,
  'experience' => Icons.work_outline_rounded,
  'certification' => Icons.workspace_premium_outlined,
  'project' => Icons.lightbulb_outline_rounded,
  'skill' => Icons.stars_rounded,
  _ => Icons.people_alt_outlined,
};

String _date(dynamic value) {
  try { return DateFormat('d MMM yyyy').format(DateTime.parse('$value').toLocal()); } catch (_) { return '$value'; }
}
