<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD\Front;

use APD\Support\Assets;
use APD\Support\DesignerAssets;
use APD\Support\Nonces;

defined('ABSPATH') || exit;

class FrontAssets
{
    public function register() : void
    {
        $styleFile = DesignerAssets::styleFile();
        $coreFile = DesignerAssets::coreFile();

        wp_register_style('apd-vendor', DesignerAssets::url($styleFile), [], DesignerAssets::version($styleFile));
        wp_register_style('apd-front', ASUKA_PRODUCT_DESIGNER_ASSETS_URL . 'css/front.css', ['apd-vendor'], Assets::version('assets/css/front.css'));

        wp_register_script('apd-vendor', DesignerAssets::url($coreFile), [], DesignerAssets::version($coreFile), true);
        wp_register_script('apd-runtime-bridge', ASUKA_PRODUCT_DESIGNER_ASSETS_URL . 'js/runtime-bridge.js', ['apd-vendor'], Assets::version('assets/js/runtime-bridge.js'), true);

        $frontDeps = ['apd-runtime-bridge'];
        $moduleHandles = ['apd-vendor', 'apd-runtime-bridge'];

        wp_register_script('apd-front-app', ASUKA_PRODUCT_DESIGNER_ASSETS_URL . 'js/front-app.js', $frontDeps, Assets::version('assets/js/front-app.js'), true);
        $moduleHandles[] = 'apd-front-app';

        foreach (array_unique($moduleHandles) as $moduleHandle) {
            wp_script_add_data($moduleHandle, 'type', 'module');
        }

        $currency = function_exists('get_woocommerce_currency') ? get_woocommerce_currency() : '';
        $charset = get_bloginfo('charset') ?: 'UTF-8';
        $decodeMoneyText = static fn(string $value) : string => html_entity_decode($value, ENT_QUOTES | ENT_HTML5, $charset);
        $priceFormat = [
            'symbol' => function_exists('get_woocommerce_currency_symbol')
                ? $decodeMoneyText((string) get_woocommerce_currency_symbol($currency))
                : '',
            'priceFormat' => function_exists('get_woocommerce_price_format')
                ? $decodeMoneyText((string) get_woocommerce_price_format())
                : '%2$s',
            'decimalSeparator' => function_exists('wc_get_price_decimal_separator') ? wc_get_price_decimal_separator() : '.',
            'thousandSeparator' => function_exists('wc_get_price_thousand_separator') ? wc_get_price_thousand_separator() : ',',
            'precision' => function_exists('wc_get_price_decimals') ? wc_get_price_decimals() : 2,
            'trimZeros' => function_exists('wc_prices_include_tax') ? false : false,
            'code' => $currency,
        ];

        wp_localize_script('apd-front-app', 'APD_RUNTIME', [
            'restUrl' => esc_url_raw(rest_url('asuka-designer/v1/')),
            'restUploadUrl' => esc_url_raw(add_query_arg('apd_source', 'frontend', rest_url('asuka-designer/v1/upload'))),
            'nonce' => Nonces::runtime(),
            'pluginUrl' => ASUKA_PRODUCT_DESIGNER_URL,
            'priceFormat' => $priceFormat,
            'labels' => [
                'customizationIncluded' => __('Customization included', 'asuka-product-designer'),
                'statusNoPreview' => __('No preview could be generated yet.', 'asuka-product-designer'),
                'statusStoringPreview' => __('Storing preview...', 'asuka-product-designer'),
                'statusPreviewStored' => __('Preview stored.', 'asuka-product-designer'),
                'statusPreviewFailed' => __('Preview storage failed.', 'asuka-product-designer'),
                'statusSavingDesign' => __('Saving design...', 'asuka-product-designer'),
                'statusDesignSaved' => __('Design saved.', 'asuka-product-designer'),
                'statusDesignSaveFailed' => __('Design save failed.', 'asuka-product-designer'),
                'savedDesignTitle' => __('Saved design', 'asuka-product-designer'),
                'cartEditSubmitLabel' => __('Update cart item', 'asuka-product-designer'),
                'validationRequireDesign' => __('Please complete your customization before adding this product to the cart.', 'asuka-product-designer'),
                'validationMinObjects' => __('Please add at least {min} customization element(s) before adding this product to the cart.', 'asuka-product-designer'),
                'validationMaxObjects' => __('Please remove some customization elements before adding this product to the cart. Maximum allowed: {max}.', 'asuka-product-designer'),
                'validationMinTextObjects' => __('Please add at least {min} text element(s) before adding this product to the cart.', 'asuka-product-designer'),
                'validationMaxTextObjects' => __('Please remove some text elements before adding this product to the cart. Maximum allowed: {max}.', 'asuka-product-designer'),
                'validationMinImageObjects' => __('Please add at least {min} image element(s) before adding this product to the cart.', 'asuka-product-designer'),
                'validationMaxImageObjects' => __('Please remove some image elements before adding this product to the cart. Maximum allowed: {max}.', 'asuka-product-designer'),
                'validationRequireText' => __('Please add personalized text before adding this product to the cart.', 'asuka-product-designer'),
                'validationMinTextLength' => __('Please enter at least {min} text character(s) before adding this product to the cart.', 'asuka-product-designer'),
                'validationRequirePreview' => __('A preview is required before adding this customized product to the cart.', 'asuka-product-designer'),
                'validationRequiredViewsCount' => __('Please customize at least {count} view(s) before adding this product to the cart.', 'asuka-product-designer'),
                'validationRequireEveryView' => __('Please complete every required view before adding this product to the cart.', 'asuka-product-designer'),
                'validationRequiredViews' => __('Please customize the required views before adding this product to the cart: {views}.', 'asuka-product-designer'),
                'validationAllowedObjectTypes' => __('This customization contains unsupported element types for this product.', 'asuka-product-designer'),
                'validationForbiddenObjectTypes' => __('Please remove the forbidden element types before adding this product to the cart.', 'asuka-product-designer'),
                'validationRequiredObjectTypes' => __('This product requires the following element types: {types}.', 'asuka-product-designer'),
                'validationTextForbidden' => __('Text customization is not allowed for this product.', 'asuka-product-designer'),
                'validationImageForbidden' => __('Image customization is not allowed for this product.', 'asuka-product-designer'),
                'pricingLivePricing' => __('Live pricing', 'asuka-product-designer'),
                'pricingUpdatedFromCustomization' => __('Price updated from your customization', 'asuka-product-designer'),
                'pricingMetricProduct' => __('Product', 'asuka-product-designer'),
                'pricingMetricAdded' => __('Added', 'asuka-product-designer'),
                'pricingMetricFinal' => __('Final', 'asuka-product-designer'),
                'pricingBreakdown' => __('Price breakdown', 'asuka-product-designer'),
                'pricingAppliedRules' => __('Applied rules', 'asuka-product-designer'),
                'pricingColumnItem' => __('Item', 'asuka-product-designer'),
                'pricingColumnDetails' => __('Details', 'asuka-product-designer'),
                'pricingColumnAmount' => __('Amount', 'asuka-product-designer'),
                'pricingColumnProperty' => __('Property', 'asuka-product-designer'),
                'pricingColumnCondition' => __('Condition', 'asuka-product-designer'),
                'pricingColumnAddPrice' => __('+Price', 'asuka-product-designer'),
                'pricingProductPrice' => __('Product price', 'asuka-product-designer'),
                'pricingWooBasePrice' => __('WooCommerce base price', 'asuka-product-designer'),
                'pricingSetupFee' => __('Setup fee', 'asuka-product-designer'),
                'pricingOneTimeSetupCharge' => __('One-time setup charge', 'asuka-product-designer'),
                'pricingCustomProductBase' => __('Custom product base', 'asuka-product-designer'),
                'pricingBaseAmountFromDesignerConfig' => __('Base amount from designer configuration', 'asuka-product-designer'),
                'pricingStandardOptions' => __('Standard options', 'asuka-product-designer'),
                'pricingDefaultOptionSurcharges' => __('Default option surcharges', 'asuka-product-designer'),
                'pricingPricingRules' => __('Pricing rules', 'asuka-product-designer'),
                'pricingDynamicRulesMatched' => __('Dynamic rules matched by your design', 'asuka-product-designer'),
                'pricingFinalPrice' => __('Final price', 'asuka-product-designer'),
                'pricingProductCustomizationTotal' => __('Product + customization total', 'asuka-product-designer'),
                'pricingRulesTotal' => __('Pricing rules total', 'asuka-product-designer'),
                'pricingDetailedRulesNotExposed' => __('Detailed matched rules are not exposed by the current runtime breakdown.', 'asuka-product-designer'),
                'pricingMatchedCurrentDesign' => __('Matched in current design', 'asuka-product-designer'),
                'pricingTriggeredByCurrentDesign' => __('Triggered by current design', 'asuka-product-designer'),
                'pricingConditionMatched' => __('Condition matched', 'asuka-product-designer'),
                'pricingFirstMatch' => __('first match', 'asuka-product-designer'),
                'pricingCurrentView' => __('current view', 'asuka-product-designer'),
                'pricingWholeDocument' => __('whole document', 'asuka-product-designer'),
                'pricingRule' => __('Rule', 'asuka-product-designer'),
                'pricingTextLength' => __('Text length', 'asuka-product-designer'),
                'pricingLinesLength' => __('Lines length', 'asuka-product-designer'),
                'pricingFontSize' => __('Font size', 'asuka-product-designer'),
                'pricingColorsUsed' => __('Colors used', 'asuka-product-designer'),
                'pricingCoverage' => __('Coverage', 'asuka-product-designer'),
                'pricingLayersAmount' => __('Layers amount', 'asuka-product-designer'),
                'pricingLayerSize' => __('Layer size', 'asuka-product-designer'),
                'pricingScale' => __('Scale', 'asuka-product-designer'),
                'pricingMetricChars' => __('chars', 'asuka-product-designer'),
                'pricingMetricLines' => __('lines', 'asuka-product-designer'),
                'pricingMetricPt' => __('pt', 'asuka-product-designer'),
                'pricingMetricColors' => __('colors', 'asuka-product-designer'),
                'pricingMetricLayers' => __('layers', 'asuka-product-designer'),
                'pricingWidth' => __('width', 'asuka-product-designer'),
                'pricingHeight' => __('height', 'asuka-product-designer'),
                'pricingAppliedRuleCount' => __('{count} applied rule', 'asuka-product-designer'),
                'pricingAppliedRuleCountPlural' => __('{count} applied rules', 'asuka-product-designer'),
                'pricingInferred' => __('inferred', 'asuka-product-designer'),
                'galleryChooseVariation' => __('Choose a variation to load the linked custom product designer.', 'asuka-product-designer'),
                'galleryNoLinkedCustomProduct' => __('No custom product is linked to this variation.', 'asuka-product-designer'),
                'runtimeDesignerMounted' => __('Designer mounted.', 'asuka-product-designer'),
                'runtimeDesignerMountFailed' => __('Designer mount failed.', 'asuka-product-designer'),
                'runtimeWaitingForDesigner' => __('Waiting for AsukaDesigner…', 'asuka-product-designer'),
                'runtimeDesignerUnavailable' => __('AsukaDesigner could not be loaded in this context yet.', 'asuka-product-designer'),
                'runtimeDesignPayloadSynchronized' => __('Design payload synchronized.', 'asuka-product-designer'),
            ],
        ]);
    }

    public function enqueue() : void
    {
        $this->register();

        wp_enqueue_style('apd-front');
        wp_enqueue_script('apd-front-app');
    }
}
