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

/**
 * Yatoon App Shell (v3.5.0)
 *
 * Renders an independent left navigation rail + top bar on Yatoon admin
 * screens, replacing the default WordPress chrome there only. Inspired by
 * the "looks and feels like a SaaS app, not a WP submenu list" pattern
 * used by best-in-class booking products. Every link still points at the
 * existing admin.php?page=... URLs registered in YATOON_Admin::add_admin_menu,
 * so no routing/capability logic changes — this is presentation only.
 */
class YATOON_App_Shell {

	public function __construct() {
		add_filter( 'admin_body_class', array( $this, 'maybe_add_body_class' ) );
		add_action( 'in_admin_header', array( $this, 'render' ) );
	}

	public static function is_booking_admin_page() {
		$page_slug = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
		if ( '' === $page_slug ) {
			return false;
		}

		if ( strpos( $page_slug, 'sbs-' ) === 0 ) {
			return true;
		}

		$booking_slugs = array(
			'yatoon-booking-system',
			'yatoon-dashboard',
			'yatoon-calendar',
			'yatoon-clients',
			'yatoon-reports',
			'yatoon-automations',
			'yatoon-loyalty',
			'yatoon-broadcasts',
			'yatoon-packages',
			'yatoon-gift-cards',
			'yatoon-service-menu',
			'yatoon-catalog-settings',
			'yatoon-reviews',
			'yatoon-recurring',
			'yatoon-addons',
			'yatoon-form-fields',
			'yatoon-closed-dates',
			'yatoon-setup-wizard',
			'yatoon-ai-assistant',
			'yatoon-resources',
			'yatoon-service-menu',
			'yatoon-locations',
			'yatoon-orders',
			'yatoon-operations',
			'yatoon-import',
			'yatoon-migrate',
			'yatoon-performance',
			'yatoon-staff-locations',
			'yatoon-salon-operations',
			'yatoon-insights',
			'yatoon-feature-modules',
			'yatoon-group-sessions',
			'yatoon-growth-modules',
			'yatoon-deposit-pro',
			'yatoon-noshow-pro',
			'yatoon-waitlist-pro',
		);

		if ( in_array( $page_slug, $booking_slugs, true ) ) {
			return true;
		}

		if ( strpos( $page_slug, 'yatoon-booking-system-' ) === 0 ) {
			return true;
		}

		if ( strpos( $page_slug, 'yatoon_booking_system' ) === 0 ) {
			return true;
		}

		return false;
	}

	private function is_yatoon_screen() {
		if ( self::is_booking_admin_page() ) {
			return true;
		}

		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( ! $screen ) {
			return false;
		}
		return ( strpos( $screen->id, 'sbs-' ) !== false || strpos( $screen->id, 'yatoon-booking-system' ) !== false );
	}

	public function maybe_add_body_class( $classes ) {
		if ( $this->is_yatoon_screen() ) {
			$classes .= ' yatoon-app-shell-on';
		}
		return $classes;
	}

	/**
	 * Grouped nav structure. Kept in one place so the sidebar, the topbar
	 * search index, and (eventually) breadcrumbs all stay in sync.
	 */
	public static function get_nav_groups() {
		$is_pro = function_exists( 'ybs_is_pro' ) ? ybs_is_pro() : false;
		$people_items = array(
			array( 'slug' => 'yatoon-clients', 'label' => 'Clients', 'icon' => 'dashicons-groups' ),
			array( 'slug' => 'sbs-staff', 'label' => 'Staff', 'icon' => 'dashicons-businessperson' ),
			array( 'slug' => 'sbs-messages', 'label' => 'Messages', 'icon' => 'dashicons-email' ),
			array( 'slug' => 'yatoon-reviews', 'label' => 'Reviews', 'icon' => 'dashicons-star-filled' ),
		);
		$catalog_items = array(
			array( 'slug' => 'sbs-services', 'label' => 'Services', 'icon' => 'dashicons-tag' ),
			array( 'slug' => 'yatoon-resources', 'label' => 'Resources', 'icon' => 'dashicons-screenoptions' ),
			array( 'slug' => 'yatoon-catalog-settings', 'label' => 'Catalog', 'icon' => 'dashicons-format-gallery' ),
			array( 'slug' => 'yatoon-service-menu', 'label' => 'Service Menu', 'icon' => 'dashicons-list-view' ),
			array( 'slug' => 'yatoon-gift-cards', 'label' => 'Gift Cards', 'icon' => 'dashicons-tickets-alt' ),
		);
		$schedule_items = array(
			array( 'slug' => 'yatoon-calendar', 'label' => 'Calendar', 'icon' => 'dashicons-calendar' ),
			array( 'slug' => 'sbs-bookings', 'label' => 'Bookings', 'icon' => 'dashicons-calendar-alt' ),
			array( 'slug' => 'sbs-waitlist', 'label' => 'Waitlist', 'icon' => 'dashicons-clock' ),
			array( 'slug' => 'yatoon-recurring', 'label' => 'Recurring', 'icon' => 'dashicons-update' ),
			array( 'slug' => 'yatoon-closed-dates', 'label' => 'Closed Dates', 'icon' => 'dashicons-no-alt' ),
		);
		$growth_items = array(
			array( 'slug' => 'yatoon-reports', 'label' => 'Reports', 'icon' => 'dashicons-chart-bar' ),
			array( 'slug' => 'yatoon-growth-modules', 'label' => 'Growth Modules', 'icon' => 'dashicons-chart-line' ),
		);
		$advanced_items = array(
			array( 'slug' => 'yatoon-import', 'label' => 'Import & Migration', 'icon' => 'dashicons-migrate' ),
			array( 'slug' => 'yatoon-orders', 'label' => 'Orders & Invoices', 'icon' => 'dashicons-media-spreadsheet' ),
			array( 'slug' => 'yatoon-operations', 'label' => 'Operations', 'icon' => 'dashicons-clipboard' ),
			array( 'slug' => 'yatoon-performance', 'label' => 'Performance', 'icon' => 'dashicons-dashboard' ),
			array( 'slug' => 'sbs-blacklist', 'label' => 'Blacklist', 'icon' => 'dashicons-shield' ),
			array( 'slug' => 'sbs-sync-log', 'label' => 'Sync & Logs', 'icon' => 'dashicons-update-alt' ),
		);
		if ( get_option( 'yatoon_multi_location_enabled', '0' ) === '1' ) {
			array_unshift( $advanced_items, array( 'slug' => 'yatoon-locations', 'label' => 'Locations', 'icon' => 'dashicons-location-alt' ) );
		}
		$settings_items = array(
			array( 'slug' => 'yatoon-booking-system', 'label' => 'General', 'icon' => 'dashicons-admin-settings' ),
			array( 'slug' => 'yatoon-ai-assistant', 'label' => 'AI Assistant', 'icon' => 'dashicons-superhero-alt' ),
			array( 'slug' => 'sbs-brand', 'label' => 'Brand & Colors', 'icon' => 'dashicons-admin-customizer' ),
			array( 'slug' => 'sbs-notifications', 'label' => 'Notifications', 'icon' => 'dashicons-bell' ),
			array( 'slug' => 'yatoon-form-fields', 'label' => 'Form Fields', 'icon' => 'dashicons-feedback' ),
			array( 'slug' => 'yatoon-setup-wizard', 'label' => 'Setup Wizard', 'icon' => 'dashicons-controls-play' ),
		);
		$module_enabled = static function ( $module ) {
			return ! class_exists( 'YATOON_Feature_Modules' ) || YATOON_Feature_Modules::enabled( $module );
		};
		if ( ! $module_enabled( 'resources' ) ) { $catalog_items = array_values( array_filter( $catalog_items, static function ( $item ) { return 'yatoon-resources' !== $item['slug']; } ) ); }
		if ( ! $module_enabled( 'insights' ) ) { $growth_items = array_values( array_filter( $growth_items, static function ( $item ) { return 'yatoon-reports' !== $item['slug']; } ) ); $advanced_items = array_values( array_filter( $advanced_items, static function ( $item ) { return 'yatoon-performance' !== $item['slug']; } ) ); }
		if ( ! $module_enabled( 'ai' ) ) { $settings_items = array_values( array_filter( $settings_items, static function ( $item ) { return 'yatoon-ai-assistant' !== $item['slug']; } ) ); }
		if ( ! $module_enabled( 'data_tools' ) ) { $advanced_items = array_values( array_filter( $advanced_items, static function ( $item ) { return 'yatoon-import' !== $item['slug']; } ) ); }
		if ( ! $module_enabled( 'commerce' ) ) { $advanced_items = array_values( array_filter( $advanced_items, static function ( $item ) { return 'yatoon-orders' !== $item['slug']; } ) ); }
		if ( ! $module_enabled( 'operations' ) ) { $advanced_items = array_values( array_filter( $advanced_items, static function ( $item ) { return 'yatoon-operations' !== $item['slug']; } ) ); }
		if ( ! $module_enabled( 'notifications' ) ) { $settings_items = array_values( array_filter( $settings_items, static function ( $item ) { return 'sbs-notifications' !== $item['slug']; } ) ); }
		if ( $is_pro ) {
			$people_items[] = array( 'slug' => 'yatoon-loyalty', 'label' => 'Loyalty', 'icon' => 'dashicons-awards' );
			$catalog_items[] = array( 'slug' => 'yatoon-packages', 'label' => 'Packages', 'icon' => 'dashicons-archive' );
			$growth_items[] = array( 'slug' => 'yatoon-automations', 'label' => 'Automation', 'icon' => 'dashicons-networking' );
			$growth_items[] = array( 'slug' => 'yatoon-broadcasts', 'label' => 'Broadcasts', 'icon' => 'dashicons-megaphone' );
			$settings_items[] = array( 'slug' => 'sbs-sms-pro', 'label' => 'SMS & WhatsApp', 'icon' => 'dashicons-smartphone' );
			$settings_items[] = array( 'slug' => 'sbs-gcal-pro', 'label' => 'Google Calendar', 'icon' => 'dashicons-calendar' );
			$settings_items[] = array( 'slug' => 'yatoon-deposit-pro', 'label' => 'Deposits', 'icon' => 'dashicons-money-alt' );
			$settings_items[] = array( 'slug' => 'yatoon-noshow-pro', 'label' => 'No-show Rules', 'icon' => 'dashicons-dismiss' );
		} else {
			$growth_items[] = array( 'slug' => 'yatoon-addons', 'label' => 'Explore Pro', 'icon' => 'dashicons-star-filled' );
		}

		return array(
			array(
				'label' => 'Today',
				'items' => array(
					array( 'slug' => 'yatoon-dashboard', 'label' => 'Today', 'icon' => 'dashicons-admin-home' ),
				),
			),
			array( 'label' => 'Schedule', 'items' => $schedule_items ),
			array( 'label' => 'People', 'items' => $people_items ),
			array( 'label' => 'Catalog', 'items' => $catalog_items ),
			array( 'label' => 'Growth', 'items' => $growth_items ),
			array(
				'label' => 'Settings',
				'items' => $settings_items,
			),
			array( 'label' => 'Advanced', 'items' => $advanced_items ),
		);
	}

	public function render() {
		if ( ! $this->is_yatoon_screen() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Inline, guaranteed-to-apply critical CSS. This duplicates rules already
		// in yatoon-app-shell.css, but is printed directly in the page (not as a
		// separate enqueued file), so it can't be dropped by asset-combining,
		// minification, or aggressive caching plugins/CDNs. If the external
		// stylesheet fails to load for any reason, the shell still works.
		echo '<style id="yatoon-app-shell-critical-css">
			body.yatoon-app-shell-on #adminmenumain,
			body.yatoon-app-shell-on #adminmenuwrap,
			body.yatoon-app-shell-on #adminmenuback,
			body.yatoon-app-shell-on #wpadminbar,
			body.yatoon-app-shell-on #wpfooter,
			body.yatoon-app-shell-on #screen-meta-links,
			body.yatoon-app-shell-on #screen-meta { display: none !important; }
			body.yatoon-app-shell-on .update-nag,
			body.yatoon-app-shell-on .notice:not(.yatoon-keep-notice) {
				margin-left: 28px;
				margin-right: 28px;
				border-radius: 10px;
			}
			body.yatoon-app-shell-on .yatoon-app-nav-label {
				color: #475569 !important;
				font-size: 11.5px !important;
				font-weight: 800 !important;
				letter-spacing: .09em !important;
			}
			body.yatoon-app-shell-on .yatoon-app-nav-label:hover,
			body.yatoon-app-shell-on .yatoon-app-nav-label:focus-visible,
			body.yatoon-app-shell-on .yatoon-app-nav-group.has-active > .yatoon-app-nav-label {
				color: #334155 !important;
			}
			html.wp-toolbar { padding-top: 0 !important; }
		</style>';

		$current_page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
		if ( 'yatoon-migrate' === $current_page ) {
			$current_page = 'yatoon-import';
		}
		$groups       = self::get_nav_groups();
		$book_url     = get_option( 'yatoon_book_new_url', '' );
		if ( ! $book_url ) {
			$page_id = (int) get_option( 'yatoon_manage_booking_page_id', 0 );
			if ( $page_id ) {
				$book_url = get_permalink( $page_id );
			}
		}

		echo '<div class="yatoon-app-sidebar" id="yatoon-app-sidebar">';
		echo '<div class="yatoon-app-brand"><span class="dot"></span>' . esc_html( defined( 'YATOON_BRAND_NAME' ) ? YATOON_BRAND_NAME : 'Yatoon' ) . ' Booking</div>';
		echo '<nav class="yatoon-app-nav">';
		foreach ( $groups as $group ) {
			$group_active = false;
			foreach ( $group['items'] as $group_item ) {
				if ( $current_page === $group_item['slug'] ) {
					$group_active = true;
					break;
				}
			}
			echo '<div class="yatoon-app-nav-group' . ( $group_active ? ' has-active' : '' ) . '">';
			if ( ! empty( $group['label'] ) ) {
				echo '<button type="button" class="yatoon-app-nav-label" aria-expanded="true"><span>' . esc_html( $group['label'] ) . '</span><span class="dashicons dashicons-arrow-up-alt2" aria-hidden="true"></span></button>';
			}
			foreach ( $group['items'] as $item ) {
				$is_active = ( $current_page === $item['slug'] );
				$locked    = ! empty( $item['locked'] );
				$url       = admin_url( 'admin.php?page=' . $item['slug'] );
				printf(
					'<a href="%1$s" class="%2$s"><span class="dashicons %3$s"></span>%4$s%5$s</a>',
					esc_url( $url ),
					$is_active ? 'is-active' : ( $locked ? 'is-locked' : '' ),
					esc_attr( $item['icon'] ),
					esc_html( $item['label'] ),
					$locked ? '<span class="lock-badge">PRO</span>' : ''
				);
			}
			echo '</div>';
		}
		echo '</nav>';
		echo '<div class="yatoon-app-sidebar-footer">Yatoon Booking v' . esc_html( defined( 'YATOON_VERSION' ) ? YATOON_VERSION : '' ) . '</div>';
		echo '</div>';

		echo '<div class="yatoon-app-topbar">';
		echo '<button type="button" class="yatoon-app-menu-toggle" aria-label="Menu" aria-controls="yatoon-app-sidebar" aria-expanded="false"><span class="dashicons dashicons-menu"></span></button>';
		echo '<div class="yatoon-app-search">';
		echo '<span class="dashicons dashicons-search"></span>';
		echo '<input type="text" id="yatoon-app-search-input" placeholder="Search all Yatoon pages and settings... (press /)" autocomplete="off" />';
		echo '<div class="yatoon-app-search-results" id="yatoon-app-search-results"></div>';
		echo '</div>';
		echo '<div class="yatoon-app-topbar-spacer"></div>';
		printf(
			'<a class="yatoon-app-topbar-icon" href="%s" title="System notices"><span class="dashicons dashicons-warning"></span></a>',
			esc_url( admin_url( 'update-core.php' ) )
		);
		if ( $book_url ) {
			printf(
				'<a class="yatoon-app-quick-create" href="%s" target="_blank" rel="noreferrer"><span class="dashicons dashicons-plus-alt2"></span>New Booking</a>',
				esc_url( $book_url )
			);
		}
		printf(
			'<a class="yatoon-app-topbar-icon" href="%s" title="Sync Log"><span class="dashicons dashicons-update-alt"></span></a>',
			esc_url( admin_url( 'admin.php?page=sbs-sync-log' ) )
		);
		printf(
			'<a class="yatoon-app-topbar-icon" href="%s" title="Notifications"><span class="dashicons dashicons-bell"></span></a>',
			esc_url( admin_url( 'admin.php?page=sbs-notifications' ) )
		);
		printf(
			'<a class="yatoon-app-topbar-icon" href="%s" title="Back to WordPress Dashboard"><span class="dashicons dashicons-wordpress"></span></a>',
			esc_url( admin_url() )
		);
		printf(
			'<a class="yatoon-app-topbar-icon" href="%s" title="View Site" target="_blank" rel="noreferrer"><span class="dashicons dashicons-external"></span></a>',
			esc_url( home_url( '/' ) )
		);
		echo '</div>';
	}

	/**
	 * Complete admin-page and settings-section catalog. This intentionally
	 * includes registered Yatoon pages that are not always shown in the compact
	 * left rail, so topbar search remains a complete navigation tool.
	 */
	private static function get_admin_page_index() {
		$is_pro = function_exists( 'ybs_is_pro' ) && ybs_is_pro() && is_dir( YATOON_PLUGIN_DIR . 'includes/pro' );
		$pages = array(
			array( 'Launch Center', 'yatoon-dashboard', 'dashicons-admin-home', 'today home dashboard getting started launch 首页 控制台 启动中心' ),
			array( 'Bookings', 'sbs-bookings', 'dashicons-calendar-alt', 'appointments reservations schedule 预约 订单 预约记录' ),
			array( 'Calendar', 'yatoon-calendar', 'dashicons-calendar', 'schedule diary appointments 日历 排班' ),
			array( 'Clients', 'yatoon-clients', 'dashicons-groups', 'customers contacts crm 顾客 客户 联系人' ),
			array( 'Services', 'sbs-services', 'dashicons-tag', 'catalog treatments pricing duration 服务 项目 价格 时长' ),
			array( 'Staff', 'sbs-staff', 'dashicons-businessperson', 'employees team technicians assistants 员工 技师 团队' ),
			array( 'Reports', 'yatoon-reports', 'dashicons-chart-bar', 'analytics revenue performance export 报表 营收 分析' ),
			array( 'AI Assistant', 'yatoon-ai-assistant', 'dashicons-superhero-alt', 'artificial intelligence reply drafts service helper 人工智能 助手' ),
			array( 'Add-ons', 'yatoon-addons', 'dashicons-admin-plugins', 'extensions upgrade pro 扩展 插件' ),
			array( 'Brand & Colors', 'sbs-brand', 'dashicons-admin-customizer', 'logo theme design appearance typography 品牌 颜色 标志 外观' ),
			array( 'Messages', 'sbs-messages', 'dashicons-email', 'contact text us inbox messages 消息 联系 留言' ),
			array( 'Waitlist', 'sbs-waitlist', 'dashicons-clock', 'waiting list queue 候补 等候名单' ),
			array( 'Catalog & Gallery', 'yatoon-catalog-settings', 'dashicons-format-gallery', 'gallery categories service catalog images 目录 图库 分类' ),
			array( 'Service Menu', 'yatoon-service-menu', 'dashicons-list-view', 'menu shortcode service display 服务菜单 项目菜单' ),
			array( 'Gift Cards', 'yatoon-gift-cards', 'dashicons-tickets-alt', 'voucher balance gift certificate 礼品卡 储值卡' ),
			array( 'Packages', 'yatoon-packages', 'dashicons-archive', 'service bundles package 套餐 组合', true ),
			array( 'Reviews', 'yatoon-reviews', 'dashicons-star-filled', 'ratings feedback google review 评价 评分 反馈' ),
			array( 'Recurring Appointments', 'yatoon-recurring', 'dashicons-update', 'repeat series recurrence 重复预约 周期预约' ),
			array( 'Closed Dates', 'yatoon-closed-dates', 'dashicons-no-alt', 'holidays closure unavailable dates 休息日 关闭日期 节假日' ),
			array( 'Form Fields', 'yatoon-form-fields', 'dashicons-feedback', 'custom fields booking form intake 表单字段 自定义字段' ),
			array( 'Setup Wizard', 'yatoon-setup-wizard', 'dashicons-controls-play', 'onboarding setup install configuration 设置向导 安装向导' ),
			array( 'Notifications', 'sbs-notifications', 'dashicons-bell', 'email reminder review follow up alerts 通知 提醒 邮件' ),
			array( 'Sync & Logs', 'sbs-sync-log', 'dashicons-update-alt', 'synchronization log errors square sync 同步 日志 错误' ),
			array( 'Blacklist', 'sbs-blacklist', 'dashicons-shield', 'blocked customers phones email deny 黑名单 屏蔽' ),
			array( 'SMS Notifications', 'sbs-sms-pro', 'dashicons-smartphone', 'twilio text message sms 短信', true ),
			array( 'Google Calendar', 'sbs-gcal-pro', 'dashicons-calendar', 'calendar sync busy events 谷歌日历 日历同步', true ),
			array( 'Deposits & Prepay', 'yatoon-deposit-pro', 'dashicons-money-alt', 'payments stripe paypal square deposit refund 支付 押金 预付 退款', true ),
			array( 'No-show Tracking', 'yatoon-noshow-pro', 'dashicons-dismiss', 'missed appointment cancellation fee 爽约 未到店', true ),
			array( 'Waitlist Auto-notify', 'yatoon-waitlist-pro', 'dashicons-megaphone', 'waitlist automatic notification 候补自动通知', true ),
			array( 'Import & Migration', 'yatoon-import', 'dashicons-migrate', 'import export migration backup restore csv bookly amelia 导入 导出 迁移 备份 恢复' ),
			array( 'Locations', 'yatoon-locations', 'dashicons-location-alt', 'stores branches multi location 门店 分店 多门店' ),
			array( 'Staff Locations', 'yatoon-staff-locations', 'dashicons-location', 'employee location schedule price staff service 门店员工 员工门店' ),
			array( 'Performance', 'yatoon-performance', 'dashicons-dashboard', 'speed slow ajax requests profiling 性能 速度 慢查询' ),
			array( 'Compensation & Stock', 'yatoon-salon-operations', 'dashicons-money', 'commission payroll inventory stock compensation 佣金 工资 库存' ),
			array( 'Operations', 'yatoon-operations', 'dashicons-clipboard', 'health jobs recovery webhooks diagnostics snapshots 运维 健康检查 恢复 诊断' ),
			array( 'Insights & Reliability', 'yatoon-insights', 'dashicons-chart-line', 'audit reliability insights metrics 审计 洞察 可靠性' ),
			array( 'Resources', 'yatoon-resources', 'dashicons-screenoptions', 'rooms chairs equipment capacity 资源 房间 椅子 设备' ),
			array( 'Feature Modules', 'yatoon-feature-modules', 'dashicons-screenoptions', 'enable disable modules features 功能模块 开关' ),
			array( 'Group Sessions', 'yatoon-group-sessions', 'dashicons-groups', 'classes capacity attendees group appointments 团体预约 课程 容量' ),
			array( 'Growth Modules', 'yatoon-growth-modules', 'dashicons-chart-line', 'coupons memberships packages growth 优惠券 会员 套餐 增长' ),
			array( 'Orders & Invoices', 'yatoon-orders', 'dashicons-media-spreadsheet', 'commerce payments receipts invoices orders 发票 订单 收据' ),
			array( 'Automation', 'yatoon-automations', 'dashicons-networking', 'workflow triggers actions follow up 自动化 工作流', true ),
			array( 'Loyalty', 'yatoon-loyalty', 'dashicons-awards', 'points rewards retention 会员积分 忠诚度 奖励', true ),
			array( 'Broadcasts', 'yatoon-broadcasts', 'dashicons-megaphone', 'campaign bulk email sms marketing 群发 营销 活动', true ),
		);
		$index = array();
		$module_pages = array(
			'yatoon-reports'=>'insights', 'yatoon-performance'=>'insights', 'yatoon-insights'=>'insights', 'yatoon-salon-operations'=>'insights',
			'yatoon-ai-assistant'=>'ai', 'yatoon-import'=>'data_tools', 'yatoon-orders'=>'commerce', 'yatoon-operations'=>'operations',
			'yatoon-resources'=>'resources', 'yatoon-staff-locations'=>'staff_locations', 'yatoon-group-sessions'=>'group_appointments', 'sbs-notifications'=>'notifications',
		);
		foreach ( $pages as $page ) {
			if ( ! empty( $page[4] ) && ! $is_pro ) { continue;
            }
			$module_key = $module_pages[ $page[1] ] ?? '';
			$module_disabled = $module_key && class_exists( 'YATOON_Feature_Modules' ) && ! YATOON_Feature_Modules::enabled( $module_key );
			$label = $module_disabled ? sprintf( __( '%s — Enable feature', 'yatoon-booking-system' ), $page[0] ) : $page[0];
			$url = $module_disabled
				? admin_url( 'admin.php?page=yatoon-feature-modules#yatoon-module-' . $module_key )
				: admin_url( 'admin.php?page=' . $page[1] );
			$index[] = array(
				'label' => $label, 'url' => $url,
				'icon' => $page[2], 'keywords' => strtolower( $page[0] . ' ' . $page[1] . ' ' . $page[3] . ( $module_disabled ? ' disabled hidden enable feature module 已停用 隐藏 启用 功能模块' : '' ) ),
			);
		}

		$settings = array(
			array( 'General Settings', 'general', '', 'general settings business details currency timezone 常规设置 商家设置' ),
			array( 'Platform & Booking Setup', 'general', 'platform', 'square vagaro local platform connection api booking setup 平台 连接 预约设置' ),
			array( 'Rules & Policies', 'general', 'rules', 'booking rules cancellation policy consent lead time 规则 政策 取消 同意' ),
			array( 'Customer Portal & Messaging', 'general', 'portal', 'customer portal manage booking text us whatsapp link 客户门户 管理预约 消息' ),
			array( 'Payments Settings', 'general', 'deposit', 'payments tax invoice tips gifts coupons deposit 支付 税 发票 小费 押金' ),
			array( 'AI Assistant Setup', 'general', '', 'ai artificial intelligence connectors models assistant service helper 人工智能 助手 模型 连接器', false, 'yatoon-ai-settings' ),
			array( 'Business Hours', 'hours', '', 'opening closing breaks schedule hours 营业时间 休息时间' ),
			array( 'Email Settings', 'email', '', 'email confirmation reminder cancellation reschedule review 邮件 确认 提醒' ),
			array( 'SMS & WhatsApp', 'sms', '', 'sms twilio whatsapp meta cloud api messaging templates 短信 whatsapp 模板', true ),
			array( 'WhatsApp Cloud API', 'sms', '', 'whatsapp meta cloud api access token phone number id templates business messaging', true, 'yatoon-whatsapp-cloud-api' ),
			array( 'Google Calendar Settings', 'calendar', '', 'google calendar oauth two way busy sync 谷歌日历 同步' ),
			array( 'Integrations', 'integrations', '', 'woocommerce webhook zapier make n8n zoom google meet automation 集成 自动化 视频会议', true ),
			array( 'WooCommerce Checkout', 'integrations', '', 'woocommerce payment gateways checkout orders tax 支付 结账 订单', true ),
			array( 'Webhook Automation', 'integrations', '', 'webhook zapier make n8n hmac api automation 网络钩子 自动化', true ),
			array( 'Zoom Meetings', 'integrations', '', 'zoom virtual appointment video meeting 视频会议 在线预约', true ),
			array( 'Google Meet', 'integrations', '', 'google meet conference virtual appointment 谷歌会议 视频会议', true ),
			array( 'Brand & Colors Settings', 'colors', '', 'brand colors logo typography buttons 品牌 颜色 标志' ),
			array( 'Staff Settings', 'staff_crud', '', 'staff employee profile schedule 员工设置 员工资料' ),
		);
		foreach ( $settings as $setting ) {
			if ( ! empty( $setting[4] ) && ! $is_pro ) { continue;
            }
			$url = admin_url( 'admin.php?page=yatoon-booking-system&tab=' . $setting[1] );
			if ( '' !== $setting[2] ) { $url .= '&section=' . $setting[2];
            }
			if ( ! empty( $setting[5] ) ) { $url .= '#' . $setting[5];
            }
			$index[] = array( 'label' => $setting[0], 'url' => $url, 'icon' => 'dashicons-admin-settings', 'keywords' => strtolower( $setting[0] . ' ' . $setting[3] ) );
		}
		return $index;
	}

	/**
	 * Flat searchable index of every nav item, localized to JS for the
	 * topbar quick-search box.
	 */
	public static function get_search_index() {
		$index = array();
		foreach ( self::get_nav_groups() as $group ) {
			foreach ( $group['items'] as $item ) {
				$index[] = array(
					'label'    => $item['label'],
					'url'      => admin_url( 'admin.php?page=' . $item['slug'] ),
					'icon'     => $item['icon'],
					'keywords' => strtolower( $item['label'] . ' ' . $item['slug'] ),
				);
			}
		}
		$index = array_merge( $index, self::get_admin_page_index() );

		// Include every Yatoon submenu registered by core or an extension at
		// runtime. The static catalog above supplies rich aliases and hidden
		// pages; this loop makes newly registered menus searchable automatically.
		global $submenu;
		$runtime_is_pro = function_exists( 'ybs_is_pro' ) && ybs_is_pro() && is_dir( YATOON_PLUGIN_DIR . 'includes/pro' );
		$pro_only_slugs = array( 'yatoon-packages', 'sbs-sms-pro', 'sbs-gcal-pro', 'yatoon-deposit-pro', 'yatoon-noshow-pro', 'yatoon-waitlist-pro', 'yatoon-automations', 'yatoon-loyalty', 'yatoon-broadcasts' );
		foreach ( (array) $submenu as $entries ) {
			foreach ( (array) $entries as $entry ) {
				$slug = isset( $entry[2] ) ? (string) $entry[2] : '';
				if ( strpos( $slug, 'yatoon-' ) !== 0 && strpos( $slug, 'sbs-' ) !== 0 && 'yatoon-booking-system' !== $slug ) { continue;
                }
				if ( ! $runtime_is_pro && in_array( $slug, $pro_only_slugs, true ) ) { continue;
                }
				$capability = isset( $entry[1] ) ? (string) $entry[1] : 'manage_options';
				if ( function_exists( 'current_user_can' ) && ! current_user_can( $capability ) ) { continue;
                }
				$label = trim( wp_strip_all_tags( (string) ( $entry[0] ?? $slug ) ) );
				$index[] = array( 'label' => $label, 'url' => admin_url( 'admin.php?page=' . $slug ), 'icon' => 'dashicons-admin-generic', 'keywords' => strtolower( $label . ' ' . $slug ) );
			}
		}

		// Searchable feature shortcuts. These expose settings that live inside a
		// larger page and therefore cannot be discovered from the sidebar label
		// alone. Keep English names plus common Chinese terms used by merchants.
		$feature_index = array(
			array(
				'label'    => 'Complete Backup & Restore',
				'url'      => admin_url( 'admin.php?page=yatoon-import' ) . '#yatoon-complete-backup',
				'icon'     => 'dashicons-backup',
				'keywords' => 'backup restore complete backup full backup download backup upload backup recovery archive data portability export import migration snapshot 备份 恢复 完整备份 下载备份 上传备份 数据备份 数据恢复 迁移 快照',
			),
			array(
				'label'    => 'Any Staff assignment',
				'url'      => admin_url( 'admin.php?page=sbs-staff' ) . '#yatoon-any-staff-assignment',
				'icon'     => 'dashicons-randomize',
				'keywords' => 'any staff assignment employee allocation staff priority sort order round robin least loaded preferred random 任意员工 员工分配 自动分配 员工排序 优先级 轮询 最少负载 老客户偏好 随机',
			),
			array(
				'label'    => 'Staff Priority',
				'url'      => admin_url( 'admin.php?page=sbs-staff' ) . '#sbs-staff-table',
				'icon'     => 'dashicons-sort',
				'keywords' => 'staff priority employee order sort order team order 员工优先级 员工排序 排序顺序',
			),
			array(
				'label'    => 'Payment gateways',
				'url'      => admin_url( 'admin.php?page=yatoon-deposit-pro' ),
				'icon'     => 'dashicons-money-alt',
				'keywords' => 'payment gateway deposit prepay paypal stripe square checkout refund 支付网关 押金 预付款 贝宝 退款',
			),
			array(
				'label'    => 'Business Hours',
				'url'      => admin_url( 'admin.php?page=yatoon-booking-system&tab=hours' ),
				'icon'     => 'dashicons-clock',
				'keywords' => 'opening hours business hours schedule break closed 营业时间 工作时间 休息时间',
			),
			array(
				'label'    => 'Booking rules & policies',
				'url'      => admin_url( 'admin.php?page=yatoon-booking-system&tab=general&section=rules' ),
				'icon'     => 'dashicons-yes-alt',
				'keywords' => 'booking rules policy consent cancellation reschedule lead time notice 预约规则 政策 同意 取消 改期 提前预约',
			),
			array(
				'label'    => 'Database concurrency',
				'url'      => admin_url( 'admin.php?page=yatoon-booking-system&tab=general&section=platform' ) . '#yatoon-database-concurrency',
				'icon'     => 'dashicons-database',
				'keywords' => 'database concurrency single writer multi writer mysql slot guard 数据库 单写节点 多写节点 并发 防重复预约',
			),
		);

		if ( ! ( function_exists( 'ybs_is_pro' ) && ybs_is_pro() && is_dir( YATOON_PLUGIN_DIR . 'includes/pro' ) ) ) {
			$feature_index = array_values( array_filter( $feature_index, static function ( $feature ) {
				return 'Payment gateways' !== $feature['label'] && 'Any Staff assignment' !== $feature['label'];
			} ) );
		}

		return array_merge( $index, $feature_index );
	}
}
