/**
 * storzen — Required Fields System
 *
 * When a widget toggle is switched ON, any field marked as
 * data-szp-required-when="toggle_slug" becomes mandatory.
 * The Save button is blocked until all required fields for
 * enabled toggles have a value.
 *
 * How it works:
 *  1. On page load and on every toggle change, scan all
 *     [data-szp-required-when] inputs/selects/textareas.
 *  2. If the referenced toggle is checked (ON), the row
 *     receives .szp-required and the field gets the HTML
 *     `required` attribute + a visible asterisk.
 *  3. On Save click, we intercept before Storzen's own
 *     handler, validate, and show inline errors if any
 *     required field is empty.
 *
 * Mapping: data-szp-required-when="archive_grid"
 *          means "this field is required when pk_fields[archive_grid] is checked"
 */
(function ($) {
    'use strict';

    // ── Required-field rules ───────────────────────────────────────────────
    // Map:  field_slug  →  toggle_slug (the toggle that makes it required)
    var REQUIRED_WHEN = {
        // Shop tab
        archive_grid_columns    : 'archive_grid',
        archive_grid_per_page   : 'archive_grid',
        archive_ordering_default: 'archive_ordering',
        sidebar_recent_count    : 'sidebar_recent',
        // Shop Details tab
        related_count           : 'related_products',
        // Checkout tab
        checkout_notice         : 'checkout_form',
        checkout_notice_s       : 'express_checkout_s',
        // Landing tab
        carousel_slides         : 'enable_carousel',
    };

    // ── Helpers ────────────────────────────────────────────────────────────

    function getToggleChecked( fieldSlug ) {
        var $toggle = $( '#pk_' + fieldSlug );
        return $toggle.length ? $toggle.is( ':checked' ) : false;
    }

    function getField( fieldSlug ) {
        return $( '#pk_' + fieldSlug );
    }

    function markRequired( $field, isRequired ) {
        var $row = $field.closest( '.pk-row' );
        var $label = $row.find( 'label' );

        if ( isRequired ) {
            $field.attr( 'required', 'required' );
            $row.addClass( 'szp-required' );
            if ( ! $label.find( '.szp-req-star' ).length ) {
                $label.append( '<span class="szp-req-star" aria-hidden="true"> *</span>' );
            }
        } else {
            $field.removeAttr( 'required' );
            $row.removeClass( 'szp-required szp-required--error' );
            $label.find( '.szp-req-star' ).remove();
            $row.find( '.szp-error-msg' ).remove();
        }
    }

    function refreshRequiredStates() {
        $.each( REQUIRED_WHEN, function ( fieldSlug, toggleSlug ) {
            var $field    = getField( fieldSlug );
            if ( ! $field.length ) return;
            var isEnabled = getToggleChecked( toggleSlug );
            markRequired( $field, isEnabled );
        } );
    }

    function validateAll() {
        var errors = [];
        $.each( REQUIRED_WHEN, function ( fieldSlug, toggleSlug ) {
            var $field = getField( fieldSlug );
            if ( ! $field.length ) return;
            if ( ! getToggleChecked( toggleSlug ) ) return; // toggle is OFF — skip
            var val = $.trim( $field.val() );
            if ( val === '' || val === '0' ) {
                errors.push( fieldSlug );
                var $row = $field.closest( '.pk-row' );
                $row.addClass( 'szp-required--error' );
                if ( ! $row.find( '.szp-error-msg' ).length ) {
                    $row.append(
                        '<p class="szp-error-msg">' +
                        ( window.WCP && WCP.i18n && WCP.i18n.required
                            ? WCP.i18n.required
                            : 'This field is required.' ) +
                        '</p>'
                    );
                }
            } else {
                $field.closest( '.pk-row' ).removeClass( 'szp-required--error' )
                      .find( '.szp-error-msg' ).remove();
            }
        } );
        return errors;
    }

    // ── Event bindings ─────────────────────────────────────────────────────

    $( document ).on( 'change', '.pk-toggle input[type="checkbox"]', function () {
        refreshRequiredStates();
    } );

    // Intercept Save before Storzen fires (use capture via higher priority)
    $( document ).on( 'click.wcpRequired', '.js-pk-save', function ( e ) {
        var errors = validateAll();
        if ( errors.length ) {
            e.stopImmediatePropagation();
            var msg = window.WCP && WCP.i18n && WCP.i18n.fill_required
                ? WCP.i18n.fill_required
                : 'Please fill in all required fields before saving.';
            if ( typeof window.pkToast === 'function' ) {
                window.pkToast( msg, 'error' );
            }
            // Scroll to first error
            var $first = $( '.szp-required--error' ).first();
            if ( $first.length ) {
                $( 'html, body' ).animate( { scrollTop: $first.offset().top - 120 }, 300 );
            }
        }
    } );

    // ── Init ───────────────────────────────────────────────────────────────

    $( function () {
        refreshRequiredStates();

        // Inject inline styles (avoids an extra HTTP request)
        var css =
            '.szp-req-star { color: #e02020; font-weight: 700; margin-left: 2px; }' +
            '.pk-row.szp-required .pk-input,' +
            '.pk-row.szp-required .pk-select,' +
            '.pk-row.szp-required .pk-textarea {' +
            '    border-color: #e5a100 !important;' +
            '}' +
            '.pk-row.szp-required--error .pk-input,' +
            '.pk-row.szp-required--error .pk-select,' +
            '.pk-row.szp-required--error .pk-textarea {' +
            '    border-color: #e02020 !important;' +
            '    box-shadow: 0 0 0 2px rgba(224,32,32,.15) !important;' +
            '}' +
            '.szp-error-msg {' +
            '    color: #e02020;' +
            '    font-size: .78rem;' +
            '    margin: .35rem 0 0;' +
            '}';

        $( '<style id="szp-required-styles">' ).text( css ).appendTo( 'head' );
    } );

}(jQuery));
