<?php

namespace SoftminalB2B;

if (!defined('ABSPATH')) {
    exit;
}

use SoftminalB2B\Services\TranslationStrings;
use SoftminalB2B\Support\Tier;
use SoftminalB2B\Vite\Vite;

class Enqueue {
    public function init() {
        add_action('admin_enqueue_scripts', [$this, 'enqueueAdminAssets']);
        add_action('in_admin_header', [$this, 'hideAdminNotices']);
    }

    /**
     * Every Softminal plugin bundles the same `SoftminalB2B\Vite\Vite` class, and
     * its configuration lives in static properties shared across all of them.
     * Configuring once at load time is not enough: another plugin configuring
     * later would repoint this one at its own directory, and we would enqueue
     * nothing. So point it at us immediately before every use.
     */
    private function configureVite(): void {
        Vite::configure([
            /**
             * Where `npm run dev` is serving from. Only used in dev mode.
             *
             * A browser on an HTTPS admin page refuses to load modules from an
             * http:// dev server, which leaves the SPA blank. On a secured
             * local site (Herd/Valet), serve Vite over https on that hostname
             * and point this at it.
             *
             * @param string $url
             */
            'devServerUrl' => apply_filters('smb2b_vite_dev_server_url', $this->defaultDevServerUrl()),
            'pluginDir'    => SMB2B_DIR,
            'pluginUrl'    => SMB2B_URL,
            'version'      => SMB2B_VERSION,
        ]);
    }

    /**
     * On an HTTPS admin, default to an HTTPS dev server on the site's own host
     * so module loading is not blocked as mixed content. Plain localhost
     * otherwise.
     */
    private function defaultDevServerUrl(): string {
        if (!is_ssl()) {
            return 'http://localhost:4001';
        }

        $host = wp_parse_url(home_url(), PHP_URL_HOST);

        return 'https://' . ($host ?: 'localhost') . ':4001';
    }

    public function hideAdminNotices(): void {
        $screen = get_current_screen();
        if ($screen && $screen->id === 'toplevel_page_softminal-b2b-wholesale-for-woocommerce') {
            remove_all_actions('admin_notices');
            remove_all_actions('all_admin_notices');
        }
    }

    public function enqueueAdminAssets($hook) {
        if ($hook !== 'toplevel_page_softminal-b2b-wholesale-for-woocommerce') {
            return;
        }

        $this->configureVite();

        $deps = ['jquery', 'wp-api-fetch', 'wp-i18n'];
        $enqueued = Vite::enqueueAsset('smb2b-script', 'resources/admin/main.js', $deps);
        Vite::enqueueStyle('smb2b-style', 'resources/css/index.css');

        if ($enqueued) {
            Vite::localize('smb2b-script', 'smb2bAdmin', [
                'apiUrl'   => rest_url(SMB2B_API_NAMESPACE),
                'adminUrl' => admin_url(),
                'nonce'    => wp_create_nonce('wp_rest'),
                'debug'    => Vite::isDev(),
                'userName' => wp_get_current_user()->display_name,
                // Store currency symbol (decoded to a real glyph, e.g. ৳/$/€) so
                // price inputs can show the unit — display formatting still comes
                // from the server via *_html fields.
                'currency' => function_exists('get_woocommerce_currency_symbol')
                    ? html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8')
                    : '',
                // left|right|left_space|right_space — so a price input can place
                // the symbol on the side the store already uses for prices.
                'currencyPos' => get_option('woocommerce_currency_pos', 'left'),
                // The nav badges Pro screens, so it needs the tier before the
                // first paint. Individual endpoints already return this, but
                // waiting on one would make the badges pop in after render.
                'tier'     => Tier::toArray(),
                // Translated UI strings for the SPA, consumed via $t(). Sourced
                // from PHP so make-pot can extract them into the .pot.
                'i18n'     => TranslationStrings::admin(),
            ]);
        }
    }
}
