import { useEffect } from 'react';

const CONTAINER_ID = 'recomaze-app-container';

const TawkTo = (): null => {
  useEffect(() => {
    (window as any).Tawk_API = (window as any).Tawk_API || {};

    const repositionWidget = () => {
      const container = document.getElementById(CONTAINER_ID);
      if (!container) return;

      const rect = container.getBoundingClientRect();

      const iframes = document.querySelectorAll('iframe[title="chat widget"]');

      iframes.forEach(iframe => {
        const el = iframe as HTMLIFrameElement;
        // Keep fixed so it doesn't scroll away
        el.style.setProperty('position', 'fixed', 'important');
        // Pin to bottom-right of the app container
        el.style.setProperty('bottom', '20px', 'important');
        el.style.setProperty('left', `${rect.left + 20}px`, 'important');
        el.style.setProperty('right', 'auto', 'important');
      });
    };

    (window as any).Tawk_API.onLoad = () => {
      repositionWidget();

      // Reposition on scroll/resize since the container's viewport position changes
      window.addEventListener('scroll', repositionWidget, true);
      window.addEventListener('resize', repositionWidget);
    };

    const s1 = document.createElement('script');
    const s0 = document.getElementsByTagName('script')[0];
    s1.async = true;
    s1.src = 'https://embed.tawk.to/660c8bcea0c6737bd1279c5f/1hqgg486d';
    s1.charset = 'UTF-8';
    s1.setAttribute('crossorigin', '*');
    s0.parentNode?.insertBefore(s1, s0);

    return () => {
      s1.remove();
      window.removeEventListener('scroll', repositionWidget, true);
      window.removeEventListener('resize', repositionWidget);
    };
  }, []);

  return null;
};

export default TawkTo;
