(function($) {
	'use strict';

	var cfg = window.wppsContentExpiration || {};
	var busy = false;

	function saveLabel() {
		return (cfg.i18n && cfg.i18n.save) || 'Save expiration';
	}

	function savingLabel() {
		return (cfg.i18n && cfg.i18n.saving) || 'Saving…';
	}

	function expirationInput() {
		var $input = $('.wpps-content-expiration__input');
		return $input.length ? $input : $('#wpps_expiration_date');
	}

	function getPostId() {
		if (window.wp && window.wp.data) {
			var editor = window.wp.data.select('core/editor');
			if (editor && typeof editor.getCurrentPostId === 'function' && editor.getCurrentPostId()) {
				return editor.getCurrentPostId();
			}
		}
		return parseInt(cfg.postId, 10) || 0;
	}

	function metaToInputValue(stored) {
		if (!stored) {
			return '';
		}
		return String(stored).trim().replace(' ', 'T').slice(0, 16);
	}

	function setStatus(message) {
		var $status = $('.wpps-content-expiration__status').first();
		if (!$status.length) {
			return;
		}
		if (!message) {
			$status.attr('hidden', 'hidden').text('');
			return;
		}
		$status.removeAttr('hidden').text(message);
	}

	function applySavedUi(inputValue, displayValue) {
		expirationInput().val(inputValue || '');

		if (displayValue) {
			var savedLabel = (cfg.i18n && cfg.i18n.saved) || 'Saved: %s';
			setStatus(savedLabel.replace('%s', displayValue));
		} else {
			setStatus((cfg.i18n && cfg.i18n.cleared) || 'Expiration cleared.');
		}
	}

	function setSavingState(isSaving) {
		$('.wpps-content-expiration__save')
			.prop('disabled', isSaving)
			.text(isSaving ? savingLabel() : saveLabel());
	}

	function saveExpiration(value) {
		if (busy) {
			return;
		}

		var postId = getPostId();
		if (!cfg.ajaxUrl || !cfg.nonce || !postId) {
			window.alert((cfg.i18n && cfg.i18n.error) || 'Could not save expiration date.');
			return;
		}

		busy = true;
		setSavingState(true);

		$.ajax({
			url: cfg.ajaxUrl,
			method: 'POST',
			dataType: 'json',
			data: {
				action: cfg.action || 'wpps_save_content_expiration',
				nonce: cfg.nonce,
				post_id: postId,
				expiration: value == null ? String(expirationInput().val() || '') : value
			}
		})
			.done(function(response) {
				if (!response || !response.success || !response.data) {
					var message = (response && response.data && response.data.message)
						? response.data.message
						: ((cfg.i18n && cfg.i18n.error) || 'Could not save expiration date.');
					window.alert(message);
					return;
				}

				applySavedUi(response.data.input || '', response.data.display || '');

				if (response.data.unpublished) {
					window.alert((cfg.i18n && cfg.i18n.unpublished) || 'This post was unpublished because the expiration date has passed.');
					window.location.reload();
				}
			})
			.fail(function(xhr) {
				var message = (cfg.i18n && cfg.i18n.error) || 'Could not save expiration date.';
				if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
					message = xhr.responseJSON.data.message;
				}
				window.alert(message);
			})
			.always(function() {
				busy = false;
				setSavingState(false);
			});
	}

	function hydrateFromEditor() {
		if (!window.wp || !window.wp.data) {
			return;
		}

		var editor = window.wp.data.select('core/editor');
		if (!editor || !editor.getCurrentPostId()) {
			return;
		}

		var metaKey = cfg.metaKey || 'wpps_expiration_date';
		var meta = editor.getEditedPostAttribute('meta') || {};
		var stored = meta[metaKey];
		if (!stored) {
			return;
		}

		var $input = expirationInput();
		if ($input.length && !$input.val()) {
			$input.val(metaToInputValue(stored));
		}
	}

	$(document).on('click', '.wpps-content-expiration__save', function(event) {
		event.preventDefault();
		saveExpiration(null);
	});

	$(document).on('click', '.wpps-content-expiration__clear', function(event) {
		event.preventDefault();
		saveExpiration('');
	});

	$(function() {
		// One-time read from editor state; never write back via editPost (prevents core-data loops).
		window.setTimeout(hydrateFromEditor, 250);
	});
})(jQuery);
