import 'dart:async';

import 'package:app_links/app_links.dart';
import 'package:flutter/foundation.dart';

class DeepLinkData {
  final String route;
  final String? id;

  DeepLinkData({required this.route, this.id});
}

class DeepLinkService {
  final AppLinks _appLinks = AppLinks();
  final StreamController<DeepLinkData> _linkController =
      StreamController<DeepLinkData>.broadcast();

  Stream<DeepLinkData> get links => _linkController.stream;

  Future<void> init() async {
    // Handle initial link (app opened via link)
    try {
      final initialUri = await _appLinks.getInitialLink();
      if (initialUri != null) {
        _handleUri(initialUri);
      }
    } catch (e) {
      debugPrint('[DeepLink] No initial link: $e');
    }

    // Handle subsequent links (app already running)
    _appLinks.uriLinkStream.listen(
      _handleUri,
      onError: (e) => debugPrint('[DeepLink] Stream error: $e'),
    );
  }

  void _handleUri(Uri uri) {
    // Handle el3ab://match/abc123 or https://el3ab-player.../match/abc123
    final segments = uri.pathSegments;
    if (segments.isEmpty) return;

    final route = segments.first;
    final id = segments.length > 1 ? segments[1] : null;

    _linkController.add(DeepLinkData(route: route, id: id));
  }

  void dispose() {
    _linkController.close();
  }
}
