<?php
if ( ! defined( 'ABSPATH' ) ) exit;

if ( ! class_exists( 'Sifency_Frontend_Scrollup' ) ) {

	class Sifency_Frontend_Scrollup {

		public function __construct() {
			if ( is_admin() ) return;

			// Render scroll-up once
			add_action( 'wp_footer', [ $this, 'render_scrollup' ], 10 );

			// Add JS once
			add_action( 'wp_footer', [ $this, 'scrollup_js' ], 20 );
		}

		/**
		 * Render Elementor Scroll-Up template
		 */
		public function render_scrollup() {
			static $rendered = false;
			if ( $rendered ) return;
			$rendered = true;

			$scrollup_id = Sifency_Frontend_Helper::find_matching_template( 'scrollup' );
			if ( ! $scrollup_id ) return;

			echo '<!-- Sifency Custom Scroll-Up Start -->';
			echo '<div id="sifency-scrollup-wrapper" class="sifency-scrollup-wrapper">';
			echo wp_kses_post( Sifency_Frontend_Helper::render_elementor_content( $scrollup_id, true ) );
			echo '</div>';
			echo '<!-- Sifency Custom Scroll-Up End -->';
		}

		/**
		 * JS for scroll-up button
		 */
		public function scrollup_js() {
			static $js_added = false;
			if ( $js_added ) return;
			$js_added = true;
			?>
			<script>
			(function(){
				const scrollBtn = document.querySelector('#sifency-scrollup-wrapper');
				if(!scrollBtn) return;

				// Hide by default
				scrollBtn.style.display = 'none';
				scrollBtn.style.position = 'fixed';
				scrollBtn.style.bottom = '40px';
				scrollBtn.style.right = '40px';
				scrollBtn.style.cursor = 'pointer';
				scrollBtn.style.zIndex = '9999';

				// Show on scroll
				window.addEventListener('scroll', () => {
					scrollBtn.style.display = (window.scrollY > 200) ? 'block' : 'none';
				});

				// Scroll to top
				scrollBtn.addEventListener('click', () => {
					window.scrollTo({ top: 0, behavior: 'smooth' });
				});
			})();
			</script>
			<?php
		}
	}

	new Sifency_Frontend_Scrollup();
}
