/**
 * iFirma WooCommerce - Checkout Blocks NIP Field
 * 
 * Adds NIP field to WooCommerce Block Checkout
 */
(function () {
    'use strict';

    var el = wp.element.createElement;
    var registerCheckoutFilters = wp.data.select ? wp.data.select : null;

    if (typeof wc === 'undefined' || typeof wc.blocksCheckout === 'undefined') {
        return;
    }

    var registerPlugin = wp.plugins ? wp.plugins.registerPlugin : null;
    var ExperimentalOrderMeta = wc.blocksCheckout.ExperimentalOrderMeta || null;

    // Get settings
    var settings = window.ifirmaCheckoutBlocks || {
        nipLabel: 'NIP',
        nipPlaceholder: 'Enter NIP if you need an invoice',
        nipRequired: false
    };

    // NIP Field Component
    function NipFieldComponent() {
        var TextInput = wp.components ? wp.components.TextControl : null;

        if (!TextInput) {
            return null;
        }

        var useState = wp.element.useState;
        var nipValue = useState('');
        var nipState = nipValue[0];
        var setNipState = nipValue[1];

        return el('div', { className: 'ifirma-nip-field-block', style: { marginTop: '15px' } },
            el(TextInput, {
                label: settings.nipLabel,
                value: nipState,
                onChange: function (value) {
                    setNipState(value);
                    // Save to store
                    if (wp.data && wp.data.dispatch) {
                        var store = wp.data.dispatch('wc/store/checkout');
                        if (store && store.setExtensionData) {
                            store.setExtensionData('ifirma', { billing_nip: value });
                        }
                    }
                },
                placeholder: settings.nipPlaceholder,
                required: settings.nipRequired
            })
        );
    }

    // Register the component
    if (registerPlugin && ExperimentalOrderMeta) {
        registerPlugin('ifirma-checkout-nip', {
            render: function () {
                return el(ExperimentalOrderMeta, null,
                    el(NipFieldComponent)
                );
            },
            scope: 'woocommerce-checkout'
        });
    }
})();
