/**
 * MyAi CV Matcher Form
 *
 * Handles CV upload, job description input, and match result rendering.
 * Uses shared utilities from: utils/form-helpers.js, utils/i18n.js, utils/api.js
 *
 * Depends on: jQuery, i18n.js (translation dict), shared utility modules
 */
(function ($) {
	"use strict";

	/* ============================================================
	   CV FILE INPUT HANDLER
	   ============================================================ */

	/**
	 * Update displayed CV filename when file is selected.
	 */
	$('#cvFile').on('change', function () {
		var file = this.files && this.files[0];
		$('#cvFileName').text(file ? file.name : window.MyAi.t('cv.fileHint'));
	});

	/* ============================================================
	   CV MATCHER FORM HANDLER
	   ============================================================ */

	/**
	 * Handle CV Matcher form submission with async upload and match flow.
	 * Requires reCaptcha verification for both CV upload and match actions.
	 */
	$('#cvMatcherForm').on('submit', async function (event) {
		event.preventDefault();
		var file = $('#cvFile')[0] && $('#cvFile')[0].files[0];
		var jobUrl = $('#jobUrl').val();
		var jobDescription = $('#jobDescription').val();
		var matchEmail = $('#matchEmail').val();
		var consent = $('#gdprConsent').is(':checked');
		var $msg = $('#matcherMsg'),
			$button = $('#matchSubmit'),
			$result = $('#matchResult');

		window.MyAi.clearFieldErrors(['cvFileError', 'cvJobError', 'cvConsentError']);
		$msg.removeClass().addClass('form-message').text('');

		// Validate inputs
		var hasError = false;
		if (!file) { window.MyAi.showFieldError('cvFileError', window.MyAi.t('cv.noFile')); hasError = true; }
		if (!jobUrl && !jobDescription) { window.MyAi.showFieldError('cvJobError', window.MyAi.t('cv.noJob')); hasError = true; }
		if (!consent) { window.MyAi.showFieldError('cvConsentError', window.MyAi.t('cv.noConsent')); hasError = true; }
		if (hasError) return;

		var $cvLoader = $('#cvLoader');
		$button.prop('disabled', true).text(window.MyAi.t('cv.processing'));
		$msg.removeClass().addClass('form-message').text(window.MyAi.t('cv.extracting'));
		$result.html('<div class="empty-result">' + escapeHtml(window.MyAi.t('cv.processingLong')) + '</div>');
		$cvLoader.addClass('loader-visible');

		// Require reCaptcha and get CV upload token
		if (window.grecaptcha && window.MyAi.getReCaptchaSiteKey()) {
			grecaptcha.ready(function () {
				grecaptcha.execute(window.MyAi.getReCaptchaSiteKey(), {
					action: 'cv_upload'
				}).then(postCv);
			});
		} else {
			$cvLoader.removeClass('loader-visible');
			$msg.removeClass().addClass('form-message text-danger').text(window.MyAi.t('form.captchaFailed'));
			$button.prop('disabled', false).text(window.MyAi.t('cv.submit'));
			return;
		}

		/**
		 * Upload CV and request match score.
		 * Two-step process: upload CV PDF, then submit match request with fresh captcha token.
		 */
		async function postCv(token) {
			try {
				// Upload CV PDF
				var formData = new FormData();
				formData.append('file', file);
				formData.append('gdprConsent', String(consent));
				formData.append('captchaToken', token || '');
				var cvResponse = await fetch('/api/cv-matcher/upload', {
					method: 'POST',
					body: formData
				});
				if (!cvResponse.ok) {
					var cvErrBody = null;
					try { cvErrBody = await cvResponse.json(); } catch (_) {}
					throw new Error(window.MyAi.extractApiError(cvErrBody, cvResponse.status, 'cv.cvFailed', 'cv.rateLimited'));
				}
				var cvData = await cvResponse.json();

				// Get fresh captcha token for match action
				if (!(window.grecaptcha && window.MyAi.getReCaptchaSiteKey())) {
					throw new Error(window.MyAi.t('form.captchaFailed'));
				}
				var matchToken = await new Promise(function (resolve, reject) {
					try {
						grecaptcha.ready(function () {
							grecaptcha.execute(window.MyAi.getReCaptchaSiteKey(), { action: 'match_job' }).then(resolve).catch(reject);
						});
					} catch (e) { reject(e); }
				});

				// Request match
				var matchResponse = await fetch('/api/cv-matcher/match-job', {
					method: 'POST',
					headers: {
						'Content-Type': 'application/json'
					},
					body: JSON.stringify({
						cvDocumentId: cvData.documentId || cvData.cvDocumentId,
						jobUrl: jobUrl,
						jobDescription: jobDescription,
						email: matchEmail,
						gdprConsent: consent,
						captchaToken: matchToken,
						language: window.MyAi.currentLang()
					})
				});
				if (!matchResponse.ok) {
					var matchErrBody = null;
					try { matchErrBody = await matchResponse.json(); } catch (_) {}
					throw new Error(window.MyAi.extractApiError(matchErrBody, matchResponse.status, 'cv.matchFailed', 'cv.rateLimited'));
				}
				var match = await matchResponse.json();
				renderMatchResult(match);
				$msg.removeClass().addClass('form-message text-success').text(window.MyAi.t('cv.completed'));
			} catch (err) {
				console.error(err);
				var isRateLimited = err && err.message === window.MyAi.t('cv.rateLimited');
				var tone = isRateLimited ? 'text-warning' : 'text-danger';
				$msg.removeClass().addClass('form-message ' + tone).text(err.message || window.MyAi.t('cv.matchFailed'));
				$result.html('<div class="empty-result">' + escapeHtml(isRateLimited ? window.MyAi.t('cv.rateLimited') : window.MyAi.t('cv.backendMissing')) + '</div>');
			} finally {
				$cvLoader.removeClass('loader-visible');
				$button.prop('disabled', false).text(window.MyAi.t('cv.submit'));
			}
		}
	});

	/* ============================================================
	   MATCH RESULT RENDERING
	   ============================================================ */

	/**
	 * Render CV match result into #matchResult panel.
	 * Displays match score percentage, summary, strengths, gaps, and evidence excerpts.
	 */
	function renderMatchResult(match) {
		var score = match.score || match.matchScore || 0;
		var summary = match.summary || window.MyAi.t('cv.noSummary');
		var strengths = match.strengths || [];
		var gaps = match.gaps || match.missingSkills || [];
		var evidence = match.evidence || match.retrievedChunks || [];

		/**
		 * Render list of items (strengths, gaps, evidence).
		 */
		function list(items) {
			if (!items || !items.length) {
				return '<p class="empty-result">' + escapeHtml(window.MyAi.t('cv.noItems')) + '</p>';
			}
			return '<ul class="result-list">' + items.map(function (x) {
				var text = typeof x === 'string' ? x : (x.text || x.title || JSON.stringify(x));
				return '<li>' + escapeHtml(text) + '</li>';
			}).join('') + '</ul>';
		}

		$('#matchResult').html(
			'<div class="score-badge">' + Number(score).toFixed(0) + '%</div>' +
			'<p>' + escapeHtml(summary) + '</p>' +
			'<h3>' + window.MyAi.t('cv.strengths') + '</h3>' + list(strengths) +
			'<h3>' + window.MyAi.t('cv.gaps') + '</h3>' + list(gaps) +
			'<h3>' + window.MyAi.t('cv.evidence') + '</h3>' + list(evidence)
		);
	}

	/* ============================================================
	   UTILITY FUNCTIONS
	   ============================================================ */

	/**
	 * Escape HTML special characters to prevent XSS.
	 * Replaces &, <, >, ", ' with their HTML entity equivalents.
	 */
	function escapeHtml(value) {
		return String(value).replace(/[&<>'"]/g, function (char) {
			return ({
				'&': '&amp;',
				'<': '&lt;',
				'>': '&gt;',
				"'": '&#39;',
				'"': '&quot;'
			})[char];
		});
	}

	/* ============================================================
	   API CONFIGURATION LOADING (from utils/api.js)
	   ============================================================ */

	/**
	 * Load reCaptcha site key on page load (needed for CV upload).
	 * Uses shared utility: window.MyAi.getRecaptchaWebKey()
	 */
	$(window).on('load', function () {
		window.MyAi.getRecaptchaWebKey();
	});

})(jQuery);
