<?php
/**
 * FoodOrd: Scroll Categories Navigation (frontend)
 *
 * Adds a minimal, responsive scroll navigation for product categories
 * on pages that use either the [foodord_products] shortcode,
 * FoodOrd blocks, or WooCommerce product blocks.
 *
 * @package FoodOrd
 */

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

/**
 * Class Foodord_Scroll_Categories_Nav
 */
class Foodord_Scroll_Categories_Nav {
	/**
	 * Whether the navigation markup has already been rendered.
	 *
	 * @var bool
	 */
	private $has_rendered = false;
	/**
	 * Initialize hooks.
	 */
	public function init(): void {
		// Enqueue assets only when relevant content is present.
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );

		if ( $this->is_theme_active() ) {
			// When FoodOrd theme is active, rely on its custom hook.
			add_action( 'foodord_theme_after_header', array( $this, 'render_navigation' ), 25 );
		}
	}

	/**
	 * Inject scroll navigation markup into the main post content.
	 *
	 * This avoids relying on theme markup order (e.g. wp_body_open being before header)
	 * and keeps the navigation above the FoodOrd products output.
	 *
	 * @param string $content Post content HTML.
	 * @return string
	 */
	public function inject_into_content( $content ): string {
		if ( $this->has_rendered || is_admin() ) {
			return $content;
		}

		if ( ! is_singular() || ! in_the_loop() || ! is_main_query() ) {
			return $content;
		}

		if ( ! $this->should_enable() ) {
			return $content;
		}

		if ( false !== strpos( $content, 'foodord-scroll-nav' ) ) {
			return $content;
		}

		ob_start();
		$this->render_navigation();
		$nav = (string) ob_get_clean();
		if ( '' === trim( $nav ) ) {
			return $content;
		}

		return $nav . $content;
	}

	/**
	 * Determine if scroll navigation should be enabled on current request.
	 *
	 * @return bool
	 */
	public function should_enable(): bool {
		if ( is_admin() || wp_doing_ajax() ) {
			return false;
		}

		// Global enable/disable toggle from Tweaks settings.
		$enabled = get_option( 'foodord_enable_scroll_nav', 'yes' );
		if ( 'yes' !== $enabled ) {
			return false;
		}

		// Show if page uses [foodord_products] shortcode OR foodord/product(s) blocks OR card block.
		// This is now INDEPENDENT of banner visibility.
		global $post;
		if ( ! $post || ! is_object( $post ) ) {
			return false;
		}
		$content        = (string) $post->post_content;
		$should_display = false;

		if ( function_exists( 'has_shortcode' ) && has_shortcode( $content, 'foodord_products' ) ) {
			$should_display = true;
		}
		if ( function_exists( 'has_block' ) ) {
			if ( has_block( 'foodord/products', $content ) || has_block( 'foodord/card', $content ) ) {
				$should_display = true;
			}
		}

		// Check for WooCommerce blocks as well.
		if ( function_exists( 'has_block' ) ) {
			if ( has_block( 'woocommerce/products', $content ) || has_block( 'woocommerce/product-query', $content ) || has_block( 'woocommerce/handpicked-products', $content ) ) {
				$should_display = true;
			}
		}

		// Dynamic rendering flag (but not dependent on banner).
		if ( isset( $GLOBALS['foodord_scroll_nav_should_show'] ) && $GLOBALS['foodord_scroll_nav_should_show'] ) {
			$should_display = true;
		}

		if ( ! $should_display ) {
			return false;
		}

		$product_counts     = wp_count_posts( 'product' );
		$published_products = ( $product_counts && isset( $product_counts->publish ) ) ? (int) $product_counts->publish : 0;
		if ( $published_products <= 0 ) {
			return false;
		}

		return true;
	}

	/**
	 * Determine whether the FoodOrd theme is active.
	 *
	 * @return bool
	 */
	private function is_theme_active(): bool {
		return defined( 'FOODORD_THEME_ACTIVE' ) && FOODORD_THEME_ACTIVE;
	}

	/**
	 * Enqueue frontend assets when needed.
	 */
	public function enqueue_assets(): void {
		if ( ! $this->should_enable() ) {
			return;
		}

		self::enqueue_navigation_assets();
	}

	/**
	 * Enqueue frontend assets for rendered scroll navigation markup.
	 */
	public static function enqueue_navigation_assets(): void {
		// Enqueue shared frontend styles.
		if ( function_exists( 'foodord_enqueue_frontend_styles' ) ) {
			foodord_enqueue_frontend_styles();
		}

		wp_enqueue_script(
			'foodord-scroll-nav',
			FOODORD_URL . 'public/js/foodord-scroll-categories-nav.js',
			array(),
			FOODORD_VERSION,
			true
		);

		// Search module for filtering products within foodord-category-products.
		wp_enqueue_script(
			'foodord-swipe-dismiss',
			FOODORD_URL . 'public/js/foodord-swipe-dismiss.js',
			array(),
			FOODORD_VERSION,
			true
		);

		wp_enqueue_script(
			'foodord-scroll-nav-search',
			FOODORD_URL . 'public/js/foodord-scroll-nav-search.js',
			array( 'foodord-swipe-dismiss' ),
			FOODORD_VERSION,
			true
		);

		// Localized strings for accessibility and UI labels.
		wp_localize_script(
			'foodord-scroll-nav-search',
			__( 'FoodordScrollNavSearch', 'foodord' ),
			array(
				'placeholder'     => __( 'Search the menu…', 'foodord' ),
				'clearLabel'      => __( 'Clear search', 'foodord' ),
				'runSearchLabel'  => __( 'Search', 'foodord' ),
				'closeLabel'      => __( 'Close search', 'foodord' ),
				'noTitle'         => __( "That's not on the menu", 'foodord' ),
				'noDesc'          => __( 'Try something else?', 'foodord' ),
				'startTypingDesc' => __( 'Start typing to find products.', 'foodord' ),
				'backLabel'       => __( 'Back to menu', 'foodord' ),
			)
		);
	}

	/**
	 * Output the scroll navigation container after header (independent of banner).
	 */
	public function render_navigation(): void {
		if ( $this->has_rendered || ! $this->should_enable() ) {
			return;
		}

		$this->has_rendered = true;
		self::output_navigation_markup( 'theme' );
	}

	/**
	 * Build the scroll navigation markup.
	 *
	 * @param string $context Rendering context.
	 * @return string
	 */
	public static function get_navigation_markup( string $context = 'theme' ): string {
		ob_start();
		self::output_navigation_markup( $context );
		return (string) ob_get_clean();
	}

	/**
	 * Output the scroll navigation markup.
	 *
	 * @param string $context Rendering context.
	 */
	private static function output_navigation_markup( string $context ): void {
		$context = in_array( $context, array( 'theme', 'plugin' ), true ) ? $context : 'theme';
		$classes = array( 'foodord-scroll-nav', 'has-search' );

		if ( 'plugin' === $context ) {
			$classes[] = 'foodord-scroll-nav--plugin-only';
		}

		// Entries are populated via JS by inspecting the category sections present on the page.
		?>
		<div class="<?php echo esc_attr( implode( ' ', $classes ) ); ?>" role="navigation" aria-label="<?php echo esc_attr__( 'Product categories navigation', 'foodord' ); ?>" data-foodord-scroll-nav-context="<?php echo esc_attr( $context ); ?>">
			<div class="foodord-scroll-nav__inner">
				<div class="foodord-scroll-nav__menu-wrapper">
					<button class="foodord-scroll-nav__menu-btn" type="button" aria-label="<?php echo esc_attr__( 'Menu', 'foodord' ); ?>" aria-expanded="false" data-sheet-title="<?php echo esc_attr__( 'Menu', 'foodord' ); ?>" data-sheet-close="<?php echo esc_attr__( 'Close menu', 'foodord' ); ?>">
						<span class="foodord-scroll-nav__menu-icon">
							<span></span>
							<span></span>
							<span></span>
						</span>
					</button>
				</div>
				<span class="foodord-scroll-nav__active-bg" aria-hidden="true"></span>
				<ul class="foodord-scroll-nav__list" aria-live="polite" aria-busy="true"></ul>
				<span class="foodord-scroll-nav__indicator" aria-hidden="true"></span>

				<!-- Search: aligned to the far right -->
				<div class="foodord-scroll-nav__search" role="search">
					<label class="screen-reader-text" for="foodord-scroll-nav-search"><?php echo esc_html__( 'Search the menu', 'foodord' ); ?></label>
					<input type="text" id="foodord-scroll-nav-search" class="foodord-scroll-nav__search-input" placeholder="<?php echo esc_attr__( 'Search the menu…', 'foodord' ); ?>" autocomplete="off" inputmode="search" role="searchbox" />
					<button type="button" class="foodord-scroll-nav__clear-btn" aria-label="<?php echo esc_attr__( 'Clear search', 'foodord' ); ?>" hidden>&times;</button>
					<button type="button" class="foodord-scroll-nav__search-btn" aria-label="<?php echo esc_attr__( 'Search', 'foodord' ); ?>">
						<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><circle cx="11" cy="11" r="7" stroke="currentColor" stroke-width="2"></circle><line x1="20" y1="20" x2="16.65" y2="16.65" stroke="currentColor" stroke-width="2" stroke-linecap="round"></line></svg>
					</button>
				</div>
			</div>
		</div>
		<?php
	}
}
