import { TourGuideClient } from "@sjmc11/tourguidejs";

const steps = [
    {
      target: "#toplevel_page_editorial-comments",
      content: "Manage Multicollab from the admin menu: Dashboard, Settings, and Get Started.",
      title: "Welcome to Multicollab!",
      backdrop: true,
      dialogPlacement: 'top',
    },
];

document.addEventListener("DOMContentLoaded", function () {
    function initwelcomePointer() {
    
      const tg = new TourGuideClient({
        steps,
        hidePrev: true,
        showStepDots: false,
        closeButton: false,
        showStepProgress: false,
        finishLabel: 'Got it!',
        completeOnFinish: true,
        backdropClass: 'cf-multicollab-dashboard-welcome',
        exitOnClickOutside: false,
      });
    
      tg.onFinish(() => {
        return new Promise((resolve) => {
            // Store flag in database
            fetch(ajaxurl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'multicollab_set_welcome_tour_completed',
                    nonce: multicollabWelcomeTourL10n.nonce,
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Safe class removal with null checks
                    try {
                        if (document.body?.classList?.contains("cf-welcome-tour-running")) {
                            document.body.classList.remove("cf-welcome-tour-running");
                        }
                    } catch (e) {
                        console.warn('Could not remove welcome tour class:', e);
                    }
                    resolve(true);
                } else {
                    console.error('Failed to save welcome tour completion status');
                    resolve(false);
                }
            })
            .catch(error => {
                console.error('Error saving welcome tour completion status:', error);
                resolve(false);
            });
        });
      });
    
      // Safe class addition with null checks
      try {
        if (document.body?.classList) {
            document.body.classList.add("cf-welcome-tour-running");
            tg.start();
        }
      } catch (e) {
        console.error('Could not start welcome tour:', e);
      }
    }
    
    // Run after some delay to ensure iframe is loaded
    setTimeout(initwelcomePointer, 500);
});
