/* WPNest Returns for WooCommerce — frontend (wizard + guest verify) */
( function ( $ ) {
    'use strict';

    if ( typeof window.wpnest_rfw === 'undefined' ) {
        return;
    }

    var cfg = window.wpnest_rfw;
    var REASON_OTHER = 'other';

    function showFeedback( $container, message, type ) {
        $container.removeClass( 'is-error is-success' );
        if ( type ) {
            $container.addClass( 'is-' + type );
        }
        $container.text( message || '' );
    }

    /* ──────────────────────────  Wizard step navigation  ───────────────────────── */

    function gotoStep( $wizard, step ) {
        $wizard.find( '.wpnest-rfw-step' ).removeClass( 'is-active' );
        $wizard.find( '.wpnest-rfw-step[data-rfw-step="' + step + '"]' ).addClass( 'is-active' );
        $wizard.find( '.wpnest-rfw-stepper li' ).removeClass( 'is-active is-done' );
        $wizard.find( '.wpnest-rfw-stepper li' ).each( function () {
            var idx = parseInt( $( this ).data( 'rfw-step-tab' ), 10 );
            if ( idx < step ) { $( this ).addClass( 'is-done' ); }
            if ( idx === step ) { $( this ).addClass( 'is-active' ); }
        } );
        try {
            $wizard[ 0 ].scrollIntoView( { behavior: 'smooth', block: 'start' } );
        } catch ( e ) {}
    }

    /**
     * Collect items selected in step 1.
     */
    function collectSelectedItems( $wizard ) {
        var items = [];
        $wizard.find( '.wpnest-rfw-item' ).each( function () {
            var $row = $( this );
            if ( ! $row.find( '.wpnest-rfw-item__check' ).is( ':checked' ) ) { return; }
            var max = parseInt( $row.find( '.wpnest-rfw-item__qty-input' ).attr( 'max' ), 10 ) || 1;
            var qty = parseInt( $row.find( '.wpnest-rfw-item__qty-input' ).val(), 10 ) || 1;
            if ( qty < 1 ) { qty = 1; }
            if ( qty > max ) { qty = max; }
            items.push( {
                order_item_id: parseInt( $row.data( 'rfw-item' ), 10 ),
                qty: qty,
                name: ( $row.find( '.wpnest-rfw-item__name' ).text() || '' ).trim()
            } );
        } );
        return items;
    }

    /**
     * Render reason rows in step 2 from selected items.
     */
    function renderReasons( $wizard, selected ) {
        var $container = $wizard.find( '[data-rfw-reasons]' );
        var $tpl       = $wizard.find( '[data-rfw-reason-tpl]' );
        if ( ! $tpl.length ) { return; }

        $container.empty();
        selected.forEach( function ( item ) {
            var $row = $( $tpl[ 0 ].content.cloneNode( true ) ).children( '[data-rfw-reason-row]' ).first();
            $row.attr( 'data-rfw-reason-for', item.order_item_id );
            $row.find( '[data-rfw-reason-name]' ).text( item.name );
            $row.find( '[data-rfw-reason-qty]' ).text( '× ' + item.qty );
            $container.append( $row );
        } );
    }

    /**
     * Collect step-2 reasons keyed by order_item_id.
     */
    function collectReasons( $wizard ) {
        var out = {};
        $wizard.find( '[data-rfw-reason-row]' ).each( function () {
            var $row = $( this );
            var oi   = parseInt( $row.attr( 'data-rfw-reason-for' ), 10 );
            out[ oi ] = {
                code: $row.find( 'select[name="reason_code"]' ).val() || '',
                text: ( $row.find( 'textarea[name="reason_text"]' ).val() || '' ).trim()
            };
        } );
        return out;
    }

    function validateReasons( reasons ) {
        var keys = Object.keys( reasons );
        if ( ! keys.length ) {
            return { ok: false, msg: cfg.i18n.pick_reason };
        }
        for ( var i = 0; i < keys.length; i++ ) {
            var r = reasons[ keys[ i ] ];
            if ( ! r.code ) { return { ok: false, msg: cfg.i18n.pick_reason }; }
            if ( r.code === REASON_OTHER && ! r.text ) {
                return { ok: false, msg: cfg.i18n.reason_text_required };
            }
        }
        return { ok: true };
    }

    function renderSummary( $wizard, selected, reasons ) {
        var $container = $wizard.find( '[data-rfw-summary]' );
        var html = '<table class="wpnest-rfw-summary__table"><thead><tr>'
            + '<th>' + escapeHtml( $wizard.find( '.wpnest-rfw-item__name' ).first().closest( '.wpnest-rfw-app' ).length ? '' : '' ) + '</th>'
            + '</tr></thead></table>';
        // build manually
        html  = '<table class="wpnest-rfw-summary__table">';
        html += '<thead><tr>';
        html += '<th>' + escapeHtml( cfg.i18n.qty_label ) + '</th>';
        html += '<th>' + escapeHtml( $wizard.find( '.wpnest-rfw-item__name' ).first().text() ? '' : '' ) + '</th>';
        html += '</tr></thead><tbody>';
        selected.forEach( function ( item ) {
            var r = reasons[ item.order_item_id ] || { code: '', text: '' };
            var label = $wizard.find( 'select[name="reason_code"] option[value="' + r.code + '"]' ).first().text() || r.code;
            html += '<tr>';
            html += '<td class="qty">' + item.qty + '</td>';
            html += '<td>'
                  + '<div class="name">' + escapeHtml( item.name ) + '</div>'
                  + '<div class="reason">' + escapeHtml( label ) + '</div>'
                  + ( r.text ? ( '<div class="note">' + escapeHtml( r.text ) + '</div>' ) : '' )
                  + '</td>';
            html += '</tr>';
        } );
        html += '</tbody></table>';
        $container.html( html );
    }

    function escapeHtml( s ) {
        return String( s == null ? '' : s )
            .replace( /&/g, '&amp;' )
            .replace( /</g, '&lt;' )
            .replace( />/g, '&gt;' )
            .replace( /"/g, '&quot;' )
            .replace( /'/g, '&#039;' );
    }

    /* ──────────────────────────  Submit  ───────────────────────── */

    function submitWizard( $wizard ) {
        var selected = collectSelectedItems( $wizard );
        if ( ! selected.length ) {
            showFeedback( $wizard.find( '.wpnest-rfw-step[data-rfw-step="3"] .wpnest-rfw-feedback' ), cfg.i18n.select_at_least_one, 'error' );
            return;
        }
        var reasons = collectReasons( $wizard );
        var rv      = validateReasons( reasons );
        if ( ! rv.ok ) {
            showFeedback( $wizard.find( '.wpnest-rfw-step[data-rfw-step="3"] .wpnest-rfw-feedback' ), rv.msg, 'error' );
            return;
        }
        if ( ! $wizard.find( 'input[name="confirm"]' ).is( ':checked' ) ) {
            showFeedback( $wizard.find( '.wpnest-rfw-step[data-rfw-step="3"] .wpnest-rfw-feedback' ), cfg.i18n.must_confirm, 'error' );
            return;
        }

        var payload = {
            order_id: parseInt( $wizard.data( 'order-id' ), 10 ),
            guest_token: $wizard.data( 'guest-token' ) || '',
            items: selected.map( function ( item ) {
                var r = reasons[ item.order_item_id ] || {};
                return {
                    order_item_id: item.order_item_id,
                    qty: item.qty,
                    reason_code: r.code,
                    reason_text: r.text || ''
                };
            } )
        };

        var $btn      = $wizard.find( '.wpnest-rfw-submit' );
        var originalText = $btn.text();
        var $feedback = $wizard.find( '.wpnest-rfw-step[data-rfw-step="3"] .wpnest-rfw-feedback' );
        $btn.prop( 'disabled', true ).text( cfg.i18n.submitting );

        $.ajax( {
            url: cfg.rest_url + '/submit',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify( payload ),
            beforeSend: function ( xhr ) {
                if ( cfg.nonce ) {
                    xhr.setRequestHeader( 'X-WP-Nonce', cfg.nonce );
                }
            }
        } )
        .done( function ( response ) {
            if ( response && response.success ) {
                $wizard.find( '.wpnest-rfw-wizard__form' ).hide();
                $wizard.find( '.wpnest-rfw-stepper' ).hide();
                showFeedback( $feedback, response.message || cfg.i18n.success, 'success' );
                $wizard.append( '<div class="wpnest-rfw-success">' + escapeHtml( response.message || cfg.i18n.success ) + '</div>' );
            } else {
                showFeedback( $feedback, ( response && response.message ) || cfg.i18n.error, 'error' );
                $btn.prop( 'disabled', false ).text( originalText );
            }
        } )
        .fail( function ( jqXHR ) {
            var msg = cfg.i18n.error;
            if ( jqXHR && jqXHR.responseJSON && jqXHR.responseJSON.message ) {
                msg = jqXHR.responseJSON.message;
            }
            showFeedback( $feedback, msg, 'error' );
            $btn.prop( 'disabled', false ).text( originalText );
        } );
    }

    /* ──────────────────────────  Guest verify  ───────────────────────── */

    function submitGuestForm( e ) {
        e.preventDefault();
        var $form     = $( e.currentTarget );
        var $feedback = $form.find( '.wpnest-rfw-feedback' );
        var $btn      = $form.find( 'button[type="submit"]' );

        var email   = $.trim( $form.find( 'input[name="email"]' ).val() );
        // Akceptujemy oba inputy podczas migracji 1.0.0 → 1.0.1 (cached page).
        var orderNumber = $.trim( $form.find( 'input[name="order_number"]' ).val() );
        if ( ! orderNumber ) {
            orderNumber = $.trim( $form.find( 'input[name="order_key"]' ).val() );
        }
        if ( ! email || ! orderNumber ) {
            showFeedback( $feedback, cfg.i18n.error, 'error' );
            return;
        }

        $btn.prop( 'disabled', true );
        showFeedback( $feedback, '', '' );

        $.ajax( {
            url: cfg.rest_url + '/verify-guest',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify( { email: email, order_number: orderNumber } )
        } )
        .done( function ( response ) {
            if ( response && response.success ) {
                // Reload page with token so the wizard branch renders server-side.
                var url = window.location.pathname + '?token=' + encodeURIComponent( response.guest_token );
                window.location.href = url;
            } else {
                showFeedback( $feedback, ( response && response.message ) || cfg.i18n.error, 'error' );
                $btn.prop( 'disabled', false );
            }
        } )
        .fail( function ( jqXHR ) {
            var msg = cfg.i18n.error;
            if ( jqXHR && jqXHR.responseJSON && jqXHR.responseJSON.message ) {
                msg = jqXHR.responseJSON.message;
            }
            showFeedback( $feedback, msg, 'error' );
            $btn.prop( 'disabled', false );
        } );
    }

    /* ──────────────────────────  Wiring  ───────────────────────── */

    $( function () {
        var $wizard = $( '.wpnest-rfw-wizard' );

        // Step navigation buttons.
        $wizard.on( 'click', '[data-rfw-next]', function () {
            var step = parseInt( $( this ).data( 'rfw-next' ), 10 );
            var $w   = $( this ).closest( '.wpnest-rfw-wizard' );

            if ( step === 2 ) {
                var selected = collectSelectedItems( $w );
                if ( ! selected.length ) {
                    showFeedback( $w.find( '.wpnest-rfw-step[data-rfw-step="1"] .wpnest-rfw-feedback' ), cfg.i18n.select_at_least_one, 'error' );
                    return;
                }
                showFeedback( $w.find( '.wpnest-rfw-step[data-rfw-step="1"] .wpnest-rfw-feedback' ), '', '' );
                renderReasons( $w, selected );
                gotoStep( $w, 2 );
                return;
            }

            if ( step === 3 ) {
                var reasons = collectReasons( $w );
                var rv      = validateReasons( reasons );
                if ( ! rv.ok ) {
                    showFeedback( $w.find( '.wpnest-rfw-step[data-rfw-step="2"] .wpnest-rfw-feedback' ), rv.msg, 'error' );
                    return;
                }
                showFeedback( $w.find( '.wpnest-rfw-step[data-rfw-step="2"] .wpnest-rfw-feedback' ), '', '' );
                var selected2 = collectSelectedItems( $w );
                renderSummary( $w, selected2, reasons );
                gotoStep( $w, 3 );
                return;
            }
        } );

        $wizard.on( 'click', '[data-rfw-prev]', function () {
            var step = parseInt( $( this ).data( 'rfw-prev' ), 10 );
            gotoStep( $( this ).closest( '.wpnest-rfw-wizard' ), step );
        } );

        // "Other" reason → toggle text field visibility.
        $wizard.on( 'change', 'select[name="reason_code"]', function () {
            var $row  = $( this ).closest( '[data-rfw-reason-row]' );
            var $text = $row.find( '.wpnest-rfw-reason__text' );
            if ( $( this ).val() === REASON_OTHER ) {
                $text.removeAttr( 'hidden' );
                $text.find( 'textarea' ).prop( 'required', true );
            } else {
                $text.attr( 'hidden', 'hidden' );
                $text.find( 'textarea' ).prop( 'required', false );
            }
        } );

        // Auto-toggle qty input enabled state on checkbox change.
        $wizard.on( 'change', '.wpnest-rfw-item__check', function () {
            var $row = $( this ).closest( '.wpnest-rfw-item' );
            $row.toggleClass( 'is-selected', $( this ).is( ':checked' ) );
        } );

        // Final submit.
        $wizard.on( 'submit', '.wpnest-rfw-wizard__form', function ( e ) {
            e.preventDefault();
            submitWizard( $( this ).closest( '.wpnest-rfw-wizard' ) );
        } );

        // Guest verify form.
        $( document ).on( 'submit', '#wpnest-rfw-guest-form', submitGuestForm );
    } );

} )( jQuery );
