import 'dart:convert';
import 'dart:typed_data';

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

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

const cvGreen = Color(0xFF026930);
const cvGold = Color(0xFFCC7504);
const cvInk = Color(0xFF1E2A24);
const cvMuted = Color(0xFF6E7973);
const cvLine = Color(0xFFDDE5E0);
const cvPage = Color(0xFFF3F6F4);

const cvSectionNames = <String, String>{
  'education': 'Education background',
  'certification': 'Academic certification',
  'experience': 'Employment and work experience',
  'internship': 'Internship experience',
  'work_learning': 'Work-based learning',
  'project': 'Projects developed',
  'skill': 'Competences and skills',
  'referee': 'Referees',
};

const cvEntryFields = <String, Map<String, String>>{
  'education': {'qualification': 'Qualification / award', 'institution': 'School / institution', 'start_year': 'From year', 'end_year': 'To year', 'details': 'Details'},
  'certification': {'name': 'Certificate / qualification', 'issuer': 'Issuing institution', 'start_year': 'From year', 'end_year': 'To year', 'details': 'Details'},
  'experience': {'position': 'Position / job title', 'employer': 'Employer / institution', 'start_year': 'From year', 'end_year': 'To year', 'responsibilities': 'Responsibilities and achievements'},
  'internship': {'position': 'Internship role', 'employer': 'Organization', 'start_year': 'From year', 'end_year': 'To year', 'responsibilities': 'Tasks and experience gained'},
  'work_learning': {'position': 'Work-based learning role', 'employer': 'Organization / workplace', 'start_year': 'From year', 'end_year': 'To year', 'responsibilities': 'Tasks and experience gained'},
  'project': {'title': 'Project title', 'role': 'Your role', 'year': 'Year', 'description': 'Description / outcome'},
  'skill': {'name': 'Competence / skill', 'level': 'Proficiency (optional)', 'category': 'Area (optional)'},
  'referee': {'name': 'Full name', 'title': 'Position / relationship', 'organization': 'Organization', 'email': 'Email', 'phone': 'Phone'},
};

const _cvProfileFields = <String, String>{
  'cv_name': 'Name',
  'professional_title': 'Professional title / position',
  'career_objective': 'Career objective',
  'professional_summary': 'Personal personality / professional profile',
  'phone': 'Cell phone',
  'contact_email': 'Email address',
  'address': 'Address',
  'date_of_birth': 'Date of birth (YYYY-MM-DD)',
  'marital_status': 'Marital status',
  'place_of_birth': 'Place of birth',
  'religion': 'Religion',
  'gender': 'Gender',
  'languages': 'Languages',
  'nationality': 'Nationality',
  'nrc_number': 'NRC number',
  'website': 'Portfolio or website (optional)',
  'linkedin_url': 'LinkedIn profile (optional)',
  'hobbies': 'Hobbies and interests',
};

const _contactKeys = ['cv_name', 'address', 'phone', 'contact_email'];
const _personalKeys = ['date_of_birth', 'marital_status', 'place_of_birth', 'religion', 'gender', 'languages', 'nationality', 'nrc_number'];
const _professionalKeys = ['professional_title', 'career_objective', 'professional_summary', 'website', 'linkedin_url', 'hobbies'];

/// Put this widget in the dashboard's existing content panel.
/// It deliberately does not create a Scaffold, route, or full-screen dialog.
class MyCvTab extends StatefulWidget {
  const MyCvTab({super.key});
  @override
  State<MyCvTab> createState() => _MyCvTabState();
}

class _MyCvTabState extends State<MyCvTab> {
  bool _loading = true;
  bool _editing = false;
  bool _saving = false;
  String? _error;
  Map<String, dynamic> _cv = {};
  final Map<String, TextEditingController> _profile = {};
  final Map<String, List<Map<String, TextEditingController>>> _entries = {};
  Uint8List? _photoBytes;
  bool _photoChanged = false;

  @override
  void initState() { super.initState(); CvService.offlineRevision.addListener(_onOfflineRevision); _load(); }
  @override
  void dispose() { CvService.offlineRevision.removeListener(_onOfflineRevision); _disposeFields(); super.dispose(); }

  void _onOfflineRevision() {
    if (mounted && !_editing && !_saving) _load();
  }

  void _disposeFields() {
    for (final field in _profile.values) { field.dispose(); }
    for (final list in _entries.values) {
      for (final row in list) { for (final field in row.values) { field.dispose(); } }
    }
    _profile.clear();
    _entries.clear();
    _photoBytes = null;
    _photoChanged = false;
  }

  Future<void> _load({bool refresh = false}) async {
    setState(() { _loading = _cv.isEmpty; _error = null; });
    try {
      final cv = await CvService.mine(refresh: refresh);
      if (!mounted) return;
      setState(() { _cv = cv; _loading = false; });
      if (_editing) _startEditing();
    } catch (e) {
      if (!mounted) return;
      setState(() { if (_cv.isEmpty) _error = CvService.cleanError(e); _loading = false; });
    }
  }

  void _startEditing() {
    _disposeFields();
    for (final key in _cvProfileFields.keys) {
      final fallback = key == 'contact_email' ? _cv['account_email'] : key == 'cv_name' ? _cv['full_name'] : '';
      _profile[key] = TextEditingController(text: '${_cv[key] ?? fallback ?? ''}');
    }
    // Keep the current server photo URL when saving other CV details.
    _profile['photo_url'] = TextEditingController(text: '${_cv['photo_url'] ?? ''}');
    try {
      final photo = '${_cv['_photo_base64'] ?? ''}';
      _photoBytes = photo.isEmpty ? null : base64Decode(photo);
    } catch (_) { _photoBytes = null; }
    _photoChanged = false;
    final savedEntries = _cv['entries'];
    for (final section in cvSectionNames.keys) {
      final raw = savedEntries is Map && savedEntries[section] is List ? savedEntries[section] as List : const [];
      _entries[section] = raw.whereType<Map>().map((item) {
        final data = item.map((key, value) => MapEntry(key.toString(), value));
        return _newEntry(section, data);
      }).toList();
    }
    setState(() => _editing = true);
  }

  Map<String, TextEditingController> _newEntry(String section, [Map<String, dynamic>? initial]) => {
    for (final field in cvEntryFields[section]!.keys)
      field: TextEditingController(text: '${initial?[field] ?? ''}'),
  };

  void _addEntry(String section) => setState(() => _entries[section]!.add(_newEntry(section)));
  void _removeEntry(String section, int index) {
    for (final field in _entries[section]![index].values) { field.dispose(); }
    setState(() => _entries[section]!.removeAt(index));
  }

  Future<void> _choosePhoto() async {
    try {
      // file_picker v12 exposes pickFile directly on FilePicker.
      final file = await FilePicker.pickFile(type: FileType.image);
      if (file == null) return;
      final size = await file.length();
      if (size! > 2 * 1024 * 1024) {
        _notice('Please choose an image smaller than 2 MB.');
        return;
      }
      final bytes = await file.readAsBytes();
      if (bytes.isEmpty) {
        _notice('This image could not be read. Please choose another photo.');
        return;
      }
      setState(() { _photoBytes = bytes; _photoChanged = true; });
    } catch (error) {
      _notice('The photo picker could not open: ${CvService.cleanError(error)}');
    }
  }

  Future<void> _save() async {
    setState(() => _saving = true);
    final payload = <String, dynamic>{
      'profile': _profile.map((key, field) => MapEntry(key, field.text.trim())),
      'entries': _entries.map((section, rows) => MapEntry(section, rows.map((row) => row.map((key, field) => MapEntry(key, field.text.trim()))).toList())),
      if (_photoChanged && _photoBytes != null) 'photo_data': base64Encode(_photoBytes!),
    };
    try {
      final result = await CvService.save(payload);
      if (!mounted) return;
      _disposeFields();
      setState(() { _editing = false; _saving = false; });
      await _load();
      if (mounted) _notice('${result['message'] ?? 'Your CV has been saved on this device.'}', success: true);
    } catch (e) {
      if (!mounted) return;
      setState(() => _saving = false);
      _notice(CvService.cleanError(e));
    }
  }

  void _notice(String message, {bool success = false}) => ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message), backgroundColor: success ? cvGreen : Colors.red.shade700));

  @override
  Widget build(BuildContext context) {
    if (_loading) return const Center(child: Padding(padding: EdgeInsets.all(50), child: CircularProgressIndicator(color: cvGreen)));
    if (_error != null) return _PanelMessage(message: _error!, onRetry: _load);
    return Column(children: [
      _CvPanelHeader(title: 'MY CURRICULUM VITAE', subtitle: 'Build and update your official professional profile', icon: Icons.badge_outlined, trailing: Wrap(spacing: 6, crossAxisAlignment: WrapCrossAlignment.center, children: [IconButton(tooltip: 'Refresh and sync', onPressed: () => _load(refresh: true), icon: const Icon(Icons.sync_rounded, color: cvGreen)), _editing ? _HeaderAction(icon: Icons.close_rounded, label: 'CANCEL', onTap: () { _disposeFields(); setState(() => _editing = false); }) : _HeaderAction(icon: Icons.edit_rounded, label: 'EDIT MY CV', onTap: _startEditing)])),
      Expanded(child: _editing ? _editor() : _preview()),
    ]);
  }

  Widget _preview() => SingleChildScrollView(padding: const EdgeInsets.all(20), child: Center(child: Column(children: [if (_cv['_offline_cached'] == true) _OfflineBanner(pending: _cv['_offline_pending'] == true, onSync: () => _load(refresh: true)), if (_cv['_offline_cached'] == true) const SizedBox(height: 12), StaffCvDocument(cv: _cv)])));

  Widget _editor() => ListView(padding: const EdgeInsets.all(18), children: [
    const _MessageStrip(text: 'Complete each section from the reference CV. Use the formatting toolbar for bold text, emphasis, underlining, bullets and numbered points.'),
    const SizedBox(height: 14),
    _FormCard(title: 'CV photograph', icon: Icons.photo_camera_outlined, child: _photoEditor()),
    const SizedBox(height: 12),
    _FormCard(title: 'CONTACT INFORMATION', icon: Icons.contact_mail_outlined, child: _fieldGrid(_contactKeys)),
    const SizedBox(height: 12),
    _FormCard(title: 'PERSONAL INFORMATION', icon: Icons.person_outline_rounded, child: _fieldGrid(_personalKeys)),
    const SizedBox(height: 12),
    _FormCard(title: 'CAREER OBJECTIVE AND PERSONALITY', icon: Icons.edit_note_rounded, child: _fieldGrid(_professionalKeys)),
    for (final section in cvSectionNames.keys) ...[
      const SizedBox(height: 12),
      _FormCard(title: cvSectionNames[section]!.toUpperCase(), icon: _sectionIcon(section), trailing: TextButton.icon(onPressed: () => _addEntry(section), icon: const Icon(Icons.add_rounded), label: const Text('ADD')), child: _entriesEditor(section)),
    ],
    const SizedBox(height: 18),
    Align(alignment: Alignment.centerRight, child: FilledButton.icon(onPressed: _saving ? null : _save, icon: const Icon(Icons.save_rounded), label: Text(_saving ? 'SAVING…' : 'SAVE MY CV'), style: FilledButton.styleFrom(backgroundColor: cvGreen, padding: const EdgeInsets.symmetric(horizontal: 22, vertical: 16)))),
  ]);

  Widget _photoEditor() => LayoutBuilder(builder: (context, box) {
    final preview = Container(width: 148, height: 148, decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: cvGold, width: 2), color: const Color(0xFFE8F3ED)), clipBehavior: Clip.antiAlias, child: _photoBytes != null
        ? Image.memory(_photoBytes!, fit: BoxFit.cover)
        : ('${_cv['photo_url'] ?? _cv['account_photo'] ?? ''}'.isEmpty
            ? const Icon(Icons.person_rounded, color: cvGreen, size: 68)
            : Image.network('${_cv['photo_url'] ?? _cv['account_photo']}', fit: BoxFit.cover, errorBuilder: (_, __, ___) => const Icon(Icons.person_rounded, color: cvGreen, size: 68))));
    final action = Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      const Text('Choose a photograph from your device', style: TextStyle(color: cvInk, fontWeight: FontWeight.w800)),
      const SizedBox(height: 5),
      const Text('JPG, PNG or WEBP • maximum 2 MB', style: TextStyle(color: cvMuted, fontSize: 12)),
      const SizedBox(height: 10),
      OutlinedButton.icon(onPressed: _choosePhoto, icon: const Icon(Icons.upload_file_rounded), label: const Text('CHOOSE PHOTO')),
    ]);
    if (box.maxWidth < 480) return Column(children: [preview, const SizedBox(height: 12), action]);
    return Row(children: [preview, const SizedBox(width: 18), Expanded(child: action)]);
  });

  Widget _fieldGrid(List<String> keys) => LayoutBuilder(builder: (context, box) {
    final width = box.maxWidth > 760 ? (box.maxWidth - 14) / 2 : box.maxWidth;
    return Wrap(spacing: 14, runSpacing: 5, children: keys.map((key) {
      final controller = _profile[key]!;
      final multi = ['career_objective', 'professional_summary', 'hobbies'].contains(key);
      final field = key == 'marital_status'
          ? DropdownButtonFormField<String>(value: _dropdownValue(controller.text, const ['Single', 'Married', 'Divorced', 'Widowed']), decoration: _cvInput(_cvProfileFields[key]!), items: const ['Single', 'Married', 'Divorced', 'Widowed'].map((v) => DropdownMenuItem(value: v, child: Text(v))).toList(), onChanged: (value) => controller.text = value ?? '')
          : key == 'gender'
          ? DropdownButtonFormField<String>(value: _dropdownValue(controller.text, const ['Female', 'Male', 'Prefer not to say']), decoration: _cvInput(_cvProfileFields[key]!), items: const ['Female', 'Male', 'Prefer not to say'].map((v) => DropdownMenuItem(value: v, child: Text(v))).toList(), onChanged: (value) => controller.text = value ?? '')
          : key == 'date_of_birth'
          ? TextField(controller: controller, readOnly: true, decoration: _cvInput(_cvProfileFields[key]!).copyWith(suffixIcon: const Icon(Icons.calendar_month_outlined)), onTap: () async { final now = DateTime.now(); final initial = DateTime.tryParse(controller.text) ?? DateTime(now.year - 25); final picked = await showDatePicker(context: context, initialDate: initial, firstDate: DateTime(1900), lastDate: now); if (picked != null) controller.text = '${picked.year.toString().padLeft(4, '0')}-${picked.month.toString().padLeft(2, '0')}-${picked.day.toString().padLeft(2, '0')}'; })
          : multi
          ? _RichTextEditor(controller: controller, label: _cvProfileFields[key]!, minLines: 3)
          : TextField(controller: controller, keyboardType: key == 'contact_email' ? TextInputType.emailAddress : TextInputType.text, decoration: _cvInput(_cvProfileFields[key]!));
      return SizedBox(width: multi ? box.maxWidth : width, child: Padding(padding: const EdgeInsets.only(bottom: 9), child: field));
    }).toList());
  });

  Widget _entriesEditor(String section) {
    final rows = _entries[section]!;
    if (rows.isEmpty) return Text('No ${cvSectionNames[section]!.toLowerCase()} entered yet.', style: const TextStyle(color: cvMuted));
    return Column(children: List.generate(rows.length, (index) => Container(
      margin: const EdgeInsets.only(bottom: 12), padding: const EdgeInsets.all(13),
      decoration: BoxDecoration(color: const Color(0xFFFAFBFA), border: Border.all(color: cvLine), borderRadius: BorderRadius.circular(11)),
      child: Column(children: [
        Row(children: [Expanded(child: Text('ENTRY ${index + 1}', style: const TextStyle(color: cvGreen, fontWeight: FontWeight.w900, letterSpacing: 1))), IconButton(tooltip: 'Remove entry', onPressed: () => _removeEntry(section, index), icon: const Icon(Icons.delete_outline_rounded, color: Colors.redAccent))]),
        LayoutBuilder(builder: (context, box) {
          final width = box.maxWidth > 760 ? (box.maxWidth - 14) / 2 : box.maxWidth;
          return Wrap(spacing: 14, runSpacing: 4, children: cvEntryFields[section]!.entries.map((field) {
            final multi = ['details', 'responsibilities', 'description'].contains(field.key);
            final editor = multi ? _RichTextEditor(controller: rows[index][field.key]!, label: field.value, minLines: 3) : TextField(controller: rows[index][field.key], keyboardType: ['start_year', 'end_year', 'year'].contains(field.key) ? TextInputType.number : TextInputType.text, decoration: _cvInput(field.value));
            return SizedBox(width: multi ? box.maxWidth : width, child: Padding(padding: const EdgeInsets.only(bottom: 8), child: editor));
          }).toList());
        }),
      ]),
    )));
  }
}

/// A scrollable, page-style CV that follows the submitted reference layout.
/// It can be displayed inside both the owner's panel and the admin panel.
class StaffCvDocument extends StatelessWidget {
  final Map<String, dynamic> cv;
  const StaffCvDocument({super.key, required this.cv});

  String _value(String key) => '${cv[key] ?? (key == 'photo_url' ? cv['account_photo'] : '') ?? ''}'.trim();
  Map<String, List<Map<String, dynamic>>> _allEntries() {
    final source = cv['entries'];
    return {for (final section in cvSectionNames.keys) section: (source is Map && source[section] is List ? source[section] as List : const []).whereType<Map>().map((item) => item.map((key, value) => MapEntry(key.toString(), value))).toList()};
  }

  @override
  Widget build(BuildContext context) {
    final entries = _allEntries();
    final name = (_value('cv_name').isEmpty ? _value('full_name') : _value('cv_name')).isEmpty ? 'Your Full Name' : (_value('cv_name').isEmpty ? _value('full_name') : _value('cv_name'));
    return ConstrainedBox(constraints: const BoxConstraints(maxWidth: 820), child: Column(children: [
      _CvPaperPage(cover: true, child: Column(children: [
        const Text('CURRICULUM VITAE', textAlign: TextAlign.center, style: TextStyle(color: cvInk, fontFamily: 'serif', fontSize: 23, fontWeight: FontWeight.w900, letterSpacing: 3)),
        const SizedBox(height: 17),
        Text(name.toUpperCase(), textAlign: TextAlign.center, style: const TextStyle(color: cvGreen, fontSize: 22, fontWeight: FontWeight.w900, letterSpacing: 1.2)),
        if (_value('professional_title').isNotEmpty) Padding(padding: const EdgeInsets.only(top: 5), child: Text(_value('professional_title'), textAlign: TextAlign.center, style: const TextStyle(color: cvMuted, fontSize: 14, fontWeight: FontWeight.w600))),
        const SizedBox(height: 22),
        _CvPortrait(url: _value('photo_url'), photoBase64: '${cv['_photo_base64'] ?? ''}'),
        if (_value('career_objective').isNotEmpty) ...[
          const SizedBox(height: 22),
          _ReferenceSection(title: 'CAREER OBJECTIVE', child: _FormattedText(text: _value('career_objective'), style: const TextStyle(color: cvInk, fontFamily: 'serif', height: 1.7, fontSize: 14))),
        ],
      ])),
      _CvPaperPage(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        _ReferenceSection(title: 'CONTACT INFORMATION', child: Column(children: [
          _InfoRow(label: 'Name', value: name),
          _InfoRow(label: 'Address', value: _value('address')),
          _InfoRow(label: 'Cell phone', value: _value('phone')),
          _InfoRow(label: 'Email', value: _value('contact_email').isEmpty ? '${cv['account_email'] ?? ''}' : _value('contact_email')),
        ])),
        const SizedBox(height: 20),
        _ReferenceSection(title: 'PERSONAL INFORMATION', child: Column(children: [
          _InfoRow(label: 'Date of birth', value: _value('date_of_birth')),
          _InfoRow(label: 'Marital status', value: _value('marital_status')),
          _InfoRow(label: 'Place of birth', value: _value('place_of_birth')),
          _InfoRow(label: 'Religion', value: _value('religion')),
          _InfoRow(label: 'Gender', value: _value('gender')),
          _InfoRow(label: 'Languages', value: _value('languages')),
          _InfoRow(label: 'Nationality', value: _value('nationality')),
          _InfoRow(label: 'NRC number', value: _value('nrc_number')),
        ])),
        if ([cv['campus'], cv['program'], _value('website'), _value('linkedin_url')].any((value) => value != null && '$value'.trim().isNotEmpty)) ...[
          const SizedBox(height: 16),
          _ReferenceSection(title: 'ADDITIONAL PROFESSIONAL DETAILS', child: Column(children: [
            _InfoRow(label: 'Campus / department', value: [cv['campus'], cv['program']].where((v) => v != null && '$v'.trim().isNotEmpty).join(' • ')),
            _InfoRow(label: 'Website', value: _value('website')),
            _InfoRow(label: 'LinkedIn', value: _value('linkedin_url')),
          ])),
        ],
        if (_value('professional_summary').isNotEmpty) ...[
          const SizedBox(height: 24),
          _ReferenceSection(title: 'PERSONAL PERSONALITY', child: _FormattedText(text: _value('professional_summary'), style: const TextStyle(color: cvInk, fontFamily: 'serif', height: 1.8, fontSize: 14))),
        ],
      ])),
      if (entries['education']!.isNotEmpty || entries['certification']!.isNotEmpty)
        _CvPaperPage(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          if (entries['education']!.isNotEmpty) _RecordSection(title: 'EDUCATIONAL BACKGROUND', rows: entries['education']!, headingKeys: const ['qualification'], detailKeys: const ['institution','details'], dateFromKey: 'start_year', dateToKey: 'end_year'),
          if (entries['certification']!.isNotEmpty) ...[
            const SizedBox(height: 18),
            _RecordSection(title: 'ACADEMIC CERTIFICATION', rows: entries['certification']!, headingKeys: const ['name'], detailKeys: const ['issuer','details'], dateFromKey: 'start_year', dateToKey: 'end_year'),
          ],
        ])),
      if (_value('hobbies').isNotEmpty || entries['experience']!.isNotEmpty || entries['internship']!.isNotEmpty || entries['work_learning']!.isNotEmpty || entries['project']!.isNotEmpty || entries['skill']!.isNotEmpty || entries['referee']!.isNotEmpty)
        _CvPaperPage(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          if (_value('hobbies').isNotEmpty) _ReferenceSection(title: 'HOBBIES', child: _FormattedText(text: _value('hobbies'), style: const TextStyle(color: cvInk, fontFamily: 'serif', height: 1.6))),
          if (entries['experience']!.isNotEmpty) _RecordSection(title: 'EMPLOYMENT AND WORK EXPERIENCE', rows: entries['experience']!, headingKeys: const ['position'], detailKeys: const ['employer','responsibilities'], dateFromKey: 'start_year', dateToKey: 'end_year'),
          if (entries['internship']!.isNotEmpty) ...[const SizedBox(height: 18), _RecordSection(title: 'INTERNSHIP EXPERIENCE', rows: entries['internship']!, headingKeys: const ['position'], detailKeys: const ['employer','responsibilities'], dateFromKey: 'start_year', dateToKey: 'end_year')],
          if (entries['work_learning']!.isNotEmpty) ...[const SizedBox(height: 18), _RecordSection(title: 'WORK-BASED LEARNING EXPERIENCE', rows: entries['work_learning']!, headingKeys: const ['position'], detailKeys: const ['employer','responsibilities'], dateFromKey: 'start_year', dateToKey: 'end_year')],
          if (entries['project']!.isNotEmpty) ...[const SizedBox(height: 18), _RecordSection(title: 'PROJECTS DEVELOPED', rows: entries['project']!, headingKeys: const ['title'], detailKeys: const ['role','year','description'])],
          if (entries['skill']!.isNotEmpty) ...[const SizedBox(height: 18), _RecordSection(title: 'COMPETENCES AND SKILLS', rows: entries['skill']!, headingKeys: const ['name'], detailKeys: const ['category','level'])],
          if (entries['referee']!.isNotEmpty) ...[const SizedBox(height: 18), _RecordSection(title: 'REFEREES', rows: entries['referee']!, headingKeys: const ['name'], detailKeys: const ['title','organization','email','phone'])],
        ])),
      const SizedBox(height: 10),
    ]));
  }
}

class _CvPaperPage extends StatelessWidget {
  final Widget child;
  final bool cover;
  const _CvPaperPage({required this.child, this.cover = false});
  @override
  Widget build(BuildContext context) => Container(width: double.infinity, margin: const EdgeInsets.only(bottom: 18), padding: const EdgeInsets.all(7), decoration: BoxDecoration(color: Colors.white, border: Border.all(color: const Color(0xFF212121), width: 2.4), boxShadow: const [BoxShadow(color: Color(0x16000000), blurRadius: 12, offset: Offset(0, 4))]), child: Container(padding: EdgeInsets.fromLTRB(cover ? 36 : 30, cover ? 42 : 30, cover ? 36 : 30, 34), decoration: BoxDecoration(border: Border.all(color: const Color(0xFF303030), width: 1.2)), child: child));
}

class _CvPortrait extends StatelessWidget {
  final String url, photoBase64;
  const _CvPortrait({required this.url, required this.photoBase64});
  @override
  Widget build(BuildContext context) => LayoutBuilder(builder: (context, constraints) {
    // Fill the available CV page width, like the supplied reference, while
    // letting the page layout reduce the image width on narrow mobile screens.
    final width = constraints.maxWidth.isFinite ? constraints.maxWidth : 680.0;
    const fallback = Center(child: Icon(Icons.person_rounded, color: cvGreen, size: 86));
    Widget image = fallback;
    if (photoBase64.isNotEmpty) {
      try { image = Image.memory(base64Decode(photoBase64), fit: BoxFit.cover); } catch (_) { image = fallback; }
    } else if (url.isNotEmpty) {
      image = Image.network(url, fit: BoxFit.cover, errorBuilder: (_, __, ___) => fallback);
    }
    return Container(width: width, height: width * .92, decoration: BoxDecoration(border: Border.all(color: cvGold, width: 2), color: const Color(0xFFE8F3ED)), clipBehavior: Clip.antiAlias, child: image);
  });
}

class _ReferenceSection extends StatelessWidget {
  final String title;
  final Widget child;
  const _ReferenceSection({required this.title, required this.child});
  @override
  Widget build(BuildContext context) => Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [Container(padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7), color: cvGreen, child: Text(title, style: const TextStyle(color: Colors.white, letterSpacing: 1.1, fontSize: 12, fontWeight: FontWeight.w900))), const SizedBox(height: 10), child]);
}

class _InfoRow extends StatelessWidget {
  final String label, value;
  const _InfoRow({required this.label, required this.value});
  @override
  Widget build(BuildContext context) { if (value.trim().isEmpty) return const SizedBox.shrink(); return Padding(padding: const EdgeInsets.symmetric(vertical: 6), child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [Expanded(flex: 4, child: Text('$label:', style: const TextStyle(color: cvInk, fontFamily: 'serif', fontWeight: FontWeight.w700))), Expanded(flex: 6, child: Text(value, style: const TextStyle(color: cvInk, fontFamily: 'serif')))])); }
}

/// A small offline-friendly rich text editor. Formatting is stored as simple
/// readable markers, so it works without a web editor or an internet service.
class _RichTextEditor extends StatelessWidget {
  final TextEditingController controller;
  final String label;
  final int minLines;
  const _RichTextEditor({required this.controller, required this.label, this.minLines = 3});

  void _wrap(String left, String right) {
    final text = controller.text;
    final selection = controller.selection;
    final start = selection.isValid ? selection.start : text.length;
    final end = selection.isValid ? selection.end : text.length;
    final selected = text.substring(start, end);
    final next = text.replaceRange(start, end, '$left$selected$right');
    controller.value = TextEditingValue(text: next, selection: TextSelection.collapsed(offset: selected.isEmpty ? start + left.length : start + left.length + selected.length + right.length));
  }

  void _list(String marker) {
    final value = controller.value;
    final text = value.text;
    var start = value.selection.isValid ? value.selection.start : text.length;
    var end = value.selection.isValid ? value.selection.end : text.length;
    final previousNewline = start == 0 ? -1 : text.lastIndexOf('\n', start - 1);
    start = previousNewline + 1;
    final newline = text.indexOf('\n', end);
    end = newline < 0 ? text.length : newline;
    final lines = text.substring(start, end).split('\n');
    var number = 1;
    final replacement = lines.map((line) {
      final label = switch (marker) {
        '1.' => '${number++}. ',
        'a)' => '${_alphaLabel(number++, upper: false)}) ',
        'A)' => '${_alphaLabel(number++, upper: true)}) ',
        'i)' => '${_romanLabel(number++, upper: false)}) ',
        'I)' => '${_romanLabel(number++, upper: true)}) ',
        _ => marker,
      };
      if (line.isEmpty) return label;
      if (marker == '1.' || marker == 'a)' || marker == 'A)' || marker == 'i)' || marker == 'I)') return '$label$line';
      return '$marker$line';
    }).join('\n');
    final next = text.replaceRange(start, end, replacement);
    controller.value = TextEditingValue(text: next, selection: TextSelection.collapsed(offset: start + replacement.length));
  }

  Widget _tool(String tip, IconData icon, VoidCallback action) => IconButton(visualDensity: VisualDensity.compact, tooltip: tip, onPressed: action, icon: Icon(icon, size: 18, color: cvGreen));

  @override
  Widget build(BuildContext context) => Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
    Container(decoration: BoxDecoration(color: const Color(0xFFE8F3ED), border: Border.all(color: cvLine), borderRadius: const BorderRadius.vertical(top: Radius.circular(9))), child: Wrap(spacing: 0, children: [
      _tool('Bold', Icons.format_bold, () => _wrap('**', '**')),
      _tool('Italic', Icons.format_italic, () => _wrap('*', '*')),
      _tool('Underline', Icons.format_underlined, () => _wrap('<u>', '</u>')),
      PopupMenuButton<String>(tooltip: 'Bullets and numbering', icon: const Icon(Icons.format_list_bulleted, size: 19, color: cvGreen), onSelected: _list, itemBuilder: (context) => const [
        PopupMenuItem(value: '• ', child: Text('•  Filled circle bullets')),
        PopupMenuItem(value: '◦ ', child: Text('◦  Hollow circle bullets')),
        PopupMenuItem(value: '▪ ', child: Text('▪  Square bullets')),
        PopupMenuItem(value: '– ', child: Text('–  Dash bullets')),
        PopupMenuItem(value: '➤ ', child: Text('➤  Arrow bullets')),
        PopupMenuItem(value: '✓ ', child: Text('✓  Check bullets')),
        PopupMenuDivider(),
        PopupMenuItem(value: '1.', child: Text('1.  Numbered list')),
        PopupMenuItem(value: 'a)', child: Text('a)  Lowercase letters')),
        PopupMenuItem(value: 'A)', child: Text('A)  Uppercase letters')),
        PopupMenuItem(value: 'i)', child: Text('i)  Lowercase Roman numerals')),
        PopupMenuItem(value: 'I)', child: Text('I)  Uppercase Roman numerals')),
      ]),
    ])),
    TextField(controller: controller, minLines: minLines, maxLines: null, keyboardType: TextInputType.multiline, decoration: _cvInput(label).copyWith(border: const OutlineInputBorder(borderRadius: BorderRadius.vertical(bottom: Radius.circular(9))))),
  ]);
}

class _FormattedText extends StatelessWidget {
  final String text;
  final TextStyle style;
  const _FormattedText({required this.text, required this.style});

  List<InlineSpan> _spans(String source, TextStyle base) {
    final result = <InlineSpan>[];
    final pattern = RegExp(r'\*\*(.+?)\*\*|\*(.+?)\*|<u>(.+?)</u>', dotAll: true);
    var cursor = 0;
    for (final match in pattern.allMatches(source)) {
      if (match.start > cursor) result.add(TextSpan(text: source.substring(cursor, match.start), style: base));
      final bold = match.group(1);
      final italic = match.group(2);
      final underline = match.group(3);
      result.add(TextSpan(text: bold ?? italic ?? underline ?? '', style: base.copyWith(fontWeight: bold != null ? FontWeight.bold : base.fontWeight, fontStyle: italic != null ? FontStyle.italic : base.fontStyle, decoration: underline != null ? TextDecoration.underline : base.decoration)));
      cursor = match.end;
    }
    if (cursor < source.length) result.add(TextSpan(text: source.substring(cursor), style: base));
    return result;
  }

  @override
  Widget build(BuildContext context) => RichText(text: TextSpan(children: _spans(text, style)));
}

String? _dropdownValue(String value, List<String> options) => options.contains(value) ? value : null;

String _alphaLabel(int value, {required bool upper}) {
  var number = value;
  var result = '';
  while (number > 0) {
    number--;
    result = String.fromCharCode((upper ? 65 : 97) + number % 26) + result;
    number ~/= 26;
  }
  return result;
}

String _romanLabel(int value, {required bool upper}) {
  const numerals = <int, String>{1000:'M', 900:'CM', 500:'D', 400:'CD', 100:'C', 90:'XC', 50:'L', 40:'XL', 10:'X', 9:'IX', 5:'V', 4:'IV', 1:'I'};
  var number = value;
  var result = '';
  for (final entry in numerals.entries) {
    while (number >= entry.key) {
      result += entry.value;
      number -= entry.key;
    }
  }
  return upper ? result : result.toLowerCase();
}

class _RecordSection extends StatelessWidget {
  final String title;
  final List<Map<String, dynamic>> rows;
  final List<String> headingKeys, detailKeys;
  final String? dateFromKey, dateToKey;
  const _RecordSection({required this.title, required this.rows, required this.headingKeys, required this.detailKeys, this.dateFromKey, this.dateToKey});
  String _first(Map<String, dynamic> row, List<String> keys) => keys.map((key) => '${row[key] ?? ''}'.trim()).firstWhere((value) => value.isNotEmpty, orElse: () => '');
  String _dateRange(Map<String, dynamic> row) {
    final from = dateFromKey == null ? '' : '${row[dateFromKey] ?? ''}'.trim();
    final to = dateToKey == null ? '' : '${row[dateToKey] ?? ''}'.trim();
    if (from.isEmpty && to.isEmpty) return '';
    if (from.isEmpty) return 'To $to';
    if (to.isEmpty) return 'From $from';
    return 'From $from to $to';
  }
  @override
  Widget build(BuildContext context) => _ReferenceSection(title: title, child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
    for (final row in rows) Padding(padding: const EdgeInsets.only(bottom: 15), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Expanded(child: Text(_first(row, headingKeys), style: const TextStyle(color: cvInk, fontFamily: 'serif', fontWeight: FontWeight.w900, fontSize: 14))),
        if (_dateRange(row).isNotEmpty) ...[
          const SizedBox(width: 8),
          Flexible(child: Text(_dateRange(row), textAlign: TextAlign.right, style: const TextStyle(color: cvMuted, fontFamily: 'serif', fontWeight: FontWeight.w700, fontSize: 12))),
        ],
      ]),
      const SizedBox(height: 4),
      for (final key in detailKeys) if ('${row[key] ?? ''}'.trim().isNotEmpty) Padding(padding: const EdgeInsets.only(left: 10, top: 3), child: _FormattedText(text: '${row[key]}', style: const TextStyle(color: cvInk, fontFamily: 'serif', height: 1.5))),
    ])),
  ]));
}

class _CvPanelHeader extends StatelessWidget {
  final String title, subtitle;
  final IconData icon;
  final Widget? trailing;
  const _CvPanelHeader({required this.title, required this.subtitle, required this.icon, this.trailing});
  Widget _heading() => Row(children: [
    Container(width: 44, height: 44, decoration: BoxDecoration(color: cvGreen, borderRadius: BorderRadius.circular(10)), child: Icon(icon, color: Colors.white)),
    const SizedBox(width: 13),
    Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Text(title, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(color: cvGreen, fontWeight: FontWeight.w900, fontSize: 16, letterSpacing: .25)),
      const SizedBox(height: 3), Text(subtitle, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(color: cvMuted, fontSize: 12)),
    ])),
  ]);

  @override
  Widget build(BuildContext context) => Container(
    padding: const EdgeInsets.fromLTRB(18, 15, 14, 15),
    decoration: const BoxDecoration(color: Colors.white, border: Border(bottom: BorderSide(color: cvGold, width: 3))),
    child: LayoutBuilder(builder: (context, box) {
      if (box.maxWidth < 650) {
        return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
          _heading(),
          if (trailing != null) Align(alignment: Alignment.centerRight, child: trailing!),
        ]);
      }
      return Row(children: [Expanded(child: _heading()), if (trailing != null) ...[const SizedBox(width: 12), trailing!]]);
    }),
  );
}

class _HeaderAction extends StatelessWidget {
  final IconData icon;
  final String label;
  final VoidCallback onTap;
  const _HeaderAction({required this.icon, required this.label, required this.onTap});
  @override
  Widget build(BuildContext context) => OutlinedButton.icon(onPressed: onTap, icon: Icon(icon, size: 18), label: Text(label, style: const TextStyle(fontWeight: FontWeight.w900)), style: OutlinedButton.styleFrom(foregroundColor: cvGreen, side: const BorderSide(color: cvGreen), padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 13)));
}

class _FormCard extends StatelessWidget {
  final String title;
  final IconData icon;
  final Widget child;
  final Widget? trailing;
  const _FormCard({required this.title, required this.icon, required this.child, this.trailing});
  @override
  Widget build(BuildContext context) => Container(width: double.infinity, padding: const EdgeInsets.all(17), decoration: BoxDecoration(color: Colors.white, border: Border.all(color: cvLine), borderRadius: BorderRadius.circular(13)), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Row(children: [Icon(icon, color: cvGreen), const SizedBox(width: 9), Expanded(child: Text(title, style: const TextStyle(color: cvInk, fontSize: 15, fontWeight: FontWeight.w900))), if (trailing != null) trailing!]), const SizedBox(height: 13), child]));
}

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


class _OfflineBanner extends StatelessWidget {
  final bool pending;
  final VoidCallback onSync;
  const _OfflineBanner({required this.pending, required this.onSync});
  @override
  Widget build(BuildContext context) => Container(
    width: double.infinity,
    margin: const EdgeInsets.only(bottom: 4),
    padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 11),
    decoration: BoxDecoration(color: const Color(0xFFFFF5E6), border: Border.all(color: const Color(0xFFEBCB98)), borderRadius: BorderRadius.circular(9)),
    child: Row(children: [
      const Icon(Icons.cloud_off_rounded, color: cvGold, size: 19),
      const SizedBox(width: 9),
      Expanded(child: Text(pending ? 'Saved on this device; waiting to sync.' : 'Showing the saved copy on this device.', style: const TextStyle(color: cvInk, fontSize: 12))),
      TextButton(onPressed: onSync, child: const Text('SYNC')),
    ]),
  );
}

class _PanelMessage extends StatelessWidget {
  final String message;
  final VoidCallback onRetry;
  const _PanelMessage({required this.message, required this.onRetry});
  @override
  Widget build(BuildContext context) => Center(child: Padding(padding: const EdgeInsets.all(25), child: Column(mainAxisSize: MainAxisSize.min, children: [const Icon(Icons.info_outline_rounded, color: cvGold, size: 34), const SizedBox(height: 10), Text(message, textAlign: TextAlign.center, style: const TextStyle(color: cvInk)), const SizedBox(height: 12), OutlinedButton.icon(onPressed: onRetry, icon: const Icon(Icons.refresh), label: const Text('TRY AGAIN'))])));
}

InputDecoration _cvInput(String label) => InputDecoration(labelText: label, filled: true, fillColor: const Color(0xFFFAFBFA), contentPadding: const EdgeInsets.symmetric(horizontal: 13, vertical: 13), border: OutlineInputBorder(borderRadius: BorderRadius.circular(9), borderSide: const BorderSide(color: cvLine)), enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(9), borderSide: const BorderSide(color: cvLine)), focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(9), borderSide: const BorderSide(color: cvGreen, width: 1.5)));

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