import { attachPlacesAutocomplete, renderGoogleMap } from '../includes/utils/gmds-map';

function initializeDirectionsAutocomplete() {
	document.querySelectorAll('.gmds-google-map').forEach((mapElement) => {
		const input = mapElement.querySelector('.gmds-directions-input');
		const apiKey = mapElement.dataset.apiKey || '';

		if (!input || !apiKey) {
			return;
		}

		attachPlacesAutocomplete(input, apiKey).catch(() => {});
	});
}

function initializeMaps() {
	document.querySelectorAll('.gmds-google-map').forEach((mapElement) => {
		const canvas = mapElement.querySelector('.gmds-google-map__canvas');
		const address = mapElement.dataset.address || '';
		const apiKey = mapElement.dataset.apiKey || '';
		const zoomLevel = parseInt(mapElement.dataset.zoomLevel || '15', 10);
		const allowMouseWheelScroll = mapElement.dataset.allowMouseWheelScroll === 'on';
		const allowTouchOperations = mapElement.dataset.allowTouchOperations !== 'off';

		if (!canvas || !address || !apiKey || canvas.dataset.gmdsInitialized === 'true') {
			return;
		}

		canvas.dataset.gmdsInitialized = 'true';

		renderGoogleMap(canvas, {
			address,
			apiKey,
			zoomLevel,
			allowMouseWheelScroll,
			allowTouchOperations,
		}).catch(() => {
			canvas.dataset.gmdsInitialized = 'false';
		});
	});
}

if (document.readyState === 'loading') {
	document.addEventListener('DOMContentLoaded', () => {
		initializeMaps();
		initializeDirectionsAutocomplete();
	});
} else {
	initializeMaps();
	initializeDirectionsAutocomplete();
}

window.addEventListener('load', initializeMaps);
window.addEventListener('load', initializeDirectionsAutocomplete);
