/**
 * Spellmatic Onboarding Wizard
 *
 * Handles step navigation, post-type selection persistence,
 * and onboarding completion via the REST API.
 *
 * Expects `spellmaticOnboarding` to be localized with:
 *   - nonce   {string}  WP REST nonce
 *   - restUrl {string}  REST endpoint for onboarding/complete
 *   - dashUrl {string}  Admin URL for the main dashboard page
 *   - scanUrl {string}  Admin URL for the dashboard with trigger_scan=1
 *
 * @package Spellmatic
 */

/* global spellmaticOnboarding */

( function () {
    'use strict';

    function showStep( step ) {
        document.querySelectorAll( '.onboarding-step' ).forEach( function ( el ) {
            el.classList.remove( 'active' );
        } );
        document.querySelector( '.onboarding-step[data-step="' + step + '"]' ).classList.add( 'active' );
    }

    function getSelectedPostTypes() {
        var selected = [];
        document.querySelectorAll( '.post-type-checkbox-input:checked' ).forEach( function ( checkbox ) {
            selected.push( checkbox.value );
        } );
        return selected;
    }

    function saveSelectedPostTypes() {
        var postTypes = getSelectedPostTypes();

        fetch( spellmaticOnboarding.restUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce': spellmaticOnboarding.nonce
            },
            body: JSON.stringify( { post_types: postTypes } )
        } ).catch( function ( err ) {
            console.error( 'Onboarding save error:', err );
        } );
    }

    function goToStep( step ) {
        if ( step === 3 ) {
            saveSelectedPostTypes();
        }
        showStep( step );
    }

    function completeOnboarding( shouldScan ) {
        var loading = document.getElementById( 'onboarding-loading' );
        loading.style.display = 'block';

        var postTypes = getSelectedPostTypes();

        fetch( spellmaticOnboarding.restUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce': spellmaticOnboarding.nonce
            },
            body: JSON.stringify( { post_types: postTypes } )
        } ).then( function () {
            if ( shouldScan ) {
                window.location.href = spellmaticOnboarding.scanUrl;
            } else {
                window.location.href = spellmaticOnboarding.dashUrl;
            }
        } ).catch( function ( err ) {
            console.error( 'Onboarding error:', err );
            window.location.href = spellmaticOnboarding.dashUrl;
        } );
    }

    // Expose to onclick handlers in the template markup.
    window.goToStep            = goToStep;
    window.completeOnboarding  = completeOnboarding;
} )();
