<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Templates use local variables supplied by the render context.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

$wizard_steps = isset($wizard_steps) && is_array($wizard_steps) ? $wizard_steps : [];
$wizard_steps = array_values($wizard_steps);
$step_count = count($wizard_steps);
if ($step_count <= 0) {
    $wizard_steps = [
        ['title' => __('Step', 'nexdirectory'), 'icon' => 'fa-circle', 'description' => __('Setup step.', 'nexdirectory')],
    ];
    $step_count = 1;
}
$initial_step = isset($step) ? (int) $step : 1;
if ($initial_step < 1 || $initial_step > $step_count) {
    $initial_step = 1;
}
$step_was_requested = !empty($step_was_requested);
$resume_storage_key = 'nexdirectory_onboarding_step_' . absint((int) get_current_blog_id()) . '_' . absint((int) get_current_user_id());
$initial_done = !empty($done);
$brand_name = isset($brand_name) ? (string) $brand_name : __('Nex Directory Free', 'nexdirectory');
$plural_label = isset($plural_label) ? (string) $plural_label : __('Listings', 'nexdirectory');
$operating_mode = isset($operating_mode) ? (string) $operating_mode : 'user';
$site_name = isset($site_name) ? (string) $site_name : '';
$accent_color = isset($accent_color) ? (string) $accent_color : '#4F46E5';
$starter_blueprints = isset($starter_blueprints) && is_array($starter_blueprints) ? $starter_blueprints : [];
$active_starter_blueprint = isset($active_starter_blueprint) ? sanitize_key((string) $active_starter_blueprint) : '';
$active_blueprint_label = isset($active_blueprint_label) ? sanitize_text_field((string) $active_blueprint_label) : '';
$active_demo_profile = isset($active_demo_profile) ? sanitize_key((string) $active_demo_profile) : 'events';
if ($active_demo_profile === '') {
    $active_demo_profile = 'events';
}
$sample_profile_label = $active_blueprint_label !== ''
    ? $active_blueprint_label
    : sanitize_text_field(ucwords(str_replace('_', ' ', $active_demo_profile)));

$save_preferences_action = isset($save_preferences_action) ? (string) $save_preferences_action : admin_url('admin-post.php');
$onboarding_step_three_url = admin_url('admin.php?page=nexdirectory-onboarding&step=3');
$onboarding_step_five_url = admin_url('admin.php?page=nexdirectory-onboarding&step=5');
$onboarding_step_six_url = admin_url('admin.php?page=nexdirectory-onboarding&step=6');
$dashboard_url = isset($dashboard_url) ? (string) $dashboard_url : admin_url('admin.php?page=nexdirectory-dashboard');
$add_listing_url = isset($add_listing_url) ? (string) $add_listing_url : admin_url('post-new.php?post_type=nexdirectory_event');
$manage_listings_url = isset($manage_listings_url) ? (string) $manage_listings_url : admin_url('edit.php?post_type=nexdirectory_event');
$view_directory_url = isset($view_directory_url) ? (string) $view_directory_url : home_url('/');
$needs_attention_url = isset($needs_attention_url) ? (string) $needs_attention_url : admin_url('admin.php?page=nexdirectory-needs-attention');
$settings_url = isset($settings_url) ? (string) $settings_url : admin_url('admin.php?page=nexdirectory-settings');
$pages_url = isset($pages_url) ? (string) $pages_url : admin_url('edit.php?post_type=page');
$setup_ready_count = isset($setup_ready_count) ? max(0, min($step_count, (int) $setup_ready_count)) : 0;
$core_page_expected = isset($core_page_expected) ? max(1, (int) $core_page_expected) : 18;
$core_page_count = isset($core_page_count) ? max(0, (int) $core_page_count) : 0;
$core_pages_ready = !empty($core_pages_ready);
$total_listing_count = isset($total_listing_count) ? max(0, (int) $total_listing_count) : 0;
$published_listing_count = isset($published_listing_count) ? max(0, (int) $published_listing_count) : 0;
$demo_listing_count = isset($demo_listing_count) ? max(0, (int) $demo_listing_count) : 0;
$homepage_id = isset($homepage_id) ? max(0, (int) $homepage_id) : 0;
$homepage_title = isset($homepage_title) ? sanitize_text_field((string) $homepage_title) : '';
$homepage_url = isset($homepage_url) ? (string) $homepage_url : home_url('/');
$whats_new_page_id = isset($whats_new_page_id) ? max(0, (int) $whats_new_page_id) : 0;
$is_whats_new_homepage = !empty($is_whats_new_homepage);
$preflight_checks = isset($preflight_checks) && is_array($preflight_checks) ? array_values($preflight_checks) : [];
$preflight_check_count = isset($preflight_check_count) ? max(0, (int) $preflight_check_count) : count($preflight_checks);
$preflight_ready_count = isset($preflight_ready_count) ? max(0, min($preflight_check_count, (int) $preflight_ready_count)) : 0;
$demo_import_count = 12;
$demo_import_confirm_message = __(
    'This adds up to 12 profile-matched sample listings and taxonomy terms, and applies the active starter preset. It is duplicate-aware, does not delete or overwrite live listings, does not copy remote images into your Media Library, and does not create sample messages, orders, or RSVPs. Continue?',
    'nexdirectory'
);
$blueprint_confirm_message = __(
    'This applies the selected design preset, updates directory terminology and feature defaults, creates missing core pages where their slugs are available, refreshes routes, and adds the blueprint’s configured duplicate-aware sample content. Existing pages and live listings are not deleted or overwritten. Continue?',
    'nexdirectory'
);

$wizard_payload = [
    'step' => $initial_step,
    'stepExplicit' => $step_was_requested,
    'resumeStorageKey' => $resume_storage_key,
    'isComplete' => $initial_done,
    'operatingMode' => $operating_mode,
    'siteName' => $site_name,
    'accentColor' => $accent_color,
    'brandName' => $brand_name,
    'pluralLabel' => $plural_label,
    'stepsData' => $wizard_steps,
    'stepCount' => $step_count,
    'demoImportConfirmMessage' => $demo_import_confirm_message,
    'reducedMotionQuery' => '(prefers-reduced-motion: reduce)',
    'strings' => [
        'step' => __('Step', 'nexdirectory'),
        'of' => __('of', 'nexdirectory'),
        'reviewAnyStep' => __('choose any step to review it', 'nexdirectory'),
        'current' => __('current', 'nexdirectory'),
        'complete' => __('complete', 'nexdirectory'),
        'optional' => __('optional', 'nexdirectory'),
        'notComplete' => __('not complete', 'nexdirectory'),
        'nextStep' => __('Next Step', 'nexdirectory'),
    ],
];
$current_step_data = isset($wizard_steps[$initial_step - 1]) && is_array($wizard_steps[$initial_step - 1])
    ? $wizard_steps[$initial_step - 1]
    : (array) $wizard_steps[0];
$current_step_title = sanitize_text_field((string) ($current_step_data['title'] ?? __('Step', 'nexdirectory')));
$current_step_description = sanitize_text_field((string) ($current_step_data['description'] ?? __('Setup step.', 'nexdirectory')));
$current_step_icon = sanitize_html_class((string) ($current_step_data['icon'] ?? 'fa-circle'));
if ($current_step_icon === '') {
    $current_step_icon = 'fa-circle';
}
$required_setup_remaining = 0;
foreach ($wizard_steps as $wizard_step_index => $wizard_step_row) {
    if ($wizard_step_index >= 5) {
        break;
    }
    if (empty($wizard_step_row['optional']) && empty($wizard_step_row['is_ready'])) {
        $required_setup_remaining++;
    }
}
?>

<?php $this->enqueue_local_style_asset('templates-admin-onboarding-php-style-1', 'assets/generated/templates-admin-onboarding-php-style-1.css'); ?>

<?php ob_start(); ?>
(function () {
    var seed = <?php echo wp_json_encode($wizard_payload); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- JSON is encoded for a JavaScript value. ?>;
    var pendingDemoImportForm = null;
    var modalReturnFocus = null;

    function toArray(nodes) {
        return Array.prototype.slice.call(nodes || []);
    }

    function getRoot() {
        return document.querySelector('.nexdirectory-onboarding-modern');
    }

    function getSteps() {
        return seed.stepsData && seed.stepsData.length ? seed.stepsData : [{ title: 'Step', icon: 'fa-circle', description: 'Setup step.' }];
    }

    function getMaxStep() {
        return getSteps().length;
    }

    function getString(key, fallback) {
        return seed.strings && seed.strings[key] ? String(seed.strings[key]) : fallback;
    }

    function rememberStep(stepNumber) {
        if (!seed.resumeStorageKey || !window.localStorage) {
            return;
        }
        try {
            window.localStorage.setItem(seed.resumeStorageKey, String(stepNumber));
        } catch (error) {
            // Storage can be unavailable in privacy-focused browser modes.
        }
    }

    function forgetRememberedStep() {
        if (!seed.resumeStorageKey || !window.localStorage) {
            return;
        }
        try {
            window.localStorage.removeItem(seed.resumeStorageKey);
        } catch (error) {
            // Storage can be unavailable in privacy-focused browser modes.
        }
    }

    function getRememberedStep() {
        var rememberedStep = 0;
        if (seed.stepExplicit || seed.isComplete || !seed.resumeStorageKey || !window.localStorage) {
            return 0;
        }
        try {
            rememberedStep = parseInt(window.localStorage.getItem(seed.resumeStorageKey) || '0', 10);
        } catch (error) {
            rememberedStep = 0;
        }
        return rememberedStep >= 1 && rememberedStep <= getMaxStep() ? rememberedStep : 0;
    }

    function getInitialState() {
        var rememberedStep = getRememberedStep();
        return {
            step: rememberedStep || Math.min(Math.max(parseInt(seed.step || 1, 10), 1), getMaxStep()),
            isComplete: !!seed.isComplete,
            operatingMode: String(seed.operatingMode || 'user'),
            siteName: String(seed.siteName || ''),
            accentColor: String(seed.accentColor || '#4f46e5')
        };
    }

    function setVisible(el, isVisible, displayValue) {
        if (!el) {
            return;
        }
        el.hidden = !isVisible;
        el.style.display = isVisible ? (displayValue || '') : 'none';
        el.setAttribute('aria-hidden', isVisible ? 'false' : 'true');
    }

    function setText(selector, text) {
        var el = document.querySelector(selector);
        if (el) {
            el.textContent = text;
        }
    }

    function removeClasses(el, classes) {
        var i;
        if (!el) {
            return;
        }
        for (i = 0; i < classes.length; i++) {
            el.classList.remove(classes[i]);
        }
    }

    function addClasses(el, classString) {
        var parts;
        var i;
        if (!el || !classString) {
            return;
        }
        parts = classString.split(/\s+/);
        for (i = 0; i < parts.length; i++) {
            if (parts[i]) {
                el.classList.add(parts[i]);
            }
        }
    }

    function updateHiddenOperatingInputs(state) {
        toArray(document.querySelectorAll('input[name="nexdirectory_onboarding_operating_mode"]')).forEach(function (input) {
            input.value = state.operatingMode;
        });
    }

    function submitForm(form) {
        if (!form) {
            return;
        }
        if (typeof form.requestSubmit === 'function') {
            form.requestSubmit();
            return;
        }
        form.submit();
    }

    function getStepClass(stepNumber, currentStep) {
        var stepData = getSteps()[stepNumber - 1] || {};
        if (stepNumber === currentStep) {
            return 'bg-white border-2 border-indigo-600 text-indigo-600 shadow-md ring-4 ring-indigo-50 cursor-pointer';
        }
        if (stepData.is_ready) {
            return 'bg-emerald-600 text-white shadow-md cursor-pointer hover:bg-emerald-700';
        }
        if (stepNumber < currentStep && stepData.optional) {
            return 'bg-amber-50 border-2 border-amber-300 text-amber-700 cursor-pointer hover:border-amber-400';
        }
        if (stepNumber < currentStep) {
            return 'bg-slate-100 border-2 border-slate-300 text-slate-600 cursor-pointer hover:border-slate-400';
        }
        return 'bg-white border-2 border-slate-200 text-slate-400 hover:border-slate-300 cursor-pointer';
    }

    function getStepLabelClass(stepNumber, currentStep) {
        var stepData = getSteps()[stepNumber - 1] || {};
        if (stepNumber === currentStep) {
            return 'text-indigo-600';
        }
        if (stepData.is_ready) {
            return 'text-emerald-700';
        }
        return stepNumber < currentStep ? 'text-slate-600' : 'text-slate-400';
    }

    function setStep(state, nextStep) {
        var url;
        var heading;
        var reducedMotion = window.matchMedia && window.matchMedia(seed.reducedMotionQuery || '(prefers-reduced-motion: reduce)').matches;
        state.step = Math.min(Math.max(parseInt(nextStep || 1, 10), 1), getMaxStep());
        rememberStep(state.step);
        if (window.history && typeof window.history.replaceState === 'function') {
            try {
                url = new URL(window.location.href);
                url.searchParams.set('step', String(state.step));
                window.history.replaceState({}, '', url.toString());
            } catch (error) {
                // The wizard still works if the History URL API is unavailable.
            }
        }
        renderWizard(state);
        heading = document.querySelector('[data-nexdirectory-current-title]');
        if (heading && typeof heading.focus === 'function') {
            heading.focus({ preventScroll: true });
        }
        if (heading && typeof heading.scrollIntoView === 'function') {
            heading.scrollIntoView({ behavior: reducedMotion ? 'auto' : 'smooth', block: 'center' });
        } else if (window.scrollTo) {
            window.scrollTo({ top: 0, behavior: reducedMotion ? 'auto' : 'smooth' });
        }
    }

    function renderWizard(state) {
        var steps = getSteps();
        var current = steps[state.step - 1] || steps[0];
        var progress = getMaxStep() <= 0 ? 0 : (state.step / getMaxStep()) * 100;
        var stepClasses = ['bg-indigo-600', 'text-white', 'shadow-md', 'cursor-pointer', 'hover:bg-indigo-700', 'bg-emerald-600', 'hover:bg-emerald-700', 'bg-amber-50', 'border-amber-300', 'text-amber-700', 'hover:border-amber-400', 'bg-slate-100', 'border-slate-300', 'text-slate-600', 'hover:border-slate-400', 'bg-white', 'border-2', 'border-indigo-600', 'text-indigo-600', 'ring-4', 'ring-indigo-50', 'border-slate-200', 'text-slate-400', 'hover:border-slate-300'];
        var labelClasses = ['text-indigo-600', 'text-emerald-700', 'text-slate-600', 'text-slate-400'];
        var modeClasses = ['border-indigo-600', 'ring-1', 'ring-indigo-600', 'bg-indigo-50/30', 'border-slate-200', 'hover:border-slate-300', 'hover:bg-slate-50'];
        var progressEl = document.querySelector('[data-nexdirectory-onboarding-progress]');
        var nextWrap = document.querySelector('[data-nexdirectory-next-step-wrap]');
        var nextLabel = document.querySelector('[data-nexdirectory-next-label]');
        var prevButton = document.querySelector('[data-nexdirectory-prev-step]');
        var currentIcon = document.querySelector('[data-nexdirectory-current-icon]');

        if (progressEl) {
            progressEl.style.width = progress + '%';
        }
        if (currentIcon) {
            currentIcon.className = 'fas text-xl ' + (current.icon || 'fa-circle');
        }
        setText('[data-nexdirectory-current-title]', getString('step', 'Step') + ' ' + state.step + ': ' + (current.title || getString('step', 'Step')));
        setText('[data-nexdirectory-current-description]', current.description || 'Setup step.');
        setText('[data-nexdirectory-current-help]', current.help || '');
        setText('[data-nexdirectory-progress-summary]', getString('step', 'Step') + ' ' + state.step + ' ' + getString('of', 'of') + ' ' + getMaxStep() + ' · ' + getString('reviewAnyStep', 'choose any step to review it'));
        if (nextLabel) {
            nextLabel.textContent = current.next_label || getString('nextStep', 'Next Step');
        }

        toArray(document.querySelectorAll('[data-nexdirectory-step-panel]')).forEach(function (panel) {
            setVisible(panel, parseInt(panel.getAttribute('data-nexdirectory-step-panel'), 10) === state.step);
        });

        toArray(document.querySelectorAll('[data-nexdirectory-step-button]')).forEach(function (button) {
            var stepNumber = parseInt(button.getAttribute('data-nexdirectory-step-button'), 10);
            var stepData = steps[stepNumber - 1] || {};
            var ready = !!stepData.is_ready;
            var statusLabel = stepNumber === state.step
                ? getString('current', 'current')
                : (ready ? getString('complete', 'complete') : (stepData.optional ? getString('optional', 'optional') : getString('notComplete', 'not complete')));
            removeClasses(button, stepClasses);
            addClasses(button, getStepClass(stepNumber, state.step));
            if (stepNumber === state.step) {
                button.setAttribute('aria-current', 'step');
            } else {
                button.removeAttribute('aria-current');
            }
            button.setAttribute('aria-label', getString('step', 'Step') + ' ' + stepNumber + ': ' + (stepData.title || getString('step', 'Step')) + ' — ' + statusLabel);
            toArray(button.querySelectorAll('[data-nexdirectory-step-check]')).forEach(function (check) {
                setVisible(check, ready);
            });
            toArray(button.querySelectorAll('[data-nexdirectory-step-number]')).forEach(function (number) {
                setVisible(number, !ready);
            });
        });

        toArray(document.querySelectorAll('[data-nexdirectory-step-label]')).forEach(function (label) {
            var stepNumber = parseInt(label.getAttribute('data-nexdirectory-step-label'), 10);
            removeClasses(label, labelClasses);
            addClasses(label, getStepLabelClass(stepNumber, state.step));
        });

        toArray(document.querySelectorAll('[data-nexdirectory-mode-option]')).forEach(function (option) {
            var mode = option.getAttribute('data-nexdirectory-mode-option');
            removeClasses(option, modeClasses);
            addClasses(option, mode === state.operatingMode ? 'border-indigo-600 ring-1 ring-indigo-600 bg-indigo-50/30' : 'border-slate-200 hover:border-slate-300 hover:bg-slate-50');
        });
        toArray(document.querySelectorAll('[data-nexdirectory-mode-check]')).forEach(function (check) {
            check.classList.toggle('opacity-100', check.getAttribute('data-nexdirectory-mode-check') === state.operatingMode);
            check.classList.toggle('opacity-0', check.getAttribute('data-nexdirectory-mode-check') !== state.operatingMode);
        });
        toArray(document.querySelectorAll('input[name="operatingMode"]')).forEach(function (radio) {
            radio.checked = radio.value === state.operatingMode;
        });

        setVisible(nextWrap, state.step < getMaxStep());
        if (prevButton) {
            prevButton.disabled = state.step === 1;
            prevButton.classList.toggle('invisible', state.step === 1);
        }
        updateHiddenOperatingInputs(state);
    }

    function bindWizard() {
        var root = getRoot();
        var state;
        var accentInput;
        var siteNameInput;
        var closeNotice;
        var completionForm;
        var homepageForm;
        var nextButton;
        var prevButton;
        if (!root || root.getAttribute('data-nexdirectory-onboarding-bound') === '1') {
            return;
        }
        root.setAttribute('data-nexdirectory-onboarding-bound', '1');
        state = getInitialState();
        root.__nexdirectoryOnboardingState = state;

        toArray(document.querySelectorAll('[data-nexdirectory-step-button]')).forEach(function (button) {
            button.addEventListener('click', function () {
                setStep(state, button.getAttribute('data-nexdirectory-step-button'));
            });
        });
        toArray(document.querySelectorAll('[data-nexdirectory-go-step]')).forEach(function (button) {
            button.addEventListener('click', function () {
                setStep(state, button.getAttribute('data-nexdirectory-go-step'));
            });
        });
        toArray(document.querySelectorAll('[data-nexdirectory-mode-option]')).forEach(function (option) {
            option.addEventListener('click', function () {
                state.operatingMode = option.getAttribute('data-nexdirectory-mode-option') || 'user';
                renderWizard(state);
            });
        });
        toArray(document.querySelectorAll('input[name="operatingMode"]')).forEach(function (radio) {
            radio.addEventListener('change', function () {
                if (radio.checked) {
                    state.operatingMode = radio.value;
                    renderWizard(state);
                }
            });
        });

        siteNameInput = document.querySelector('[data-nexdirectory-site-name]');
        if (siteNameInput) {
            siteNameInput.addEventListener('input', function () {
                state.siteName = siteNameInput.value;
                setText('[data-nexdirectory-brand-preview]', state.siteName || seed.brandName || '');
            });
        }
        accentInput = document.querySelector('[data-nexdirectory-accent-color]');
        if (accentInput) {
            accentInput.addEventListener('input', function () {
                state.accentColor = accentInput.value || state.accentColor;
                setText('[data-nexdirectory-accent-preview]', String(state.accentColor).toUpperCase());
                toArray(document.querySelectorAll('[data-nexdirectory-accent-swatch]')).forEach(function (swatch) {
                    swatch.style.backgroundColor = state.accentColor;
                });
            });
        }

        closeNotice = document.querySelector('[data-nexdirectory-close-notice]');
        if (closeNotice) {
            closeNotice.addEventListener('click', function () {
                setVisible(closeNotice.closest('[data-nexdirectory-welcome-notice]'), false);
            });
        }

        homepageForm = document.querySelector('[data-nexdirectory-homepage-form]');
        if (homepageForm) {
            homepageForm.addEventListener('submit', function () {
                var submitButton = homepageForm.querySelector('button[type="submit"]');
                rememberStep(6);
                if (submitButton) {
                    submitButton.disabled = true;
                }
                toArray(homepageForm.querySelectorAll('[data-nexdirectory-busy-idle]')).forEach(function (element) {
                    setVisible(element, false);
                });
                toArray(homepageForm.querySelectorAll('[data-nexdirectory-busy-active]')).forEach(function (element) {
                    setVisible(element, true, 'inline-flex');
                });
            });
        }

        nextButton = document.querySelector('[data-nexdirectory-next-step]');
        if (nextButton) {
            nextButton.addEventListener('click', function () {
                if (state.step === 1) {
                    updateHiddenOperatingInputs(state);
                    rememberStep(2);
                    submitForm(document.querySelector('[data-nexdirectory-step1-save-form]'));
                    return;
                }
                if (state.step === 3) {
                    updateHiddenOperatingInputs(state);
                    rememberStep(4);
                    submitForm(document.querySelector('[data-nexdirectory-step3-save-form]'));
                    return;
                }
                setStep(state, state.step + 1);
            });
        }

        prevButton = document.querySelector('[data-nexdirectory-prev-step]');
        if (prevButton) {
            prevButton.addEventListener('click', function () {
                setStep(state, state.step - 1);
            });
        }

        completionForm = document.querySelector('[data-nexdirectory-complete-form]');
        if (completionForm) {
            completionForm.addEventListener('submit', function () {
                var submitButton = completionForm.querySelector('button[type="submit"]');
                state.isComplete = true;
                forgetRememberedStep();
                if (submitButton) {
                    submitButton.disabled = true;
                }
            });
        }
        renderWizard(state);
    }

    function hideConfirmModal(restoreFocus) {
        var confirmModal = document.getElementById('nexdirectory-demo-import-confirm-modal');
        setVisible(confirmModal, false, 'flex');
        if (restoreFocus && modalReturnFocus && typeof modalReturnFocus.focus === 'function') {
            modalReturnFocus.focus();
        }
        modalReturnFocus = null;
    }

    function showConfirmModal(form) {
        var confirmModal = document.getElementById('nexdirectory-demo-import-confirm-modal');
        var confirmedInput = form ? form.querySelector('[data-nexdirectory-confirmed-input]') : null;
        var confirmButton;
        var title = form ? form.getAttribute('data-confirm-title') : '';
        var message = form ? form.getAttribute('data-confirm-message') : '';
        var buttonLabel = form ? form.getAttribute('data-confirm-button-label') : '';
        modalReturnFocus = document.activeElement;
        pendingDemoImportForm = form;
        if (confirmedInput) {
            confirmedInput.value = '0';
        }
        if (title) {
            setText('[data-nexdirectory-confirm-title]', title);
        }
        if (message) {
            setText('[data-nexdirectory-confirm-message]', message);
        }
        if (buttonLabel) {
            setText('[data-nexdirectory-confirm-button-label]', buttonLabel);
        }
        setVisible(confirmModal, true, 'flex');
        confirmButton = confirmModal ? confirmModal.querySelector('[data-nexdirectory-confirm-import]') : null;
        if (confirmButton) {
            confirmButton.focus();
        }
    }

    function showLoadingOverlay(form) {
        var loadingOverlay = document.getElementById('nexdirectory-onboarding-import-loading');
        var loadingTitle = form ? form.getAttribute('data-loading-title') : '';
        var loadingMessage = form ? form.getAttribute('data-loading-message') : '';
        if (!loadingOverlay) {
            return;
        }
        if (loadingTitle) {
            setText('[data-nexdirectory-loading-title]', loadingTitle);
        }
        if (loadingMessage) {
            setText('[data-nexdirectory-loading-message]', loadingMessage);
        }
        setVisible(loadingOverlay, true, 'flex');
        loadingOverlay.classList.add('is-visible');
    }

    function bindDemoImportConfirmation() {
        var confirmModal = document.getElementById('nexdirectory-demo-import-confirm-modal');
        var loadingOverlay = document.getElementById('nexdirectory-onboarding-import-loading');
        var root = getRoot();
        hideConfirmModal(false);
        if (loadingOverlay) {
            setVisible(loadingOverlay, false, 'flex');
            loadingOverlay.classList.remove('is-visible');
        }

        toArray(document.querySelectorAll('[data-nexdirectory-confirm-form]')).forEach(function (form) {
            if (form.getAttribute('data-confirmation-bound') === '1') {
                return;
            }
            form.setAttribute('data-confirmation-bound', '1');
            form.addEventListener('submit', function (event) {
                if (form.getAttribute('data-confirmed-submit') === '1') {
                    return;
                }
                event.preventDefault();
                showConfirmModal(form);
            });
        });

        toArray(document.querySelectorAll('[data-nexdirectory-cancel-import]')).forEach(function (button) {
            if (button.getAttribute('data-confirmation-bound') === '1') {
                return;
            }
            button.setAttribute('data-confirmation-bound', '1');
            button.addEventListener('click', function () {
                var confirmedInput = pendingDemoImportForm ? pendingDemoImportForm.querySelector('[data-nexdirectory-confirmed-input]') : null;
                if (confirmedInput) {
                    confirmedInput.value = '0';
                }
                pendingDemoImportForm = null;
                hideConfirmModal(true);
            });
        });

        toArray(document.querySelectorAll('[data-nexdirectory-confirm-import]')).forEach(function (button) {
            if (button.getAttribute('data-confirmation-bound') === '1') {
                return;
            }
            button.setAttribute('data-confirmation-bound', '1');
            button.addEventListener('click', function () {
                var form = pendingDemoImportForm;
                var confirmedInput = form ? form.querySelector('[data-nexdirectory-confirmed-input]') : null;
                var redirectInput = form ? form.querySelector('input[name="nexdirectory_redirect_to"]') : null;
                var redirectUrl;
                var redirectStep;
                if (!form) {
                    hideConfirmModal(true);
                    return;
                }
                if (confirmedInput) {
                    confirmedInput.value = '1';
                }
                form.setAttribute('data-confirmed-submit', '1');
                if (redirectInput && redirectInput.value) {
                    try {
                        redirectUrl = new URL(redirectInput.value, window.location.href);
                        redirectStep = parseInt(redirectUrl.searchParams.get('step') || '0', 10);
                        if (redirectStep >= 1 && redirectStep <= getMaxStep()) {
                            rememberStep(redirectStep);
                        }
                    } catch (error) {
                        // The server redirect remains authoritative if URL parsing fails.
                    }
                }
                hideConfirmModal(false);
                showLoadingOverlay(form);
                HTMLFormElement.prototype.submit.call(form);
            });
        });

        if (root && root.getAttribute('data-nexdirectory-modal-keys-bound') !== '1') {
            root.setAttribute('data-nexdirectory-modal-keys-bound', '1');
            document.addEventListener('keydown', function (event) {
                var focusable;
                var first;
                var last;
                if (!confirmModal || confirmModal.hidden) {
                    return;
                }
                if (event.key === 'Escape') {
                    event.preventDefault();
                    pendingDemoImportForm = null;
                    hideConfirmModal(true);
                    return;
                }
                if (event.key !== 'Tab') {
                    return;
                }
                focusable = toArray(confirmModal.querySelectorAll('button:not([disabled]), a[href], input:not([disabled]), [tabindex]:not([tabindex="-1"])'));
                if (!focusable.length) {
                    return;
                }
                first = focusable[0];
                last = focusable[focusable.length - 1];
                if (event.shiftKey && document.activeElement === first) {
                    event.preventDefault();
                    last.focus();
                } else if (!event.shiftKey && document.activeElement === last) {
                    event.preventDefault();
                    first.focus();
                }
            });
        }
    }

    function init() {
        bindWizard();
        bindDemoImportConfirmation();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
}());
<?php $this->enqueue_inline_script_asset('nexdirectory-admin-onboarding', ob_get_clean()); ?>

<div class="wrap nxd-ui nexdirectory-onboarding-page nexdirectory-onboarding-modern">
    <?php echo wp_kses_post((string) $this->render_notice()); ?>

    <div class="max-w-4xl mx-auto space-y-6 py-4">
        <div data-nexdirectory-welcome-notice class="bg-blue-50 border-l-4 border-blue-500 p-4 rounded-r-md flex justify-between items-start shadow-sm">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas fa-info-circle text-blue-500 mt-1"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm font-semibold text-blue-900"><?php esc_html_e('A guided first launch, usually under five minutes.', 'nexdirectory'); ?></p>
                    <p class="mt-1 text-sm text-blue-700"><?php esc_html_e('Your choices remain editable, optional steps can be skipped, and setup actions never delete live listings.', 'nexdirectory'); ?></p>
                </div>
            </div>
            <button type="button" data-nexdirectory-close-notice class="text-blue-500 hover:text-blue-700 transition" aria-label="<?php esc_attr_e('Dismiss welcome message', 'nexdirectory'); ?>"><i class="fas fa-times" aria-hidden="true"></i></button>
        </div>

        <header class="bg-white rounded-2xl shadow-sm p-8 border border-slate-200 text-center relative overflow-hidden">
            <div class="absolute -top-24 -right-24 w-48 h-48 bg-indigo-50 rounded-full blur-3xl opacity-60 pointer-events-none"></div>
            <span class="inline-block py-1 px-3 rounded-full bg-indigo-100 text-indigo-700 text-xs font-bold tracking-wider uppercase mb-4"><?php esc_html_e('First-launch guide', 'nexdirectory'); ?></span>
            <h1 class="text-3xl sm:text-4xl font-extrabold text-slate-900 mb-4 tracking-tight"><?php echo esc_html($brand_name); ?> <?php esc_html_e('Setup', 'nexdirectory'); ?></h1>
            <p class="text-lg text-slate-500 max-w-2xl mx-auto"><?php /* translators: 1: Brand name, 2: Plural listing label. */ echo esc_html(sprintf(__('Prepare your %1$s workflow for %2$s, with a clear check before launch.', 'nexdirectory'), $brand_name, $plural_label)); ?></p>
            <div class="mt-5 flex flex-wrap items-center justify-center gap-2 text-xs font-bold">
                <span class="inline-flex items-center gap-2 rounded-full bg-emerald-50 border border-emerald-200 px-3 py-1.5 text-emerald-800">
                    <i class="fas fa-infinity" aria-hidden="true"></i><?php esc_html_e('Unlimited core publishing', 'nexdirectory'); ?>
                </span>
                <span class="inline-flex items-center gap-2 rounded-full bg-slate-100 border border-slate-200 px-3 py-1.5 text-slate-700">
                    <i class="fas fa-list-check" aria-hidden="true"></i>
                    <?php /* translators: 1: Number of ready setup steps, 2: Total number of setup steps. */ echo esc_html(sprintf(__('%1$d of %2$d steps prepared', 'nexdirectory'), $setup_ready_count, $step_count)); ?>
                </span>
            </div>
        </header>

        <section class="grid grid-cols-1 sm:grid-cols-3 gap-3" aria-label="<?php esc_attr_e('Setup snapshot', 'nexdirectory'); ?>">
            <div class="bg-white rounded-xl border border-slate-200 p-4 shadow-sm">
                <p class="text-xs font-bold uppercase tracking-wider text-slate-500"><?php esc_html_e('Core pages', 'nexdirectory'); ?></p>
                <p class="mt-2 text-2xl font-extrabold text-slate-900"><?php echo esc_html((string) $core_page_count); ?><span class="text-base text-slate-400">/<?php echo esc_html((string) $core_page_expected); ?></span></p>
                <p class="mt-1 text-xs <?php echo esc_attr($core_pages_ready ? 'text-emerald-700' : 'text-amber-700'); ?>"><?php echo esc_html($core_pages_ready ? __('Ready', 'nexdirectory') : __('Needs a page check', 'nexdirectory')); ?></p>
            </div>
            <div class="bg-white rounded-xl border border-slate-200 p-4 shadow-sm">
                <p class="text-xs font-bold uppercase tracking-wider text-slate-500"><?php echo esc_html($plural_label); ?></p>
                <p class="mt-2 text-2xl font-extrabold text-slate-900"><?php echo esc_html((string) $total_listing_count); ?></p>
                <p class="mt-1 text-xs text-slate-500"><?php /* translators: %d: Number of published listings. */ echo esc_html(sprintf(__('%d published', 'nexdirectory'), $published_listing_count)); ?></p>
            </div>
            <div class="bg-white rounded-xl border border-slate-200 p-4 shadow-sm">
                <p class="text-xs font-bold uppercase tracking-wider text-slate-500"><?php esc_html_e('Launch preflight', 'nexdirectory'); ?></p>
                <p class="mt-2 text-2xl font-extrabold text-slate-900"><?php echo esc_html((string) $preflight_ready_count); ?><span class="text-base text-slate-400">/<?php echo esc_html((string) $preflight_check_count); ?></span></p>
                <p class="mt-1 text-xs <?php echo esc_attr($preflight_ready_count === $preflight_check_count ? 'text-emerald-700' : 'text-amber-700'); ?>"><?php echo esc_html($preflight_ready_count === $preflight_check_count ? __('Environment ready', 'nexdirectory') : __('Review recommended items', 'nexdirectory')); ?></p>
            </div>
        </section>

        <section class="bg-white rounded-2xl shadow-sm p-6 sm:p-8 border border-slate-200" aria-label="<?php esc_attr_e('Setup progress', 'nexdirectory'); ?>">
            <div class="relative max-w-2xl mx-auto">
                <div class="absolute top-5 left-0 w-full h-1 bg-slate-100 -translate-y-1/2 rounded-full z-0"></div>
                <div data-nexdirectory-onboarding-progress class="absolute top-5 left-0 h-1 bg-indigo-600 -translate-y-1/2 rounded-full z-0 transition-all duration-500 ease-out" style="width: <?php echo esc_attr((string) (($initial_step / max(1, $step_count)) * 100)); ?>%"></div>

                <ul class="flex w-full justify-between relative z-10">
                    <?php foreach ($wizard_steps as $step_index => $step_row) : ?>
                        <?php
                        $step_number = (int) $step_index + 1;
                        $step_is_past = $step_number < $initial_step;
                        $step_is_current = $step_number === $initial_step;
                        $step_is_ready = !empty($step_row['is_ready']);
                        $step_is_optional = !empty($step_row['optional']);
                        $step_title = sanitize_text_field((string) ($step_row['title'] ?? __('Step', 'nexdirectory')));
                        $step_short_title = sanitize_text_field((string) ($step_row['short_title'] ?? $step_title));
                        if ($step_is_current) {
                            $step_button_state_classes = 'bg-white border-2 border-indigo-600 text-indigo-600 shadow-md ring-4 ring-indigo-50 cursor-pointer';
                            $step_label_state_classes = 'text-indigo-600';
                            $step_status_label = __('current', 'nexdirectory');
                        } elseif ($step_is_ready) {
                            $step_button_state_classes = 'bg-emerald-600 text-white shadow-md cursor-pointer hover:bg-emerald-700';
                            $step_label_state_classes = 'text-emerald-700';
                            $step_status_label = __('complete', 'nexdirectory');
                        } elseif ($step_is_past && $step_is_optional) {
                            $step_button_state_classes = 'bg-amber-50 border-2 border-amber-300 text-amber-700 cursor-pointer hover:border-amber-400';
                            $step_label_state_classes = 'text-slate-600';
                            $step_status_label = __('optional', 'nexdirectory');
                        } elseif ($step_is_past) {
                            $step_button_state_classes = 'bg-slate-100 border-2 border-slate-300 text-slate-600 cursor-pointer hover:border-slate-400';
                            $step_label_state_classes = 'text-slate-600';
                            $step_status_label = __('not complete', 'nexdirectory');
                        } else {
                            $step_button_state_classes = 'bg-white border-2 border-slate-200 text-slate-400 hover:border-slate-300 cursor-pointer';
                            $step_label_state_classes = 'text-slate-400';
                            $step_status_label = $step_is_optional ? __('optional', 'nexdirectory') : __('not complete', 'nexdirectory');
                        }
                        /* translators: 1: Wizard step number, 2: Wizard step title, 3: Wizard step status. */
                        $step_accessible_label = sprintf(__('Step %1$d: %2$s — %3$s', 'nexdirectory'), $step_number, $step_title, $step_status_label);
                        ?>
                        <li class="flex flex-col items-center group">
                            <button type="button" data-nexdirectory-step-button="<?php echo esc_attr((string) $step_number); ?>" class="w-10 h-10 rounded-full flex items-center justify-center transition-all duration-300 focus:outline-none focus:ring-4 focus:ring-indigo-100 <?php echo esc_attr($step_button_state_classes); ?>" aria-label="<?php echo esc_attr($step_accessible_label); ?>"<?php if ($step_is_current) : ?> aria-current="step"<?php endif; ?>>
                                <span data-nexdirectory-step-check <?php echo $step_is_ready ? '' : 'hidden'; ?>><i class="fas fa-check" aria-hidden="true"></i></span>
                                <span data-nexdirectory-step-number <?php echo $step_is_ready ? 'hidden' : ''; ?> class="font-bold text-sm"><?php echo esc_html((string) $step_number); ?></span>
                            </button>
                            <span data-nexdirectory-step-label="<?php echo esc_attr((string) $step_number); ?>" class="mt-3 text-xs font-bold uppercase tracking-wider hidden sm:block transition-colors <?php echo esc_attr($step_label_state_classes); ?>"><?php echo esc_html($step_short_title); ?></span>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <p data-nexdirectory-progress-summary class="mt-5 text-center text-xs font-semibold text-slate-500"><?php /* translators: 1: Current wizard step, 2: Total wizard steps. */ echo esc_html(sprintf(__('Step %1$d of %2$d · choose any step to review it', 'nexdirectory'), $initial_step, $step_count)); ?></p>
        </section>

        <section class="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden transform transition-all">
            <div class="p-8 sm:p-10">
                <div class="flex flex-col sm:flex-row sm:items-center gap-4 mb-6">
                    <div class="flex-shrink-0 w-12 h-12 bg-indigo-50 text-indigo-600 rounded-xl flex items-center justify-center">
                        <i data-nexdirectory-current-icon class="fas text-xl <?php echo esc_attr($current_step_icon); ?>" aria-hidden="true"></i>
                    </div>
                    <div aria-live="polite">
                        <h2 data-nexdirectory-current-title tabindex="-1" class="text-2xl font-bold text-slate-900"><?php /* translators: 1: Wizard step number, 2: Wizard step title. */ echo esc_html(sprintf(__('Step %1$d: %2$s', 'nexdirectory'), $initial_step, $current_step_title)); ?></h2>
                    </div>
                </div>

                <p data-nexdirectory-current-description class="text-slate-600 text-lg leading-relaxed mb-4"><?php echo esc_html($current_step_description); ?></p>
                <div class="mb-8 rounded-xl border border-indigo-100 bg-indigo-50/60 px-4 py-3 text-sm text-indigo-900 flex items-start gap-3">
                    <i class="fas fa-circle-info mt-0.5 text-indigo-500" aria-hidden="true"></i>
                    <div><strong><?php esc_html_e('Good to know:', 'nexdirectory'); ?></strong> <span data-nexdirectory-current-help><?php echo esc_html((string) ($current_step_data['help'] ?? '')); ?></span></div>
                </div>

                <div data-nexdirectory-step-panel="1" <?php echo $initial_step !== 1 ? 'hidden' : ''; ?> class="space-y-4 mb-8">
                    <section class="rounded-2xl border border-slate-200 bg-slate-50 p-5 mb-7" aria-labelledby="nexdirectory-onboarding-preflight-title">
                        <div class="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3 mb-4">
                            <div>
                                <h3 id="nexdirectory-onboarding-preflight-title" class="m-0 text-lg font-extrabold text-slate-900"><?php esc_html_e('Launch preflight', 'nexdirectory'); ?></h3>
                                <p class="mt-1 text-sm text-slate-600"><?php esc_html_e('A quick read-only check of the WordPress environment before you build.', 'nexdirectory'); ?></p>
                            </div>
                            <span class="self-start inline-flex rounded-full px-3 py-1 text-xs font-bold <?php echo esc_attr($preflight_ready_count === $preflight_check_count ? 'bg-emerald-100 text-emerald-800' : 'bg-amber-100 text-amber-800'); ?>">
                                <?php /* translators: 1: Number of ready checks, 2: Total number of checks. */ echo esc_html(sprintf(__('%1$d of %2$d ready', 'nexdirectory'), $preflight_ready_count, $preflight_check_count)); ?>
                            </span>
                        </div>
                        <?php if (!empty($preflight_checks)) : ?>
                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                                <?php foreach ($preflight_checks as $preflight_check) : ?>
                                    <?php
                                    $preflight_check = is_array($preflight_check) ? $preflight_check : [];
                                    $check_ready = !empty($preflight_check['ready']);
                                    $check_label = sanitize_text_field((string) ($preflight_check['label'] ?? __('Environment check', 'nexdirectory')));
                                    $check_description = sanitize_text_field((string) ($preflight_check['description'] ?? ''));
                                    $check_action_url = (string) ($preflight_check['action_url'] ?? '');
                                    $check_action_label = sanitize_text_field((string) ($preflight_check['action_label'] ?? ''));
                                    ?>
                                    <div class="nexdirectory-onboarding-preflight-card rounded-xl border bg-white p-4 <?php echo esc_attr($check_ready ? 'border-emerald-200' : 'border-amber-200'); ?>">
                                        <div class="flex items-start gap-3">
                                            <span class="mt-0.5 inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full <?php echo esc_attr($check_ready ? 'bg-emerald-100 text-emerald-700' : 'bg-amber-100 text-amber-700'); ?>">
                                                <i class="fas <?php echo esc_attr($check_ready ? 'fa-check' : 'fa-exclamation'); ?> text-xs" aria-hidden="true"></i>
                                            </span>
                                            <div>
                                                <h4 class="m-0 text-sm font-bold text-slate-900"><?php echo esc_html($check_label); ?></h4>
                                                <?php if ($check_description !== '') : ?>
                                                    <p class="mt-1 text-xs leading-5 text-slate-600"><?php echo esc_html($check_description); ?></p>
                                                <?php endif; ?>
                                                <?php if (!$check_ready && $check_action_url !== '' && $check_action_label !== '') : ?>
                                                    <a href="<?php echo esc_url($check_action_url); ?>" class="mt-2 inline-flex items-center gap-1 text-xs font-bold text-indigo-700 hover:text-indigo-900">
                                                        <?php echo esc_html($check_action_label); ?><i class="fas fa-arrow-up-right-from-square text-[10px]" aria-hidden="true"></i>
                                                    </a>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </section>

                    <div class="rounded-xl border border-indigo-100 bg-indigo-50/50 p-4 text-sm text-indigo-900 mb-5">
                        <strong><?php esc_html_e('One click prepares the foundation:', 'nexdirectory'); ?></strong>
                        <?php esc_html_e('a visual preset, profile terminology, sensible feature defaults, core routes, and the blueprint’s configured sample content. You can still continue manually below.', 'nexdirectory'); ?>
                    </div>

                    <?php if (!empty($starter_blueprints)) : ?>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-7">
                            <?php foreach ($starter_blueprints as $blueprint_key => $blueprint) : ?>
                                <?php
                                $blueprint_key = sanitize_key((string) $blueprint_key);
                                $blueprint = is_array($blueprint) ? $blueprint : [];
                                if ($blueprint_key === '') {
                                    continue;
                                }
                                $blueprint_label = sanitize_text_field((string) ($blueprint['label'] ?? $blueprint_key));
                                $blueprint_description = sanitize_text_field((string) ($blueprint['description'] ?? ''));
                                $blueprint_icon = sanitize_html_class((string) ($blueprint['icon'] ?? 'layer-group'), 'layer-group');
                                $blueprint_features = array_values(array_filter(array_map('sanitize_text_field', (array) ($blueprint['features'] ?? []))));
                                $blueprint_sample_count = max(0, min(12, (int) ($blueprint['sample_count'] ?? 6)));
                                $is_active_blueprint = $active_starter_blueprint === $blueprint_key;
                                /* translators: %s: Starter blueprint label. */
                                $blueprint_confirm_title = sprintf(__('Apply the %s blueprint?', 'nexdirectory'), $blueprint_label);
                                /* translators: %s: Starter blueprint label. */
                                $blueprint_confirm_button_label = sprintf(__('Apply %s', 'nexdirectory'), $blueprint_label);
                                /* translators: %s: Starter blueprint label. */
                                $blueprint_loading_title = sprintf(__('Preparing %s', 'nexdirectory'), $blueprint_label);
                                if ($is_active_blueprint) {
                                    /* translators: %s: Starter blueprint label. */
                                    $blueprint_action_label = sprintf(__('Reapply %s', 'nexdirectory'), $blueprint_label);
                                } else {
                                    /* translators: %s: Starter blueprint label. */
                                    $blueprint_action_label = sprintf(__('Use %s', 'nexdirectory'), $blueprint_label);
                                }
                                ?>
                                <form
                                    method="post"
                                    action="<?php echo esc_url($save_preferences_action); ?>"
                                    class="relative flex flex-col rounded-2xl border p-5 shadow-sm transition-all <?php echo esc_attr($is_active_blueprint ? 'border-indigo-500 bg-indigo-50/40 ring-1 ring-indigo-500' : 'border-slate-200 bg-white hover:border-indigo-300 hover:shadow-md'); ?>"
                                    data-nexdirectory-confirm-form
                                    data-confirm-title="<?php echo esc_attr($blueprint_confirm_title); ?>"
                                    data-confirm-message="<?php echo esc_attr($blueprint_confirm_message); ?>"
                                    data-confirm-button-label="<?php echo esc_attr($blueprint_confirm_button_label); ?>"
                                    data-loading-title="<?php echo esc_attr($blueprint_loading_title); ?>"
                                    data-loading-message="<?php esc_attr_e('Keep this tab open while the preset, routes, missing pages, and duplicate-aware samples are prepared.', 'nexdirectory'); ?>"
                                >
                                    <input type="hidden" name="action" value="nexdirectory_apply_starter_blueprint">
                                    <input type="hidden" name="nexdirectory_starter_blueprint" value="<?php echo esc_attr($blueprint_key); ?>">
                                    <input type="hidden" name="nexdirectory_blueprint_include_content" value="1">
                                    <input type="hidden" name="nexdirectory_blueprint_confirmed" value="0" data-nexdirectory-confirmed-input>
                                    <input type="hidden" name="nexdirectory_redirect_to" value="<?php echo esc_url($onboarding_step_three_url); ?>">
                                    <?php wp_nonce_field('nexdirectory_apply_starter_blueprint', 'nexdirectory_starter_blueprint_nonce'); ?>

                                    <div class="flex items-start gap-4">
                                        <span class="w-11 h-11 shrink-0 rounded-xl bg-indigo-100 text-indigo-700 flex items-center justify-center">
                                            <i class="fas fa-<?php echo esc_attr($blueprint_icon); ?>" aria-hidden="true"></i>
                                        </span>
                                        <div class="min-w-0">
                                            <div class="flex flex-wrap items-center gap-2">
                                                <h3 class="text-base font-extrabold text-slate-900 m-0"><?php echo esc_html($blueprint_label); ?></h3>
                                                <?php if ($is_active_blueprint) : ?>
                                                    <span class="inline-flex items-center rounded-full bg-indigo-100 px-2 py-0.5 text-[11px] font-bold text-indigo-700"><?php esc_html_e('Active', 'nexdirectory'); ?></span>
                                                <?php endif; ?>
                                                <span class="inline-flex items-center rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-bold text-slate-600">
                                                    <?php /* translators: %d: Number of sample listings included with a starter blueprint. */ echo esc_html(sprintf(_n('%d sample', '%d samples', $blueprint_sample_count, 'nexdirectory'), $blueprint_sample_count)); ?>
                                                </span>
                                            </div>
                                            <?php if ($blueprint_description !== '') : ?>
                                                <p class="mt-1 text-sm leading-6 text-slate-600"><?php echo esc_html($blueprint_description); ?></p>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <?php if (!empty($blueprint_features)) : ?>
                                        <ul class="mt-4 mb-5 space-y-2 text-sm text-slate-600">
                                            <?php foreach ($blueprint_features as $feature) : ?>
                                                <li class="flex gap-2"><i class="fas fa-check text-emerald-500 mt-1" aria-hidden="true"></i><span><?php echo esc_html($feature); ?></span></li>
                                            <?php endforeach; ?>
                                        </ul>
                                    <?php endif; ?>
                                    <button type="submit" class="mt-auto inline-flex items-center justify-center px-4 py-2.5 rounded-lg text-white bg-indigo-600 hover:bg-indigo-700 shadow-sm font-semibold transition-all">
                                        <?php echo esc_html($blueprint_action_label); ?>
                                        <i class="fas fa-arrow-right ml-2 text-xs" aria-hidden="true"></i>
                                    </button>
                                </form>
                            <?php endforeach; ?>
                        </div>
                        <div class="flex items-center gap-3 py-2" aria-hidden="true">
                            <span class="h-px flex-1 bg-slate-200"></span>
                            <span class="text-xs font-bold uppercase tracking-wider text-slate-400"><?php esc_html_e('Advanced operating mode', 'nexdirectory'); ?></span>
                            <span class="h-px flex-1 bg-slate-200"></span>
                        </div>
                    <?php else : ?>
                        <div class="rounded-2xl border border-dashed border-slate-300 bg-slate-50 p-6 text-center mb-6">
                            <span class="mx-auto mb-3 flex h-11 w-11 items-center justify-center rounded-full bg-white text-slate-500 shadow-sm"><i class="fas fa-layer-group" aria-hidden="true"></i></span>
                            <h3 class="m-0 text-base font-bold text-slate-900"><?php esc_html_e('Starter blueprints are temporarily unavailable', 'nexdirectory'); ?></h3>
                            <p class="mt-2 text-sm text-slate-600"><?php esc_html_e('Nothing is blocked. Choose an operating mode below, then create the core pages manually in the next step.', 'nexdirectory'); ?></p>
                        </div>
                    <?php endif; ?>

                    <label data-nexdirectory-mode-option="user" class="relative flex cursor-pointer rounded-xl border bg-white p-5 shadow-sm transition-all <?php echo esc_attr($operating_mode === 'user' ? 'border-indigo-600 ring-1 ring-indigo-600 bg-indigo-50/30' : 'border-slate-200 hover:border-slate-300 hover:bg-slate-50'); ?>">
                        <input type="radio" name="operatingMode" value="user" class="sr-only" <?php checked($operating_mode, 'user'); ?>>
                        <span class="flex flex-1">
                            <span class="flex flex-col">
                                <span class="block text-base font-bold text-slate-900"><?php esc_html_e('Multi-user Directory (Default)', 'nexdirectory'); ?></span>
                                <span class="mt-1 flex items-center text-sm text-slate-500"><?php esc_html_e('Allows members, employers, sellers, or organizers to submit and manage their own listings.', 'nexdirectory'); ?></span>
                            </span>
                        </span>
                        <i data-nexdirectory-mode-check="user" class="fas fa-check-circle text-indigo-600 text-2xl ml-4 self-center transition-opacity <?php echo esc_attr($operating_mode === 'user' ? 'opacity-100' : 'opacity-0'); ?>"></i>
                    </label>

                    <label data-nexdirectory-mode-option="single" class="relative flex cursor-pointer rounded-xl border bg-white p-5 shadow-sm transition-all <?php echo esc_attr($operating_mode === 'single' ? 'border-indigo-600 ring-1 ring-indigo-600 bg-indigo-50/30' : 'border-slate-200 hover:border-slate-300 hover:bg-slate-50'); ?>">
                        <input type="radio" name="operatingMode" value="single" class="sr-only" <?php checked($operating_mode, 'single'); ?>>
                        <span class="flex flex-1">
                            <span class="flex flex-col">
                                <span class="block text-base font-bold text-slate-900"><?php esc_html_e('Single-Organisation Directory', 'nexdirectory'); ?></span>
                                <span class="mt-1 flex items-center text-sm text-slate-500"><?php esc_html_e('Only administrators can create and manage listings.', 'nexdirectory'); ?></span>
                            </span>
                        </span>
                        <i data-nexdirectory-mode-check="single" class="fas fa-check-circle text-indigo-600 text-2xl ml-4 self-center transition-opacity <?php echo esc_attr($operating_mode === 'single' ? 'opacity-100' : 'opacity-0'); ?>"></i>
                    </label>

                    <form data-nexdirectory-step1-save-form method="post" action="<?php echo esc_url($save_preferences_action); ?>" class="hidden">
                        <input type="hidden" name="action" value="nexdirectory_save_onboarding_preferences">
                        <input type="hidden" name="nexdirectory_onboarding_step" value="2">
                        <?php wp_nonce_field('nexdirectory_onboarding_save_preferences', 'nexdirectory_onboarding_save_nonce'); ?>
                        <input type="hidden" name="nexdirectory_onboarding_operating_mode" value="<?php echo esc_attr($operating_mode); ?>">
                    </form>
                </div>

                <div data-nexdirectory-step-panel="2" <?php echo $initial_step !== 2 ? 'hidden' : ''; ?> class="mb-8">
                    <div class="rounded-2xl border <?php echo esc_attr($core_pages_ready ? 'border-emerald-200 bg-emerald-50/50' : 'border-amber-200 bg-amber-50/40'); ?> p-6">
                        <div class="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
                            <div class="flex items-start gap-4">
                                <span class="inline-flex h-12 w-12 shrink-0 items-center justify-center rounded-xl <?php echo esc_attr($core_pages_ready ? 'bg-emerald-100 text-emerald-700' : 'bg-amber-100 text-amber-700'); ?>">
                                    <i class="fas <?php echo esc_attr($core_pages_ready ? 'fa-check' : 'fa-file-circle-plus'); ?>" aria-hidden="true"></i>
                                </span>
                                <div>
                                    <h3 class="m-0 text-lg font-extrabold text-slate-900">
                                        <?php echo esc_html($core_pages_ready ? __('Core pages are ready', 'nexdirectory') : __('Create the missing app pages', 'nexdirectory')); ?>
                                    </h3>
                                    <p class="mt-1 text-sm text-slate-600">
                                        <?php /* translators: 1: Number of detected pages, 2: Expected number of pages. */ echo esc_html(sprintf(__('%1$d of %2$d expected Nex Directory pages are currently detected.', 'nexdirectory'), $core_page_count, $core_page_expected)); ?>
                                    </p>
                                    <p class="mt-2 text-xs leading-5 text-slate-500"><?php esc_html_e('The check preserves matching pages and their content. If another page already owns a required slug, it is left untouched for you to review.', 'nexdirectory'); ?></p>
                                </div>
                            </div>
                        </div>
                        <div class="mt-5 flex flex-wrap gap-3">
                            <form method="post" action="<?php echo esc_url($save_preferences_action); ?>">
                                <input type="hidden" name="action" value="nexdirectory_generate_pages">
                                <input type="hidden" name="nexdirectory_redirect_to" value="<?php echo esc_attr($onboarding_step_three_url); ?>">
                                <input type="hidden" name="nexdirectory_onboarding_step" value="3">
                                <?php wp_nonce_field('nexdirectory_generate_pages', 'nexdirectory_generate_pages_nonce'); ?>
                                <button type="submit" class="inline-flex items-center justify-center px-6 py-3 rounded-lg text-white bg-indigo-600 hover:bg-indigo-700 shadow-md font-semibold transition-all">
                                    <i class="fas fa-file-medical mr-2" aria-hidden="true"></i>
                                    <?php echo esc_html($core_pages_ready ? __('Re-check & Refresh Routes', 'nexdirectory') : __('Create Missing Core Pages', 'nexdirectory')); ?>
                                </button>
                            </form>
                            <a href="<?php echo esc_url($pages_url); ?>" class="inline-flex items-center justify-center px-5 py-3 rounded-lg border border-slate-300 bg-white text-slate-700 hover:bg-slate-50 font-semibold transition-all">
                                <?php esc_html_e('Review WordPress Pages', 'nexdirectory'); ?><i class="fas fa-arrow-up-right-from-square ml-2 text-xs" aria-hidden="true"></i>
                            </a>
                        </div>
                    </div>
                </div>

                <div data-nexdirectory-step-panel="3" <?php echo $initial_step !== 3 ? 'hidden' : ''; ?> class="space-y-6 mb-8">
                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
                        <form data-nexdirectory-step3-save-form method="post" action="<?php echo esc_url($save_preferences_action); ?>" class="space-y-6 rounded-2xl border border-slate-200 bg-white p-6">
                            <input type="hidden" name="action" value="nexdirectory_save_onboarding_preferences">
                            <input type="hidden" name="nexdirectory_onboarding_step" value="4">
                            <?php wp_nonce_field('nexdirectory_onboarding_save_preferences', 'nexdirectory_onboarding_save_nonce'); ?>

                            <div>
                                <label for="nexdirectory-onboarding-site-name" class="block text-sm font-semibold text-slate-700 mb-2"><?php esc_html_e('Site Name', 'nexdirectory'); ?></label>
                                <input id="nexdirectory-onboarding-site-name" data-nexdirectory-site-name type="text" name="nexdirectory_onboarding_site_name" value="<?php echo esc_attr($site_name); ?>" class="w-full rounded-lg border-slate-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 px-4 py-2 border outline-none" placeholder="<?php esc_attr_e('E.g. My Local Directory', 'nexdirectory'); ?>" maxlength="140" required>
                                <p class="mt-2 text-xs text-slate-500"><?php esc_html_e('Used as the WordPress site title and as the default directory brand name.', 'nexdirectory'); ?></p>
                            </div>
                            <div>
                                <label for="nexdirectory-onboarding-accent-color" class="block text-sm font-semibold text-slate-700 mb-2"><?php esc_html_e('Brand Accent Color', 'nexdirectory'); ?></label>
                                <div class="flex items-center space-x-4">
                                    <input id="nexdirectory-onboarding-accent-color" data-nexdirectory-accent-color type="color" name="nexdirectory_onboarding_accent_color" value="<?php echo esc_attr($accent_color); ?>" class="h-12 w-12 rounded-lg border border-slate-200 cursor-pointer p-0.5 outline-none">
                                    <span data-nexdirectory-accent-preview class="text-sm text-slate-600 font-mono bg-slate-100 px-3 py-1 rounded-md"><?php echo esc_html(strtoupper($accent_color)); ?></span>
                                </div>
                                <p class="mt-2 text-xs text-slate-500"><?php esc_html_e('Applied to primary controls and highlights; contrast-aware text colors remain automatic.', 'nexdirectory'); ?></p>
                            </div>
                            <input type="hidden" name="nexdirectory_onboarding_operating_mode" value="<?php echo esc_attr($operating_mode); ?>">
                        </form>

                        <aside class="relative overflow-hidden rounded-2xl border border-slate-200 bg-slate-900 p-6 text-white" aria-label="<?php esc_attr_e('Brand preview', 'nexdirectory'); ?>">
                            <div class="absolute -right-10 -top-10 h-36 w-36 rounded-full opacity-30 blur-2xl" data-nexdirectory-accent-swatch style="background-color: <?php echo esc_attr($accent_color); ?>;"></div>
                            <p class="relative text-xs font-bold uppercase tracking-wider text-slate-400"><?php esc_html_e('Live preview', 'nexdirectory'); ?></p>
                            <div class="relative mt-10 rounded-xl border border-white/10 bg-white/5 p-5">
                                <span class="mb-4 inline-flex h-10 w-10 items-center justify-center rounded-xl text-white shadow-lg" data-nexdirectory-accent-swatch style="background-color: <?php echo esc_attr($accent_color); ?>;"><i class="fas fa-compass" aria-hidden="true"></i></span>
                                <h3 data-nexdirectory-brand-preview class="m-0 text-xl font-extrabold text-white"><?php echo esc_html($site_name); ?></h3>
                                <p class="mt-2 text-sm text-slate-300"><?php /* translators: %s: Plural listing label. */ echo esc_html(sprintf(__('Discover and manage %s in one polished experience.', 'nexdirectory'), $plural_label)); ?></p>
                                <span class="mt-5 inline-flex rounded-lg px-4 py-2 text-sm font-bold text-white shadow-md" data-nexdirectory-accent-swatch style="background-color: <?php echo esc_attr($accent_color); ?>;"><?php /* translators: %s: Plural listing label. */ echo esc_html(sprintf(__('Explore %s', 'nexdirectory'), $plural_label)); ?></span>
                            </div>
                        </aside>
                    </div>
                </div>

                <div data-nexdirectory-step-panel="4" <?php echo $initial_step !== 4 ? 'hidden' : ''; ?> class="mb-8">
                    <?php if ($demo_listing_count > 0) : ?>
                        <div class="mb-5 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 rounded-xl border border-emerald-200 bg-emerald-50 p-4">
                            <div class="flex items-start gap-3">
                                <span class="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-emerald-100 text-emerald-700"><i class="fas fa-check" aria-hidden="true"></i></span>
                                <div>
                                    <p class="m-0 text-sm font-bold text-emerald-900"><?php /* translators: %d: Number of detected sample listings. */ echo esc_html(sprintf(_n('%d sample listing detected', '%d sample listings detected', $demo_listing_count, 'nexdirectory'), $demo_listing_count)); ?></p>
                                    <p class="mt-1 text-xs text-emerald-800"><?php esc_html_e('You can continue without importing more. Re-running the importer skips matching duplicates.', 'nexdirectory'); ?></p>
                                </div>
                            </div>
                            <a href="<?php echo esc_url($manage_listings_url); ?>" class="text-xs font-bold text-emerald-800 hover:text-emerald-950"><?php esc_html_e('Manage samples', 'nexdirectory'); ?><i class="fas fa-arrow-right ml-1" aria-hidden="true"></i></a>
                        </div>
                    <?php endif; ?>

                    <div class="grid grid-cols-1 lg:grid-cols-5 gap-5">
                        <div class="lg:col-span-3 rounded-2xl border border-slate-200 bg-white p-6">
                            <div class="flex items-start gap-4">
                                <span class="inline-flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-indigo-100 text-indigo-700"><i class="fas fa-box-open" aria-hidden="true"></i></span>
                                <div>
                                    <h3 class="m-0 text-lg font-extrabold text-slate-900"><?php /* translators: %s: Active sample profile name. */ echo esc_html(sprintf(__('%s sample pack', 'nexdirectory'), $sample_profile_label)); ?></h3>
                                    <p class="mt-1 text-sm leading-6 text-slate-600"><?php /* translators: %d: Requested number of sample listings. */ echo esc_html(sprintf(__('Adds up to %d realistic examples so you can test discovery, submission, moderation, and account journeys before adding live content.', 'nexdirectory'), $demo_import_count)); ?></p>
                                </div>
                            </div>
                            <form
                                method="post"
                                action="<?php echo esc_url($save_preferences_action); ?>"
                                class="mt-6"
                                data-nexdirectory-confirm-form
                                data-confirm-title="<?php echo esc_attr(__('Import sample content?', 'nexdirectory')); ?>"
                                data-confirm-message="<?php echo esc_attr($demo_import_confirm_message); ?>"
                                data-confirm-button-label="<?php /* translators: %d: Number of requested sample listings. */ echo esc_attr(sprintf(__('Import Up to %d Samples', 'nexdirectory'), $demo_import_count)); ?>"
                                data-loading-title="<?php esc_attr_e('Importing Sample Content', 'nexdirectory'); ?>"
                                data-loading-message="<?php esc_attr_e('Keep this tab open. The importer is checking duplicates and preparing profile-matched listings and terms.', 'nexdirectory'); ?>"
                            >
                                <input type="hidden" name="action" value="nexdirectory_import_demo_events">
                                <input type="hidden" name="nexdirectory_demo_count" value="<?php echo esc_attr((string) $demo_import_count); ?>">
                                <input type="hidden" name="nexdirectory_demo_profile" value="<?php echo esc_attr($active_demo_profile); ?>">
                                <input type="hidden" name="nexdirectory_demo_apply_presets" value="1">
                                <input type="hidden" name="nexdirectory_demo_localize_media" value="0">
                                <input type="hidden" name="nexdirectory_demo_seed_runtime" value="0">
                                <input type="hidden" name="nexdirectory_demo_import_confirmed" value="0" data-nexdirectory-confirmed-input>
                                <input type="hidden" name="nexdirectory_redirect_to" value="<?php echo esc_url($onboarding_step_five_url); ?>">
                                <?php wp_nonce_field('nexdirectory_import_demo_events_nonce', 'nexdirectory_import_demo_nonce'); ?>
                                <button type="submit" class="inline-flex items-center justify-center px-6 py-3 rounded-lg text-white bg-indigo-600 hover:bg-indigo-700 shadow-md font-semibold transition-all">
                                    <i class="fas fa-cloud-arrow-down mr-2" aria-hidden="true"></i>
                                    <?php /* translators: %d: Number of requested sample listings. */ echo esc_html(sprintf(__('Import Up to %d Samples', 'nexdirectory'), $demo_import_count)); ?>
                                </button>
                            </form>
                        </div>

                        <aside class="lg:col-span-2 rounded-2xl border border-slate-200 bg-slate-50 p-5">
                            <h3 class="m-0 text-sm font-extrabold text-slate-900"><?php esc_html_e('Exactly what happens', 'nexdirectory'); ?></h3>
                            <ul class="mt-4 space-y-3 text-xs leading-5 text-slate-600">
                                <li class="flex gap-2"><i class="fas fa-check mt-1 text-emerald-600" aria-hidden="true"></i><span><?php esc_html_e('Matching titles are skipped instead of duplicated.', 'nexdirectory'); ?></span></li>
                                <li class="flex gap-2"><i class="fas fa-check mt-1 text-emerald-600" aria-hidden="true"></i><span><?php esc_html_e('Live listings and existing page content are not overwritten.', 'nexdirectory'); ?></span></li>
                                <li class="flex gap-2"><i class="fas fa-image mt-1 text-slate-500" aria-hidden="true"></i><span><?php esc_html_e('Remote sample images are referenced, not downloaded into Media Library.', 'nexdirectory'); ?></span></li>
                                <li class="flex gap-2"><i class="fas fa-shield-halved mt-1 text-slate-500" aria-hidden="true"></i><span><?php esc_html_e('No sample messages, orders, tickets, RSVPs, or member activity are created.', 'nexdirectory'); ?></span></li>
                                <li class="flex gap-2"><i class="fas fa-house mt-1 text-slate-500" aria-hidden="true"></i><span><?php esc_html_e('If no static homepage exists, the What’s New page may be selected automatically.', 'nexdirectory'); ?></span></li>
                            </ul>
                        </aside>
                    </div>
                </div>

                <div id="nexdirectory-demo-import-confirm-modal" hidden aria-hidden="true" role="dialog" aria-modal="true" aria-labelledby="nexdirectory-demo-import-confirm-title" aria-describedby="nexdirectory-demo-import-confirm-description" class="fixed inset-0 z-50 items-center justify-center p-4">
                    <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" data-nexdirectory-cancel-import aria-hidden="true"></div>
                    <div class="relative z-10 bg-white rounded-2xl shadow-xl px-6 py-5 w-full max-w-md border border-slate-200" role="document">
                        <h3 id="nexdirectory-demo-import-confirm-title" data-nexdirectory-confirm-title class="text-lg font-bold text-slate-900 mb-2"><?php esc_html_e('Confirm setup change', 'nexdirectory'); ?></h3>
                        <p id="nexdirectory-demo-import-confirm-description" data-nexdirectory-confirm-message class="text-sm text-slate-600 mb-5"><?php echo esc_html($demo_import_confirm_message); ?></p>
                        <div class="flex flex-col sm:flex-row sm:justify-end gap-3">
                            <button type="button" data-nexdirectory-cancel-import class="inline-flex items-center justify-center px-4 py-2 rounded-lg border border-slate-300 bg-white text-slate-700 hover:bg-slate-50 font-semibold transition-all">
                                <?php esc_html_e('Cancel', 'nexdirectory'); ?>
                            </button>
                            <button type="button" data-nexdirectory-confirm-import class="inline-flex items-center justify-center px-4 py-2 rounded-lg text-white bg-indigo-600 hover:bg-indigo-700 font-semibold shadow-sm transition-all">
                                <span data-nexdirectory-confirm-button-label><?php esc_html_e('Continue', 'nexdirectory'); ?></span>
                            </button>
                        </div>
                    </div>
                </div>

                <div id="nexdirectory-onboarding-import-loading" hidden aria-hidden="true" role="status" aria-live="polite" class="fixed inset-0 z-50 items-center justify-center p-4">
                    <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm"></div>
                    <div class="relative z-10 bg-white rounded-2xl shadow-xl px-6 py-5 w-full max-w-sm border border-slate-200 text-center">
                        <div class="w-12 h-12 rounded-full bg-indigo-50 text-indigo-600 flex items-center justify-center mx-auto mb-4">
                            <svg class="animate-spin h-6 w-6" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
                            </svg>
                        </div>
                        <h3 data-nexdirectory-loading-title class="text-base font-bold text-slate-900 mb-1"><?php esc_html_e('Preparing Your Starter Site', 'nexdirectory'); ?></h3>
                        <p data-nexdirectory-loading-message class="text-sm text-slate-500"><?php esc_html_e('Keep this tab open while the requested setup work finishes.', 'nexdirectory'); ?></p>
                    </div>
                </div>

                <div data-nexdirectory-step-panel="5" <?php echo $initial_step !== 5 ? 'hidden' : ''; ?> class="mb-8">
                    <div class="grid grid-cols-1 lg:grid-cols-5 gap-5">
                        <div class="lg:col-span-2 rounded-2xl border <?php echo esc_attr($homepage_id > 0 ? 'border-emerald-200 bg-emerald-50/50' : 'border-slate-200 bg-slate-50'); ?> p-5">
                            <p class="text-xs font-bold uppercase tracking-wider text-slate-500"><?php esc_html_e('Current homepage', 'nexdirectory'); ?></p>
                            <div class="mt-3 flex items-start gap-3">
                                <span class="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-xl <?php echo esc_attr($homepage_id > 0 ? 'bg-emerald-100 text-emerald-700' : 'bg-white text-slate-500'); ?>"><i class="fas fa-house" aria-hidden="true"></i></span>
                                <div>
                                    <h3 class="m-0 text-base font-extrabold text-slate-900"><?php echo esc_html($homepage_id > 0 && $homepage_title !== '' ? $homepage_title : __('Your latest posts', 'nexdirectory')); ?></h3>
                                    <p class="mt-1 text-xs leading-5 text-slate-600">
                                        <?php echo esc_html($homepage_id > 0 ? __('A static WordPress homepage is active.', 'nexdirectory') : __('WordPress is currently showing the latest posts.', 'nexdirectory')); ?>
                                    </p>
                                    <a href="<?php echo esc_url($homepage_url); ?>" target="_blank" rel="noopener noreferrer" class="mt-2 inline-flex items-center text-xs font-bold text-indigo-700 hover:text-indigo-900"><?php esc_html_e('View current homepage', 'nexdirectory'); ?><i class="fas fa-arrow-up-right-from-square ml-1" aria-hidden="true"></i></a>
                                </div>
                            </div>
                        </div>

                        <div class="lg:col-span-3 rounded-2xl border border-slate-200 bg-white p-6">
                            <div class="flex items-start gap-4">
                                <span class="inline-flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-indigo-100 text-indigo-700"><i class="fas fa-wand-magic-sparkles" aria-hidden="true"></i></span>
                                <div>
                                    <h3 class="m-0 text-lg font-extrabold text-slate-900"><?php echo esc_html($is_whats_new_homepage ? __('What’s New is already your homepage', 'nexdirectory') : __('Lead with fresh directory activity', 'nexdirectory')); ?></h3>
                                    <p class="mt-1 text-sm leading-6 text-slate-600"><?php esc_html_e('What’s New gives visitors an immediate stream of recently published and updated listings. Choosing it replaces only the WordPress homepage selection.', 'nexdirectory'); ?></p>
                                </div>
                            </div>

                            <?php if ($is_whats_new_homepage) : ?>
                                <div class="mt-5 inline-flex items-center gap-2 rounded-lg bg-emerald-50 px-4 py-2 text-sm font-bold text-emerald-800"><i class="fas fa-check-circle" aria-hidden="true"></i><?php esc_html_e('Recommended homepage active', 'nexdirectory'); ?></div>
                            <?php elseif ($whats_new_page_id > 0) : ?>
                                <form data-nexdirectory-homepage-form method="post" action="<?php echo esc_url($save_preferences_action); ?>" class="mt-5">
                                    <input type="hidden" name="action" value="nexdirectory_set_onboarding_homepage">
                                    <input type="hidden" name="nexdirectory_onboarding_step" value="6">
                                    <?php wp_nonce_field('nexdirectory_set_onboarding_homepage', 'nexdirectory_set_onboarding_homepage_nonce'); ?>
                                    <button type="submit" class="inline-flex items-center justify-center px-6 py-3 rounded-lg text-white bg-indigo-600 hover:bg-indigo-700 shadow-md font-semibold transition-all disabled:opacity-70 disabled:cursor-not-allowed">
                                        <span data-nexdirectory-busy-idle class="inline-flex items-center">
                                            <i class="fas fa-check mr-2" aria-hidden="true"></i> <?php esc_html_e('Use What’s New as Homepage', 'nexdirectory'); ?>
                                        </span>
                                        <span data-nexdirectory-busy-active hidden class="inline-flex items-center">
                                            <svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                                                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
                                            </svg>
                                            <?php esc_html_e('Saving Homepage…', 'nexdirectory'); ?>
                                        </span>
                                    </button>
                                </form>
                            <?php else : ?>
                                <div class="mt-5 rounded-xl border border-amber-200 bg-amber-50 p-4">
                                    <p class="m-0 text-sm font-semibold text-amber-900"><?php esc_html_e('The What’s New page has not been created yet.', 'nexdirectory'); ?></p>
                                    <button type="button" data-nexdirectory-go-step="2" class="mt-2 text-xs font-bold text-amber-800 hover:text-amber-950"><?php esc_html_e('Return to Core Pages', 'nexdirectory'); ?><i class="fas fa-arrow-right ml-1" aria-hidden="true"></i></button>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <p class="mt-4 text-xs text-slate-500"><i class="fas fa-circle-info mr-1 text-slate-400" aria-hidden="true"></i><?php esc_html_e('Prefer your existing homepage? Leave it unchanged and use “Keep Current Homepage & Continue” below.', 'nexdirectory'); ?></p>
                </div>

                <div data-nexdirectory-step-panel="6" <?php echo $initial_step !== 6 ? 'hidden' : ''; ?> class="mb-8">
                    <div class="bg-slate-900 rounded-2xl shadow-xl p-7 sm:p-9 border border-slate-800 relative overflow-hidden">
                        <div class="absolute -right-16 -top-16 h-48 w-48 rounded-full bg-indigo-500/20 blur-3xl" aria-hidden="true"></div>
                        <div class="mx-auto w-16 h-16 bg-green-500/20 text-green-400 rounded-full flex items-center justify-center mb-6">
                            <i class="fas fa-flag-checkered text-2xl" aria-hidden="true"></i>
                        </div>
                        <div class="text-center">
                            <h3 class="text-2xl font-bold text-white mb-3"><?php echo esc_html($initial_done ? __('Setup complete', 'nexdirectory') : ($required_setup_remaining > 0 ? __('Ready for a final review?', 'nexdirectory') : __('Ready to launch', 'nexdirectory'))); ?></h3>
                            <p class="text-slate-300 mb-8 max-w-2xl mx-auto">
                                <?php
                                if ($initial_done) {
                                    esc_html_e('Your first-run setup is complete. Use the shortcuts below to keep building.', 'nexdirectory');
                                } elseif ($required_setup_remaining > 0) {
                                    /* translators: %d: Number of recommended setup items still incomplete. */
                                    echo esc_html(sprintf(_n('%d recommended setup item still needs attention. You can review it now or finish and return later.', '%d recommended setup items still need attention. You can review them now or finish and return later.', $required_setup_remaining, 'nexdirectory'), $required_setup_remaining));
                                } else {
                                    esc_html_e('The essential foundation is ready. Finish setup, then add your first live listing or review the visitor experience.', 'nexdirectory');
                                }
                                ?>
                            </p>
                        </div>

                        <div class="grid grid-cols-1 lg:grid-cols-2 gap-5 text-left">
                            <section class="rounded-2xl border border-white/10 bg-white/5 p-5" aria-labelledby="nexdirectory-launch-checklist-title">
                                <h4 id="nexdirectory-launch-checklist-title" class="m-0 text-sm font-extrabold text-white"><?php esc_html_e('Launch checklist', 'nexdirectory'); ?></h4>
                                <ul class="mt-4 space-y-3">
                                    <?php foreach (array_slice($wizard_steps, 0, 5) as $launch_step_index => $launch_step) : ?>
                                        <?php
                                        $launch_step_number = (int) $launch_step_index + 1;
                                        $launch_step_ready = !empty($launch_step['is_ready']);
                                        $launch_step_optional = !empty($launch_step['optional']);
                                        $launch_step_title = sanitize_text_field((string) ($launch_step['short_title'] ?? $launch_step['title'] ?? __('Setup item', 'nexdirectory')));
                                        $launch_step_status = $launch_step_ready
                                            ? __('Ready', 'nexdirectory')
                                            : ($launch_step_optional ? __('Optional — skipped', 'nexdirectory') : __('Review recommended', 'nexdirectory'));
                                        ?>
                                        <li class="flex items-center gap-3">
                                            <span class="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full <?php echo esc_attr($launch_step_ready ? 'bg-emerald-500/20 text-emerald-300' : ($launch_step_optional ? 'bg-slate-500/20 text-slate-300' : 'bg-amber-500/20 text-amber-300')); ?>">
                                                <i class="fas <?php echo esc_attr($launch_step_ready ? 'fa-check' : ($launch_step_optional ? 'fa-minus' : 'fa-exclamation')); ?> text-xs" aria-hidden="true"></i>
                                            </span>
                                            <button type="button" data-nexdirectory-go-step="<?php echo esc_attr((string) $launch_step_number); ?>" class="min-w-0 flex-1 text-left group">
                                                <span class="block text-sm font-bold text-white group-hover:text-indigo-200"><?php echo esc_html($launch_step_title); ?></span>
                                                <span class="block text-xs text-slate-400"><?php echo esc_html($launch_step_status); ?></span>
                                            </button>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            </section>

                            <section class="rounded-2xl border border-white/10 bg-white/5 p-5" aria-labelledby="nexdirectory-launch-next-title">
                                <h4 id="nexdirectory-launch-next-title" class="m-0 text-sm font-extrabold text-white"><?php esc_html_e('Best next actions', 'nexdirectory'); ?></h4>
                                <div class="mt-4 grid grid-cols-1 sm:grid-cols-2 gap-3">
                                    <a href="<?php echo esc_url($add_listing_url); ?>" class="rounded-xl border border-white/10 bg-white/5 p-3 text-white hover:bg-white/10 transition">
                                        <i class="fas fa-plus-circle text-emerald-300" aria-hidden="true"></i><span class="ml-2 text-sm font-bold"><?php esc_html_e('Add first listing', 'nexdirectory'); ?></span>
                                    </a>
                                    <a href="<?php echo esc_url($view_directory_url); ?>" target="_blank" rel="noopener noreferrer" class="rounded-xl border border-white/10 bg-white/5 p-3 text-white hover:bg-white/10 transition">
                                        <i class="fas fa-eye text-indigo-300" aria-hidden="true"></i><span class="ml-2 text-sm font-bold"><?php esc_html_e('View directory', 'nexdirectory'); ?></span>
                                    </a>
                                    <a href="<?php echo esc_url($needs_attention_url); ?>" class="rounded-xl border border-white/10 bg-white/5 p-3 text-white hover:bg-white/10 transition">
                                        <i class="fas fa-bell text-amber-300" aria-hidden="true"></i><span class="ml-2 text-sm font-bold"><?php esc_html_e('Needs Attention', 'nexdirectory'); ?></span>
                                    </a>
                                    <a href="<?php echo esc_url($settings_url); ?>" class="rounded-xl border border-white/10 bg-white/5 p-3 text-white hover:bg-white/10 transition">
                                        <i class="fas fa-sliders text-slate-300" aria-hidden="true"></i><span class="ml-2 text-sm font-bold"><?php esc_html_e('Review settings', 'nexdirectory'); ?></span>
                                    </a>
                                </div>
                            </section>
                        </div>

                        <div class="mt-7 flex flex-wrap justify-center gap-3">
                            <?php if (!$initial_done) : ?>
                                <form data-nexdirectory-complete-form method="post" action="<?php echo esc_url($save_preferences_action); ?>">
                                    <input type="hidden" name="action" value="nexdirectory_mark_onboarding_complete">
                                    <input type="hidden" name="nexdirectory_redirect_to" value="<?php echo esc_url($dashboard_url); ?>">
                                    <?php wp_nonce_field('nexdirectory_mark_onboarding_complete', 'nexdirectory_onboarding_nonce'); ?>
                                    <button type="submit" class="inline-flex items-center px-6 py-3 border border-transparent text-sm font-bold rounded-xl shadow-lg text-slate-900 bg-gradient-to-r from-green-400 to-emerald-500 hover:from-green-500 hover:to-emerald-600 transition-all disabled:opacity-70">
                                        <?php esc_html_e('Finish Setup & Open Dashboard', 'nexdirectory'); ?>
                                        <i class="fas fa-rocket ml-2" aria-hidden="true"></i>
                                    </button>
                                </form>
                            <?php else : ?>
                                <a href="<?php echo esc_url($dashboard_url); ?>" class="inline-flex items-center px-6 py-3 border border-transparent text-sm font-bold rounded-xl shadow-lg text-slate-900 bg-gradient-to-r from-green-400 to-emerald-500 hover:from-green-500 hover:to-emerald-600 transition-all">
                                    <?php esc_html_e('Open Dashboard', 'nexdirectory'); ?><i class="fas fa-arrow-right ml-2" aria-hidden="true"></i>
                                </a>
                            <?php endif; ?>
                            <a href="<?php echo esc_url($manage_listings_url); ?>" class="inline-flex items-center px-6 py-3 rounded-xl text-sm font-bold text-white bg-indigo-600 hover:bg-indigo-700 shadow-lg transition-all">
                                <?php /* translators: %s: Plural listing label. */ echo esc_html(sprintf(__('Manage %s', 'nexdirectory'), $plural_label)); ?>
                                <i class="fas fa-arrow-right ml-2" aria-hidden="true"></i>
                            </a>
                        </div>

                        <?php if ($initial_done) : ?>
                            <div class="mt-6 flex justify-center items-center text-green-300 text-sm font-medium bg-green-400/10 mx-auto px-4 py-2 rounded-full max-w-max">
                                <i class="fas fa-check-circle mr-2" aria-hidden="true"></i> <?php esc_html_e('First-run setup is marked complete.', 'nexdirectory'); ?>
                            </div>
                        <?php else : ?>
                            <p class="mt-5 text-center text-xs text-slate-400"><?php esc_html_e('Finishing setup dismisses the first-run prompt. It does not lock or hide any settings.', 'nexdirectory'); ?></p>
                        <?php endif; ?>
                    </div>
                </div>

                <div data-nexdirectory-next-step-wrap class="pt-2 flex justify-end" <?php echo $initial_step >= $step_count ? 'hidden' : ''; ?>>
                    <button type="button" data-nexdirectory-next-step class="inline-flex items-center px-6 py-3 rounded-lg text-sm font-semibold text-white bg-indigo-600 hover:bg-indigo-700 shadow-md transition-all">
                        <span data-nexdirectory-next-label><?php echo esc_html((string) ($current_step_data['next_label'] ?? __('Next Step', 'nexdirectory'))); ?></span><i class="fas fa-arrow-right ml-2" aria-hidden="true"></i>
                    </button>
                </div>
            </div>

            <div class="bg-slate-50 px-8 py-5 border-t border-slate-200 flex justify-start items-center">
                <button type="button" data-nexdirectory-prev-step class="inline-flex items-center px-4 py-2 text-sm font-semibold text-slate-600 hover:text-slate-900 transition-colors <?php echo esc_attr($initial_step === 1 ? 'invisible' : ''); ?>" <?php disabled($initial_step, 1); ?>>
                    <i class="fas fa-arrow-left mr-2" aria-hidden="true"></i> <?php esc_html_e('Previous Step', 'nexdirectory'); ?>
                </button>
            </div>
        </section>

        <noscript>
            <div class="rounded-xl border border-amber-200 bg-amber-50 p-5 text-sm text-amber-900">
                <strong><?php esc_html_e('JavaScript is unavailable.', 'nexdirectory'); ?></strong>
                <?php esc_html_e('Setup actions still work, but use these links to move between steps:', 'nexdirectory'); ?>
                <span class="mt-3 flex flex-wrap gap-2">
                    <?php foreach ($wizard_steps as $noscript_step_index => $noscript_step) : ?>
                        <?php $noscript_step_number = (int) $noscript_step_index + 1; ?>
                        <a class="rounded-md border border-amber-300 bg-white px-3 py-1.5 font-semibold text-amber-900" href="<?php echo esc_url(admin_url('admin.php?page=nexdirectory-onboarding&step=' . $noscript_step_number)); ?>"><?php echo esc_html((string) ($noscript_step['short_title'] ?? $noscript_step['title'] ?? $noscript_step_number)); ?></a>
                    <?php endforeach; ?>
                </span>
            </div>
        </noscript>
    </div>
</div>
