/**
 * Main Chat Widget Component
 * Combines all chat components + Smart Triggers
 */

import { useEffect, useRef } from 'react';
import { ChatBubble } from './components/ChatBubble';
import { ChatWindow } from './components/ChatWindow';
import { useChatStore } from './store/chatStore';
import { initTriggers, destroyTriggers } from './components/TriggerHandler';
import { resolveValue } from './utils/resolveAppearance';

const SEARCH_AUTO_OPEN_SESSION_KEY = 'boostbot-open-chat-after-search';

export function ChatWidget() {
  const { loadConfig, isLoaded, config, openChat } = useChatStore();
  const fontStyleRef = useRef<HTMLStyleElement | null>(null);
  
  // Load config on mount
  useEffect(() => {
    loadConfig();
  }, [loadConfig]);
  
  // Inject custom font CSS and apply font family
  useEffect(() => {
    if (!isLoaded) return;
    
    // Apply custom font CSS if available
    if (config.custom_font_css) {
      // Remove existing custom font style if any
      const existingStyle = document.getElementById('boostbot-custom-fonts');
      if (existingStyle) {
        existingStyle.remove();
      }
      if (fontStyleRef.current) {
        fontStyleRef.current.remove();
      }
      
      // Create and inject new style element
      const style = document.createElement('style');
      style.id = 'boostbot-custom-fonts';
      style.textContent = config.custom_font_css;
      document.head.appendChild(style);
      fontStyleRef.current = style;
    }
    
    // Apply font-family to widget root (with slight delay to ensure DOM is ready).
    // IMPORTANT: in the new appearance system this value can be a FieldValue (global ref),
    // so we must resolve it against global_values.
    const globalValues = config.appearance_preset?.global_values as any;
    const fontFamilyResolved =
      config.appearance?.font_family ||
      resolveValue(globalValues?.typography?.fontFamily, globalValues, '');
    
    const applyFont = () => {
      if (fontFamilyResolved && fontFamilyResolved !== 'inherit') {
        const widgetRoot = document.getElementById('boostbot-widget-root');
        if (widgetRoot) {
          // Apply as CSS variable for better inheritance (used by widget.css)
          const stack = `${fontFamilyResolved}, 'Heebo', system-ui, sans-serif`;
          widgetRoot.style.setProperty('--bb-font-family', stack);
          widgetRoot.style.fontFamily = stack;
          console.log('[BoostBot] Applied font:', fontFamilyResolved);
        }
      }
    };
    
    // Apply immediately and again after a short delay to ensure it takes effect
    applyFont();
    const timer = setTimeout(applyFont, 100);
    
    // Cleanup on unmount
    return () => {
      clearTimeout(timer);
      if (fontStyleRef.current) {
        fontStyleRef.current.remove();
        fontStyleRef.current = null;
      }
    };
  }, [isLoaded, config.custom_font_css, config.appearance?.font_family, config.appearance_preset?.global_values]);
  
  // Initialize Smart Triggers after config is loaded
  useEffect(() => {
    if (!isLoaded) return;
    if (config.is_active === false) return;
    
    // TODO: In the future, triggers config will come from the API
    // For now, using defaults
    initTriggers();
    
    // Cleanup on unmount
    return () => {
      destroyTriggers();
    };
  }, [isLoaded]);
  
  // Auto-open after delay (if configured)
  useEffect(() => {
    if (!isLoaded || config.is_active === false || !config.auto_open_delay) return;
    
    const timer = setTimeout(() => {
      openChat();
    }, config.auto_open_delay * 1000);
    
    return () => clearTimeout(timer);
  }, [isLoaded, config.auto_open_delay, openChat]);

  useEffect(() => {
    if (!isLoaded) return;

    const pendingSearchOpen = sessionStorage.getItem(SEARCH_AUTO_OPEN_SESSION_KEY);
    if (!pendingSearchOpen) return;

    sessionStorage.removeItem(SEARCH_AUTO_OPEN_SESSION_KEY);

    if (config.is_active === false || config.chat_available === false) {
      return;
    }

    openChat();
  }, [isLoaded, config.is_active, config.chat_available, openChat]);
  
  // Check if should show on mobile
  const isMobile = window.innerWidth < 640;
  if (isMobile && !config.show_on_mobile) {
    return null;
  }
  
  // Wait for config to load
  if (!isLoaded) {
    return null;
  }

  // Config decided that the widget should not render on this page (e.g. default bot excluded)
  if (config.is_active === false) {
    return null;
  }

  // Week 26 policy: if chat is not available (no credits / site disabled / backend not configured),
  // hide the entire widget (no bubble) to avoid a "dead" chatbot entry point on the site.
  if (config.chat_available === false) {
    return null;
  }
  
  return (
    <>
      <ChatBubble />
      <ChatWindow />
    </>
  );
}
