/* ==========================================================================
   Niwa Chatbot -- Activity Tracking & Chat History Cleaner
   ---------------------------------------------------------------------------
   Self-contained IIFE: detects 30-minute inactivity and resets chat.
   No jQuery dependency.

   Uses selectors:
     .niwa-morph__body  (was #za-flyout .za-window)
     Niwa.MorphController.isOpen()  (was .active class check)
   ========================================================================== */

(function () {
  'use strict';

  // Configuration
  var INACTIVITY_TIMEOUT = 30 * 60 * 1000; // 30 minutes
  var STORAGE_KEY = (window.NiwaAI && window.NiwaAI.storage_key)
    ? window.NiwaAI.storage_key
    : 'niwa_ai_chat_history_v1';
  var LAST_ACTIVITY_KEY = 'niwa_ai_last_activity';
  var CLEANED_FLAG_KEY = 'niwa_ai_cleaned_this_session';

  var inactivityTimer = null;
  var isCleanedThisSession = false;

  function now() {
    return Date.now();
  }

  function setLastActivity() {
    try { localStorage.setItem(LAST_ACTIVITY_KEY, String(now())); } catch (e) { /* ignore */ }
  }

  function getLastActivity() {
    try { return parseInt(localStorage.getItem(LAST_ACTIVITY_KEY) || '0', 10); } catch (e) { return 0; }
  }

  function wasInactiveForTooLong() {
    var lastActivity = getLastActivity();
    if (!lastActivity) return false;
    return (now() - lastActivity) > INACTIVITY_TIMEOUT;
  }

  function isAlreadyCleanedThisSession() {
    try { return localStorage.getItem(CLEANED_FLAG_KEY) === '1' || isCleanedThisSession; } catch (e) { return isCleanedThisSession; }
  }

  function markCleanedThisSession() {
    try {
      localStorage.setItem(CLEANED_FLAG_KEY, '1');
      localStorage.setItem(CLEANED_FLAG_KEY + '_timestamp', String(now()));
    } catch (e) { /* ignore */ }
    isCleanedThisSession = true;
  }

  function findChatBody() {
    return document.querySelector('.niwa-morph__body')
      || document.querySelector('.niwa-center__body');
  }

  function shouldForceFrontendReset() {
    return !!(window.NiwaAI && window.NiwaAI.cleanup_local_storage_on_load);
  }

  function clearStorageArea(area, prefixes, exactKeys) {
    if (!area) return;

    for (var i = area.length - 1; i >= 0; i--) {
      var key = area.key(i);
      if (!key) continue;

      if (exactKeys.indexOf(key) !== -1) {
        area.removeItem(key);
        continue;
      }

      for (var j = 0; j < prefixes.length; j++) {
        if (key.indexOf(prefixes[j]) === 0) {
          area.removeItem(key);
          break;
        }
      }
    }
  }

  function clearFrontendRuntimeState() {
    var storagePrefixes = ['niwa_ai_', STORAGE_KEY];
    var exactKeys = [
      LAST_ACTIVITY_KEY,
      CLEANED_FLAG_KEY,
      CLEANED_FLAG_KEY + '_timestamp',
      'niwa_validated_email'
    ];

    try { clearStorageArea(localStorage, storagePrefixes, exactKeys); } catch (e) { /* ignore */ }
    try { clearStorageArea(sessionStorage, ['niwa_ai_'], ['niwa_validated_email']); } catch (e) { /* ignore */ }

    try {
      document.cookie = 'niwa_ai_session=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; SameSite=Lax';
    } catch (e) { /* ignore */ }

    isCleanedThisSession = false;
  }

  function clearServerCleanupFlag() {
    if (!window.NiwaAI || !window.NiwaAI.ajax || !window.NiwaAI.nonce || !window.NiwaAI.cleanup_flag_action || !window.fetch) {
      return;
    }

    var body = 'action=' + encodeURIComponent(window.NiwaAI.cleanup_flag_action)
      + '&nonce=' + encodeURIComponent(window.NiwaAI.nonce);

    window.fetch(window.NiwaAI.ajax, {
      method: 'POST',
      credentials: 'same-origin',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      },
      body: body
    }).catch(function () {
      // Ignore cleanup flag transport failures.
    });
  }

  function clearChatHistory() {
    // Clear localStorage
    try {
      localStorage.removeItem(STORAGE_KEY);
      localStorage.removeItem(STORAGE_KEY + '_structured');
    } catch (e) { /* ignore */ }

    // Clear chat DOM
    var chatBody = findChatBody();
    if (chatBody) {
      while (chatBody.firstChild) {
        chatBody.removeChild(chatBody.firstChild);
      }

      // Add greeting
      var greeting;
      var globalEmail = null;
      try { globalEmail = sessionStorage.getItem('niwa_validated_email'); } catch (e) { /* ignore */ }

      var phoneMode = (window.NiwaAI && window.NiwaAI.phone_capture_mode) || 'email_phone';
      var phoneCaptureEnabled = !!(window.NiwaAI && window.NiwaAI.phone_capture_enabled);
      var shouldShowEmail = phoneMode !== 'phone_only';

      if (window.NiwaAI && window.NiwaAI.email_optin_enabled && !globalEmail && shouldShowEmail) {
        greeting = (window.NiwaAI.labels && window.NiwaAI.labels.name_greeting)
          || 'Hello, I am Niwa, what is your name? How can I address you?';
      } else if (window.NiwaAI && window.NiwaAI.email_optin_enabled && phoneCaptureEnabled && !shouldShowEmail) {
        greeting = (window.NiwaAI.labels && window.NiwaAI.labels.name_greeting)
          || 'Hello, I am Niwa, what is your name? How can I address you?';
      } else {
        greeting = (window.NiwaAI && window.NiwaAI.greeting) || "Hi! I'm Niwa 🌿 How can I help you today?";
      }

      // Re-initialize message renderer with greeting
      if (window.Niwa && window.Niwa.MessageRenderer) {
        window.Niwa.MessageRenderer.init(chatBody);
        window.Niwa.MessageRenderer.addMessage(greeting, 'bot');
      }
    }
  }

  function resetInactivityTimer() {
    if (inactivityTimer) clearTimeout(inactivityTimer);

    // Clear cleaned flag if enough time passed
    try {
      var cleanedTimestamp = parseInt(localStorage.getItem(CLEANED_FLAG_KEY + '_timestamp') || '0', 10);
      if (cleanedTimestamp && (now() - cleanedTimestamp) > (INACTIVITY_TIMEOUT / 2)) {
        localStorage.removeItem(CLEANED_FLAG_KEY);
        localStorage.removeItem(CLEANED_FLAG_KEY + '_timestamp');
        isCleanedThisSession = false;
      }
    } catch (e) { /* ignore */ }

    inactivityTimer = setTimeout(function () {
      if (!isAlreadyCleanedThisSession()) {
        clearChatHistory();
        markCleanedThisSession();
      }
    }, INACTIVITY_TIMEOUT);

    setLastActivity();
  }

  function onActivity() {
    resetInactivityTimer();
  }

  function initActivityListeners() {
    var events = ['click', 'keydown', 'input', 'touchstart'];
    for (var i = 0; i < events.length; i++) {
      document.addEventListener(events[i], onActivity, { passive: true });
    }

    // Chat-specific events
    document.addEventListener('click', function (e) {
      if (e.target.closest('.niwa-morph, .niwa-center, .niwa-morph__body, .niwa-center__body, .niwa-products')) {
        onActivity();
      }
    }, { passive: true });
  }

  function handleVisibilityChange() {
    if (document.visibilityState === 'visible') {
      if (wasInactiveForTooLong() && !isAlreadyCleanedThisSession()) {
        clearChatHistory();
        markCleanedThisSession();
      } else {
        resetInactivityTimer();
      }
    }
  }

  function init() {
    if (shouldForceFrontendReset()) {
      clearFrontendRuntimeState();
      clearChatHistory();
      clearServerCleanupFlag();
    }

    // Check existing history
    var hasHistory = false;
    try {
      var raw = localStorage.getItem(STORAGE_KEY);
      if (raw) {
        var msgs = JSON.parse(raw);
        hasHistory = Array.isArray(msgs) && msgs.length > 0;
      }
    } catch (e) { /* ignore */ }

    if (hasHistory) {
      setLastActivity();
      resetInactivityTimer();
      initActivityListeners();
      document.addEventListener('visibilitychange', handleVisibilityChange);
      window.addEventListener('focus', handleVisibilityChange);
      return;
    }

    if (wasInactiveForTooLong() && !isAlreadyCleanedThisSession()) {
      setTimeout(function () {
        clearChatHistory();
        markCleanedThisSession();
      }, 100);
    } else {
      resetInactivityTimer();
    }

    initActivityListeners();
    document.addEventListener('visibilitychange', handleVisibilityChange);
    window.addEventListener('focus', handleVisibilityChange);
  }

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