<?php

namespace MODELORA\Core;

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

class Assets
{
    private function asset_version(string $relative_path): string
    {
        $absolute = MODELORA_PLUGIN_DIR . ltrim($relative_path, '/');
        if (file_exists($absolute)) {
            return (string) filemtime($absolute);
        }

        return MODELORA_VERSION;
    }

    private function is_debug_enabled(): bool
    {
        $enabled = true;
        return (bool) apply_filters('modelora_debug_logs_enabled', $enabled);
    }

    private function add_model_viewer_globals(): void
    {
        $plugin_url = esc_url_raw(MODELORA_PLUGIN_URL);
        $inline = 'window.modeloraConfig = window.modeloraConfig || {};'
            . 'window.modeloraConfig.pluginUrl = ' . wp_json_encode($plugin_url) . ';'
            . 'window.modeloraConfig.modelViewerUrl = ' . wp_json_encode($plugin_url . 'assets/js/model-viewer.min.js') . ';'
            . 'window.ModelViewerElement = window.ModelViewerElement || {};'
            . 'window.ModelViewerElement.lottieLoaderLocation = window.ModelViewerElement.lottieLoaderLocation || '
            . wp_json_encode($plugin_url . 'assets/vendor/LottieLoader.js') . ';';

        wp_add_inline_script('modelora-model-viewer', $inline, 'before');
    }

    public function register(): void
    {
        add_action('wp_enqueue_scripts', [$this, 'frontend']);
        add_action('admin_enqueue_scripts', [$this, 'admin']);
        add_action('enqueue_block_editor_assets', [$this, 'block_editor']);
    }

    public function frontend(): void
    {
        wp_register_style('modelora-viewer', MODELORA_PLUGIN_URL . 'assets/css/viewer.css', [], $this->asset_version('assets/css/viewer.css'));
        
        wp_register_script('modelora-model-viewer', MODELORA_PLUGIN_URL . 'assets/js/model-viewer-bootstrap.js', [], $this->asset_version('assets/js/model-viewer-bootstrap.js'), ['strategy' => 'defer']);
        wp_register_script('modelora-viewer', MODELORA_PLUGIN_URL . 'assets/js/viewer.js', ['modelora-model-viewer'], $this->asset_version('assets/js/viewer.js'), true);
        $this->add_model_viewer_globals();

        wp_localize_script('modelora-viewer', 'modeloraViewerData', [
            'nonce' => wp_create_nonce('wp_rest'),
            'debug' => $this->is_debug_enabled(),
            'version' => MODELORA_VERSION,
            'modelViewerUrl' => esc_url_raw(MODELORA_PLUGIN_URL . 'assets/js/model-viewer.min.js'),
        ]);
    }

    public function admin(string $hook): void
    {
        if (strpos($hook, 'modelora-add-models') === false && strpos($hook, 'post.php') === false && strpos($hook, 'post-new.php') === false) {
            return;
        }

        wp_enqueue_media();

        if (! wp_script_is('modelora-model-viewer', 'registered')) {
            wp_register_script('modelora-model-viewer', MODELORA_PLUGIN_URL . 'assets/js/model-viewer-bootstrap.js', [], $this->asset_version('assets/js/model-viewer-bootstrap.js'), ['strategy' => 'defer']);
        }
        $this->add_model_viewer_globals();

        wp_enqueue_style('modelora-admin', MODELORA_PLUGIN_URL . 'assets/css/admin.css', [], $this->asset_version('assets/css/admin.css'));
        wp_enqueue_script('modelora-model-viewer');
        wp_enqueue_script('modelora-admin-app', MODELORA_PLUGIN_URL . 'assets/js/admin-app.js', ['wp-element', 'wp-components', 'wp-api-fetch', 'modelora-model-viewer'], $this->asset_version('assets/js/admin-app.js'), true);

        wp_localize_script('modelora-admin-app', 'modeloraAdminData', [
            'restUrl' => esc_url_raw(rest_url('modelora/v1/')),
            'pluginUrl' => esc_url_raw(MODELORA_PLUGIN_URL),
            'nonce' => wp_create_nonce('wp_rest'),
            'maxUploadMb' => (int) (get_option('modelora_settings')['max_upload_mb'] ?? 50),
            'debug' => $this->is_debug_enabled(),
            'version' => MODELORA_VERSION,
            'presets' => [
                ['key' => 'studio', 'label' => 'Studio'],
                ['key' => 'outdoor', 'label' => 'Outdoor'],
                ['key' => 'dark', 'label' => 'Dark'],
            ],
            'i18n' => [
                'uploadTitle' => __('Upload your 3D model', 'modelora-3d-product-viewer'),
                'largeFile' => __('Your file is too large. Click here to optimize.', 'modelora-3d-product-viewer'),
                'unsupported' => __('Unsupported format. Use GLB, GLTF, FBX, OBJ, STL, DAE, or USDZ.', 'modelora-3d-product-viewer'),
            ],
        ]);
    }

    public function block_editor(): void
    {
        if (! wp_script_is('modelora-model-viewer', 'registered')) {
            wp_register_script('modelora-model-viewer', MODELORA_PLUGIN_URL . 'assets/js/model-viewer-bootstrap.js', [], $this->asset_version('assets/js/model-viewer-bootstrap.js'), ['strategy' => 'defer']);
        }
        $this->add_model_viewer_globals();
        if (! wp_script_is('modelora-viewer', 'registered')) {
            wp_register_script('modelora-viewer', MODELORA_PLUGIN_URL . 'assets/js/viewer.js', ['modelora-model-viewer'], $this->asset_version('assets/js/viewer.js'), true);
        }
        if (! wp_style_is('modelora-viewer', 'registered')) {
            wp_register_style('modelora-viewer', MODELORA_PLUGIN_URL . 'assets/css/viewer.css', [], $this->asset_version('assets/css/viewer.css'));
        }
        
        wp_enqueue_script(
            'modelora-block-editor',
            MODELORA_PLUGIN_URL . 'assets/js/block-editor.js',
            ['wp-blocks', 'wp-element', 'wp-i18n', 'wp-components', 'wp-block-editor'],
            $this->asset_version('assets/js/block-editor.js'),
            true
        );
    }
}

