<?php

defined('ABSPATH') || exit;

$is_static = dracula_get_settings('colorType') === 'static';
$is_active = dracula_get_settings('frontendDarkMode', true) && !dracula_page_excluded();
$is_active_tax = dracula_get_settings('frontendDarkMode', true) && !dracula_taxonomy_excluded();

if (!$is_active || !$is_active_tax) {
    return;
}

$timeBasedMode = dracula_get_settings('timeBasedMode', false);
$timeBasedModeStart = dracula_get_settings('timeBasedModeStart', '19:00');
$timeBasedModeEnd = dracula_get_settings('timeBasedModeEnd', '07:00');

$config = dracula_get_config();

$is_default_mode = dracula_get_settings('defaultDarkMode', false);
$is_auto = dracula_get_settings('matchOsTheme', true);

$url_parameter = dracula_get_settings('urlParameter', false);

$color_mode = dracula_get_settings('colorMode', 'dynamic');
$preset_key = apply_filters( 'dracula_preset_key', dracula_get_settings('preset', 'dracula') );
$dark_to_light = dracula_get_settings('darkToLight');

$colors = [
    'bg' => '#181a1b',
    'text' => '#e8e6e3',
    'secondary_bg' => '#202324',
    'link' => '#6ea5d9',
    'link_hover' => '#88b9e3',
    'btn_bg' => '#3b6f99',
    'btn_text' => '#dcdcdc',
    'btn_text_hover' => '#f0f0f0',
    'btn_hover_bg' => '#325d80',
    'input_text' => '#e8e6e3',
    'input_bg' => '#1f2223',
    'input_placeholder' => '#8c8c8c',
    'border' => '#2d2d2d',
];

if ('presets' === $color_mode) {
    $preset = dracula_get_preset($preset_key);

    if ($preset) {
        $colors = array_merge($colors, $preset['colors']);
    }

    if ($is_static && $dark_to_light) {
        $colors = apply_filters('dark_to_light_colors', $colors);
    }
} else if ('custom' === $color_mode) {
    $colors = apply_filters('custom_preset_colors', $colors);
}

?>

<!-- Colors Variable -->
<?php if ($is_static || 'custom' == $color_mode) { ?>
    <style id="dracula-color-css">
        <?php

        $css_mapping = [
            '--dracula-bg-color' => 'bg',
            '--dracula-secondary-bg-color' => 'secondary_bg',
            '--dracula-text-color' => 'text',
            '--dracula-link-color' => 'link',
            '--dracula-link-hover-color' => 'link_hover',
            '--dracula-btn-bg-color' => 'btn_bg',
            '--dracula-btn-text-color' => 'btn_text',
            '--dracula-btn-hover-bg-color' => 'btn_hover_bg',
            '--dracula-btn-text-hover-color' => 'btn_text_hover',
            '--dracula-input-placeholder-color' => 'input_placeholder',
            '--dracula-input-text-color' => 'input_text',
            '--dracula-input-bg-color' => 'input_bg',
            '--dracula-border-color' => 'border',
        ];

        echo ":root {\n";

        foreach ($css_mapping as $var => $key) {
            $value = isset($colors[$key]) && '' !== $colors[$key] ? $colors[$key] : '';
            // Use esc_attr() for values and esc_html() for the var name to be conservative.
            echo "    " . esc_html($var) . ": " . esc_attr($value) . ";\n";
        }

        echo "}\n";

        ?>
    </style>
<?php } ?>

<?php

// Toggle size css
$toggle_size = dracula_get_settings('toggleSize', 'normal');
$toggle_scale = 1;
if (in_array($toggle_size, ['small', 'large'])) {
    $toggle_scale = 'small' == $toggle_size ? '.8' : '1.2';
}

if( 'custom' === $toggle_size ){
    $toggle_scale = apply_filters('dracula_toggle_scale', $toggle_scale);
}

// Menu toggle size css
$menu_toggle_scale = '1';
$menu_toggle_size = dracula_get_settings('menuToggleSize', 'normal');

if (in_array($menu_toggle_size, ['small', 'large'])) {
    $menu_toggle_scale = 'small' == $menu_toggle_size ? '.8' : '1.2';
}

// Menu toggle size css
if ('custom' == $menu_toggle_size) {
    $menu_toggle_scale = apply_filters('dracula_menu_toggle_scale', $menu_toggle_scale);
}

?>
<style id="dracula-inline-css" class="dracula-inline-css">
    <?php

    $absolute_toggle_selector = '.dracula-toggle-wrap.position-absolute';

    if (isset($toggle_scale)) {
        echo sprintf(':not(.menu-item) > .dracula-toggle-wrap .dracula-toggle{ --toggle-scale: %s; }', esc_attr($toggle_scale));
    }

    if (isset($menu_toggle_scale)) {
        echo sprintf('.menu-item-type-dracula-dark-mode-switch .dracula-toggle{ --toggle-scale: %s; }', esc_attr($menu_toggle_scale));
    }

    // Toggle absolute position css
    do_action('dracula_toggle_absolute_position');

    // Toggle custom position css
    do_action('dracula_toggle_custom_position');

    // Font size css
    do_action('dracula_change_font_size');
    
    ?>
</style>
<?php


// Scrollbar CSS
$scrollbar_dark_mode = dracula_get_settings('scrollbarDarkMode', 'auto');

if ('auto' == $scrollbar_dark_mode || 'custom' == $scrollbar_dark_mode) {

    $track_color = dracula_color_brightness($colors['secondary_bg'], 10);
    $thumb_color = dracula_color_brightness($colors['secondary_bg'], 30);

    if ('custom' == $scrollbar_dark_mode) {
        $custom_colors = apply_filters(
            'dracula_custom_scrollbar_colors',
            [],
            $track_color,
            $thumb_color
        );

        if (isset($custom_colors['track'])) {
            $track_color = $custom_colors['track'];
        }

        if (isset($custom_colors['thumb'])) {
            $thumb_color = $custom_colors['thumb'];
        }
    }

?>
    <style id="dracula-scrollbar-css">
        html,
        * {
            scrollbar-width: thin;

            &[data-dracula-scheme="dark"] {
                scrollbar-color: <?php echo esc_attr($thumb_color); ?> <?php echo esc_attr($track_color); ?>;
            }
        }
    </style>
<?php } ?>

<script>
    const isPerformanceMode = <?php echo wp_json_encode(apply_filters('dracula_performance_mode', dracula_get_settings('performanceMode', false))); ?>;

    const isStatic = <?php echo wp_json_encode($is_static); ?>;
    const isDefaultMode = <?php echo wp_json_encode($is_default_mode); ?>;
    const isAuto = <?php echo wp_json_encode($is_auto); ?>;
    const isTimeBasedMode = <?php echo wp_json_encode($timeBasedMode); ?>;
    const timeBasedModeStart = <?php echo wp_json_encode($timeBasedModeStart); ?>;
    const timeBasedModeEnd = <?php echo wp_json_encode($timeBasedModeEnd); ?>;
    const urlParameterEnabled = <?php echo wp_json_encode($url_parameter); ?>;

    const draculaConfig = <?php echo wp_json_encode($config); ?>;

    function initDraculaDarkMode() {
        const draculaDarkMode = window.draculaDarkMode;

        if (isDefaultMode) {
            window.draculaMode = 'dark';
        }

        const savedMode = localStorage.getItem('dracula_mode');

        if (savedMode) {
            window.draculaMode = savedMode;
        }

        if ('dark' === window.draculaMode) {
            draculaDarkMode?.enable(draculaConfig);
        } else if ('auto' === savedMode || (isAuto && !savedMode)) {
            draculaDarkMode?.auto(draculaConfig);
        }

        // Time based mode
        <?php do_action('dracula_time_based_mode'); ?>

        // URL Parameter
        <?php do_action('dracula_url_parameter'); ?>

        if (draculaDarkMode?.isEnabled()) {
            jQuery(document).ready(function() {
                // Change toggle text
                const toggleTextElements = document.querySelectorAll('.toggle-prefix-text');
                toggleTextElements.forEach(el => {
                    el.textContent = "Dark Mode";
                });

                // Send dark mode page view analytics event
                if (dracula.isPro && dracula.settings.enableAnalytics) {
                    wp.ajax.post('dracula_track_analytics', {
                        type: 'dark_view'
                    });
                }
            });
        } else {
            const toggleTextElements = document.querySelectorAll('.toggle-prefix-text');
            toggleTextElements.forEach(el => {
                el.textContent = "Light Mode";
            });
        }
    }

    if (isPerformanceMode) {
        <?php do_action('dracula_performance_mode_init'); ?>
    } else {
        initDraculaDarkMode();
    }
</script>