import { useEffect } from 'react';

declare global {
	interface Window {
		Tawk_API?: Partial<{
			onLoad: () => void;
			hideWidget: () => void;
			maximize: () => void;
			toggle: () => void;
			setWidgetPosition: (x: string, y: string) => void;
			onChatMaximized: () => void;
			onChatMinimized: () => void;
			onChatHidden: () => void;
		}>;
		Tawk_LoadStart?: Date;
	}
}

interface TawkChatProps {
	setIsOpen: any; // You can replace 'any' with a more specific type
}

const TawkChat: React.FC<TawkChatProps> = ({ setIsOpen }: { setIsOpen: any }) => {
	useEffect(() => {
		window.Tawk_API = window.Tawk_API || {};
		window.Tawk_LoadStart = new Date();

		const script = document.createElement('script');
		script.src = 'https://embed.tawk.to/6848eb52d08039190efe9bab/1itedeeq4';
		script.async = true;
		script.charset = 'UTF-8';
		script.setAttribute('crossorigin', '*');

		script.onload = () => {
			if (window.Tawk_API) {
				window.Tawk_API.onLoad = () => {
					window.Tawk_API?.hideWidget?.();

					// Add CSS override to move widget 445px left
					// 			const style = document.createElement('style');
					// 			style.innerHTML = `
					//     iframe[title="chat widget"] {
					//       right: 445px !important;
					//     }
					//   `;
					// 			document.head.appendChild(style);
				};

				window.Tawk_API!.onChatMaximized = () => {
					console.log('Tawk.to chat opened');
				};
				window.Tawk_API!.onChatMinimized = () => {
					console.log('Tawk.to chat closed/minimized');
					setIsOpen(true);
				};
				window.Tawk_API!.onChatHidden = () => {
					console.log('Tawk.to chat hidden');
				};
			}
		};

		document.body.appendChild(script);

		return () => {
			document.body.removeChild(script);
		};
	}, []);

	return null;
};

export default TawkChat;
