<?php

declare(strict_types=1);

namespace Numinix\SeekmodoWordPress\Frontend;

use Numinix\SeekmodoWordPress\Config\Options;
use Numinix\SeekmodoWordPress\Gateway\BrowserToken;

/**
 * Storefront wiring for `<seekmodo-ask>` when Ask AI is enabled for
 * the tenant. Emits SDK meta tags on any page that renders the
 * widget; enqueues the vendored ask IIFE for shortcode embeds. Gutenberg
 * blocks are covered by {@see \Numinix\SeekmodoWordPress\Blocks\Registry}
 * which loads the full web-components bundle from CDN.
 */
final class AskUI
{
    public const SCRIPT_HANDLE = 'seekmodo-ask';
    public const CORS_HANDLE   = 'seekmodo-cors-notice';

    public static function register(): void
    {
        if (!function_exists('add_action')) {
            return;
        }
        add_action('wp_head', [self::class, 'renderMeta'], 2);
        add_action('wp_enqueue_scripts', [self::class, 'enqueue']);
    }

    public static function renderMeta(): void
    {
        if (!self::pageUsesAskWidget() || !Options::askAiEnabled()) {
            return;
        }
        $tenant = Options::tenantId();
        if ($tenant === '') {
            return;
        }
        $gateway = trim(Options::gatewayUrl());
        if ($gateway === '' && defined('SEEKMODO_WP_GATEWAY_URL')) {
            $gateway = (string) SEEKMODO_WP_GATEWAY_URL;
        }
        $refresh = function_exists('rest_url')
            ? (string) rest_url('seekmodo/v1/browser-token')
            : '';
        $bt    = BrowserToken::current();
        $token = is_array($bt) && isset($bt['token']) ? (string) $bt['token'] : '';

        $emit = static function (string $name, string $content): void {
            if ($content === '') {
                return;
            }
            printf(
                "<meta name=\"%s\" content=\"%s\">\n",
                esc_attr($name),
                esc_attr($content)
            );
        };
        $emit('seekmodo:tenant', $tenant);
        $emit('seekmodo:gateway', $gateway);
        $emit('seekmodo:refresh', $refresh);
        $emit('seekmodo:token', $token);
    }

    public static function enqueue(): void
    {
        if (!self::pageUsesAskWidget() || !Options::askAiEnabled()) {
            return;
        }
        if (function_exists('has_block') && has_block('seekmodo/ask')) {
            return;
        }
        if (!function_exists('wp_register_script') || !function_exists('wp_enqueue_script')) {
            return;
        }

        $base = defined('SEEKMODO_WP_PLUGIN_URL') ? (string) SEEKMODO_WP_PLUGIN_URL : '';
        $ver  = defined('SEEKMODO_WP_VERSION') ? (string) SEEKMODO_WP_VERSION : '0.0.0';

        wp_register_script(
            self::CORS_HANDLE,
            $base . 'assets/suggest/seekmodo-cors-notice.js',
            [],
            $ver,
            true
        );
        wp_enqueue_script(self::CORS_HANDLE);

        wp_register_script(
            self::SCRIPT_HANDLE,
            $base . 'assets/ask/seekmodo-ask.global.js',
            [self::CORS_HANDLE],
            $ver,
            true
        );
        wp_enqueue_script(self::SCRIPT_HANDLE);
    }

    private static function pageUsesAskWidget(): bool
    {
        if (!Options::isPaired()) {
            return false;
        }
        if (function_exists('has_block') && has_block('seekmodo/ask')) {
            return true;
        }
        if (function_exists('is_singular') && is_singular()) {
            $post = function_exists('get_post') ? get_post() : null;
            if ($post instanceof \WP_Post && is_string($post->post_content)) {
                if (str_contains($post->post_content, '[seekmodo_ask')) {
                    return true;
                }
            }
        }
        if (function_exists('apply_filters')) {
            return (bool) apply_filters('seekmodo_enqueue_ask', false);
        }

        return false;
    }
}
