/**
 * Live 360° preview: wraps the frontend viewer in editable mode.
 */
import { useRef, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { Empty } from 'antd';

import PanoramaViewer from '../../../../frontend/src/viewer';
import { scenesForViewer } from '../../api';

const I18N = {
	loading: __( 'Loading preview…', 'vistour-virtual-tour-builder' ),
	fullscreen: '',
	autorotate: '',
	share: '',
	scenes: '',
	close: __( 'Close', 'vistour-virtual-tour-builder' ),
	copyLink: '',
	webglError: __(
		'Your browser does not support WebGL.',
		'vistour-virtual-tour-builder'
	),
};

const LivePreview = ( { scenes, sceneIndex, onPick, onHotspotEdit } ) => {
	const containerRef = useRef( null );
	const viewerRef = useRef( null );
	const callbacksRef = useRef( { onPick, onHotspotEdit } );
	callbacksRef.current = { onPick, onHotspotEdit };

	const viewerScenes = scenesForViewer( scenes );
	const hasImage = !! viewerScenes[ sceneIndex ]?.image_url;

	useEffect( () => {
		if ( ! containerRef.current || ! hasImage ) {
			return undefined;
		}

		if ( ! viewerRef.current ) {
			try {
				viewerRef.current = new PanoramaViewer( containerRef.current, {
					editable: true,
					scenes: viewerScenes,
					viewer: { start_scene: sceneIndex, height: 420 },
					i18n: I18N,
					onPick: ( yaw, pitch ) =>
						callbacksRef.current.onPick?.( yaw, pitch ),
					onHotspotEdit: ( index ) =>
						callbacksRef.current.onHotspotEdit?.( index ),
				} );
			} catch {
				return undefined;
			}
		} else {
			viewerRef.current.setScenes( viewerScenes, sceneIndex );
		}

		return undefined;
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [ JSON.stringify( viewerScenes ), sceneIndex, hasImage ] );

	useEffect(
		() => () => {
			viewerRef.current?.destroy();
			viewerRef.current = null;
		},
		[]
	);

	if ( ! hasImage ) {
		return (
			<div className="vist360-preview vist360-preview--empty">
				<Empty
					description={ __(
						'Add a 360° image to this scene to see the live preview.',
						'vistour-virtual-tour-builder'
					) }
				/>
			</div>
		);
	}

	return (
		<div className="vist360-preview">
			<div ref={ containerRef } className="vist360-viewer" />
			<span className="vist360-preview__hint">
				{ __(
					'Drag to look around · Click to place a hotspot',
					'vistour-virtual-tour-builder'
				) }
			</span>
		</div>
	);
};

export default LivePreview;
