/**
 * WooCommerce Checkout Blocks Integration
 *
 * Adds a domain field to the checkout block for licensed products.
 *
 * @package WcLicensedProduct
 */

(function () {
    'use strict';

    const { registerCheckoutBlock } = wc.blocksCheckout;
    const { createElement, useState, useEffect } = wp.element;
    const { TextControl } = wp.components;
    const { __ } = wp.i18n;
    const { extensionCartUpdate } = wc.blocksCheckout;
    const { getSetting } = wc.wcSettings;

    // Get settings passed from PHP
    const settings = getSetting('wc-licensed-product_data', {});

    /**
     * Validate domain format
     */
    function isValidDomain(domain) {
        if (!domain || domain.length > 255) {
            return false;
        }
        const pattern = /^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
        return pattern.test(domain);
    }

    /**
     * Normalize domain (remove protocol and www)
     */
    function normalizeDomain(domain) {
        let normalized = domain.toLowerCase().trim();
        normalized = normalized.replace(/^https?:\/\//, '');
        normalized = normalized.replace(/^www\./, '');
        normalized = normalized.replace(/\/.*$/, '');
        return normalized;
    }

    /**
     * License Domain Block Component
     */
    const LicenseDomainBlock = ({ checkoutExtensionData, extensions }) => {
        const [domain, setDomain] = useState('');
        const [error, setError] = useState('');
        const { setExtensionData } = checkoutExtensionData;

        // Only show if cart has licensed products
        if (!settings.hasLicensedProducts) {
            return null;
        }

        const handleChange = (value) => {
            const normalized = normalizeDomain(value);
            setDomain(normalized);

            // Validate
            if (normalized && !isValidDomain(normalized)) {
                setError(settings.validationError || __('Please enter a valid domain.', 'wc-licensed-product'));
            } else {
                setError('');
            }

            // Update extension data for server-side processing
            setExtensionData('wc-licensed-product', 'licensed_product_domain', normalized);
        };

        return createElement(
            'div',
            { className: 'wc-block-components-licensed-product-domain' },
            createElement(
                'h3',
                { className: 'wc-block-components-title' },
                settings.sectionTitle || __('License Domain', 'wc-licensed-product')
            ),
            createElement(TextControl, {
                label: settings.fieldLabel || __('Domain for License Activation', 'wc-licensed-product'),
                value: domain,
                onChange: handleChange,
                placeholder: settings.fieldPlaceholder || 'example.com',
                help: error || settings.fieldDescription || __('Enter the domain where you will use this license.', 'wc-licensed-product'),
                className: error ? 'has-error' : '',
                required: true,
            })
        );
    };

    // Register the checkout block
    registerCheckoutBlock({
        metadata: {
            name: 'wc-licensed-product/domain-field',
            parent: ['woocommerce/checkout-contact-information-block'],
        },
        component: LicenseDomainBlock,
    });
})();
