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

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

	var cfg = window.wppsPublicPreview || {};
	var enabledTypes = cfg.enabledTypes || [];

	function PublicPreviewPanel() {
		var postId = useSelect(function (select) {
			var ed = select('core/editor');
			return ed ? ed.getCurrentPostId() : 0;
		}, []);
		var status = useSelect(function (select) {
			var ed = select('core/editor');
			return ed && ed.getEditedPostAttribute ? ed.getEditedPostAttribute('status') : '';
		}, []);
		var postType = useSelect(function (select) {
			var ed = select('core/editor');
			return ed && ed.getCurrentPostType ? ed.getCurrentPostType() : '';
		}, []);

		var urlState = useState('');
		var url = urlState[0];
		var setUrl = urlState[1];
		var loadingState = useState(false);
		var loading = loadingState[0];
		var setLoading = loadingState[1];
		var errState = useState('');
		var err = errState[0];
		var setErr = errState[1];
		var refreshState = useState(0);
		var refreshKey = refreshState[0];
		var setRefreshKey = refreshState[1];

		useEffect(
			function () {
				if (status !== 'draft' || !postId || enabledTypes.indexOf(postType) === -1) {
					setUrl('');
					setErr('');
					setLoading(false);
					return;
				}
				var cancelled = false;
				setLoading(true);
				setErr('');
				apiFetch({ path: '/wp-powersuite/v1/public-preview-link/' + postId })
					.then(function (res) {
						if (!cancelled && res && res.url) {
							setUrl(res.url);
						}
					})
					.catch(function (e) {
						if (!cancelled) {
							setUrl('');
							var msg =
								(e && e.data && e.data.message) ||
								(e && e.message) ||
								(cfg.strings && cfg.strings.error) ||
								'Error';
							setErr(String(msg));
						}
					})
					.finally(function () {
						if (!cancelled) {
							setLoading(false);
						}
					});
				return function () {
					cancelled = true;
				};
			},
			[postId, status, postType, refreshKey]
		);

		if (status !== 'draft' || enabledTypes.indexOf(postType) === -1) {
			return null;
		}
		if (!postId) {
			return null;
		}

		function copyLink() {
			if (!url) {
				return;
			}
			if (navigator.clipboard && navigator.clipboard.writeText) {
				navigator.clipboard.writeText(url).catch(function () {
					fallbackCopy(url);
				});
			} else {
				fallbackCopy(url);
			}
		}

		function fallbackCopy(text) {
			var ta = document.createElement('textarea');
			ta.value = text;
			ta.setAttribute('readonly', '');
			ta.style.position = 'absolute';
			ta.style.left = '-9999px';
			document.body.appendChild(ta);
			ta.select();
			try {
				document.execCommand('copy');
			} catch (ignore) {}
			document.body.removeChild(ta);
		}

		var children = [];
		if (cfg.strings && cfg.strings.help) {
			children.push(
				createElement(
					'p',
					{ key: 'help', className: 'description', style: { marginTop: 0 } },
					cfg.strings.help
				)
			);
		}
		if (loading) {
			children.push(createElement(Spinner, { key: 'sp' }));
		}
		if (err) {
			children.push(
				createElement(
					'p',
					{ key: 'err', className: 'description', style: { color: '#b32d2e', marginBottom: 0 } },
					err
				)
			);
		}
		if (url && !loading) {
			children.push(
				createElement('input', {
					key: 'inp',
					type: 'text',
					readOnly: true,
					className: 'widefat',
					value: url,
					onFocus: function (e) {
						e.target.select();
					},
					style: {
						marginBottom: '8px',
						fontFamily: 'monospace',
						fontSize: '12px',
						width: '100%',
						boxSizing: 'border-box',
					},
					'aria-label': (cfg.strings && cfg.strings.urlLabel) || '',
				})
			);
			children.push(
				createElement(
					'div',
					{ key: 'btns', style: { display: 'flex', gap: '8px', flexWrap: 'wrap' } },
					[
						createElement(
							Button,
							{
								key: 'copy',
								variant: 'secondary',
								isSmall: true,
								onClick: copyLink,
							},
							(cfg.strings && cfg.strings.copy) || 'Copy link'
						),
						createElement(
							Button,
							{
								key: 'ref',
								variant: 'tertiary',
								isSmall: true,
								onClick: function () {
									setRefreshKey(function (k) {
										return k + 1;
									});
								},
							},
							(cfg.strings && cfg.strings.refresh) || 'Refresh link'
						),
					]
				)
			);
		}

		return createElement(
			PluginDocumentSettingPanel,
			{
				name: 'wpps-public-preview',
				title: (cfg.strings && cfg.strings.title) || 'Public preview',
				className: 'wpps-public-preview-panel',
				icon: 'visibility',
			},
			children
		);
	}

	registerPlugin('wpps-public-preview', {
		render: PublicPreviewPanel,
		icon: 'visibility',
	});
})(window.wp);
