import React, { useEffect, useState } from 'react';
import { __ } from '@wordpress/i18n';
import CfIcon from '@WizardImages/cartflows-icon.svg';
import { getExitSetupWizard } from '@Utils/Helpers';
import apiFetch from '@wordpress/api-fetch';
import { useLocation, useHistory } from 'react-router-dom';
import { Disclosure } from '@headlessui/react';
import { XMarkIcon } from '@heroicons/react/24/outline';
function Index() {
const search = useLocation().search;
const history = useHistory();
const stepParam = new URLSearchParams( search ).get( 'step' );
const step = stepParam || 'welcome';
const [ lastVisitedStep ] = useState( step );
const woocommerce_status = window.cartflows_wizard?.woocommerce_status;
const [ completedSteps ] = useState( () => {
return JSON.parse( localStorage.getItem( 'completedSteps' ) ) || [];
} );
// Add useEffect to synchronize completedSteps with navigation
useEffect( () => {
localStorage.setItem(
'completedSteps',
JSON.stringify( completedSteps )
);
}, [ completedSteps ] );
const menus = [
{ name: __( 'Welcome', 'cartflows' ), id: 'welcome' },
{ name: __( 'Page Builder', 'cartflows' ), id: 'page-builder' },
{ name: __( 'Required Plugins', 'cartflows' ), id: 'plugin-install' },
{ name: __( 'Store Checkout', 'cartflows' ), id: 'store-checkout' },
{ name: __( 'Subscribe', 'cartflows' ), id: 'optin' },
{ name: __( 'Done', 'cartflows' ), id: 'ready' },
];
const handleExit = ( e ) => {
e.preventDefault();
const ajaxData = new window.FormData();
ajaxData.append( 'action', 'cartflows_onboarding_exit' );
ajaxData.append( 'security', cartflows_wizard.onboarding_exit_nonce );
ajaxData.append( 'current_step', step );
apiFetch( { url: ajaxurl, method: 'POST', body: ajaxData } ).then(
( response ) => {
if ( response.success ) {
window.location.href = getExitSetupWizard();
}
}
);
};
const handleStepRedirection = ( e ) => {
e.preventDefault();
const stepToRedirect = e.target.id;
const stepIndex = menus.findIndex(
( menu ) => menu.id === stepToRedirect
);
const currentStepIndex = menus.findIndex(
( menu ) => menu.id === step
);
if (
stepIndex < currentStepIndex ||
lastVisitedStep === stepToRedirect
) {
history.push( {
pathname: 'index.php',
search: `?page=cartflow-setup&step=${ stepToRedirect }`,
} );
return;
}
if (
stepToRedirect === 'store-checkout' &&
step === 'plugin-install' &&
woocommerce_status === 'active'
) {
history.push( {
pathname: 'index.php',
search: `?page=cartflow-setup&step=store-checkout`,
} );
return;
}
if ( ! completedSteps.includes( menus[ stepIndex - 1 ]?.id ) ) {
alert(
__(
'Please complete the previous step before proceeding.',
'cartflows'
)
);
return;
}
history.push( {
pathname: 'index.php',
search: `?page=cartflow-setup&step=${ stepToRedirect }`,
} );
};
return (