<?php

/**
 * Scroll Top Feature
 *
 * @package Blynex
 */

if (! defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

// Set up scroll top hooks based on settings
add_action('wp', 'blynex_scroll_top_init');

/**
 * Initialize scroll to top feature based on theme settings
 */
function blynex_scroll_top_init()
{
    // Get site settings
    $scroll_top_enabled = get_option('blynex_scroll_top', false);

    // Only enable the feature if the option is set to true
    if ($scroll_top_enabled) {
        add_action('wp_enqueue_scripts', 'blynex_scroll_top_assets', 20);
        add_action('wp_footer', 'blynex_render_scroll_top');
    }
}

/**
 * Enqueue Scroll Top CSS and JS.
 */
function blynex_scroll_top_assets()
{
    $version = wp_get_theme()->get('Version');

    // Register a dummy script handle to attach inline JS
    wp_register_script('blynex-scroll-top', '', array(), $version, true);
    wp_enqueue_script('blynex-scroll-top');

    // Inline JS for smooth scroll and show/hide
    $inline_js = "(function(){
        function docReady(fn) {
            if (document.readyState === 'complete' || document.readyState === 'interactive') {
                setTimeout(fn, 1);
            } else {
                document.addEventListener('DOMContentLoaded', fn);
            }
        }
        docReady(function() {
            var scrollTopBtn = document.querySelector('.blynex-scroll-top');
            if (! scrollTopBtn) return;
            scrollTopBtn.addEventListener('click', function() {
                window.scrollTo({top: 0, behavior: 'smooth'});
            });
        });

        window.addEventListener('scroll', function() {
            var scrollTopBtn = document.querySelector('.blynex-scroll-top');
            if (! scrollTopBtn) return;
            scrollTopBtn.style.transform = window.scrollY >= 100 ? 'scale(1)' : 'scale(0)';
        }, true);
    })();";
    wp_add_inline_script('blynex-scroll-top', $inline_js);

    // Inline CSS for button styling and animation (uses Blynex presets)
    $css  = ".blynex-scroll-top{display:flex;align-items:center;justify-content:center;position:fixed;right:var(--wp--preset--spacing--30);bottom:var(--wp--preset--spacing--30);width:var(--wp--preset--spacing--40);height:var(--wp--preset--spacing--40);background-color:var(--wp--preset--color--contrast);border-radius:50%;cursor:pointer;transform:scale(0);transition:.2s;z-index:9999;}";
    $css .= ".blynex-scroll-top svg path{stroke:var(--wp--preset--color--base);fill:none;}";
    wp_add_inline_style('blynex-style', $css);
}

/**
 * Render Scroll Top Button markup.
 */
function blynex_render_scroll_top()
{
    echo '<div class="blynex-scroll-top" aria-label="' . esc_attr__('Scroll to top', 'blynex') . '">';
    echo '<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">';
    echo '<path d="M18 15L12 9L6 15" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>';
    echo '</svg>';
    echo '</div>';
}
