<?php

defined('ABSPATH') || exit;

final class DSProofwp_Block
{
    private const SCRIPT_HANDLE = 'dsproofwp-block-editor';
    private const STYLE_HANDLE = 'dsproofwp-block-editor';

    public function __construct()
    {
        add_action('admin_enqueue_scripts', [$this, 'enqueue_block_editor_assets']);
    }

    public function enqueue_block_editor_assets(): void
    {
        if (! function_exists('get_current_screen')) {
            return;
        }

        $screen = get_current_screen();

        if (! $screen || ! method_exists($screen, 'is_block_editor') || ! $screen->is_block_editor()) {
            return;
        }

        $script_path = plugin_dir_path(__DIR__) . '../dist/block.min.js';
        if (! file_exists($script_path)) {
            return;
        }

        $script_url = plugins_url('dist/block.min.js', dirname(__DIR__, 2) . '/proofwp.php');
        $style_path = plugin_dir_path(__DIR__) . '../dist/block.css';

        wp_enqueue_script(
            self::SCRIPT_HANDLE,
            $script_url,
            ['wp-blocks', 'wp-block-editor', 'wp-components', 'wp-element', 'wp-i18n'],
            (string) filemtime($script_path),
            true
        );

        wp_localize_script(
            self::SCRIPT_HANDLE,
            'dsproofwpBlockInfo',
            [
                'nonce' => wp_create_nonce('wp_rest'),
                'apiBase' => rest_url('dsproofwp/v1/'),
                'isProActive' => class_exists('DSProofwp_Plugin') && method_exists('DSProofwp_Plugin', 'is_pro_active')
                    ? DSProofwp_Plugin::is_pro_active()
                    : false,
                'isLicenseActive' => class_exists('DSProofwp_Plugin') && method_exists('DSProofwp_Plugin', 'is_license_active')
                    ? DSProofwp_Plugin::is_license_active()
                    : false,
            ]
        );

        wp_set_script_translations(self::SCRIPT_HANDLE, 'proofwp');

        if (file_exists($style_path)) {
            wp_enqueue_style(
                self::STYLE_HANDLE,
                plugins_url('dist/block.css', dirname(__DIR__, 2) . '/proofwp.php'),
                [],
                (string) filemtime($style_path)
            );
        }
    }
}

new DSProofwp_Block();
