<?php

namespace Repetito\Web;

// If this file is called directly, abort.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Repetito\Traits\Singleton;
use Repetito\Traits\FileSystem;
use const Repetito\NAME;
use const Repetito\FILE;
use const Repetito\VERSION;

class Shortcodes {
	use FileSystem;
	use Singleton;

	/**
	 * It takes an array of shortcode tags, and for each tag, it adds a shortcode callback that calls the `scripts` and
	 * `render` methods
	 *
	 * @param array $tags An array of shortcode tags.
	 */
	protected function __construct( array $tags ) {
		$files = $this->filesystem();
		foreach ( $tags as $tag ) {
			switch ($tag) {
				case 'repetito':
					add_shortcode(
						$tag,
						static function () use ( $files, $tag ) {
							$handle = NAME . '-' . $tag;
								$style_path  = plugins_url( 'assets/website/dist/style.css', FILE );
								$script_path = plugins_url( 'assets/website/dist/' . $tag . '.js', FILE );
							wp_enqueue_style( $handle, $style_path, array(), VERSION );

							if ( ! wp_script_is( $handle, 'enqueued' ) ) {
								wp_enqueue_script( $handle, $script_path, array('jquery'), VERSION, true );

								wp_add_inline_script(
									$handle,
									'window.repetito = ' . wp_json_encode(
										array(
											'ajax_url' => admin_url( 'admin-ajax.php' ),
											'nonce'    => wp_create_nonce( NAME ),
										)
									),
									'before'
								);
							}

							wp_localize_script( $handle, $tag . '_l10n', array(
								'name'      => __( 'Repetito reusable returnable packaging', 'repetito' ),
								'desc'      => __( 'Help us reduce waste from online shopping.', 'repetito' ),
								'desc_long' => __( 'What is reusable returnable packaging?', 'repetito' ),
							) );

							add_filter(
								'script_loader_tag',
								function ( $tag, $id ) use ( $handle ) {
									if ( $handle === $id ) {
										$tag = str_replace( '<script ', '<script type="module" ', $tag );
									}

									return $tag;
								},
								10,
								3
							);
						}
					);
				}
		}
	}
}
