(function () {
  const instances = document.querySelectorAll('.aiapp-instance');
  if (!instances.length) return;

  // --- GLOBAL QUEUE/LOCK ---
  let isSending = false;
  let pendingPayload = null;

  instances.forEach((instance) => {
    const appId = instance.dataset.appId;
    if (!appId) return;

    const sessionKey = `aiao_session_${appId}`;
    const now = Date.now();

    // Track time
    const appStartTime = now;
    let resultsStartTime = null;

    // Setup session
    let session = getSession(sessionKey, now);
    saveSession(sessionKey, session);

    // Data state
    const sessionData = {
      app_id          : appId,
      response_id     : '',
      user_id         : session.id,
      time_on_app     : '',
      app_use         : 'N',
      results_visited : 'N',
      time_on_results : '',
      app_reuse       : 'N',
      results_liked   : '',
      results_disliked: '',
    };

    /** ----------- EVENT BINDINGS ----------- **/

    // Detect Submit Button
    instance.addEventListener('click', (e) => {
      if (!isSubmitButton(e.target)) return;
      markAppUsed();
      pushUpdate();
    });

    // Watch results
    const resultWrap = document.querySelector('#ai-app-result');
    const responseField = document.getElementById('ai_response_id');
    if (resultWrap) {
      new MutationObserver(() => {
        if (sessionData.results_visited === 'Y') return;
        if (!resultWrap.innerText.trim()) return;

        sessionData.results_visited = 'Y';
        sessionData.response_id = responseField?.value || '';

        if (sessionData.app_use === 'N') markAppUsed();

        resultsStartTime = Date.now();
        pushUpdate();

        bindTryAgain();
        bindFeedback();
      }).observe(resultWrap, { childList: true, subtree: true });
    }

    // Fallback on unload
    window.addEventListener('beforeunload', () => {
      if (resultsStartTime && !sessionData.time_on_results) {
        sessionData.time_on_results = elapsed(resultsStartTime);
      }
      if (!sessionData.time_on_app) markAppUsed();

      if (navigator.sendBeacon) {
        navigator.sendBeacon(
          myPluginAjax.ajaxurl,
          new URLSearchParams({ action: 'ai_app_onsite_store_session', ...sessionData })
        );
      }
    });

    /** ----------- HELPERS ----------- **/

    function markAppUsed() {
      sessionData.app_use = 'Y';
      sessionData.time_on_app = elapsed(appStartTime);
    }

    function bindTryAgain() {
      const btn = document.querySelector('#ai-app-refresh');
      if (!btn || btn.dataset.bound) return;
      btn.dataset.bound = 'true';
      btn.addEventListener('click', () => {
        if (resultsStartTime) {
          sessionData.time_on_results = elapsed(resultsStartTime);
        }
        session.reuse_count++;
        saveSession(sessionKey, session);
        sessionData.app_reuse = 'Y';
        pushUpdate();
      });
    }

    function bindFeedback() {
      jQuery(".ai-app-feedback-section .like i, .ai-app-feedback-section .dislike i")
        .off("click.session") // prevent duplicate binding
        .on("click.session", function () {
          const feedback = jQuery(this).hasClass("fa-thumbs-up") ? "thumbs_up" : "thumbs_down";
          const response_id = jQuery("#ai_response_id").val();

          jQuery.post(myPluginAjax.ajaxurl, {
            action: "ai_app_onsite_save_feedback",
            feedback,
            response_id
          }, () => {
            jQuery("#ai-app-feedback-btns").hide();
            jQuery("#ai-feedback-response").show();

            sessionData.results_liked = feedback === "thumbs_up" ? "Y" : "N";
            sessionData.results_disliked = feedback === "thumbs_down" ? "Y" : "N";
            pushUpdate();
          });
        });
    }

    function pushUpdate() {
      const snapshot = { ...sessionData };
      const payload = new URLSearchParams({ action: 'ai_app_onsite_store_session', ...snapshot });

      if (isSending) {
        // Replace any pending payload with the latest state
        pendingPayload = payload;
        return;
      }

      isSending = true;
      fetch(myPluginAjax.ajaxurl, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: payload
      }).catch(() => { /* fail silently */ })
      .finally(() => {
        isSending = false;
        if (pendingPayload) {
          const nextPayload = pendingPayload;
          pendingPayload = null;
          // immediately send the latest pending
          isSending = true;
          
          fetch(myPluginAjax.ajaxurl, {
              method: "POST",
              headers: { "Content-Type": "application/x-www-form-urlencoded" },
              body: nextPayload
          })
          .catch(() => {})
          .finally(() => {
            isSending = false;
            if (pendingPayload) pushUpdate();
          });
        }
      });
    }

    function getSession(key, now) {
      try {
        let session = JSON.parse(sessionStorage.getItem(key));
        if (!session) throw new Error("missing");
        if (!session || isExpired(session?.timestamp)) {
          session = {
            id: 'sess_' + Math.random().toString(36).substring(2, 12),
            timestamp: now,
            reuse_count: 0,
          };
        }
        return session;
      }
      catch {
        return { id: 'sess_' + Math.random().toString(36).slice(2, 12), timestamp: now, reuse_count: 0 };
      }
    }

    function isExpired(timestamp) {
      return !timestamp || (now - timestamp > 30 * 60 * 1000);
    }


    function saveSession(key, value) {
      sessionStorage.setItem(key, JSON.stringify(value));
    }

    function elapsed(start) {
      const ms = Date.now() - start;
      return `${Math.floor(ms / 60000)}:${String(Math.floor(ms / 1000 % 60)).padStart(2, '0')}`;
    }

    function isSubmitButton(el) {
      return el.matches('button[name="save-plugin-settings"]') ||
             el.onclick?.toString().includes('ai_app_onsite_get_the_ai_response');
    }
  });
})();
