import 'package:flutter_riverpod/flutter_riverpod.dart';

class TableContext {
  const TableContext({
    this.tableId,
    this.tableNumber,
    this.cafeSlug,
  });

  final String? tableId;
  final String? tableNumber;
  final String? cafeSlug;

  TableContext copyWith({
    String? tableId,
    String? tableNumber,
    String? cafeSlug,
  }) =>
      TableContext(
        tableId: tableId ?? this.tableId,
        tableNumber: tableNumber ?? this.tableNumber,
        cafeSlug: cafeSlug ?? this.cafeSlug,
      );
}

class TableContextNotifier extends StateNotifier<TableContext> {
  TableContextNotifier() : super(const TableContext());

  void setTable({
    required String tableId,
    required String tableNumber,
    required String cafeSlug,
  }) {
    state = TableContext(
      tableId: tableId,
      tableNumber: tableNumber,
      cafeSlug: cafeSlug,
    );
  }

  void clear() => state = const TableContext();
}

final tableContextProvider =
    StateNotifierProvider<TableContextNotifier, TableContext>((ref) => TableContextNotifier());

/// Extract QR code from full URL or raw token.
String? parseQrCode(String raw) {
  final trimmed = raw.trim();
  if (trimmed.isEmpty) return null;
  final uri = Uri.tryParse(trimmed);
  if (uri != null && uri.pathSegments.isNotEmpty) {
    return uri.pathSegments.last;
  }
  return trimmed;
}
