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

class UNODOCK_Frontend {

	private $settings;
	private $current_url;
	private $icons_flat;

	public function __construct() {
		add_action( 'wp_enqueue_scripts', array( $this, 'maybe_enqueue' ) );
		add_action( 'wp_footer', array( $this, 'render_bar' ) );
		add_filter( 'woocommerce_add_to_cart_fragments', array( $this, 'cart_count_fragment' ) );
	}

	private function get_settings() {
		if ( null === $this->settings ) {
			$this->settings = UNODOCK_Settings::get_settings();
		}
		return $this->settings;
	}

	/**
	 * Checks whether the bar should be shown on this page, for this user.
	 */
	private function should_display() {
		$s = $this->get_settings();
		$g = $s['general'];

		// Bar turned off entirely.
		if ( empty( $g['enabled'] ) ) {
			return false;
		}

		// No buttons, nothing to show.
		if ( empty( $s['buttons'] ) ) {
			return false;
		}

		// Visibility by user type (PRO only — free tier always shows to everyone,
		// even if a stale PRO value is still saved from an expired license).
		if ( udock_is_pro_functional() ) {
			if ( 'logged_in' === $g['visibility'] && ! is_user_logged_in() ) {
				return false;
			}
			if ( 'logged_out' === $g['visibility'] && is_user_logged_in() ) {
				return false;
			}
		}
		if ( ! empty( $g['hide_for_admins'] ) && current_user_can( 'manage_options' ) ) {
			return false;
		}

		// Visibility by page.
		if ( 'specific' === $g['show_on'] ) {
			if ( empty( $g['show_on_pages'] ) || ! is_page( $g['show_on_pages'] ) ) {
				return false;
			}
		} elseif ( 'exclude' === $g['show_on'] ) {
			if ( ! empty( $g['show_on_exclude_pages'] ) && is_page( $g['show_on_exclude_pages'] ) ) {
				return false;
			}
		}

		return true;
	}

	public function maybe_enqueue() {
		if ( ! $this->should_display() ) {
			return;
		}

		wp_enqueue_style(
			'udock-icons',
			UNODOCK_URL . 'assets/css/unodock-icons.css',
			array(),
			udock_asset_version( 'assets/css/unodock-icons.css' )
		);

		wp_enqueue_style(
			'udock-frontend',
			UNODOCK_URL . 'assets/css/frontend.css',
			array( 'udock-icons' ),
			udock_asset_version( 'assets/css/frontend.css' )
		);

		wp_enqueue_script(
			'udock-frontend',
			UNODOCK_URL . 'assets/js/frontend.js',
			array(),
			udock_asset_version( 'assets/js/frontend.js' ),
			true
		);

		$s = $this->get_settings();

		wp_localize_script( 'udock-frontend', 'UNODOCK_FRONT', array(
			'searchUrl'       => home_url( '/' ),
			'vibrateEnabled'  => ! empty( $s['general']['vibrate_enabled'] ) && udock_is_pro_functional(),
		) );
	}

	/**
	 * Resolves a button's final URL (manual URL or selected page). Not used for 'search' buttons.
	 */
	private function resolve_url( $btn ) {
		if ( 'page' === $btn['link_type'] && ! empty( $btn['page_id'] ) ) {
			$url = get_permalink( $btn['page_id'] );
			return $url ? $url : '#';
		}
		return ! empty( $btn['url'] ) ? $btn['url'] : '#';
	}

	/**
	 * The current page URL, computed once per request and reused for every
	 * button comparison instead of recalculating it in every loop iteration.
	 */
	private function get_current_url() {
		if ( null === $this->current_url ) {
			$this->current_url = untrailingslashit( strtok( home_url( add_query_arg( null, null ) ), '?' ) );
		}
		return $this->current_url;
	}

	/**
	 * Checks whether a button matches the current page (to mark it as active).
	 * Buttons with no real destination (empty URL, or the '#' placeholder used
	 * when a link hasn't been set yet) are never considered active.
	 */
	private function is_active( $btn, $resolved_url ) {
		if ( 'page' === $btn['link_type'] && ! empty( $btn['page_id'] ) ) {
			return is_page( $btn['page_id'] );
		}

		if ( empty( $resolved_url ) || '#' === $resolved_url ) {
			return false;
		}

		$target = untrailingslashit( strtok( $resolved_url, '?' ) );

		return $target && '#' !== $target && $this->get_current_url() && $target === $this->get_current_url();
	}

	/**
	 * Builds the inline CSS for a button's icon background (solid color or gradient, always filled).
	 */
	private function icon_bg_style( $btn ) {
		if ( empty( $btn['icon_bg_enabled'] ) ) {
			return '';
		}

		if ( 'gradient' === $btn['icon_bg_type'] ) {
			$gradient = 'linear-gradient(135deg,' . esc_attr( $btn['icon_bg_gradient_start'] ) . ',' . esc_attr( $btn['icon_bg_gradient_end'] ) . ')';
			return 'background:' . $gradient . ';';
		}

		return 'background:' . esc_attr( $btn['icon_bg_color'] ) . ';';
	}

	/**
	 * Renders the bar background CSS (solid color or gradient).
	 */
	private function bar_bg_style( $g ) {
		if ( 'gradient' === $g['bg_type'] ) {
			return 'linear-gradient(135deg,' . esc_attr( $g['bg_gradient_start'] ) . ',' . esc_attr( $g['bg_gradient_end'] ) . ')';
		}
		return esc_attr( $g['bg_color'] );
	}

	/**
	 * WooCommerce cart item count, if WooCommerce is active and the cart is available.
	 */
	private function cart_count() {
		if ( ! class_exists( 'WooCommerce' ) || ! function_exists( 'WC' ) || null === WC()->cart ) {
			return 0;
		}
		return WC()->cart->get_cart_contents_count();
	}

	/**
	 * Keeps the cart badge in sync with WooCommerce's AJAX cart fragments
	 * (updates instantly after an AJAX add-to-cart, without a page reload).
	 */
	public function cart_count_fragment( $fragments ) {
		$count = $this->cart_count();
		ob_start();
		?>
		<span class="udock-cart-count-badge"><?php echo $count > 0 ? esc_html( $count ) : ''; ?></span>
		<?php
		$fragments['.udock-cart-count-badge'] = ob_get_clean();
		return $fragments;
	}

	/**
	 * Falls back to the icon's own human-readable name (e.g. "Home", "Cart")
	 * when a button has no visible text set, so screen readers still
	 * announce something meaningful instead of nothing. The icon list is
	 * flattened once per request and reused for every button.
	 */
	private function icon_fallback_label( $icon ) {
		if ( null === $this->icons_flat ) {
			$this->icons_flat = UNODOCK_Icons::get_list();
		}
		return isset( $this->icons_flat[ $icon ] ) ? $this->icons_flat[ $icon ] : __( 'Menu item', 'unodock' );
	}

	public function render_bar() {
		if ( ! $this->should_display() ) {
			return;
		}

		$s = $this->get_settings();
		$g = $s['general'];

		$is_pro  = udock_is_pro_functional();
		$buttons = array_slice( $s['buttons'], 0, udock_max_buttons() );
		if ( empty( $buttons ) ) {
			return;
		}

		$sticky_class      = ! empty( $g['sticky'] ) ? 'udock-sticky' : 'udock-static';
		$safe_area_class   = ! empty( $g['safe_area'] ) ? 'udock-safe-area' : '';
		$top_radius_px     = $is_pro ? absint( $g['top_corner_radius'] ) * 2 : 0;
		$featured_scale    = $is_pro ? UNODOCK_Settings::featured_scale( $g['featured_size'] ) : 1.5;
		$underline_class   = empty( $g['underline_enabled'] ) ? ' udock-underline-off' : '';
		// If "Active icon color" is off, the active icon simply reuses the
		// regular icon color, so no visual change happens on active state.
		$icon_color_active = ! empty( $g['active_icon_enabled'] ) ? $g['icon_color_active'] : $g['icon_color'];

		$style_vars = sprintf(
			'--udock-bg:%s;--udock-icon:%s;--udock-icon-active:%s;--udock-text:%s;--udock-underline:%s;--udock-height:%dpx;--udock-icon-size:%dpx;--udock-font-size:%dpx;--udock-zindex:%d;--udock-top-radius:%dpx;--udock-featured-scale:%s;',
			$this->bar_bg_style( $g ),
			esc_attr( $g['icon_color'] ),
			esc_attr( $icon_color_active ),
			esc_attr( $g['text_color'] ),
			esc_attr( $g['underline_color'] ),
			absint( $g['bar_height'] ),
			absint( $g['icon_size'] ),
			absint( $g['font_size'] ),
			absint( $g['z_index'] ),
			$top_radius_px,
			esc_attr( $featured_scale )
		);

		echo '<nav class="udock-bottom-nav ' . esc_attr( $sticky_class . ' ' . $safe_area_class . $underline_class ) . '" style="' . esc_attr( $style_vars ) . '">';

		foreach ( $buttons as $index => $btn ) {
			// PRO only: featured (larger) button and click animations.
			$is_featured = $is_pro && ! empty( $g['featured_enabled'] ) && ( absint( $g['featured_button_number'] ) === $index + 1 );
			$animation   = $is_pro && isset( $btn['click_animation'] ) ? $btn['click_animation'] : 'none';

			$classes = 'udock-nav-item udock-label-' . esc_attr( $btn['label_position'] )
				. ( $is_featured ? ' udock-featured' : '' );

			$is_active = false;

			// Accessible label: falls back to the icon's name if no text was set,
			// so screen readers always announce something meaningful.
			$aria_label = ! empty( $btn['label'] ) ? $btn['label'] : $this->icon_fallback_label( $btn['icon'] );

			if ( 'search' === $btn['link_type'] ) {
				echo '<button type="button" class="' . esc_attr( $classes ) . '" data-udock-search-trigger="1" aria-label="' . esc_attr( $aria_label ) . '"';
				if ( 'none' !== $animation ) {
					echo ' data-udock-anim="' . esc_attr( $animation ) . '"';
				}
				echo '>';
			} else {
				$url       = $this->resolve_url( $btn );
				$is_active = $this->is_active( $btn, $url );
				$classes  .= $is_active ? ' udock-active' : '';
				echo '<a href="' . esc_url( $url ) . '" class="' . esc_attr( $classes ) . '" aria-label="' . esc_attr( $aria_label ) . '"';
				if ( $is_active ) {
					echo ' aria-current="page"';
				}
				if ( 'none' !== $animation ) {
					echo ' data-udock-anim="' . esc_attr( $animation ) . '"';
				}
				echo '>';
			}

			if ( ! empty( $btn['show_label'] ) && 'top' === $btn['label_position'] ) {
				echo '<span class="udock-nav-label">' . esc_html( $btn['label'] ) . '</span>';
			}

			$icon_wrap_class = 'udock-nav-icon-wrap';
			$icon_wrap_css   = '';

			if ( $is_featured ) {
				$icon_wrap_class .= ' udock-icon-featured';
			}

			if ( ! empty( $btn['icon_bg_enabled'] ) ) {
				$icon_wrap_class .= ' udock-icon-bg udock-icon-filled';
				$icon_wrap_css    = $this->icon_bg_style( $btn );
			}

			echo '<span class="' . esc_attr( trim( $icon_wrap_class ) ) . '"';
			if ( $icon_wrap_css ) {
				echo ' style="' . esc_attr( $icon_wrap_css ) . '"';
			}
			echo '>';
			echo '<i class="fa-solid ' . esc_attr( $btn['icon'] ) . '"></i>';

			if ( ! empty( $btn['show_cart_count'] ) && $is_pro && class_exists( 'WooCommerce' ) ) {
				$count = $this->cart_count();
				echo '<span class="udock-cart-count-badge">' . ( $count > 0 ? esc_html( $count ) : '' ) . '</span>';
			}

			echo '</span>';

			if ( ! empty( $btn['show_label'] ) && 'top' !== $btn['label_position'] ) {
				echo '<span class="udock-nav-label">' . esc_html( $btn['label'] ) . '</span>';
			}

			echo ( 'search' === $btn['link_type'] ) ? '</button>' : '</a>';
		}

		echo '</nav>';

		// Search overlay markup (shared, shown/hidden via JS).
		echo '<div class="udock-search-overlay" id="udock-search-overlay">';
		echo '<form class="udock-search-form" action="' . esc_url( home_url( '/' ) ) . '" method="get">';
		echo '<input type="search" name="s" class="udock-search-input" placeholder="' . esc_attr__( 'Search…', 'unodock' ) . '" />';
		echo '<button type="button" class="udock-search-close" aria-label="' . esc_attr__( 'Close', 'unodock' ) . '">&times;</button>';
		echo '</form>';
		echo '</div>';
	}
}
