import 'package:flutter/material.dart';
import '../telemetry/telemetry_service.dart';

/// 路由遥测观察者
///
/// 挂载到 GoRouter.observers，自动追踪所有页面访问。
/// 无需在每个页面手动调用 logPageView()。
class TelemetryRouteObserver extends NavigatorObserver {
  static const _pageNames = {
    '/': 'splash',
    '/login': 'login',
    '/register': 'register',
    '/forgot-password': 'forgot_password',
    '/change-password': 'change_password',
    '/trade-password': 'trade_password',
    '/contribution': 'contribution',
    '/trading': 'trading',
    '/asset': 'asset',
    '/profile': 'profile',
    '/edit-profile': 'edit_profile',
    '/mining-records': 'mining_records',
    '/batch-mining-records': 'batch_mining_records',
    '/contribution-records': 'contribution_records',
    '/planting-records': 'planting_records',
    '/send-shares': 'send_shares',
    '/receive-shares': 'receive_shares',
    '/c2c-market': 'c2c_market',
    '/c2c-publish': 'c2c_publish',
    '/c2c-order-detail': 'c2c_order_detail',
    '/my-team': 'my_team',
    '/trading-records': 'trading_records',
    '/transfer-records': 'transfer_records',
    '/p2p-transfer-records': 'p2p_transfer_records',
    '/notifications': 'notifications',
    '/help-center': 'help_center',
    '/about': 'about',
  };

  void _log(Route? route) {
    if (route == null) return;
    final name = route.settings.name;
    if (name == null || name.isEmpty) return;
    final path = name.split('?').first;
    final pageName = _pageNames[path] ?? path.replaceAll('/', '').replaceAll('-', '_');
    TelemetryService().logPageView(pageName);
  }

  @override
  void didPush(Route route, Route? previousRoute) {
    super.didPush(route, previousRoute);
    _log(route);
  }

  @override
  void didReplace({Route? newRoute, Route? oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    _log(newRoute);
  }
}
