/**
 * Rentals & Bookings for WooCommerce & Dokan - Wizard PHP Template Scripts
 *
 * Handles all interactive behavior for the PHP multi-step wizard:
 * - Product selection on the landing screen
 * - Draft deletion
 * - Step navigation (next/prev/progress clicks)
 * - Draft auto-save
 * - Publish action
 *
 * Requires wahrbWizardPhpConfig to be localized via wp_localize_script().
 *
 * @package WahraRentalsBookings
 */

(function () {
    'use strict';

    var cfg = window.wahrbWizardPhpConfig || {};

    // Debug: log initial config
    console.log('[WAHRB] Wizard PHP config loaded:', {
        currentStep: cfg.currentStep,
        draftId: cfg.draftId,
        productId: cfg.productId,
        wizardUrl: cfg.wizardUrl,
        autosaveEnabled: cfg.autosaveEnabled,
        autosaveInterval: cfg.autosaveInterval
    });

    /* ================================================================
     * SELECTION SCREEN (step 0)
     * ================================================================ */

    function initSelectionScreen() {
        var select = document.getElementById('wahrb-product-select');
        var btn = document.getElementById('wahrb-configure-btn');

        if (!select || !btn) {
            return;
        }

        select.addEventListener('change', function () {
            btn.disabled = !select.value;
        });

        btn.addEventListener('click', function () {
            var productId = select.value;
            if (productId) {
                var sep = cfg.wizardUrl.indexOf('?') >= 0 ? '&' : '?';
                window.location.href = cfg.wizardUrl + sep + 'product_id=' + encodeURIComponent(productId);
            }
        });

        // Delete draft buttons
        var deleteButtons = document.querySelectorAll('.wahrb-delete-draft-btn');
        deleteButtons.forEach(function (dbtn) {
            dbtn.addEventListener('click', function () {
                var draftId = dbtn.getAttribute('data-draft-id');
                var draftName = dbtn.getAttribute('data-draft-name');

                if (!confirm(cfg.i18n.confirmDeleteDraft + ' "' + draftName + '" ?')) {
                    return;
                }

                dbtn.disabled = true;
                dbtn.textContent = '...';

                apiRequest('DELETE', '/vendor/wizard/draft/' + draftId, null, function (ok) {
                    if (ok) {
                        var item = dbtn.closest('.wahrb-draft-item');
                        if (item) {
                            item.style.transition = 'opacity 0.3s';
                            item.style.opacity = '0';
                            setTimeout(function () {
                                item.remove();
                                if (!document.querySelector('.wahrb-draft-item')) {
                                    window.location.reload();
                                }
                            }, 300);
                        }
                    } else {
                        alert(cfg.i18n.errorDeletion);
                        dbtn.disabled = false;
                        dbtn.textContent = '\uD83D\uDDD1\uFE0F'; // 🗑️
                    }
                });
            });
        });
    }

    /* ================================================================
     * WIZARD FORM (steps 1–6)
     * ================================================================ */

    var autosaveTimer = null;
    var lastSavedData = null;

    /* ── Step Validation ─────────────────────────────────────── */

    /**
     * Validate the current step's required fields before allowing navigation.
     * Returns { valid: boolean, message: string }
     */
    function validateCurrentStep() {
        var step = cfg.currentStep;
        var data = collectFormData();

        switch (step) {
            case 1:
                // Must select a platform category
                if (!data.platform_category && !data.offer_type) {
                    return { valid: false, message: cfg.i18n.validationStep1 || 'Please select a rental category.' };
                }
                break;

            case 2:
                // Must have a product selected or product name
                if (!data.product_id && !data.product_name) {
                    return { valid: false, message: cfg.i18n.validationStep2 || 'Please select or name a product.' };
                }
                break;

            case 3:
                // Must have at least one day selected
                var hasDays = data.recurring_days && (
                    (Array.isArray(data.recurring_days) && data.recurring_days.length > 0) ||
                    (typeof data.recurring_days === 'string' && data.recurring_days.length > 0)
                );
                if (!hasDays) {
                    return { valid: false, message: cfg.i18n.validationStep3 || 'Please select at least one availability day.' };
                }
                break;

            case 4:
                // Base price must be set (can be 0 for free items, but field must exist)
                if (data.base_price === '' || data.base_price === undefined) {
                    return { valid: false, message: cfg.i18n.validationStep4 || 'Please set a base price.' };
                }
                break;

            case 5:
                // Payment step has sensible defaults, always valid
                break;

            case 6:
                // Publication — terms must be accepted if required
                var termsCheckbox = document.getElementById('terms_accepted');
                if (termsCheckbox && termsCheckbox.required && !termsCheckbox.checked) {
                    return { valid: false, message: cfg.i18n.acceptTerms || 'Please accept the terms and conditions.' };
                }
                break;
        }

        return { valid: true, message: '' };
    }

    function initWizardForm() {
        var form = document.getElementById('wahrb-wizard-form');
        if (!form) {
            return;
        }

        // Progress step clicks — save current step, then navigate
        var progressSteps = document.querySelectorAll('.wahrb-progress-step');
        progressSteps.forEach(function (el) {
            el.addEventListener('click', function () {
                var targetStep = parseInt(el.getAttribute('data-step'), 10);
                console.log('[WAHRB] Progress step clicked:', { targetStep: targetStep, currentStep: cfg.currentStep });
                if (!targetStep || targetStep === cfg.currentStep) {
                    return;
                }

                // Going forward requires validation
                if (targetStep > cfg.currentStep) {
                    var check = validateCurrentStep();
                    if (!check.valid) {
                        alert(check.message);
                        return;
                    }
                }

                // Save current step before navigating
                saveDraft(collectFormData(), function (success) {
                    if (success) {
                        goToStep(targetStep);
                    }
                    // On failure, saveDraft already shows an alert — user stays on current step
                });
            });
        });

        // Next button — validate then save then advance
        var nextBtn = document.getElementById('wahrb-next-btn');
        if (nextBtn) {
            nextBtn.addEventListener('click', function () {
                // Validate before saving
                var check = validateCurrentStep();
                if (!check.valid) {
                    alert(check.message);
                    return;
                }

                nextBtn.disabled = true;
                nextBtn.textContent = cfg.i18n.saving;

                // Compute target step BEFORE the async save — ensures it's always currentStep + 1
                var nextStep = cfg.currentStep + 1;
                if (nextStep > 6) nextStep = 6;
                console.log('[WAHRB] Next clicked: currentStep=' + cfg.currentStep + ', will navigate to step ' + nextStep);

                saveDraft(collectFormData(), function (success) {
                    if (success) {
                        // Navigate directly to nextStep — guarantees +1 increment
                        var url = new URL(window.location.href);
                        url.searchParams.set('step', nextStep);
                        if (cfg.draftId) {
                            url.searchParams.set('draft_id', cfg.draftId);
                        }
                        if (cfg.productId) {
                            url.searchParams.set('product_id', cfg.productId);
                        }
                        console.log('[WAHRB] Next → navigating to:', url.toString());
                        window.location.href = url.toString();
                    } else {
                        nextBtn.disabled = false;
                        nextBtn.textContent = cfg.i18n.next + ' \u2192';
                    }
                });
            });
        }

        // Previous button — save current step silently then go back
        var prevBtn = document.getElementById('wahrb-prev-btn');
        if (prevBtn) {
            prevBtn.addEventListener('click', function () {
                prevBtn.disabled = true;
                prevBtn.textContent = cfg.i18n.saving;

                saveDraft(collectFormData(), function (success) {
                    // Navigate back regardless of save result (don't block backward navigation)
                    goToStep(cfg.currentStep - 1);
                }, true); // silent = true
            });
        }

        // Save and Close button
        var saveCloseBtn = document.getElementById('wahrb-save-close-btn');
        if (saveCloseBtn) {
            saveCloseBtn.addEventListener('click', function () {
                saveCloseBtn.disabled = true;
                saveCloseBtn.textContent = cfg.i18n.saving;

                saveDraft(collectFormData(), function (success) {
                    if (success) {
                        window.location.href = cfg.wizardUrl;
                    } else {
                        saveCloseBtn.disabled = false;
                        saveCloseBtn.textContent = cfg.i18n.saveAndClose;
                    }
                });
            });
        }

        // Publish button
        var publishBtn = document.getElementById('wahrb-publish-btn');
        if (publishBtn) {
            publishBtn.addEventListener('click', function () {
                var termsCheckbox = document.getElementById('terms_accepted');
                if (termsCheckbox && !termsCheckbox.checked) {
                    alert(cfg.i18n.acceptTerms);
                    return;
                }

                publishBtn.disabled = true;
                publishBtn.textContent = cfg.i18n.publishing;

                saveDraft(collectFormData(), function (success) {
                    if (!success) {
                        publishBtn.disabled = false;
                        publishBtn.textContent = cfg.i18n.publishListing;
                        return;
                    }

                    apiRequest('POST', '/vendor/wizard/publish', { draft_id: cfg.draftId }, function (ok, response) {
                        if (ok && response) {
                            alert(cfg.i18n.publishSuccess);
                            window.location.href = response.edit_url || cfg.productsUrl;
                        } else {
                            var msg = (response && response.message) ? response.message : cfg.i18n.publishError;
                            alert(msg);
                            publishBtn.disabled = false;
                            publishBtn.textContent = cfg.i18n.publishListing;
                        }
                    });
                });
            });
        }

        // Save draft button (step 7)
        var saveDraftBtn = document.getElementById('wahrb-save-draft-btn');
        if (saveDraftBtn) {
            saveDraftBtn.addEventListener('click', function () {
                saveDraftBtn.disabled = true;
                saveDraftBtn.textContent = cfg.i18n.saving;

                saveDraft(collectFormData(), function (success) {
                    saveDraftBtn.disabled = false;
                    saveDraftBtn.textContent = cfg.i18n.saveDraft;
                    if (success) {
                        alert(cfg.i18n.draftSaved);
                    }
                });
            });
        }

        // Start auto-save
        startAutosave();
    }

    /* ── Navigation ──────────────────────────────────────────── */

    function goToStep(step) {
        console.log('[WAHRB] goToStep() called:', { from: cfg.currentStep, to: step, draftId: cfg.draftId, productId: cfg.productId, href: window.location.href });

        // Clamp to valid range
        if (step < 1) step = 1;
        if (step > 6) step = 6;

        // SAFETY: Warn if jumping more than 1 step forward
        if (step > cfg.currentStep + 1) {
            console.warn('[WAHRB] Forward jump of ' + (step - cfg.currentStep) + ' steps detected (from ' + cfg.currentStep + ' to ' + step + ')');
        }

        var url = new URL(window.location.href);
        url.searchParams.set('step', step);
        if (cfg.draftId) {
            url.searchParams.set('draft_id', cfg.draftId);
        }
        if (cfg.productId) {
            url.searchParams.set('product_id', cfg.productId);
        }
        console.log('[WAHRB] Navigating to:', url.toString());
        window.location.href = url.toString();
    }

    /* ── Form data collection ────────────────────────────────── */

    function collectFormData() {
        var form = document.getElementById('wahrb-wizard-form');
        if (!form) {
            return {};
        }

        var data = {};
        var elements = form.querySelectorAll('input, select, textarea');

        elements.forEach(function (el) {
            var name = el.name;
            if (!name) {
                return;
            }

            if (el.type === 'checkbox') {
                if (name.endsWith('[]')) {
                    var baseName = name.replace('[]', '');
                    if (!data[baseName]) {
                        data[baseName] = [];
                    }
                    if (el.checked) {
                        data[baseName].push(el.value);
                    }
                } else {
                    data[name] = el.checked ? el.value : '';
                }
            } else if (el.type === 'radio') {
                if (el.checked) {
                    data[name] = el.value;
                }
            } else {
                data[name] = el.value;
            }
        });

        return data;
    }

    /* ── API helpers ─────────────────────────────────────────── */

    function apiRequest(method, endpoint, payload, callback) {
        var xhr = new XMLHttpRequest();
        var url = cfg.apiUrl + endpoint;
        xhr.open(method, url, true);
        xhr.setRequestHeader('X-WP-Nonce', cfg.nonce);
        xhr.setRequestHeader('Content-Type', 'application/json');

        xhr.onload = function () {
            var response = null;
            try {
                response = JSON.parse(xhr.responseText);
            } catch (e) {
                console.error('[WAHRB] API returned non-JSON (status ' + xhr.status + '):', xhr.responseText.substring(0, 500));
            }

            if (xhr.status >= 200 && xhr.status < 300) {
                callback(true, response);
            } else {
                console.error('[WAHRB] API error ' + xhr.status + ' ' + method + ' ' + url + ':', response || xhr.responseText.substring(0, 300));
                callback(false, response);
            }
        };

        xhr.onerror = function () {
            console.error('[WAHRB] XHR network error for ' + method + ' ' + url);
            callback(false, null);
        };

        xhr.send(payload ? JSON.stringify(payload) : null);
    }

    function saveDraft(stepData, callback, silent) {
        var payload = {
            draft_id: cfg.draftId || 0,
            product_id: cfg.productId || 0,
            current_step: cfg.currentStep,
            step_data: stepData,
            version_hash: getInputValue('version_hash')
        };

        console.log('[WAHRB] saveDraft() sending:', { draft_id: payload.draft_id, product_id: payload.product_id, current_step: payload.current_step, silent: !!silent });

        apiRequest('POST', '/vendor/wizard/draft', payload, function (ok, response) {
            console.log('[WAHRB] saveDraft() response:', { ok: ok, draft_id: response && response.draft_id, current_step: response && response.current_step, status: response && response.message });

            if (ok && response) {
                if (response.draft_id) {
                    cfg.draftId = response.draft_id;
                    setInputValue('draft_id', response.draft_id);
                }
                if (response.version_hash) {
                    setInputValue('version_hash', response.version_hash);
                }
            } else {
                console.error('[WAHRB] saveDraft failed:', { ok: ok, response: response, payload: payload });
                if (!silent) {
                    var msg = (response && response.message) ? response.message : cfg.i18n.saveError;
                    alert(msg);
                }
            }
            if (callback) {
                callback(ok);
            }
        });
    }

    /* ── Auto-save ───────────────────────────────────────────── */

    function startAutosave() {
        if (!cfg.autosaveEnabled) {
            return;
        }

        if (autosaveTimer) {
            clearInterval(autosaveTimer);
        }

        autosaveTimer = setInterval(function () {
            var currentData = JSON.stringify(collectFormData());

            if (currentData !== lastSavedData) {
                saveDraft(collectFormData(), function (success) {
                    if (success) {
                        lastSavedData = currentData;
                        showAutosaveNotice();
                    }
                }, true);
            }
        }, cfg.autosaveInterval);
    }

    function showAutosaveNotice() {
        var notice = document.getElementById('wahrb-autosave-notice');
        if (!notice) {
            notice = document.createElement('div');
            notice.id = 'wahrb-autosave-notice';
            notice.style.cssText = 'position:fixed;bottom:20px;right:20px;background:#10b981;color:white;padding:10px 20px;border-radius:8px;font-size:14px;z-index:9999;opacity:0;transition:opacity 0.3s;';
            notice.textContent = '\u2713 ' + cfg.i18n.draftSaved;
            document.body.appendChild(notice);
        }
        notice.style.opacity = '1';
        setTimeout(function () {
            notice.style.opacity = '0';
        }, 2000);
    }

    /* ── Utility ─────────────────────────────────────────────── */

    function getInputValue(name) {
        var el = document.querySelector('input[name="' + name + '"]');
        return el ? el.value : '';
    }

    function setInputValue(name, value) {
        var el = document.querySelector('input[name="' + name + '"]');
        if (el) {
            el.value = value;
        }
    }

    /* ── Init ────────────────────────────────────────────────── */

    function init() {
        initSelectionScreen();
        initWizardForm();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
