/**
 * BoostBot Chat Widget - Entry Point
 * 
 * This file initializes the chat widget and mounts it to the DOM
 */

import React from 'react';
import ReactDOM from 'react-dom/client';
import { ChatWidget } from './ChatWidget';
import { ErrorBoundary } from './components/ErrorBoundary';
// [DISABLED 2026-02-04] Showcase feature commented out - no longer needed.
// import { ShowcaseApp } from './showcase/ShowcaseApp';
import './styles/widget.css';
import { getCurrentLocale, refreshLocale } from './utils/locale';
import { useChatStore } from './store/chatStore';
import { generateVisitorId } from './utils/visitor';
import { reloadTranslations } from './lib/i18n';

const SEARCH_AUTO_OPEN_SESSION_KEY = 'boostbot-open-chat-after-search';
const SEARCH_TRANSITION_CONTEXT_SESSION_KEY = 'boostbot-search-transition-context';

interface SearchTransitionContext {
  query: string;
  sourceUrl: string;
  destinationUrl: string;
  submittedAt: number;
}

/**
 * Initialize the widget when DOM is ready
 */
function initWidget() {
  // Don't mount the widget when the backend is unreachable or site is not registered
  const config = window.boostbot_config;
  if (config && config.chat_available === false) {
    return;
  }

  // Find or create the root element
  let rootElement = document.getElementById('boostbot-widget-root');
  
  if (!rootElement) {
    rootElement = document.createElement('div');
    rootElement.id = 'boostbot-widget-root';
    document.body.appendChild(rootElement);
  }
  
  // Set RTL if needed
  const isRtl = window.boostbot_config?.is_rtl ?? (
    document.documentElement.dir === 'rtl' ||
    document.documentElement.lang?.startsWith('he') ||
    document.documentElement.lang?.startsWith('ar')
  );
  
  if (isRtl) {
    rootElement.setAttribute('dir', 'rtl');
  }
  
  // Check if already mounted
  if (rootElement.hasAttribute('data-boostbot-mounted')) {
    return;
  }
  
  // Mark as mounted
  rootElement.setAttribute('data-boostbot-mounted', 'true');
  
  // Mount React app
  try {
    // [DISABLED 2026-02-04] Showcase feature commented out - no longer needed.
    // const params = new URLSearchParams(window.location.search);
    // const isShowcase = params.get('boostbot_showcase') === '1';
    const root = ReactDOM.createRoot(rootElement);
    root.render(
      <React.StrictMode>
        <ErrorBoundary>
          {/* [DISABLED 2026-02-04] Showcase: {isShowcase ? <ShowcaseApp /> : <ChatWidget />} */}
          <ChatWidget />
        </ErrorBoundary>
      </React.StrictMode>
    );
  } catch (error) {
    console.error('BoostBot Widget: Failed to mount', error);
  }
}

function isWordPressSearchForm(form: HTMLFormElement): boolean {
  if (form.getAttribute('role') === 'search') {
    return true;
  }

  if (form.classList.contains('search-form') || form.classList.contains('wp-block-search')) {
    return true;
  }

  return !!form.querySelector('input[type="search"], input[name="s"]');
}

function getSubmittedSearchQuery(form: HTMLFormElement): string {
  try {
    const formData = new FormData(form);
    const query = formData.get('s');
    return typeof query === 'string' ? query.trim() : '';
  } catch {
    const input = form.querySelector('input[name="s"], input[type="search"]');
    return input instanceof HTMLInputElement ? input.value.trim() : '';
  }
}

function buildSearchDestinationUrl(form: HTMLFormElement): string {
  try {
    const baseUrl = new URL(form.action || window.location.href, window.location.href);
    const method = (form.method || 'GET').toUpperCase();

    if (method !== 'GET') {
      return baseUrl.toString();
    }

    const formData = new FormData(form);
    const processedKeys = new Set<string>();
    for (const [key] of formData.entries()) {
      if (processedKeys.has(key)) continue;
      processedKeys.add(key);
      baseUrl.searchParams.delete(key);

      for (const value of formData.getAll(key)) {
        if (typeof value !== 'string') continue;
        baseUrl.searchParams.append(key, value);
      }
    }

    return baseUrl.toString();
  } catch {
    return window.location.href;
  }
}

function onSearchFormSubmitted(event: Event) {
  const form = event.target;
  if (!(form instanceof HTMLFormElement) || !isWordPressSearchForm(form)) {
    return;
  }

  const query = getSubmittedSearchQuery(form);
  if (!query) {
    return;
  }

  const searchContext: SearchTransitionContext = {
    query,
    sourceUrl: window.location.href,
    destinationUrl: buildSearchDestinationUrl(form),
    submittedAt: Date.now(),
  };

  sessionStorage.setItem(SEARCH_AUTO_OPEN_SESSION_KEY, String(Date.now()));
  sessionStorage.setItem(SEARCH_TRANSITION_CONTEXT_SESSION_KEY, JSON.stringify(searchContext));

  const store = useChatStore.getState();
  if (store.isLoaded) {
    store.openChat();
  }
}

// ── Language-change detection (SPA navigation / Polylang AJAX) ───────
// When the page language changes without a full reload, reset the Zustand
// store so the user sees the correct conversation for the new language.
let _lastKnownLocale = getCurrentLocale();

function onLocaleChanged() {
  const newLocale = refreshLocale();
  if (newLocale === _lastKnownLocale) return;

  console.log(`[BoostBot] Language changed: ${_lastKnownLocale} → ${newLocale}`);
  _lastKnownLocale = newLocale;

  // Reload the t() translation map so widget strings switch language too
  // (initTranslations only runs once at module load).
  reloadTranslations(newLocale);

  const hasStoredData = !!localStorage.getItem(`boostbot-chat_${newLocale}`);

  if (hasStoredData) {
    // Rehydrate from the new language's stored conversation
    void useChatStore.persist.rehydrate();
  } else {
    // No prior conversation for this language — start fresh but keep visitor ID
    useChatStore.setState({
      messages: [],
      conversationId: null,
      activeWidget: null,
      currentBotId: null,
      previousBotId: null,
      previousPageUrl: null,
      lastWidgetAssignments: null,
      firedTriggers: new Set<string>(),
      isOpen: false,
      isTyping: false,
      isStreaming: false,
      streamingContent: '',
      isThinking: false,
      thinkingMessage: null,
      cooldownUntil: null,
      remainingHour: null,
      remainingDay: null,
      visitorId: generateVisitorId(),
    });
  }

  // Reload bot config for the new language page
  useChatStore.getState().loadConfig();
}

// Detect <html lang="..."> attribute changes (covers most multilingual plugins)
const langObserver = new MutationObserver(() => onLocaleChanged());
langObserver.observe(document.documentElement, {
  attributes: true,
  attributeFilter: ['lang'],
});

// Poll window.boostbot_config.locale for plugins that update it via AJAX
// without changing the <html lang> attribute (e.g. some Polylang setups)
setInterval(() => {
  const freshRaw =
    window.boostbot_config?.locale ||
    document.documentElement.lang ||
    'en';
  const freshLocale = freshRaw.split(/[_-]/)[0].toLowerCase();
  if (freshLocale !== _lastKnownLocale) {
    onLocaleChanged();
  }
}, 2000);

// ── Widget initialisation ────────────────────────────────────────────
// Initialize when DOM is ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initWidget);
} else {
  // DOM already loaded
  initWidget();
}

document.addEventListener('submit', onSearchFormSubmitted, true);

// Export for potential external use
(window as unknown as { BoostBot?: { init: () => void } }).BoostBot = {
  init: initWidget
};

