(function(wp) {
	if (!wp || !wp.plugins || !wp.editPost) return;

	var registerPlugin = wp.plugins.registerPlugin;
	var PluginDocumentSettingPanel = wp.editPost.PluginDocumentSettingPanel;
	var useState = wp.element.useState;
	var useEffect = wp.element.useEffect;
	var createElement = wp.element.createElement;
	var Button = wp.components.Button;
	var useSelect = wp.data.useSelect;

	var panelTitle = (window.wppsLinkShortener && window.wppsLinkShortener.createShortLink) || 'Create Short Link';
	var copyLabel = (window.wppsLinkShortener && window.wppsLinkShortener.copyShortLink) || 'Copy Short Link';
	var ajaxUrl = (window.wppsLinkShortener && window.wppsLinkShortener.ajaxUrl) || '';
	var nonce = (window.wppsLinkShortener && window.wppsLinkShortener.nonce) || '';

	function ShortLinkPanel() {
		var permalink = useSelect(function(select) {
			var getPermalink = select('core/editor') && select('core/editor').getPermalink;
			return getPermalink ? getPermalink() : null;
		}, []);

		var link = useSelect(function(select) {
			var linkAttr = select('core/editor') && select('core/editor').getEditedPostAttribute && select('core/editor').getEditedPostAttribute('link');
			return linkAttr || null;
		}, []);

		var postLink = permalink || link || null;
		var shortUrl = useState(null);
		var setShortUrl = shortUrl[1];
		shortUrl = shortUrl[0];
		var loading = useState(false);
		var setLoading = loading[1];
		loading = loading[0];
		var error = useState(null);
		var setError = error[1];
		error = error[0];

		var createShortLink = function() {
			var url = permalink || link;
			if (!url) {
				setError('Save or publish the post first to get a URL.');
				return;
			}
			setLoading(true);
			setError(null);
			var formData = new FormData();
			formData.append('action', 'wpps_link_shortener_save');
			formData.append('nonce', nonce);
			formData.append('destination_url', url);
			formData.append('short_code', '');
			formData.append('active', '1');
			fetch(ajaxUrl, { method: 'POST', body: formData })
				.then(function(r) { return r.json(); })
				.then(function(res) {
					setLoading(false);
					if (res.success && res.data && res.data.id) {
						setShortUrl(res.data.short_url || url);
					} else {
						setError(res.data && res.data.message ? res.data.message : 'Failed to create short link.');
					}
				})
				.catch(function() {
					setLoading(false);
					setError('Request failed.');
				});
		};

		var copyToClipboard = function() {
			if (!shortUrl) return;
			if (navigator.clipboard && navigator.clipboard.writeText) {
				navigator.clipboard.writeText(shortUrl).then(function() { setError(null); });
			}
		};

		return createElement(PluginDocumentSettingPanel, {
			name: 'wpps-short-link-panel',
			title: 'Short Link',
			className: 'wpps-short-link-panel'
		}, [
			!postLink && createElement('p', { key: 'hint' }, 'Publish or update the post to get a permalink, then create a short link.'),
			postLink && createElement(Button, {
				key: 'btn',
				isPrimary: !shortUrl,
				variant: shortUrl ? 'secondary' : 'primary',
				onClick: createShortLink,
				isBusy: loading,
				disabled: loading
			}, shortUrl ? 'Create Another' : panelTitle),
			shortUrl && createElement('p', { key: 'url' }, createElement('code', {}, shortUrl)),
			shortUrl && createElement(Button, { key: 'copy', variant: 'secondary', onClick: copyToClipboard }, copyLabel),
			error && createElement('p', { key: 'err', style: { color: '#b32d2e' } }, error)
		]);
	}

	registerPlugin('wpps-link-shortener-panel', {
		render: function() {
			return createElement(ShortLinkPanel, null);
		}
	});
})(window.wp);
