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

if ( ! class_exists( 'Sifency_Frontend_Offcanvas' ) ) {

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

			add_action( 'wp_footer', [ $this, 'render_offcanvas' ], 10 );
			add_action( 'wp_footer', [ $this, 'offcanvas_scripts' ], 20 );
		}

		/**
		 * Render Elementor Offcanvas template
		 */
		public function render_offcanvas() {
			static $rendered = false;
			if ( $rendered ) return;
			$rendered = true;

			$offcanvas_id = Sifency_Frontend_Helper::find_matching_template( 'offcanvas' );
			if ( ! $offcanvas_id ) return;

			echo '<!-- Sifency Offcanvas Start -->';
			echo '<div id="sifency-offcanvas-wrapper" class="sifency-offcanvas-wrapper">';
				echo '<div class="sifency-offcanvas-overlay" data-sifency-offcanvas="close"></div>';
				echo '<div class="sifency-offcanvas-panel">';
					echo '<button class="sifency-offcanvas-close-btn" data-sifency-offcanvas="close" aria-label="Close">×</button>';
					echo '<div class="sifency-offcanvas-content">';
						echo wp_kses_post ( Sifency_Frontend_Helper::render_elementor_content( $offcanvas_id, true ) );
					echo '</div>';
				echo '</div>';
			echo '</div>';
			echo '<!-- Sifency Offcanvas End -->';
		}

		/**
		 * JS and CSS
		 */
		public function offcanvas_scripts() {
			?>
			<style>
				#sifency-offcanvas-wrapper {
				position: fixed;
				inset: 0;
				z-index: 99999;
				visibility: hidden;
				pointer-events: none;
				}
				#sifency-offcanvas-wrapper.sifency-open {
				visibility: visible;
				pointer-events: auto;
				}
				body.sifency-offcanvas-active {
				overflow: hidden;
				}
			</style>

			<script>
				document.addEventListener('DOMContentLoaded', function () {
					const wrapper = document.getElementById('sifency-offcanvas-wrapper');
					if (!wrapper) return;
					const openOffcanvas = () => {
						wrapper.classList.add('sifency-open');
						document.body.classList.add('sifency-offcanvas-active');
					};
					const closeOffcanvas = () => {
						wrapper.classList.remove('sifency-open');
						document.body.classList.remove('sifency-offcanvas-active');
					};
					document.body.addEventListener('click', function(e) {
						const trigger = e.target.closest('[data-sifency-offcanvas="open"]');
						if (trigger) {
							e.preventDefault();
							openOffcanvas();
						}
					});
					wrapper.addEventListener('click', function(e) {
						if ( e.target.closest('[data-sifency-offcanvas="close"]') ) {
							e.preventDefault();
							closeOffcanvas();
						}
					});
					document.addEventListener('keydown', function(e) {
						if (e.key === 'Escape' && wrapper.classList.contains('sifency-open')) {
							closeOffcanvas();
						}
					});
				});
			</script>
			<?php
		}
	}
	new Sifency_Frontend_Offcanvas();
}