<?php
namespace IcreatorCookieConsent;

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

class Frontend {
    public static function boot(): void {
        add_action('wp_enqueue_scripts', [self::class, 'assets']);
        add_action('wp_footer', [self::class, 'render_banner']);
        add_shortcode('consentpress_cookie_table', [self::class, 'shortcode_consentpress_cookie_table']);
    }

    public static function assets(): void {
        $translations = [
            'filterLabel' => __('Filter by Category:', 'consentpress'),
            'analytics'   => __('Analytics', 'consentpress'),
            'marketing'   => __('Marketing', 'consentpress'),
            'functional'  => __('Functional', 'consentpress'),
            'necessary'   => __('Necessary', 'consentpress'),
            'performance'   => __('Performance', 'consentpress'),
            'uncategorized'   => __('Uncategorized', 'consentpress'),
            'cookies'     => __('Cookies', 'consentpress'),
            'name'     => __('Name', 'consentpress'),
            'value'     => __('Value', 'consentpress'),
            'purpose'     => __('Purpose', 'consentpress'),
            'domain'     => __('Domain', 'consentpress'),
            'path'     => __('Path', 'consentpress'),
            'duration'     => __('Duration', 'consentpress'),
            'type'     => __('Type', 'consentpress'),
            'provider'     => __('Provider', 'consentpress'),
            'consent'     => __('Consent', 'consentpress'),
            'no_cookies'   => __('No cookies stored in this category.', 'consentpress'),
            'no_definitions_available' => __('No cookie definitions available.', 'consentpress')
        ];

        $accent = get_option('iccb_accent_color', '#000000');
        $custom_css = ":root { --iccb-accent: " . esc_attr($accent) . "; }";
       
        wp_enqueue_style('iccb-frontend', ICCB_ROOT_URL . 'assets/css/frontend.min.css', [], ICCB_VERSION);
        wp_enqueue_style('iccb-mobile-viewport', ICCB_ROOT_URL . 'assets/css/mobile-viewport.min.css', ['iccb-frontend'], ICCB_VERSION);
        wp_add_inline_style('iccb-mobile-viewport', $custom_css);

        wp_register_script('list-cookies-js',ICCB_ROOT_URL . 'assets/js/list-cookies.min.js', ['wp-i18n'], ICCB_VERSION, true);
        wp_enqueue_script('iccb-banner-core', ICCB_ROOT_URL . 'assets/js/banner.core.min.js', [], ICCB_VERSION, true);
        wp_enqueue_script('iccb-banner', ICCB_ROOT_URL . 'assets/js/banner.min.js', ['iccb-banner-core'], ICCB_VERSION, true);
        $tracking_script = self::tracking_script();
        if ($tracking_script !== '') {
            wp_add_inline_script('iccb-banner', $tracking_script, 'before');
        }
        wp_add_inline_script('iccb-banner', <<<'JS'
(function(){
    var root = document.documentElement;
    var queued = false;

    function setOffset() {
        queued = false;
        var vv = window.visualViewport;
        var bottom = 0;

        if (vv) {
            bottom = Math.max(0, Math.round(window.innerHeight - vv.height - vv.offsetTop));
        }

        root.style.setProperty('--iccb-visual-viewport-bottom', bottom + 'px');
    }

    function queueOffset() {
        if (queued) {
            return;
        }

        queued = true;
        window.requestAnimationFrame(setOffset);
    }

    setOffset();

    if (window.visualViewport) {
        window.visualViewport.addEventListener('resize', queueOffset);
        window.visualViewport.addEventListener('scroll', queueOffset);
    }

    window.addEventListener('resize', queueOffset);
    window.addEventListener('orientationchange', queueOffset);
    document.addEventListener('visibilitychange', queueOffset);
})();
JS
        );
        wp_localize_script('iccb-banner', 'ICCB_CONFIG', [
            'ajax_url'          => admin_url('admin-ajax.php'),
            'cookie_json_url'   => esc_url_raw(add_query_arg([
                'action' => 'iccb_cookie_definitions',
                'v' => time(),
            ], admin_url('admin-ajax.php'))),
            'default_categories'=> get_option('iccb_default_categories', []),
            'pixel_settings'    => wp_parse_args((array) get_option('iccb_pixel_settings', []), [
                'mode' => 'gtm_only',
                'gtm' => '',
                'facebook' => '',
                'linkedin' => '',
            ]),
            'user_id'           => get_current_user_id(),
            'debug' => false,
            'iccbTranslateI18n'  => $translations,
            'overlay_mode'     => 'none',
        ]);
        wp_localize_script('list-cookies-js', 'ICCB_COOKIE_LIST_I18N', $translations);
    }

    private static function tracking_script(): string {
        $pixels = wp_parse_args((array) get_option('iccb_pixel_settings', []), [
            'gtm' => '',
        ]);

        $gtm_id = trim((string) $pixels['gtm']);
        if ($gtm_id === '') {
            return '';
        }

        return sprintf(
            "window.dataLayer=window.dataLayer||[];\n" .
            "function gtag(){dataLayer.push(arguments);}\n" .
            "gtag('consent','default',{'ad_storage':'denied','ad_user_data':'denied','ad_personalization':'denied','analytics_storage':'denied','functionality_storage':'denied','security_storage':'granted'});\n" .
            "window.addEventListener('DOMContentLoaded',function(){(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.id='iccb-gtm';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','%s');});",
            esc_js($gtm_id)
        );
    }

    public static function render_banner(): void {
        $banner = new Banner();
        $banner->output();
    }

    public static function shortcode_consentpress_cookie_table(): string {
        wp_enqueue_script('list-cookies-js');
        ob_start();
        $defs = Ajax::get_cookie_definitions();
        View::render('frontend/cookie-table', ['definitions' => $defs]);
        return ob_get_clean();
    }
}
