<?php

namespace ProudNerds\Assets;

use ProudNerds\Core\ViteLoader;
use ProudNerds\Trait\Initializable;

/**
 * Load assets using Vite.
 */
class Vite
{
    use Initializable;

    private function __construct()
    {
        // Initialize Vite
        add_action('init', [$this, 'initVite']);

        add_theme_support('align-wide');
        add_theme_support('editor-styles');

        add_action('wp_enqueue_scripts', [$this, 'enqueueScripts']);
        add_action('admin_enqueue_scripts', [$this, 'adminEnqueueScripts']);
        add_action('admin_init', [$this, 'adminInit']);
        add_action('enqueue_block_editor_assets', [$this, 'enqueueBlockEditorAssets']);
    }

    /**
     * Initialize Vite.
     */
    public function initVite(): void
    {
        ViteLoader::enqueueModule();
    }

    /**
     * Enqueue front-end scripts and styles.
     *
     * @return void
     */
    public function enqueueScripts(): void
    {
        $this->enqueueStyle('pn-style', 'assets/scss/app.scss');
        $this->enqueueScript('pn-script', 'assets/js/app.js');
    }

    /**
     * Enqueue admin scripts and styles.
     */
    public function adminEnqueueScripts(): void
    {
        $this->enqueueStyle('pn-style', 'assets/scss/app-admin.scss');
        $this->enqueueScript('pn-script', 'assets/js/app-admin.js');
    }

    /**
     * Runs on admin init.
     */
    public function adminInit(): void
    {
        $this->addEditorStyle('assets/scss/app-gutenberg.scss');
        $this->addEditorStyle('assets/js/app-gutenberg.js');
    }

    /**
     * Enqueue block editor assets.
     */
    public function enqueueBlockEditorAssets(): void
    {
        $this->enqueueScript('pn-script-block-editor', 'assets/js/app-gutenberg.js');
    }

    /**
     * Update html script type to module wp hack.
     */
    private function scriptTypeModule(string $handle): void
    {
        ViteLoader::scriptTypeModule($handle);
    }

    /**
     * Add editor style.
     *
     * @param string $file
     */
    private function addEditorStyle(string $file): void
    {
        add_editor_style(ViteLoader::asset($file, true));
    }

    /**
     * Enqueue style.
     *
     * @param string $handle
     * @param string $file
     */
    private function enqueueStyle(string $handle, string $file): void
    {
        wp_enqueue_style($handle, ViteLoader::asset($file), [], null, 'screen');
    }

    /**
     * Enqueue script. Also set type to module if needed.
     *
     * @param string $handle
     * @param string $file
     */
    private function enqueueScript(string $handle, string $file): void
    {
        wp_enqueue_script($handle, ViteLoader::asset($file), ['jquery'], null, false);
        $this->scriptTypeModule($handle);
    }
}
