//#import <Foundation/Foundation.h>
//#import "MyReactNativeBridge.h"
//#import <UIKit/UIKit.h>
//#import <React/RCTBridgeModule.h>
//#import <React/RCTEventEmitter.h>
//#import "react_native_mytatva_rn_sdk-Swift.h"
//
//// ---------------- MyEventEmitterManager ----------------
//
//@implementation MyEventEmitterManager
//
//RCT_EXPORT_MODULE();
//
//- (NSArray<NSString *> *)supportedEvents {
//    return @[@"cgmDeviceEvent", @"cgmwatchdemoclicked", @"cgmWAsupportclicked", @"cgmstartconnectionlanding", @"cgmWAsupportproceedclicked", @"cgmstartconnectionjourneyclicked", @"cgmpermissionspagelanding", @"cgmpermissionsproceedclicked", @"cgmconnecttransmitterlanding", @"cgmtransmitterdetected", @"cgmtransmitterdetectionfailed", @"cgmtransmitterconnectionsuccessful", @"cgmretryconnecttransmitterclicked", @"cgmconnectsensorscanlanding", @"cgmsensorconnectionsuccessful", @"cgmsensorconnectionfailed", @"cgmretryconnectsensorclicked", @"cgmconnectsensorproceedclicked", @"cgmplacesensorlanding", @"cgmplacetransmitterlanding", @"cgmconnectioncompleteclicked"];
//}
//
//RCT_EXPORT_METHOD(emitEvent:(NSString *)message) {
//    [self sendEventWithName:@"cgmDeviceEvent" body:@{@"status": message}];
//}
//
//@end
//
//// ---------------- CgmTrackyLib ----------------
//
//UIViewController *globalAttachTransmitterVC = nil;
//
//@implementation CgmTrackyLib
//
//RCT_EXPORT_MODULE();
//
//- (NSArray<NSString *> *)supportedEvents {
//    return @[@"cgmDeviceEvent", @"cgmwatchdemoclicked", @"cgmWAsupportclicked", @"cgmstartconnectionlanding", @"cgmWAsupportproceedclicked", @"cgmstartconnectionjourneyclicked", @"cgmpermissionspagelanding", @"cgmpermissionsproceedclicked", @"cgmconnecttransmitterlanding", @"cgmtransmitterdetected", @"cgmtransmitterdetectionfailed", @"cgmtransmitterconnectionsuccessful", @"cgmretryconnecttransmitterclicked", @"cgmconnectsensorscanlanding", @"cgmsensorconnectionsuccessful", @"cgmsensorconnectionfailed", @"cgmretryconnectsensorclicked", @"cgmconnectsensorproceedclicked", @"cgmplacesensorlanding", @"cgmplacetransmitterlanding", @"cgmconnectioncompleteclicked"];
//}
//
//- (instancetype)init {
//    if (self = [super init]) {
//        for (NSString *eventName in [self supportedEvents]) {
//            [[NSNotificationCenter defaultCenter] addObserver:self
//                                                     selector:@selector(handleNotification:)
//                                                         name:eventName
//                                                       object:nil];
//        }
//    }
//    return self;
//}
//
//- (void)handleNotification:(NSNotification *)notification {
//    NSDictionary *userInfo = notification.userInfo ?: @{};
//    if ([[self supportedEvents] containsObject:notification.name]) {
//        [self sendEventWithName:notification.name body:userInfo];
//    }
//}
//
//- (void)observeTransmitterUnbindStatusInternal:(NSString *)token
//                                       response:(NSDictionary *)responseDict
//                                     completion:(void (^)(NSDictionary *response, NSError *error))completion {
//    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"authToken"];
//    [[NSUserDefaults standardUserDefaults] synchronize];
//
//    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseDict options:0 error:nil];
//    if (jsonData) {
//        [[NSUserDefaults standardUserDefaults] setObject:jsonData forKey:@"CGMStatusItem"];
//        [[NSUserDefaults standardUserDefaults] synchronize];
//    }
//
//    FinalViewModelManager *manager = [FinalViewModelManager shared];
//    [manager callForObserveTransmitterUnbindStatusWithCompletion:^(NSDictionary *response, NSError *error) {
//        if (completion) {
//            completion(response, error);
//        }
//    }];
//}
//
//- (void)dealloc {
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//}
//
//// ---------------- React Methods ----------------
//
//RCT_EXPORT_METHOD(startCgmTracky:(NSString *)token) {
//    NSLog(@"Received token: %@", token);
//
//    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"authToken"];
//    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isForReconnect"];
//    [[NSUserDefaults standardUserDefaults] synchronize];
//
//    dispatch_async(dispatch_get_main_queue(), ^{
//        UIWindow *keyWindow = [UIApplication sharedApplication].delegate.window;
//        UIViewController *rootVC = keyWindow.rootViewController;
//
//        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainCGM" bundle:nil];
//        UIViewController *nativeVC = [storyboard instantiateViewControllerWithIdentifier:@"StartConnectionViewController"];
//
//        if (nativeVC) {
//            UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:nativeVC];
//            navController.modalPresentationStyle = UIModalPresentationOverFullScreen;
//            [rootVC presentViewController:navController animated:YES completion:nil];
//        }
//    });
//}
//
//RCT_EXPORT_METHOD(reconnectCgmTracky:(NSString *)token) {
//    NSLog(@"Received token: %@", token);
//
//    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"authToken"];
//    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isForReconnect"];
//    [[NSUserDefaults standardUserDefaults] synchronize];
//
//    dispatch_async(dispatch_get_main_queue(), ^{
//        UIWindow *keyWindow = [UIApplication sharedApplication].delegate.window;
//        UIViewController *rootVC = keyWindow.rootViewController;
//
//        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainCGM" bundle:nil];
//        UIViewController *reconnectVC = [storyboard instantiateViewControllerWithIdentifier:@"StartConnectionViewController"];
//
//        reconnectVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
//        UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:reconnectVC];
//        navController.modalPresentationStyle = UIModalPresentationOverFullScreen;
//
//        if (reconnectVC) {
//            [rootVC presentViewController:navController animated:YES completion:nil];
//        }
//    });
//}
//
//RCT_EXPORT_METHOD(openHelpSupport) {
//    dispatch_async(dispatch_get_main_queue(), ^{
//        UIWindow *keyWindow = [UIApplication sharedApplication].delegate.window;
//        UIViewController *rootVC = keyWindow.rootViewController;
//
//        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainCGM" bundle:nil];
//        UIViewController *chatWithExpertVC = [storyboard instantiateViewControllerWithIdentifier:@"ChatWithExpertViewController"];
//
//        if ([chatWithExpertVC respondsToSelector:@selector(setIsOnlyThis:)]) {
//            [chatWithExpertVC setValue:@(YES) forKey:@"isOnlyThis"];
//        }
//
//        chatWithExpertVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
//        if (chatWithExpertVC) {
//            [rootVC presentViewController:chatWithExpertVC animated:YES completion:nil];
//        }
//    });
//}
//
//RCT_EXPORT_METHOD(observeAllGlucoseData:(NSString *)token) {
//    NSLog(@"Received token: %@", token);
//    FinalViewModelManager *manager = [FinalViewModelManager shared];
//    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"authToken"];
//    [[NSUserDefaults standardUserDefaults] synchronize];
//
//    dispatch_async(dispatch_get_main_queue(), ^{
//        UIWindow *keyWindow = [UIApplication sharedApplication].delegate.window;
//        UIViewController *rootVC = keyWindow.rootViewController;
//
//        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainCGM" bundle:nil];
//        globalAttachTransmitterVC = [storyboard instantiateViewControllerWithIdentifier:@"AttachTransmitterViewController"];
//    });
//}
//
//RCT_EXPORT_METHOD(observeTransmitterUnbindStatus:(NSString *)token
//                  response:(NSString *)responseJsonString
//                  resolver:(RCTPromiseResolveBlock)resolve
//                  rejecter:(RCTPromiseRejectBlock)reject) {
//    if (responseJsonString == nil || ![responseJsonString isKindOfClass:[NSString class]]) {
//        NSError *error = [NSError errorWithDomain:@"CgmTrackyLib"
//                                             code:1001
//                                         userInfo:@{NSLocalizedDescriptionKey: @"Invalid or nil JSON string passed from JS"}];
//        reject(@"invalid_params", @"Response JSON string is nil or invalid", error);
//        return;
//    }
//
//    NSData *data = [responseJsonString dataUsingEncoding:NSUTF8StringEncoding];
//    NSError *parseError = nil;
//    NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
//
//    if (parseError || ![responseDict isKindOfClass:[NSDictionary class]]) {
//        reject(@"json_parse_error", @"Failed to parse JSON string to dictionary", parseError);
//        return;
//    }
//
//    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"authToken"];
//    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"CGMStatusItem"];
//    [[NSUserDefaults standardUserDefaults] synchronize];
//
//    FinalViewModelManager *manager = [FinalViewModelManager shared];
//    [manager callForObserveTransmitterUnbindStatusWithCompletion:^(NSDictionary *response, NSError *error) {
//        if (error) {
//            reject([NSString stringWithFormat:@"%ld", (long)error.code], error.localizedDescription, error);
//        } else {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                resolve(response ?: @{});
//            });
//        }
//    }];
//}
//
//@end

#import <Foundation/Foundation.h>
#import "MyReactNativeBridge.h"
#import <UIKit/UIKit.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
#import "react_native_mytatva_rn_sdk-Swift.h"
#import "KLTDatabaseHandler.h"
#import "KLTRunLog.h"
#import "KLTAppDelegate.h"

@implementation MyEventEmitterManager

RCT_EXPORT_MODULE();

// Define the supported events
- (NSArray<NSString *> *)supportedEvents {
       return @[@"cgmDeviceEvent", @"cgmwatchdemoclicked", @"cgmWAsupportclicked", @"cgmstartconnectionlanding", @"cgmWAsupportproceedclicked", @"cgmstartconnectionjourneyclicked", @"cgmpermissionspagelanding", @"cgmpermissionsproceedclicked", @"cgmconnecttransmitterlanding", @"cgmtransmitterdetected", @"cgmtransmitterdetectionfailed", @"cgmtransmitterconnectionsuccessful", @"cgmretryconnecttransmitterclicked", @"cgmconnectsensorscanlanding", @"cgmsensorconnectionsuccessful", @"cgmsensorconnectionfailed", @"cgmretryconnectsensorclicked", @"cgmconnectsensorproceedclicked", @"cgmplacesensorlanding", @"cgmplacetransmitterlanding", @"cgmconnectioncompleteclicked"];
}

// Example method to emit an event from native to JS
RCT_EXPORT_METHOD(emitEvent:(NSString *)message) {
  // Send an event with the name "EventName" and a message payload
  [self sendEventWithName:@"cgmDeviceEvent" body:@{@"status": message}];
}

@end
UIViewController *globalAttachTransmitterVC = nil;

@implementation CgmTrackyLib

RCT_EXPORT_MODULE();

// This method returns the list of events the module supports
- (NSArray<NSString *> *)supportedEvents
{
    return @[@"cgmDeviceEvent", @"cgmwatchdemoclicked", @"cgmWAsupportclicked", @"cgmstartconnectionlanding", @"cgmWAsupportproceedclicked", @"cgmstartconnectionjourneyclicked", @"cgmpermissionspagelanding", @"cgmpermissionsproceedclicked", @"cgmconnecttransmitterlanding", @"cgmtransmitterdetected", @"cgmtransmitterdetectionfailed", @"cgmtransmitterconnectionsuccessful", @"cgmretryconnecttransmitterclicked", @"cgmconnectsensorscanlanding", @"cgmsensorconnectionsuccessful", @"cgmsensorconnectionfailed", @"cgmretryconnectsensorclicked", @"cgmconnectsensorproceedclicked", @"cgmplacesensorlanding", @"cgmplacetransmitterlanding", @"cgmconnectioncompleteclicked"];
}

// Start listening for notifications
- (instancetype)init
{
    if (self = [super init]) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmDeviceEvent"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmwatchdemoclicked"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmWAsupportclicked"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmstartconnectionlanding"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmWAsupportproceedclicked"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmstartconnectionjourneyclicked"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmpermissionspagelanding"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmpermissionsproceedclicked"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmconnecttransmitterlanding"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmtransmitterdetected"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmtransmitterdetectionfailed"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmtransmitterconnectionsuccessful"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmretryconnecttransmitterclicked"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmconnectsensorscanlanding"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmsensorconnectionsuccessful"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmsensorconnectionfailed"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmretryconnectsensorclicked"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmconnectsensorproceedclicked"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmplacesensorlanding"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmplacetransmitterlanding"
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleNotification:)
                                                     name:@"cgmconnectioncompleteclicked"
                                                   object:nil];
    }
    return self;
}



// Handle the incoming notification and emit the event to React Native
//- (void)handleNotification:(NSNotification *)notification
//{
//  // Extract data from the notification
//  NSDictionary *userInfo = notification.userInfo;
//  
//  // Send the data to React Native via event emitter
//    [self sendEventWithName:@"cgmDeviceEvent" body:@{@"status": @"WARM_PERIOD_STARTED"}];
//}


- (void)handleNotification:(NSNotification *)notification
{
    NSString *name = notification.name;

    if ([name isEqualToString:@"cgmDeviceEvent"]) {
        [self sendEventWithName:@"cgmDeviceEvent" body:@{@"status": @"WARM_PERIOD_STARTED"}];
    }
    else if ([name isEqualToString:@"cgmwatchdemoclicked"]) {
        [self sendEventWithName:@"cgmwatchdemoclicked" body:@{@"status": @"cgm_watch_demo_clicked"}];
    }
    else if ([name isEqualToString:@"cgmWAsupportclicked"]) {
        [self sendEventWithName:@"cgmWAsupportclicked" body:@{@"status": @"cgm_wa_support_clicked"}];
    }
    else if ([name isEqualToString:@"cgmstartconnectionlanding"]) {
        [self sendEventWithName:@"cgmstartconnectionlanding" body:@{@"status": @"cgm_start_connection_landing"}];
    }
    else if ([name isEqualToString:@"cgmWAsupportproceedclicked"]) {
        [self sendEventWithName:@"cgmWAsupportproceedclicked" body:@{@"status": @"cgm_wa_support_proceed_clicked"}];
    }
    else if ([name isEqualToString:@"cgmstartconnectionjourneyclicked"]) {
        [self sendEventWithName:@"cgmstartconnectionjourneyclicked" body:@{@"status": @"cgm_start_connection_journey_clicked"}];
    }
    else if ([name isEqualToString:@"cgmpermissionspagelanding"]) {
        [self sendEventWithName:@"cgmpermissionspagelanding" body:@{@"status": @"cgm_permissions_page_landing"}];
    }
    else if ([name isEqualToString:@"cgmpermissionsproceedclicked"]) {
        [self sendEventWithName:@"cgmpermissionsproceedclicked" body:@{@"status": @"cgm_permissions_proceed_clicked"}];
    }
    else if ([name isEqualToString:@"cgmconnecttransmitterlanding"]) {
        [self sendEventWithName:@"cgmconnecttransmitterlanding" body:@{@"status": @"cgm_connect_transmitter_landing"}];
    }
    else if ([name isEqualToString:@"cgmtransmitterdetected"]) {
        [self sendEventWithName:@"cgmtransmitterdetected" body:@{@"status": @"cgm_transmitter_detected"}];
    }
    else if ([name isEqualToString:@"cgmtransmitterdetectionfailed"]) {
        [self sendEventWithName:@"cgmtransmitterdetectionfailed" body:@{@"status": @"cgm_transmitter_detection_failed"}];
    }
    else if ([name isEqualToString:@"cgmtransmitterconnectionsuccessful"]) {
        [self sendEventWithName:@"cgmtransmitterconnectionsuccessful" body:@{@"status": @"cgm_transmitter_connection_successful"}];
    }
    else if ([name isEqualToString:@"cgmretryconnecttransmitterclicked"]) {
        [self sendEventWithName:@"cgmretryconnecttransmitterclicked" body:@{@"status": @"cgm_retry_connect_transmitter_clicked"}];
    }
    else if ([name isEqualToString:@"cgmconnectsensorscanlanding"]) {
        [self sendEventWithName:@"cgmconnectsensorscanlanding" body:@{@"status": @"cgm_connect_sensor_scan_landing"}];
    }
    else if ([name isEqualToString:@"cgmsensorconnectionsuccessful"]) {
        [self sendEventWithName:@"cgmsensorconnectionsuccessful" body:@{@"status": @"cgm_sensor_connection_successful"}];
    }
    else if ([name isEqualToString:@"cgmsensorconnectionfailed"]) {
        [self sendEventWithName:@"cgmsensorconnectionfailed" body:@{@"status": @"cgm_sensor_connection_failed"}];
    }
    else if ([name isEqualToString:@"cgmretryconnectsensorclicked"]) {
        [self sendEventWithName:@"cgmretryconnectsensorclicked" body:@{@"status": @"cgm_retry_connect_sensor_clicked"}];
    }
    else if ([name isEqualToString:@"cgmconnectsensorproceedclicked"]) {
        [self sendEventWithName:@"cgmconnectsensorproceedclicked" body:@{@"status": @"cgm_connect_sensor_proceed_clicked"}];
    }
    else if ([name isEqualToString:@"cgmplacesensorlanding"]) {
        [self sendEventWithName:@"cgmplacesensorlanding" body:@{@"status": @"cgm_place_sensor_landing"}];
    }
    else if ([name isEqualToString:@"cgmplacetransmitterlanding"]) {
        [self sendEventWithName:@"cgmplacetransmitterlanding" body:@{@"status": @"cgm_place_transmitter_landing"}];
    }
    else if ([name isEqualToString:@"cgmconnectioncompleteclicked"]) {
        [self sendEventWithName:@"cgmconnectioncompleteclicked" body:@{@"status": @"cgm_connection_complete_clicked"}];
    }
}


// Clean up the observer when the module is deallocated
- (void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}


RCT_EXPORT_METHOD(startCgmTracky:(NSString *)token  envType:(NSString *)envType  userData:(NSDictionary *)userData)
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:token forKey:@"authToken"];
    [defaults setBool:false forKey:@"isForReconnect"];
    [defaults setObject:envType forKey:@"envType"];
    
    // Extract and store lastConnectCgm from userData
    NSString *lastConnectCgm = @"";
    if (userData != nil) {
        NSDictionary *patientMetaInfo = userData[@"patient_meta_info"];
        if (patientMetaInfo != nil && [patientMetaInfo isKindOfClass:[NSDictionary class]]) {
            NSString *rawValue = patientMetaInfo[@"last_connect_cgm"];
            if (rawValue != nil && [rawValue isKindOfClass:[NSString class]]) {
                lastConnectCgm = rawValue;
            }
        }
    }
    [defaults setObject:lastConnectCgm forKey:@"lastConnectCgm"];
    
    [defaults synchronize];

  dispatch_async(dispatch_get_main_queue(), ^{
    UIWindow *keyWindow = [UIApplication sharedApplication].delegate.window;
    UIViewController *rootVC = keyWindow.rootViewController;
    
    // Try to get the topmost navigation controller
  
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainCGM" bundle:nil];
    UIViewController *nativeVC = [storyboard instantiateViewControllerWithIdentifier:@"StartConnectionViewController"];
    
 
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:nativeVC];
    navController.modalPresentationStyle = UIModalPresentationOverFullScreen;
      if (nativeVC) {
          [rootVC presentViewController:navController animated:YES completion:nil];
      }
  });
}


RCT_EXPORT_METHOD(reconnectCgmTracky:(NSString *)token  envType:(NSString *)envType  userData:(NSDictionary *)userData) {
    NSLog(@"Received token: %@", token);
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:token forKey:@"authToken"];
    [defaults setBool:YES forKey:@"isForReconnect"];
    [defaults setObject:envType forKey:@"envType"];
    
    // Extract and store lastConnectCgm from userData
    NSString *lastConnectCgm = @"";
    if (userData != nil) {
        NSDictionary *patientMetaInfo = userData[@"patient_meta_info"];
        if (patientMetaInfo != nil && [patientMetaInfo isKindOfClass:[NSDictionary class]]) {
            NSString *rawValue = patientMetaInfo[@"last_connect_cgm"];
            if (rawValue != nil && [rawValue isKindOfClass:[NSString class]]) {
                lastConnectCgm = rawValue;
            }
        }
    }
    [defaults setObject:lastConnectCgm forKey:@"lastConnectCgm"];
    
    [defaults synchronize];

    dispatch_async(dispatch_get_main_queue(), ^{
        UIWindow *keyWindow = [UIApplication sharedApplication].delegate.window;
        UIViewController *rootVC = keyWindow.rootViewController;

        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainCGM" bundle:nil];
        UIViewController *reconnectVC = [storyboard instantiateViewControllerWithIdentifier:@"StartConnectionViewController"];

        reconnectVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
        UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:reconnectVC];
        navController.modalPresentationStyle = UIModalPresentationOverFullScreen;

        if (reconnectVC) {
            [rootVC presentViewController:navController animated:YES completion:nil];
        }
    });
}

RCT_REMAP_METHOD(getTrackLibDbPath,
                 getTrackLibDbPathWithResolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject)
{
  @try {
    NSArray<NSURL *> *urls = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
    NSURL *documentsURL = [urls lastObject];
    NSURL *storeURL = [documentsURL URLByAppendingPathComponent:@"KaiLiTe.sqlite"];
    if (storeURL.path.length > 0) {
      resolve(storeURL.path);
    } else {
      reject(@"ERROR_DB_PATH", @"Failed to construct DB path", nil);
    }
  } @catch (NSException *exception) {
    NSError *error = [NSError errorWithDomain:@"com.mytatvarnsdk" code:500 userInfo:@{NSLocalizedDescriptionKey: exception.reason ?: @"Unknown error"}];
    reject(@"ERROR_DB_PATH", @"Exception while fetching DB path", error);
  }
}

RCT_EXPORT_METHOD(openHelpSupport)
{
  dispatch_async(dispatch_get_main_queue(), ^{
    UIWindow *keyWindow = [UIApplication sharedApplication].delegate.window;
    UIViewController *rootVC = keyWindow.rootViewController;

    // Load the storyboard
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainCGM" bundle:nil];

    // Instantiate the target ViewController
    UIViewController *chatWithExpertVC = [storyboard instantiateViewControllerWithIdentifier:@"ChatWithExpertViewController"];

    // Set presentation style
    chatWithExpertVC.modalPresentationStyle = UIModalPresentationOverFullScreen;

    // Present it directly without navigation
    if (chatWithExpertVC) {
      [rootVC presentViewController:chatWithExpertVC animated:YES completion:nil];
    }
  });
}

RCT_EXPORT_METHOD(observeAllGlucoseData:(NSString *)token isForClearData:(BOOL)isForClearData envType:(NSString *)envType)
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:token forKey:@"authToken"];
    [defaults setObject:envType forKey:@"envType"];
    [defaults synchronize];
    
    // CRITICAL: CoreData context is NSMainQueueConcurrencyType, so ALL CoreData operations
    // must happen on the main thread. React Native native modules are often called from
    // background threads, so we must dispatch to main queue.
    dispatch_async(dispatch_get_main_queue(), ^{
        if (isForClearData == YES) {
            [[KLTDatabaseHandler shared].appDelegate deleteAllCoreData];
        }
        UIWindow *keyWindow = [UIApplication sharedApplication].delegate.window;
        UIViewController *rootVC = keyWindow.rootViewController;
        
        // Load the storyboard
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainCGM" bundle:nil];
        
        // Instantiate the target ViewController
        globalAttachTransmitterVC = [storyboard instantiateViewControllerWithIdentifier:@"AttachTransmitterViewController"];
        
        // Set presentation style
        // chatWithExpertVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
        
        // Present it directly without navigation
        //if (chatWithExpertVC) {
        // [rootVC presentViewController:chatWithExpertVC animated:YES completion:nil];
        // }
    });
}


RCT_EXPORT_METHOD(observeTransmitterUnbindStatus:(NSString *)token
                  response:(NSString *)responseJsonString
                  patientId:(NSString *)patientId
                  envType:(NSString *)envType
                  resolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject) {
    if (responseJsonString == nil || ![responseJsonString isKindOfClass:[NSString class]]) {
        NSError *error = [NSError errorWithDomain:@"CgmTrackyLib"
                                             code:1001
                                         userInfo:@{NSLocalizedDescriptionKey: @"Invalid or nil JSON string passed from JS"}];
        reject(@"invalid_params", @"Response JSON string is nil or invalid", error);
        return;
    }

    NSData *data = [responseJsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *parseError = nil;
    NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

    if (parseError || ![responseDict isKindOfClass:[NSDictionary class]]) {
        reject(@"json_parse_error", @"Failed to parse JSON string to dictionary", parseError);
        return;
    }

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:token forKey:@"authToken"];
    [defaults setObject:data forKey:@"CGMStatusItem"];
    [defaults setObject:patientId forKey:@"patientId"];
    [defaults setObject:envType forKey:@"envType"];
    [defaults synchronize];

    FinalViewModelManager *manager = [FinalViewModelManager shared];
    [manager callForObserveTransmitterUnbindStatusWithCompletionWithPatientId:patientId completion:^(NSDictionary *response, NSError *error) {
        if (error) {
            reject([NSString stringWithFormat:@"%ld", (long)error.code], error.localizedDescription, error);
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                resolve(response ?: @{});
            });
        }
    }];
}

/**
 * Get all CGM log file paths
 * Returns array of absolute file paths to CGM log files (CSV format)
 */
RCT_REMAP_METHOD(getCgmLogFiles,
                 getCgmLogFilesWithResolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject)
{
    @try {
        NSMutableArray *logFilePaths = [NSMutableArray array];

        // Use the same base path strategy as getTrackLibDbPath
        NSArray<NSURL *> *urls = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
        NSURL *documentsURL = [urls lastObject];
        if (documentsURL.path.length == 0) {
            NSError *error = [NSError errorWithDomain:@"CgmTrackyLib" code:1002 userInfo:@{NSLocalizedDescriptionKey: @"Could not access Documents directory"}];
            reject(@"ERROR_DOCUMENTS_DIR", @"Failed to get documents directory", error);
            return;
        }

        NSLog(@"CGM Documents path: %@", documentsURL.path);

        // Ensure runLog directory exists (SDK may not create it before first write)
        NSURL *logFolderURL = [documentsURL URLByAppendingPathComponent:@"runLog" isDirectory:YES];
        NSFileManager *fm = [NSFileManager defaultManager];
        BOOL isDir = NO;
        if (![fm fileExistsAtPath:logFolderURL.path isDirectory:&isDir]) {
            NSError *mkErr = nil;
            [fm createDirectoryAtURL:logFolderURL withIntermediateDirectories:YES attributes:nil error:&mkErr];
            if (mkErr) {
                NSLog(@"CGM could not create runLog dir: %@", mkErr.localizedDescription);
            }
        }

        NSLog(@"CGM runLog path: %@", logFolderURL.path);

        // Use exactly what the SDK uses first: current runlog absolute path
        KLTRunLog *current = [KLTAppDelegate getCurrentKLTRunLog];
        NSString *currentPath = current.path; // absolute path the SDK writes to
        NSLog(@"CGM current runlog path: %@", currentPath);
        if (currentPath.length > 0) {
            BOOL isDir3 = NO;
            if ([fm fileExistsAtPath:currentPath isDirectory:&isDir3] && !isDir3) {
                [logFilePaths addObject:currentPath];
            }
        }

        // If current file isn’t there yet, list the runLog dir contents
        if (logFilePaths.count == 0) {
            NSError *dirErr = nil;
            NSArray<NSString *> *runLogList = [fm contentsOfDirectoryAtPath:logFolderURL.path error:&dirErr];
            if (dirErr) {
                NSLog(@"CGM failed reading runLog dir: %@", dirErr.localizedDescription);
            } else {
                for (NSString *name in runLogList) {
                    NSString *fullPath = [logFolderURL.path stringByAppendingPathComponent:name];
                    BOOL isDirLocal = NO;
                    if ([fm fileExistsAtPath:fullPath isDirectory:&isDirLocal] && !isDirLocal) {
                        [logFilePaths addObject:fullPath];
                    }
                }
            }
        }

        NSLog(@"CGM runLog resolved %lu file(s)", (unsigned long)logFilePaths.count);
        resolve(logFilePaths);
        
    } @catch (NSException *exception) {
        NSError *error = [NSError errorWithDomain:@"CgmTrackyLib"
                                            code:1003
                                        userInfo:@{NSLocalizedDescriptionKey: exception.reason ?: @"Unknown error"}];
        reject(@"ERROR_GET_LOG_FILES", exception.reason, error);
    }
}

@end
