/* ==========================================================================
   Niwa Chatbot -- Main Application Orchestrator
   ---------------------------------------------------------------------------
   Single entry point that initializes all modules on DOMContentLoaded.

   MODULE LOAD ORDER:
     1. ThemeSwitcher    — applies stored/OS/admin theme immediately
     2. MorphController  — enables morph open/close interaction
     3. MessageRenderer  — message rendering, history, typing indicator
     4. ChatClient       — AJAX communication, queue polling
     5. FormHandler      — email/phone/standard form management
     6. ProductManager   — product cards, cart operations
     7. ScrollBehavior   — auto-scroll message area
     8. Input bindings   — textarea keydown, send button click

   NAMESPACE: window.Niwa
   CONFIG:    window.NiwaAI (localized by WordPress)
   ========================================================================== */

(function () {
  'use strict';

  window.Niwa = window.Niwa || {};

  /* -- State management --------------------------------------------------- */

  // Shared state (replaces old NiwaAIFrontend.state)
  window.Niwa.state = window.Niwa.state || {
    chatState: {
      hasAskedForName: false,
      userName: '',
      userEmail: '',
      awaitingEmail: false,
      emailValidated: false,
      userPhone: '',
      awaitingPhone: false,
      phoneValidated: false,
      cbReadyForReset: false,
      cbWaitingForCoupon: false
    },
    postFlowMute: false,
    setPostFlowMute: function (val) {
      window.Niwa.state.postFlowMute = val;
    },
    saveChatState: function () {
      try {
        var key = (window.Niwa.Utils && window.Niwa.Utils.STORAGE_KEY) || 'niwa_ai_chat_history_v1';
        localStorage.setItem(key + '_state', JSON.stringify(window.Niwa.state.chatState));
      } catch (e) { /* ignore */ }
    },
    loadChatState: function () {
      try {
        var key = (window.Niwa.Utils && window.Niwa.Utils.STORAGE_KEY) || 'niwa_ai_chat_history_v1';
        var saved = localStorage.getItem(key + '_state');
        if (saved) {
          var parsed = JSON.parse(saved);
          var cs = window.Niwa.state.chatState;
          var keys = Object.keys(parsed);
          for (var i = 0; i < keys.length; i++) {
            cs[keys[i]] = parsed[keys[i]];
          }
        }

        // Check for global email validation
        var globalEmail = sessionStorage.getItem('niwa_validated_email');
        if (globalEmail && !window.Niwa.state.chatState.emailValidated) {
          window.Niwa.state.chatState.userEmail = globalEmail;
          window.Niwa.state.chatState.emailValidated = true;
          window.Niwa.state.saveChatState();
        }
      } catch (e) { /* ignore */ }
    }
  };

  /* -- Backward compatibility bridge -------------------------------------- */

  // Provide NiwaAIFrontend namespace for CB, Attention Capture, and Leave Stoper
  window.NiwaAIFrontend = window.NiwaAIFrontend || {};
  var F = window.NiwaAIFrontend;

  F.state = F.state || window.Niwa.state;
  F.cb = F.cb || {};

  // Bridge functions that external modules expect
  F.getSessionId = function () {
    return (window.Niwa.Utils && window.Niwa.Utils.getSession) ? window.Niwa.Utils.getSession() : '';
  };
  F._escapeHtml = function (t) {
    return (window.Niwa.Utils && window.Niwa.Utils.escapeHtml) ? window.Niwa.Utils.escapeHtml(t) : t;
  };
  F.normalizeProduct = function (p) {
    return (window.Niwa.Utils && window.Niwa.Utils.normalizeProduct) ? window.Niwa.Utils.normalizeProduct(p) : p;
  };
  F.buildRatingHtml = function (r, c) {
    return (window.Niwa.Utils && window.Niwa.Utils.buildRatingHtml) ? window.Niwa.Utils.buildRatingHtml(r, c) : '';
  };
  F.sanitizePriceHtml = function (h) {
    return (window.Niwa.Utils && window.Niwa.Utils.sanitizePriceHtml) ? window.Niwa.Utils.sanitizePriceHtml(h) : h;
  };
  F.enableDragScroll = function (el) {
    if (window.Niwa.ProductManager && window.Niwa.ProductManager.enableDragScroll) {
      window.Niwa.ProductManager.enableDragScroll(el);
    }
  };
  F.extractAjaxErrorMessage = function (r, fb) {
    return (window.Niwa.Utils && window.Niwa.Utils.extractAjaxErrorMessage) ? window.Niwa.Utils.extractAjaxErrorMessage(r, fb) : (fb || '');
  };

  // Animation bridge for external modules (Attention Capture, Leave Stoper, CB)
  F.animations = F.animations || {};
  F.animations.showTyping = function () {
    if (window.Niwa.MessageRenderer) window.Niwa.MessageRenderer.showTyping();
  };
  F.animations.hideTyping = function () {
    if (window.Niwa.MessageRenderer) window.Niwa.MessageRenderer.hideTyping();
  };
  F.animations.scrollBottom = function () {
    var bodyEl = document.querySelector('.niwa-morph__body') || document.querySelector('.niwa-center__body');
    if (bodyEl && window.Niwa.ScrollBehavior) {
      window.Niwa.ScrollBehavior.scrollToBottom(bodyEl);
    }
  };
  F.animations.injectAssistantMessage = function (message, source) {
    if (window.Niwa.MessageRenderer) {
      window.Niwa.MessageRenderer.injectAssistantMessage(message, source);
    }
  };
  F.animations.addCopyBtn = function () { /* no-op: handled by MessageRenderer */ };

  // Positioning bridge
  F.positioning = F.positioning || {};
  F.positioning.openFlyout = function () {
    if (window.Niwa.MorphController) window.Niwa.MorphController.open();
  };
  F.positioning.closeFlyout = function () {
    if (window.Niwa.MorphController) window.Niwa.MorphController.close();
  };

  // Forms bridge
  F.forms = F.forms || {};
  F.forms.showEmailForm = function () {
    if (window.Niwa.FormHandler) window.Niwa.FormHandler.showEmailForm();
  };
  F.forms.showEmailFormOnly = function () {
    if (window.Niwa.FormHandler) window.Niwa.FormHandler.showEmailForm(false, { force: true });
  };
  F.forms.showStandardForm = function () {
    if (window.Niwa.FormHandler) window.Niwa.FormHandler.showStandardForm();
  };
  F.forms.showPhoneForm = function (skip) {
    if (window.Niwa.FormHandler) window.Niwa.FormHandler.showPhoneForm(skip ? false : undefined);
  };

  // Render bridge
  F.render = F.render || {};
  F.render.renderProducts = function (products, skipSave) {
    if (window.Niwa.ProductManager) window.Niwa.ProductManager.renderProducts(products, skipSave);
  };
  F.render.renderSuggestions = function (list, codes, skipSave) {
    if (window.Niwa.MessageRenderer) window.Niwa.MessageRenderer.renderSuggestions(list, codes, skipSave);
  };

  // History bridge
  F.appendHistoryEntry = function (entry) {
    // MessageRenderer handles its own history
  };
  F.syncHistoryFromDom = function () {
    // Not needed: MessageRenderer tracks history internally
  };

  // Sanitization bridge
  F.formatBotRichText = function (t) {
    return (window.Niwa.Utils && window.Niwa.Utils.formatBotRichText) ? window.Niwa.Utils.formatBotRichText(t) : t;
  };
  F.sanitizeWithAllowlist = function (h) {
    return (window.Niwa.Utils && window.Niwa.Utils.sanitizeHtml) ? window.Niwa.Utils.sanitizeHtml(h) : h;
  };

  // WooCommerce fragment bridge
  F.applyWooFragments = function (fragments, cartHash, btn) {
    if (window.Niwa.ProductManager) return window.Niwa.ProductManager.applyWooFragments(fragments, cartHash, btn);
    return false;
  };

  /* -- Initialize --------------------------------------------------------- */

  var _initialized = false;

  function initializeApp() {
    if (_initialized) return;
    _initialized = true;

    if (!document.querySelector('.niwa-widget')) return;

    // 1. Theme
    if (window.Niwa.ThemeSwitcher) {
      window.Niwa.ThemeSwitcher.init();
    }

    // 2. Load chat state
    window.Niwa.state.loadChatState();

    // 3. Morph controller
    var isCenterstage = window.NiwaAI && window.NiwaAI.centerstage_mode;
    var cfg = window.NiwaAI || {};
    var desktopPos = (cfg.launcher_desktop && cfg.launcher_desktop.position) || 'br';

    if (window.Niwa.MorphController) {
      window.Niwa.MorphController.init({
        mode: isCenterstage ? 'center' : 'morph',
        position: desktopPos,
        launcher_text: cfg.launcher_text || '',
        assistant_display_name: cfg.assistant_display_name || '',
        launcher_desktop: cfg.launcher_desktop || { position: 'br' },
        launcher_tablet:  cfg.launcher_tablet  || { position: 'br' },
        launcher_mobile:  cfg.launcher_mobile  || { position: 'br' }
      });
    }

    // 4. Message renderer
    var bodyEl = document.querySelector('.niwa-morph__body')
      || document.querySelector('.niwa-center__body');

    if (bodyEl && window.Niwa.MessageRenderer) {
      window.Niwa.MessageRenderer.init(bodyEl);
      // Load history or show greeting
      var history = window.Niwa.MessageRenderer.loadFromStorage();
      if (!history || !history.length) {
        // Mode 2: Email Start Chat Cacher — replace greeting with email unlock prompt + inline form
        var escEnabled = !!(window.NiwaAI && window.NiwaAI.email_start_chat_cacher_enabled);
        var alreadyUnlocked = false;
        try { alreadyUnlocked = !!sessionStorage.getItem('niwa_validated_email'); } catch (e) { /* ignore */ }

        if (escEnabled && !alreadyUnlocked && window.Niwa.FormHandler) {
          var labels = (window.NiwaAI && window.NiwaAI.labels) || {};
          var customPrompt = (window.NiwaAI && window.NiwaAI.email_start_chat_cacher_prompt) || '';
          var unlockText = (customPrompt && String(customPrompt).trim())
            || labels.email_unlock_chat
            || 'Please enter your email to unlock the AI assistant.';
          window.Niwa.FormHandler.showEmailForm(unlockText, { force: true, messageSource: 'escc_unlock' });
        } else {
          // Normal flow: greeting + suggestions
          var greeting = window.NiwaAI && window.NiwaAI.greeting;
          if (greeting) {
            window.Niwa.MessageRenderer.addMessage(greeting, 'bot', { source: 'greeting' });
          }
          // Show initial suggestions
          if (window.NiwaAI && window.NiwaAI.initial_suggestions && window.Niwa.ChatClient) {
            var suggestions = window.Niwa.ChatClient.getDefaultSuggestions();
            var codes = window.Niwa.ChatClient.getDefaultSuggestionCodes();
            if (suggestions && suggestions.length) {
              window.Niwa.MessageRenderer.renderSuggestions(suggestions, codes, true);
            }
          }
        }
      }

      // Scroll behavior
      if (window.Niwa.ScrollBehavior) {
        window.Niwa.ScrollBehavior.init(bodyEl);
      }
    }

    // 5. Restore unread state and resume a turn that survived page navigation.
    if (window.Niwa.ChatClient && typeof window.Niwa.ChatClient.init === 'function') {
      window.Niwa.ChatClient.init();
    }

    // 6. Bind send: Enter key (without Shift) and send button click
    _bindSendHandlers();

    // 7. Export initChat for CB compatibility
    F.initChat = function () { /* already initialized */ };

    // 8. Mark niwaAI namespace ready
    _setupNiwaAINamespace();

    console.log('[Niwa] Chatbot UI initialized.');
  }

  /* -- Send handler bindings ---------------------------------------------- */

  function _bindSendHandlers() {
    var textarea = window.Niwa.MorphController ? window.Niwa.MorphController.getTextarea() : null;
    var sendBtn = window.Niwa.MorphController ? window.Niwa.MorphController.getSendBtn() : null;

    function doSend() {
      if (!textarea) return;
      var text = textarea.value.trim();
      if (!text) return;

      if (window.Niwa.ChatClient) {
        window.Niwa.ChatClient.sendMessage(text);
      }
    }

    // Enter key (without Shift)
    if (textarea) {
      textarea.addEventListener('keydown', function (e) {
        if (e.key === 'Enter' && !e.shiftKey) {
          e.preventDefault();
          doSend();
        }
      });
    }

    // Send button click
    if (sendBtn) {
      sendBtn.addEventListener('click', function () {
        doSend();
      });
    }
  }

  /* -- niwaAI global namespace (CB compatibility) ------------------------- */

  function _setupNiwaAINamespace() {
    var n = window.niwaAI = window.niwaAI || {};

    n.openChat = function () {
      if (window.Niwa.MorphController) window.Niwa.MorphController.open();
    };

    n._send = function (text, isUserInitiated) {
      if (!text || !String(text).trim()) return;

      text = String(text).trim();

      // Clear postFlowMute on user-initiated message
      if (isUserInitiated && window.Niwa.state.postFlowMute) {
        window.Niwa.state.setPostFlowMute(false);
      }

      // Block auto-messages during postFlowMute
      if (window.Niwa.state.postFlowMute && !isUserInitiated) return;

      if (window.Niwa.ChatClient) {
        window.Niwa.ChatClient.sendMessage(text);
      }
    };

    n.sendMessage = function (text) {
      n._send(text, true);
    };

    n.handleResponse = function (res) {
      // Handled by ChatClient internally, but CB may call this
      if (window.Niwa.MessageRenderer) window.Niwa.MessageRenderer.hideTyping();
    };

    n.addBotMessage = function (message, options) {
      var rendererOptions = (options && typeof options === 'object') ? Object.assign({}, options) : {};
      if (typeof rendererOptions.forceNewGroup === 'undefined') {
        rendererOptions.forceNewGroup = true;
      }

      if (!window.Niwa.MorphController || !window.Niwa.MorphController.isOpen()) {
        if (window.Niwa.MorphController) window.Niwa.MorphController.open();
      }

      setTimeout(function () {
        if (window.Niwa.MessageRenderer) {
          window.Niwa.MessageRenderer.addMessage(message, 'bot', rendererOptions);
        }
      }, 100);
    };
  }

  /* -- Bootstrap ---------------------------------------------------------- */

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeApp);
  } else {
    initializeApp();
  }
})();
