'use client';

import { useEffect } from 'react';

declare global {
  interface Window {
    chatwootSDK?: {
      run: (config: {
        websiteToken: string;
        baseUrl: string;
        hideMessageBubble?: boolean;
        type?: 'standard' | 'expanded_bubble';
        darkMode?: 'auto' | 'light' | 'dark';
      }) => void;
    };
    $chatwoot?: {
      toggle: () => void;
      open: () => void;
      close: () => void;
      setCustomAttributes?: (attributes: Record<string, any>) => void;
    };
    chatwootSettings?: {
      type?: 'standard' | 'expanded_bubble';
      hideMessageBubble?: boolean;
      position?: 'left' | 'right';
      darkMode?: 'auto' | 'light' | 'dark';
    };
  }
}

export default function ChatwootWidget() {
  useEffect(() => {
    // Add Chatwoot Settings
    const BASE_URL = 'https://ainoc-omnichannel.beprime.mx/';
    const WEBSITE_TOKEN = 'U8Ce8yUzN9hngW5sAmFDDhvv';

    // Configurar opciones antes de cargar el script
    window.chatwootSettings = {
      hideMessageBubble: true,
      position: 'right',
      type: 'expanded_bubble', // Modo Chat simple
      darkMode: 'dark', // Activar tema oscuro
    };

    // Check if script already exists
    if (document.getElementById('chatwoot-sdk')) {
      return;
    }

    // Create script element
    const script = document.createElement('script');
    script.id = 'chatwoot-sdk';
    script.src = `${BASE_URL}/packs/js/sdk.js`;
    script.async = true;

    script.onload = () => {
      window.chatwootSDK?.run({
        websiteToken: WEBSITE_TOKEN,
        baseUrl: BASE_URL,
        hideMessageBubble: true, // Ocultar el botón flotante predeterminado
        type: 'expanded_bubble', // Modo Chat simple y directo
        darkMode: 'dark', // Activar tema oscuro
      });
    };

    // Append to body
    document.body.appendChild(script);

    // Cleanup function
    return () => {
      const existingScript = document.getElementById('chatwoot-sdk');
      if (existingScript) {
        document.body.removeChild(existingScript);
      }
      // Limpiar configuración global
      delete window.chatwootSettings;
    };
  }, []);

  return (
    <>
      {/* Ocultar el botón flotante de Chatwoot con CSS */}
      <style jsx global>{`
        .woot-widget-bubble,
        .woot--bubble-holder {
          display: none !important;
        }
      `}</style>
    </>
  );
}
