<?php

/*
 * This file is part of the Fancy Bricks package.
 *
 * (c) Joshua Gugun Siagian <suabahasa@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
declare (strict_types=1);
namespace Fancy\Animations\Core;

use Fancy\Animations\Utils\Asset;
use _FancyAnimations\FANCY_ANIMATIONS;
class Runtime
{
    public function __construct()
    {
        new \Fancy\Animations\Core\Bricks();
        new \Fancy\Animations\Core\Cache();
        \add_action('wp_head', fn() => $this->script_disable_front_by_cookie(), 1000001);
        \add_action('wp_enqueue_scripts', fn() => $this->enqueue_front_css_cache(), 1000001);
        \add_action('wp_enqueue_scripts', fn() => $this->enqueue_bricks_editor_assets(), 1000001);
    }
    private function enqueue_bricks_editor_assets()
    {
        if (\bricks_is_builder_main()) {
            Asset::enqueue_entry('builder-editor', ['builder-editor.js' => ['bricks-builder']], \true);
        }
        if (\bricks_is_builder_iframe()) {
            Asset::enqueue_entry('builder-iframe', ['builder-iframe.js' => ['bricks-builder']], \true);
            // inline style
            $inline_style = \Fancy\Animations\Core\Cache::composeCustomCss();
            \wp_add_inline_style('fancy_animations:builder-iframe.css', $inline_style);
        }
    }
    private function enqueue_front_css_cache()
    {
        if (\bricks_is_builder_main()) {
            return;
        }
        $isDisabledByCookie = isset($_COOKIE['fancy-animations-disable']) && $_COOKIE['fancy-animations-disable'] === 'true';
        if ($isDisabledByCookie && !\bricks_is_builder_iframe()) {
            return;
        }
        $options = \json_decode(\get_option(FANCY_ANIMATIONS::WP_OPTION . '_options', \json_encode((object) FANCY_ANIMATIONS::DEFAULT_SETTINGS, \JSON_THROW_ON_ERROR)), null, 512, \JSON_THROW_ON_ERROR);
        $options = \apply_filters('f!fancy/animations/api/admin/setting:index', $options);
        \wp_enqueue_script('fancy-animations:frontend-observer', \plugins_url('build/frontend/observer.js', FANCY_ANIMATIONS::FILE), [], FANCY_ANIMATIONS::VERSION, ['in_footer' => \true]);
        // add inline script before the `fancy-animations:frontend-observer` script
        \wp_add_inline_script('fancy-animations:frontend-observer', \sprintf("fba_execute_once = %d;", (int) \property_exists($options, 'execute_once') && $options->execute_once === \true), 'before');
        if (\bricks_is_builder_iframe()) {
            return;
        }
        if ($isDisabledByCookie) {
            return;
        }
        if (\file_exists(\Fancy\Animations\Core\Cache::get_cache_path(\Fancy\Animations\Core\Cache::CSS_CACHE_FILE))) {
            $handle = FANCY_ANIMATIONS::WP_OPTION . '-cache';
            $version = (string) \filemtime(\Fancy\Animations\Core\Cache::get_cache_path(\Fancy\Animations\Core\Cache::CSS_CACHE_FILE));
            \wp_enqueue_style($handle, \Fancy\Animations\Core\Cache::get_cache_url(\Fancy\Animations\Core\Cache::CSS_CACHE_FILE), [], $version);
        }
    }
    private function script_disable_front_by_cookie()
    {
        if (\bricks_is_builder_main() || \bricks_is_builder_iframe()) {
            return;
        }
        echo <<<HTML
    <script>
        /*! js-cookie v3.0.5 | MIT */
        !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self,function(){var n=e.Cookies,o=e.Cookies=t();o.noConflict=function(){return e.Cookies=n,o}}())}(this,(function(){"use strict";function e(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)e[o]=n[o]}return e}var t=function t(n,o){function r(t,r,i){if("undefined"!=typeof document){"number"==typeof(i=e({},o,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),t=encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var c="";for(var u in i)i[u]&&(c+="; "+u,!0!==i[u]&&(c+="="+i[u].split(";")[0]));return document.cookie=t+"="+n.write(r,t)+c}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var t=document.cookie?document.cookie.split("; "):[],o={},r=0;r<t.length;r++){var i=t[r].split("="),c=i.slice(1).join("=");try{var u=decodeURIComponent(i[0]);if(o[u]=n.read(c,u),e===u)break}catch(e){}}return e?o[e]:o}},remove:function(t,n){r(t,"",e({},n,{expires:-1}))},withAttributes:function(n){return t(this.converter,e({},this.attributes,n))},withConverter:function(n){return t(e({},this.converter,n),this.attributes)}},{attributes:{value:Object.freeze(o)},converter:{value:Object.freeze(n)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});return t}));

        const fbaCookieName = 'fancy-animations-disable';

        function fba_is_deactivated() {
            return Cookies.get(fbaCookieName) !== undefined;
        }

        function fba_toggle_deactivation(refresh = true) {
            if (fba_is_deactivated()) {
                Cookies.remove(fbaCookieName);
            } else {
                Cookies.set(fbaCookieName, 'true', { expires: 365 });
            }

            if (refresh) {
                window.location.reload();
            }
        }

        document.addEventListener('DOMContentLoaded', function () {
            const wrapper = document.querySelectorAll('.fb-disable-animations');
            wrapper.forEach(function (item) {
                const reloadPage = item.getAttribute('data-fba-reload-page') === '1';

                const button = item.querySelector('.fb-disable-animations__btn');

                button.addEventListener('click', function () {
                    fba_toggle_deactivation(reloadPage);
                });

                button.setAttribute('aria-checked', String(!fba_is_deactivated()));
                button.setAttribute('aria-label', item.getAttribute('data-fba-aria-label'));
            });
        });
    </script>
HTML;
    }
}
