//
//  ProfileViewController.mm
#import "ProfileViewController.h"
#import "APIClient.h"
#import "ImageCacheHelper.h"
#import <Photos/Photos.h>
#import "ManageAccountViewController.h"

typedef NS_ENUM(NSInteger, AppLanguage) {
    AppLanguageMalay = 0,
    AppLanguageEnglish = 1,
    AppLanguageChinese = 2
};

@interface ProfileViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource>

// Header
@property (nonatomic, strong) UIView *headerBar;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *backButton;

// ScrollView for content
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;

// Profile Image
@property (nonatomic, strong) UIImageView *profileImageView;
@property (nonatomic, strong) UIButton *editProfileImageButton;

// Display Name
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UITextField *nameTextField;
@property (nonatomic, strong) UIButton *editNameButton;

// Buttons
@property (nonatomic, strong) UIButton *saveChangesButton;
@property (nonatomic, strong) UIButton *logoutButton;
@property (nonatomic, strong) UIButton *deleteAccountButton;

// Sections
@property (nonatomic, strong) UIView *profileSectionView;
@property (nonatomic, strong) UIView *settingsSectionView;

@property (nonatomic, strong) UILabel *emailLabel;
@property (nonatomic, strong) UILabel *contactLabel;

@property (nonatomic, strong) UITextField *linkNameField;
@property (nonatomic, strong) UIButton *createButton;
@property (nonatomic, strong) UIView *dimmedOverlay;
@property (nonatomic, strong) UIView *addLinkSheet;
@property (nonatomic, strong) UILabel *usernameLabel;

@property (nonatomic, strong) UIImage *selectedProfileImage;
@property (nonatomic, strong) NSData *selectedProfileImageData;
@property (nonatomic, strong) UIView *imageViewer;
@property (nonatomic, strong) UIScrollView *imageScrollView;
@property (nonatomic, strong) UIImageView *fullscreenImageView;
@property (nonatomic, assign) NSInteger selectedLanguageIndex;
@property (nonatomic, strong) NSArray<UIControl *> *languageRows;
@property (nonatomic, assign) AppLanguage selectedLanguage;
@property (nonatomic, strong) UITableView *accountTable;
@property (nonatomic, strong) NSArray *accounts;


@end

@implementation ProfileViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.systemBackgroundColor;
    
    self.selectedLanguageIndex = 1; // English default
    [self setupHeader];
    [self setupScrollView];
    [self setupProfile];
    [self requestProfile];  
}

#pragma mark - Header
- (void)setupHeader {
    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
    
    self.headerBar = [[UIView alloc] init];
    self.headerBar.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    [self.view addSubview:self.headerBar];
    self.headerBar.translatesAutoresizingMaskIntoConstraints = NO;
    
    [NSLayoutConstraint activateConstraints:@[
        [self.headerBar.topAnchor constraintEqualToAnchor:safe.topAnchor],
        [self.headerBar.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.headerBar.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.headerBar.heightAnchor constraintEqualToConstant:44],
    ]];
    
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"My Profile";
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    
    self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.backButton setImage:[UIImage systemImageNamed:@"chevron.backward"] forState:UIControlStateNormal];
    self.backButton.tintColor = UIColor.whiteColor;
    [self.backButton addTarget:self action:@selector(onBack) forControlEvents:UIControlEventTouchUpInside];
    self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.headerBar addSubview:self.titleLabel];
    [self.headerBar addSubview:self.backButton];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.backButton.leadingAnchor constraintEqualToAnchor:self.headerBar.leadingAnchor constant:16],
        [self.backButton.centerYAnchor constraintEqualToAnchor:self.headerBar.centerYAnchor],
        [self.backButton.heightAnchor constraintEqualToConstant:24],
        [self.backButton.widthAnchor constraintEqualToConstant:24],
        
        [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.headerBar.centerXAnchor],
        [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.headerBar.centerYAnchor],
    ]];
}

#pragma mark - ScrollView Setup
- (void)setupScrollView {
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.scrollView];
    
    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
    
    [NSLayoutConstraint activateConstraints:@[
        [self.scrollView.topAnchor constraintEqualToAnchor:self.headerBar.bottomAnchor],
        [self.scrollView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.scrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.scrollView.bottomAnchor constraintEqualToAnchor:safe.bottomAnchor],
    ]];
    
    self.contentView = [[UIView alloc] init];
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.scrollView addSubview:self.contentView];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.contentView.topAnchor constraintEqualToAnchor:self.scrollView.topAnchor],
        [self.contentView.leadingAnchor constraintEqualToAnchor:self.scrollView.leadingAnchor],
        [self.contentView.trailingAnchor constraintEqualToAnchor:self.scrollView.trailingAnchor],
        [self.contentView.bottomAnchor constraintEqualToAnchor:self.scrollView.bottomAnchor],
        [self.contentView.widthAnchor constraintEqualToAnchor:self.scrollView.widthAnchor], // important for vertical scroll
    ]];
}

#pragma mark - Profile Skeleton
- (void)setupProfile {
    // --- Profile Section ---
    self.profileSectionView = [[UIView alloc] init];
    self.profileSectionView.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0]; // match header
    self.profileSectionView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.profileSectionView];
    
    // --- Settings Section ---
    self.settingsSectionView = [[UIView alloc] init];
    self.settingsSectionView.backgroundColor = UIColor.systemBackgroundColor;
    self.settingsSectionView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.settingsSectionView];
    
    // Layout constraints
    [NSLayoutConstraint activateConstraints:@[
        [self.profileSectionView.topAnchor constraintEqualToAnchor:self.contentView.topAnchor],
        [self.profileSectionView.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor],
        [self.profileSectionView.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor],
        [self.profileSectionView.heightAnchor constraintGreaterThanOrEqualToConstant:358],
        
        [self.settingsSectionView.topAnchor constraintEqualToAnchor:self.profileSectionView.bottomAnchor constant:16],
        [self.settingsSectionView.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.settingsSectionView.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
        [self.settingsSectionView.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-16],
    ]];
    
    // --- Profile Section Contents ---
    [self setupProfileSectionContents];
    
    // --- Settings Section Contents ---
    [self setupSettingsSectionContents];
}

- (void)setupProfileSectionContents {
    CGFloat imageSize = 120.0;
    
    // Profile Image
    self.profileImageView = [[UIImageView alloc] init];
    self.profileImageView.backgroundColor = UIColor.systemGray5Color;
    self.profileImageView.clipsToBounds = YES;
    self.profileImageView.layer.cornerRadius = imageSize / 2;
    self.profileImageView.translatesAutoresizingMaskIntoConstraints = NO;
    self.profileImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.profileImageView.userInteractionEnabled = YES;

    UITapGestureRecognizer *tap =
        [[UITapGestureRecognizer alloc] initWithTarget:self
                                                action:@selector(profileImageTapped)];
    [self.profileImageView addGestureRecognizer:tap];
    [self.profileSectionView addSubview:self.profileImageView];
    
    // Edit Image Button
    self.editProfileImageButton =
        [UIButton buttonWithType:UIButtonTypeSystem];
    [self.editProfileImageButton setImage:
        [UIImage systemImageNamed:@"camera"]
                                 forState:UIControlStateNormal];

    self.editProfileImageButton.tintColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    self.editProfileImageButton.backgroundColor = [UIColor whiteColor];
    [self.editProfileImageButton addTarget:self
                                    action:@selector(editProfileImageTapped)
                          forControlEvents:UIControlEventTouchUpInside];
    self.editProfileImageButton.translatesAutoresizingMaskIntoConstraints = NO;
    self.editProfileImageButton.layer.cornerRadius = 20;
    self.editProfileImageButton.layer.shadowColor = UIColor.blackColor.CGColor;
    self.editProfileImageButton.layer.shadowOpacity = 0.15;
    self.editProfileImageButton.layer.shadowOffset = CGSizeMake(0, 2);
    self.editProfileImageButton.layer.shadowRadius = 4;
    [self.profileSectionView addSubview:self.editProfileImageButton];

    // Name Label
    self.nameLabel = [[UILabel alloc] init];
    self.nameLabel.text = @"User Name";
    self.nameLabel.font = [UIFont systemFontOfSize:24 weight:UIFontWeightSemibold];
    self.nameLabel.textColor = UIColor.whiteColor;
    self.nameLabel.textAlignment = NSTextAlignmentCenter;
    self.nameLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.profileSectionView addSubview:self.nameLabel];
    
    // Edit Name Button
    self.editNameButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.editNameButton setImage:[UIImage systemImageNamed:@"pencil"] forState:UIControlStateNormal];
    self.editNameButton.tintColor = UIColor.whiteColor;
    self.editNameButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.profileSectionView addSubview:self.editNameButton];
    [self.editNameButton addTarget:self
                            action:@selector(editNamePressed)
                  forControlEvents:UIControlEventTouchUpInside];
  
    self.usernameLabel = [[UILabel alloc] init];
    self.usernameLabel.text = @"JohnSnow132";
    self.usernameLabel.textColor = UIColor.whiteColor;
    self.usernameLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
    self.usernameLabel.backgroundColor =
        [[UIColor blackColor] colorWithAlphaComponent:0.2];
    self.usernameLabel.layer.cornerRadius = 14;
    self.usernameLabel.clipsToBounds = YES;
    self.usernameLabel.textAlignment = NSTextAlignmentCenter;
    self.usernameLabel.translatesAutoresizingMaskIntoConstraints = NO;

    [self.profileSectionView addSubview:self.usernameLabel];
    
    // Email Label
    self.emailLabel = [[UILabel alloc] init];
    self.emailLabel.text = @"example@mail.com";
    self.emailLabel.font = [UIFont systemFontOfSize:16];
    self.emailLabel.textColor = UIColor.whiteColor;
    self.emailLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.profileSectionView addSubview:self.emailLabel];
    
    // Contact Label
    self.contactLabel = [[UILabel alloc] init];
    self.contactLabel.text = @"60123456789";
    self.contactLabel.font = [UIFont systemFontOfSize:16];
    self.contactLabel.textColor = UIColor.whiteColor;
    self.contactLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.profileSectionView addSubview:self.contactLabel];
  
    [self.profileSectionView bringSubviewToFront:self.profileImageView];
    [self.profileSectionView bringSubviewToFront:self.editProfileImageButton];
    self.emailLabel.alpha = 0.9;
    self.contactLabel.alpha = 0.9;

    // Layout
    [NSLayoutConstraint activateConstraints:@[
        [self.profileImageView.topAnchor constraintEqualToAnchor:self.profileSectionView.topAnchor constant:24],
        [self.profileImageView.centerXAnchor constraintEqualToAnchor:self.profileSectionView.centerXAnchor],
        [self.profileImageView.widthAnchor constraintEqualToConstant:imageSize],
        [self.profileImageView.heightAnchor constraintEqualToConstant:imageSize],
        
        [self.editProfileImageButton.widthAnchor constraintEqualToConstant:36],
        [self.editProfileImageButton.heightAnchor constraintEqualToConstant:36],
        [self.editProfileImageButton.trailingAnchor constraintEqualToAnchor:self.profileImageView.trailingAnchor],
        [self.editProfileImageButton.bottomAnchor constraintEqualToAnchor:self.profileImageView.bottomAnchor],
        
        [self.nameLabel.topAnchor constraintEqualToAnchor:self.editProfileImageButton.bottomAnchor constant:35],
        [self.nameLabel.centerXAnchor constraintEqualToAnchor:self.profileSectionView.centerXAnchor],
        
        [self.editNameButton.centerYAnchor constraintEqualToAnchor:self.nameLabel.centerYAnchor],
        [self.editNameButton.leadingAnchor constraintEqualToAnchor:self.nameLabel.trailingAnchor constant:6],
        
        [self.usernameLabel.topAnchor constraintEqualToAnchor:self.nameLabel.bottomAnchor constant:19],
        [self.usernameLabel.centerXAnchor constraintEqualToAnchor:self.profileSectionView.centerXAnchor],
        [self.usernameLabel.heightAnchor constraintEqualToConstant:28],
        [self.usernameLabel.widthAnchor constraintGreaterThanOrEqualToConstant:120],
        
        [self.emailLabel.topAnchor constraintEqualToAnchor:self.usernameLabel.bottomAnchor constant:16],
        [self.emailLabel.centerXAnchor constraintEqualToAnchor:self.profileSectionView.centerXAnchor],
        
        [self.contactLabel.topAnchor constraintEqualToAnchor:self.emailLabel.bottomAnchor constant:12],
        [self.contactLabel.centerXAnchor constraintEqualToAnchor:self.profileSectionView.centerXAnchor],
        [self.contactLabel.bottomAnchor constraintEqualToAnchor:self.profileSectionView.bottomAnchor constant:-32],
    ]];
}

- (void)setupSettingsSectionContents {

    // Section title
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"Account Settings";
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    titleLabel.textColor = UIColor.systemGrayColor;
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.settingsSectionView addSubview:titleLabel];

    // Card container
    UIView *card = [[UIView alloc] init];
    card.backgroundColor = UIColor.whiteColor;
    card.layer.cornerRadius = 16;
    card.layer.borderWidth = 1;
    card.layer.borderColor = UIColor.systemGray4Color.CGColor;
    card.translatesAutoresizingMaskIntoConstraints = NO;
    [self.settingsSectionView addSubview:card];

    // ---- Change Language row ----
    UIButton *changeLanguageButton = [self settingsRowWithTitle:@"Change Language"
                                                           icon:@"globe"
                                                      textColor:UIColor.labelColor
                                                         action:@selector(changeLanguageTapped)];
    [card addSubview:changeLanguageButton];

    UILabel *langLabel = [[UILabel alloc] init];
    langLabel.text = @"EN";
    langLabel.textColor = UIColor.systemGrayColor;
    langLabel.font = [UIFont systemFontOfSize:16];
    langLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [changeLanguageButton addSubview:langLabel];

    // Separator
    UIView *separator = [self separatorView];
    [card addSubview:separator];
  
    UIButton *switchAccountButton = [self settingsRowWithTitle:@"Switch Account"
                                                          icon:@"person.crop.circle.badge.plus"
                                                     textColor:UIColor.labelColor
                                                        action:@selector(switchAccountTapped)];
    [card addSubview:switchAccountButton];

  
    UIView *separator2 = [self separatorView];
    [card addSubview:separator2];

    // ---- Logout row ----
    UIButton *logoutButton =
        [self settingsRowWithTitle:@"Log Out"
                              icon:@"arrow.right.square"
                         textColor:UIColor.systemRedColor
                            action:@selector(logoutTapped)];
    [card addSubview:logoutButton];

    // ---- Delete Account pill ----
    self.deleteAccountButton = [self settingsRowWithTitle:@"Delete My Account"
                                                     icon:@"person" textColor:UIColor.systemRedColor
                                                   action:@selector(deleteAccountTapped)];
    self.deleteAccountButton.backgroundColor =
        [[UIColor systemRedColor] colorWithAlphaComponent:0.1];
    self.deleteAccountButton.layer.cornerRadius = 14;
    self.deleteAccountButton.contentEdgeInsets = UIEdgeInsetsMake(14, 16, 14, 16);
    self.deleteAccountButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.deleteAccountButton addTarget:self
                                 action:@selector(deleteAccountTapped)
                       forControlEvents:UIControlEventTouchUpInside];
    [self.settingsSectionView addSubview:self.deleteAccountButton];
  
    // ---- Layout ----
    [NSLayoutConstraint activateConstraints:@[
        // Title
        [titleLabel.topAnchor constraintEqualToAnchor:self.settingsSectionView.topAnchor constant:24],
        [titleLabel.leadingAnchor constraintEqualToAnchor:self.settingsSectionView.leadingAnchor],

        // Card
        [card.topAnchor constraintEqualToAnchor:titleLabel.bottomAnchor constant:12],
        [card.leadingAnchor constraintEqualToAnchor:self.settingsSectionView.leadingAnchor],
        [card.trailingAnchor constraintEqualToAnchor:self.settingsSectionView.trailingAnchor],

        // Change Language row
        [changeLanguageButton.topAnchor constraintEqualToAnchor:card.topAnchor],
        [changeLanguageButton.leadingAnchor constraintEqualToAnchor:card.leadingAnchor],
        [changeLanguageButton.trailingAnchor constraintEqualToAnchor:card.trailingAnchor],
        [changeLanguageButton.heightAnchor constraintEqualToConstant:48],

        // Language text
        [langLabel.centerYAnchor constraintEqualToAnchor:changeLanguageButton.centerYAnchor],
        [langLabel.trailingAnchor constraintEqualToAnchor:changeLanguageButton.trailingAnchor constant:-36],

        // Separator
        [separator.topAnchor constraintEqualToAnchor:changeLanguageButton.bottomAnchor],
        [separator.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:16],
        [separator.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-16],
        [separator.heightAnchor constraintEqualToConstant:1],
        
        // Switch Button row
        [switchAccountButton.topAnchor constraintEqualToAnchor:separator.topAnchor],
        [switchAccountButton.leadingAnchor constraintEqualToAnchor:card.leadingAnchor],
        [switchAccountButton.trailingAnchor constraintEqualToAnchor:card.trailingAnchor],
        [switchAccountButton.heightAnchor constraintEqualToConstant:48],
        
        // Separator2
        [separator2.topAnchor constraintEqualToAnchor:switchAccountButton.bottomAnchor],
        [separator2.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:16],
        [separator2.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-16],
        [separator2.heightAnchor constraintEqualToConstant:1],
        
        // Logout row
        [logoutButton.topAnchor constraintEqualToAnchor:separator2.bottomAnchor],
        [logoutButton.leadingAnchor constraintEqualToAnchor:card.leadingAnchor],
        [logoutButton.trailingAnchor constraintEqualToAnchor:card.trailingAnchor],
        [logoutButton.heightAnchor constraintEqualToConstant:48],

        // Card bottom
        [card.bottomAnchor constraintEqualToAnchor:logoutButton.bottomAnchor],

        // Delete button
        [self.deleteAccountButton.topAnchor constraintEqualToAnchor:card.bottomAnchor constant:16],
        [self.deleteAccountButton.leadingAnchor constraintEqualToAnchor:self.settingsSectionView.leadingAnchor],
        [self.deleteAccountButton.trailingAnchor constraintEqualToAnchor:self.settingsSectionView.trailingAnchor],
        [self.deleteAccountButton.bottomAnchor constraintEqualToAnchor:self.settingsSectionView.bottomAnchor constant:-16],
    ]];
}

- (UIButton *)settingsRowWithTitle:(NSString *)title
                              icon:(NSString *)iconName
                         textColor:(UIColor *)color
                            action:(SEL)selector {

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.translatesAutoresizingMaskIntoConstraints = NO;
    [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];

    UIImageView *icon =
        [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:iconName]];
    icon.tintColor = color;
    icon.translatesAutoresizingMaskIntoConstraints = NO;

    UILabel *label = [[UILabel alloc] init];
    label.text = title;
    label.textColor = color;
    label.font = [UIFont systemFontOfSize:16];
    label.translatesAutoresizingMaskIntoConstraints = NO;

    UIImageView *chevron =
        [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:@"chevron.right"]];
    chevron.tintColor = UIColor.systemGray3Color;
    chevron.translatesAutoresizingMaskIntoConstraints = NO;

    [button addSubview:icon];
    [button addSubview:label];
    [button addSubview:chevron];

    [NSLayoutConstraint activateConstraints:@[
        [icon.leadingAnchor constraintEqualToAnchor:button.leadingAnchor constant:16],
        [icon.centerYAnchor constraintEqualToAnchor:button.centerYAnchor],

        [label.leadingAnchor constraintEqualToAnchor:icon.trailingAnchor constant:12],
        [label.centerYAnchor constraintEqualToAnchor:button.centerYAnchor],

        [chevron.trailingAnchor constraintEqualToAnchor:button.trailingAnchor constant:-16],
        [chevron.centerYAnchor constraintEqualToAnchor:button.centerYAnchor],
    ]];

    return button;
}

#pragma mark - API
-(void) requestProfile {
  [APIClient requestProfile:^(BOOL success, NSDictionary *data, NSError *error) {
    
      // Save debug file
      NSString *plainText = [NSString stringWithFormat:@"%@", data];
      NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
      NSString *filePath = [docsPath stringByAppendingPathComponent:@"profile.txt"];
      [plainText writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
      NSLog(@"📁 profile saved as plain text to: %@", filePath);

      if (error || !data) {
          NSLog(@"❌ profile API failed: %@", error);
          return;
      }

      if (data[@"status_code"]) {
          NSLog(@"❌ profile status error: %@", data[@"message"]);
          return;
      }

      NSDictionary *appData = data[@"AppData"];
      if (![appData[@"status"] isEqualToString:@"success"]) {
          NSLog(@"❌ profile failure: %@", appData[@"message"]);
          return;
      }

      NSDictionary *profile = data[@"Data"];
      if (![profile isKindOfClass:[NSDictionary class]]) {
          NSLog(@"❌ Invalid profile format");
          return;
      }
      dispatch_async(dispatch_get_main_queue(), ^{
          NSURL *url = [NSURL URLWithString:profile[@"avatar"]];
          [ImageCacheHelper loadImageWithURL:url completion:^(UIImage *image) {
             self.profileImageView.image = image;
          }];
          self.nameLabel.text = profile[@"name"] ?: @"";
          self.emailLabel.text = profile[@"email"] ?: @"";
          self.contactLabel.text = profile[@"contact"] ?: @"";
          self.usernameLabel.text = profile[@"ic_passport"] ?: @"";
      });
  }];
}

- (void)uploadProfileImage {

    if (!self.selectedProfileImageData) return;

    [APIClient uploadProfileImage:self.selectedProfileImageData
                              name:self.nameLabel.text
                        completion:^(BOOL success,
                                     NSDictionary *response,
                                     NSError *error) {

        if (!success || error) {
            NSLog(@"❌ Upload failed: %@", error);
            return;
        }

        NSDictionary *appData = response[@"AppData"];
        if (![appData[@"status"] isEqualToString:@"success"]) {
            NSLog(@"❌ API error: %@", appData[@"message"]);
            return;
        }

        NSLog(@"✅ Profile image updated");
        [self requestProfile];
    }];
}

- (UIView *)separatorView {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = UIColor.systemGray4Color;
    view.translatesAutoresizingMaskIntoConstraints = NO;
    return view;
}


#pragma mark - Logout & Delete Buttons
- (void)logoutTapped {
    UIAlertController *alert =
    [UIAlertController alertControllerWithTitle:@"Alert"
                                        message:@"Are you sure you want to logout?"
                                 preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *cancel =
    [UIAlertAction actionWithTitle:@"No"
                             style:UIAlertActionStyleCancel
                           handler:nil];

    UIAlertAction *confirm =
    [UIAlertAction actionWithTitle:@"Yes"
                             style:UIAlertActionStyleDestructive
                           handler:^(UIAlertAction * _Nonnull action) {

        // Clear session
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userToken"];
        [[NSUserDefaults standardUserDefaults] synchronize];

        // Exit profile
        [self dismissViewControllerAnimated:YES completion:nil];
    }];

    [alert addAction:cancel];
    [alert addAction:confirm];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)deleteAccountTapped {

    NSString *message =
    @"By submitting this account deletion request, you are acknowledging that your account will be permanently deleted. Upon submitting this request, the account will be suspended and queued for deletion. You will no longer have access.";

    UIAlertController *alert =
    [UIAlertController alertControllerWithTitle:@"Delete Account Confirmation"
                                        message:message
                                 preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *cancel =
    [UIAlertAction actionWithTitle:@"Cancel"
                             style:UIAlertActionStyleCancel
                           handler:nil];

    UIAlertAction *confirm =
    [UIAlertAction actionWithTitle:@"Confirm"
                             style:UIAlertActionStyleDestructive
                           handler:^(UIAlertAction * _Nonnull action) {
        [self performDeleteAccount];
    }];

    [alert addAction:cancel];
    [alert addAction:confirm];

    [self presentViewController:alert animated:YES completion:nil];
}


- (void)performDeleteAccount {
    [APIClient deleteProfile:^(BOOL success, NSDictionary *data, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error || !success) {
                UIAlertController *fail = [UIAlertController alertControllerWithTitle:@"Error"
                                                                             message:@"Failed to delete account. Please try again."
                                                                      preferredStyle:UIAlertControllerStyleAlert];
                [fail addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]];
                [self presentViewController:fail animated:YES completion:nil];
                return;
            }
            
            // Account deleted successfully
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userToken"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            UIAlertController *successAlert = [UIAlertController alertControllerWithTitle:@"Account Deleted"
                                                                                  message:@"Your account has been successfully deleted."
                                                                           preferredStyle:UIAlertControllerStyleAlert];
            [successAlert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                // Return to login / welcome screen
                [self dismissViewControllerAnimated:YES completion:nil];
            }]];
            
            [self presentViewController:successAlert animated:YES completion:nil];
        });
    }];
}

#pragma mark - Edit Name
- (UIView *)buildDimmedOverlay {
    UIView *overlay = [[UIView alloc] initWithFrame:self.view.bounds];
    overlay.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
    overlay.alpha = 0;
    overlay.userInteractionEnabled = YES;

    // Tap to dismiss
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                          action:@selector(dismissAddLinkSheetButtonTapped:)];
    tap.cancelsTouchesInView = NO; // <-- allow touches to pass to sheet buttons
    [overlay addGestureRecognizer:tap];

    return overlay;
}

- (UIView *)changeNameSheet {
    UIView *sheet = [[UIView alloc] init];
    sheet.backgroundColor = UIColor.whiteColor;
    sheet.layer.cornerRadius = 24;
    sheet.layer.maskedCorners =
        kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
    sheet.translatesAutoresizingMaskIntoConstraints = NO;

    UILabel *title = [[UILabel alloc] init];
    title.text = @"Change Profile Name";
    title.font = [UIFont systemFontOfSize:18 weight:UIFontWeightBold];
    title.textAlignment = NSTextAlignmentCenter;
    title.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:title];

    UILabel *subtitle = [[UILabel alloc] init];
    subtitle.text = @"Modify your name and select Update to apply changes";
    subtitle.font = [UIFont systemFontOfSize:14];
    subtitle.textAlignment = NSTextAlignmentCenter;
    subtitle.textColor = UIColor.darkGrayColor;
    subtitle.numberOfLines = 0;
    subtitle.lineBreakMode = NSLineBreakByWordWrapping;
    subtitle.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:subtitle];

    self.linkNameField = [[UITextField alloc] init];
    self.linkNameField.placeholder = @"Enter New Name";
    self.linkNameField.borderStyle = UITextBorderStyleRoundedRect;
    [self.linkNameField addTarget:self
                           action:@selector(onTextChanged:)
                 forControlEvents:UIControlEventEditingChanged];
    self.linkNameField.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:self.linkNameField];

    self.createButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.createButton setTitle:@"Create" forState:UIControlStateNormal];
    self.createButton.enabled = NO;
    self.createButton.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    self.createButton.layer.cornerRadius = 10;
    [self.createButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [self.createButton addTarget:self
                          action:@selector(updateTapped)
                forControlEvents:UIControlEventTouchUpInside];
    self.createButton.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:self.createButton];

    [NSLayoutConstraint activateConstraints:@[
      [title.centerXAnchor constraintEqualToAnchor:sheet.centerXAnchor],
      [title.topAnchor constraintEqualToAnchor:sheet.topAnchor constant:28],
      
      [subtitle.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:12],
      [subtitle.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:16],
      [subtitle.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-16],
      
      [self.linkNameField.topAnchor constraintEqualToAnchor:subtitle.bottomAnchor constant:24],
      [self.linkNameField.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:20],
      [self.linkNameField.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-20],
      [self.linkNameField.heightAnchor constraintEqualToConstant:48],
      
      [self.createButton.topAnchor constraintEqualToAnchor:self.linkNameField.bottomAnchor constant:32],
      [self.createButton.leadingAnchor constraintEqualToAnchor:subtitle.leadingAnchor],
      [self.createButton.trailingAnchor constraintEqualToAnchor:subtitle.trailingAnchor],
      [self.createButton.heightAnchor constraintEqualToConstant:48],
      [self.createButton.bottomAnchor constraintEqualToAnchor:sheet.safeAreaLayoutGuide.bottomAnchor constant:-24],
    ]];
    return sheet;
}

- (void)editNamePressed {
    [self.addLinkSheet removeFromSuperview];
    [self.dimmedOverlay removeFromSuperview];
  
    self.dimmedOverlay = [self buildDimmedOverlay];
    self.addLinkSheet = [self changeNameSheet];

    [self.view addSubview:self.dimmedOverlay];
    [self.view addSubview:self.addLinkSheet];

    NSLayoutConstraint *bottom =
        [self.addLinkSheet.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor constant:300];
    bottom.active = YES;

    [NSLayoutConstraint activateConstraints:@[
        [self.addLinkSheet.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.addLinkSheet.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
    ]];

    [self.view layoutIfNeeded];

    [UIView animateWithDuration:0.3 animations:^{
        self.dimmedOverlay.alpha = 1;
        bottom.constant = 0;
        [self.view layoutIfNeeded];
    }];
}

- (void)dismissAddLinkSheet:(void(^)(void))completion {
    [UIView animateWithDuration:0.3 animations:^{
        self.addLinkSheet.transform = CGAffineTransformMakeTranslation(0, 300);
        self.dimmedOverlay.alpha = 0;
    } completion:^(BOOL finished) {
        [self.addLinkSheet removeFromSuperview];
        [self.dimmedOverlay removeFromSuperview];
        if (completion) completion();
    }];
}

- (void)dismissAddLinkSheetButtonTapped:(id)sender {
    [self dismissAddLinkSheet:nil]; // no completion needed
}

- (void)onTextChanged:(UITextField *)textField {
    BOOL hasText = textField.text.length > 0;
    self.createButton.enabled = hasText;
    self.createButton.backgroundColor =
        hasText ? [UIColor colorWithRed:0.05 green:0.45 blue:0.57 alpha:1.0]
                : UIColor.systemGray5Color;
}

#pragma mark - Change Language
- (UIView *)buildLanguageSheet {
    UIView *sheet = [[UIView alloc] init];
    sheet.backgroundColor = UIColor.whiteColor;
    sheet.layer.cornerRadius = 24;
    sheet.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
    sheet.translatesAutoresizingMaskIntoConstraints = NO;

    UIView *header = [[UIView alloc] init];
    header.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:header];

    UILabel *title = [[UILabel alloc] init];
    title.text = @"Change Language";
    title.font = [UIFont systemFontOfSize:20 weight:UIFontWeightBold];
    title.translatesAutoresizingMaskIntoConstraints = NO;

//    UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    [closeButton setImage:[UIImage systemImageNamed:@"xmark"] forState:UIControlStateNormal];
//    closeButton.tintColor = UIColor.systemGrayColor;
//    [closeButton addTarget:self action:@selector(dismissAddLinkSheetButtonTapped:)
//          forControlEvents:UIControlEventTouchUpInside];
//    closeButton.translatesAutoresizingMaskIntoConstraints = NO;

    [header addSubview:title];
//    [header addSubview:closeButton];

    UILabel *subtitle = [[UILabel alloc] init];
    subtitle.text = @"You can change your preferred language listed below.";
    subtitle.font = [UIFont systemFontOfSize:14];
    subtitle.textAlignment = NSTextAlignmentLeft;
    subtitle.numberOfLines = 0;
    subtitle.textColor = UIColor.darkGrayColor;
    subtitle.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:subtitle];

    // --- Language Buttons ---
    UIControl *bm = [self languageRow:@"Bahasa Melayu" selected:NO tag:0];
    UIControl *en = [self languageRow:@"English" selected:YES tag:1];
    UIControl *zh = [self languageRow:@"中文" selected:NO tag:2];
    UIView *sep1 = [self separatorView];
    UIView *sep2 = [self separatorView];
    self.languageRows = @[bm, en, zh];
    self.selectedLanguage = AppLanguageEnglish;

    [sheet addSubview:bm];
    [sheet addSubview:sep1];
    [sheet addSubview:en];
    [sheet addSubview:sep2];
    [sheet addSubview:zh];
    
    //Ok Button
    UIButton *okButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [okButton setTitle:@"OK" forState:UIControlStateNormal];
    okButton.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightSemibold];
    okButton.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    okButton.layer.cornerRadius = 26;
    [okButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [okButton addTarget:self action:@selector(confirmLanguage)
       forControlEvents:UIControlEventTouchUpInside];
    okButton.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:okButton];

    [NSLayoutConstraint activateConstraints:@[
        [header.topAnchor constraintEqualToAnchor:sheet.topAnchor constant:24],
        [header.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:20],
        [header.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-20],

        [title.leadingAnchor constraintEqualToAnchor:header.leadingAnchor],
        [title.centerYAnchor constraintEqualToAnchor:header.centerYAnchor],

//        [closeButton.trailingAnchor constraintEqualToAnchor:header.trailingAnchor],
//        [closeButton.centerYAnchor constraintEqualToAnchor:header.centerYAnchor],
//        [closeButton.heightAnchor constraintEqualToConstant:24],
//        [closeButton.widthAnchor constraintEqualToConstant:24],

        [subtitle.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:12],
        [subtitle.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:20],
        [subtitle.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-20],

        [bm.topAnchor constraintEqualToAnchor:subtitle.bottomAnchor constant:24],
        [bm.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor],
        [bm.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor],
        [bm.heightAnchor constraintEqualToConstant:56],

        [sep1.topAnchor constraintEqualToAnchor:bm.bottomAnchor],
        [sep1.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:20],
        [sep1.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-20],
        [sep1.heightAnchor constraintEqualToConstant:1],

        [en.topAnchor constraintEqualToAnchor:sep1.bottomAnchor],
        [en.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor],
        [en.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor],
        [en.heightAnchor constraintEqualToConstant:56],

        [sep2.topAnchor constraintEqualToAnchor:en.bottomAnchor],
        [sep2.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:20],
        [sep2.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-20],
        [sep2.heightAnchor constraintEqualToConstant:1],

        [zh.topAnchor constraintEqualToAnchor:sep2.bottomAnchor],
        [zh.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor],
        [zh.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor],
        [zh.heightAnchor constraintEqualToConstant:56],
        
        [okButton.topAnchor constraintEqualToAnchor:zh.bottomAnchor constant:32],
        [okButton.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:20],
        [okButton.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-20],
        [okButton.heightAnchor constraintEqualToConstant:52],
        [okButton.bottomAnchor constraintEqualToAnchor:sheet.safeAreaLayoutGuide.bottomAnchor constant:-16],
    ]];
    return sheet;
}

- (UIControl *)languageRow:(NSString *)title selected:(BOOL)selected tag:(NSInteger)tag {
    UIControl *row = [[UIControl alloc] init];
    row.tag = tag;
    row.translatesAutoresizingMaskIntoConstraints = NO;
    [row addTarget:self action:@selector(languageTapped:) forControlEvents:UIControlEventTouchUpInside];

    UILabel *label = [[UILabel alloc] init];
    label.text = title;
    label.font = [UIFont systemFontOfSize:18 weight:UIFontWeightSemibold];
    label.translatesAutoresizingMaskIntoConstraints = NO;

    UIView *radioOuter = [[UIView alloc] init];
    radioOuter.layer.cornerRadius = 12;
    radioOuter.layer.borderWidth = 2;
    radioOuter.layer.borderColor = UIColor.systemGray4Color.CGColor;
    radioOuter.translatesAutoresizingMaskIntoConstraints = NO;

    UIView *radioInner = [[UIView alloc] init];
    radioInner.layer.cornerRadius = 6;
    radioInner.backgroundColor = selected
        ? [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0]
        : UIColor.clearColor;
    radioInner.translatesAutoresizingMaskIntoConstraints = NO;

    [radioOuter addSubview:radioInner];
    [row addSubview:label];
    [row addSubview:radioOuter];

    [NSLayoutConstraint activateConstraints:@[
        [label.leadingAnchor constraintEqualToAnchor:row.leadingAnchor constant:20],
        [label.centerYAnchor constraintEqualToAnchor:row.centerYAnchor],

        [radioOuter.trailingAnchor constraintEqualToAnchor:row.trailingAnchor constant:-20],
        [radioOuter.centerYAnchor constraintEqualToAnchor:row.centerYAnchor],
        [radioOuter.widthAnchor constraintEqualToConstant:24],
        [radioOuter.heightAnchor constraintEqualToConstant:24],

        [radioInner.centerXAnchor constraintEqualToAnchor:radioOuter.centerXAnchor],
        [radioInner.centerYAnchor constraintEqualToAnchor:radioOuter.centerYAnchor],
        [radioInner.widthAnchor constraintEqualToConstant:12],
        [radioInner.heightAnchor constraintEqualToConstant:12],
    ]];

    return row;
}

- (void)confirmLanguage {
    // 1. Make sure user selected something
    if (self.selectedLanguage == NSNotFound) {
        UIAlertController *alert =
            [UIAlertController alertControllerWithTitle:nil
                                                message:@"Please select a language"
                                         preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction *ok =
            [UIAlertAction actionWithTitle:@"OK"
                                     style:UIAlertActionStyleDefault
                                   handler:nil];

        [alert addAction:ok];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }

    // 2. Convert to language code
    NSString *languageCode = @"en";
    
    switch (self.selectedLanguage) {
        case AppLanguageEnglish:
            languageCode = @"en";
            break;
        case AppLanguageMalay:
            languageCode = @"ms";
            break;
        case AppLanguageChinese:
            languageCode = @"zh";
            break;
    }

    // 3. Save language
    [[NSUserDefaults standardUserDefaults] setObject:languageCode forKey:@"AppLanguage"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    // 4. Apply language change
//    [LanguageManager setLanguage:languageCode];

    // 5. Notify app to refresh UI
    [[NSNotificationCenter defaultCenter]
        postNotificationName:@"LanguageDidChangeNotification"
        object:nil];

    // 6. Close popup
  [self dismissAddLinkSheet:^{NSLog(@"link sheet dismissed");}];
}

- (void)changeLanguageTapped {
    [self.addLinkSheet removeFromSuperview];
    [self.dimmedOverlay removeFromSuperview];
  
    self.dimmedOverlay = [self buildDimmedOverlay];
    self.addLinkSheet = [self buildLanguageSheet]; // reuse property for now

    [self.view addSubview:self.dimmedOverlay];
    [self.view addSubview:self.addLinkSheet];

    NSLayoutConstraint *bottom = [self.addLinkSheet.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor constant:300];
    bottom.active = YES;

    [NSLayoutConstraint activateConstraints:@[
        [self.addLinkSheet.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.addLinkSheet.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
    ]];

    [self.view layoutIfNeeded];

    [UIView animateWithDuration:0.3 animations:^{
        self.dimmedOverlay.alpha = 1;
        bottom.constant = 0;
        [self.view layoutIfNeeded];
    }];
}

- (void)languageTapped:(UIControl *)sender {
    self.selectedLanguageIndex = sender.tag;

    for (UIControl *row in self.languageRows) {
        UIView *radioOuter = row.subviews.lastObject;
        UIView *radioInner = radioOuter.subviews.firstObject;

        radioInner.backgroundColor =
            (row.tag == self.selectedLanguageIndex)
            ? [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0]
            : UIColor.clearColor;
    }
}

-(void)updateTapped{
  NSLog(@"update tapped");
  [APIClient editProfile:self.linkNameField.text completion:^(BOOL success, NSDictionary * _Nullable data, NSError * _Nullable error) {
    if (!success) {
      NSLog(@"❌ API returned success = NO");
      return;
    }
    
    if (error || !data) {
      NSLog(@"❌ Project list API failed: %@", error);
      return;
    }
    
    // RN parity: status_code check
    if (data[@"status_code"]) {
      NSLog(@"❌ API status error: %@", data[@"message"]);
      return;
    }
    
    NSDictionary *appData = data[@"AppData"];
    if (![appData[@"status"] isEqualToString:@"success"]) {
      NSLog(@"❌ API failure: %@", appData[@"message"]);
      return;
    }
    
    if (!error) {
      NSLog(@"Successfully edited profile name");
      [self dismissAddLinkSheet:^{
          [self requestProfile];
      }];
    }
  }];
}

#pragma mark - Profile Picture
- (void)editProfileImageTapped {
    UIAlertController *sheet =
    [UIAlertController alertControllerWithTitle:@"Change Profile Picture"
                                        message:nil
                                 preferredStyle:UIAlertControllerStyleActionSheet];

    UIAlertAction *camera =
    [UIAlertAction actionWithTitle:@"Camera"
                             style:UIAlertActionStyleDefault
                           handler:^(UIAlertAction * _Nonnull action) {
        [self openImagePicker:UIImagePickerControllerSourceTypeCamera];
    }];

    UIAlertAction *gallery =
    [UIAlertAction actionWithTitle:@"Photo Library"
                             style:UIAlertActionStyleDefault
                           handler:^(UIAlertAction * _Nonnull action) {
        [self openImagePicker:UIImagePickerControllerSourceTypePhotoLibrary];
    }];

    UIAlertAction *cancel =
    [UIAlertAction actionWithTitle:@"Cancel"
                             style:UIAlertActionStyleCancel
                           handler:nil];

    [sheet addAction:camera];
    [sheet addAction:gallery];
    [sheet addAction:cancel];

    [self presentViewController:sheet animated:YES completion:nil];
}

- (void)openImagePicker:(UIImagePickerControllerSourceType)type {
    if (![UIImagePickerController isSourceTypeAvailable:type]) {
        return;
    }

    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = type;
    picker.delegate = self;
    picker.allowsEditing = YES;

    [self presentViewController:picker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {

    UIImage *image = info[UIImagePickerControllerEditedImage]
                  ?: info[UIImagePickerControllerOriginalImage];

    self.selectedProfileImage = image;

    // JPEG compression (RN used image/jpeg)
    self.selectedProfileImageData = UIImageJPEGRepresentation(image, 0.85);

    // Preview immediately
    self.profileImageView.image = image;

    [picker dismissViewControllerAnimated:YES completion:^{
        [self uploadProfileImage];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)profileImageTapped {
    if (!self.profileImageView.image) return;

    self.imageViewer = [[UIView alloc] initWithFrame:self.view.bounds];
    self.imageViewer.backgroundColor = UIColor.blackColor;
    self.imageViewer.alpha = 0;
    [self.view addSubview:self.imageViewer];

    self.imageScrollView =
        [[UIScrollView alloc] initWithFrame:self.imageViewer.bounds];
    self.imageScrollView.minimumZoomScale = 1.0;
    self.imageScrollView.maximumZoomScale = 4.0;
    self.imageScrollView.delegate = self;
    [self.imageViewer addSubview:self.imageScrollView];

    self.fullscreenImageView =
        [[UIImageView alloc] initWithImage:self.profileImageView.image];
    self.fullscreenImageView.frame = self.imageScrollView.bounds;
    self.fullscreenImageView.contentMode = UIViewContentModeScaleAspectFit;
    self.fullscreenImageView.userInteractionEnabled = YES;
    [self.imageScrollView addSubview:self.fullscreenImageView];

    // Dismiss tap
    UITapGestureRecognizer *dismissTap =
        [[UITapGestureRecognizer alloc] initWithTarget:self
                                                action:@selector(dismissImageViewer)];
    [self.imageViewer addGestureRecognizer:dismissTap];

    // Double tap zoom
    UITapGestureRecognizer *doubleTap =
        [[UITapGestureRecognizer alloc] initWithTarget:self
                                                action:@selector(doubleTapZoom:)];
    doubleTap.numberOfTapsRequired = 2;
    [self.imageScrollView addGestureRecognizer:doubleTap];

    [UIView animateWithDuration:0.25 animations:^{
        self.imageViewer.alpha = 1;
    }];
}

#pragma mark - Zoom
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.fullscreenImageView;
}

- (void)doubleTapZoom:(UITapGestureRecognizer *)gesture {
    if (self.imageScrollView.zoomScale > 1.0) {
        [self.imageScrollView setZoomScale:1.0 animated:YES];
    } else {
        CGPoint point = [gesture locationInView:self.fullscreenImageView];
        CGRect zoomRect = CGRectMake(point.x - 50, point.y - 50, 100, 100);
        [self.imageScrollView zoomToRect:zoomRect animated:YES];
    }
}

- (void)dismissImageViewer {
    [UIView animateWithDuration:0.25 animations:^{
        self.imageViewer.alpha = 0;
    } completion:^(BOOL finished) {
        [self.imageScrollView removeFromSuperview];
        [self.imageViewer removeFromSuperview];
        self.imageScrollView = nil;
        self.imageViewer = nil;
        self.fullscreenImageView = nil;
    }];
}

#pragma mark - Switch Account
-(void) switchAccountTapped{
    [self.addLinkSheet removeFromSuperview];
    [self.dimmedOverlay removeFromSuperview];
  
    self.dimmedOverlay = [self buildDimmedOverlay];
    self.addLinkSheet = [self buildAccountSheet];

    self.accounts = @[
    @{
        @"name": @"Jason Snow",
        @"company_code": @"SPSetia",
        @"userName": @"jasonSnow6602",
        @"loggedIn": @NO
    },
    @{
        @"name": @"John Anthony Snow",
        @"company_code": @"QMSI",
        @"userName": @"JohnSnow132",
        @"loggedIn": @YES
    },
    @{
        @"name": @"Kenny Soo",
        @"company_code": @"QMSI",
        @"userName": @"kennys01",
        @"loggedIn": @NO
    }
    ];

    [self.view addSubview:self.dimmedOverlay];
    [self.view addSubview:self.addLinkSheet];

    NSLayoutConstraint *bottom = [self.addLinkSheet.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor constant:300];
    bottom.active = YES;

    [NSLayoutConstraint activateConstraints:@[
        [self.addLinkSheet.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.addLinkSheet.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.addLinkSheet.heightAnchor constraintEqualToConstant:423],
    ]];

    [self.view layoutIfNeeded];

    [UIView animateWithDuration:0.3 animations:^{
        self.dimmedOverlay.alpha = 1;
        bottom.constant = 0;
        [self.view layoutIfNeeded];
    }];
}

- (UIView *)buildAccountSheet {
    UIView *sheet = [[UIView alloc] init];
    sheet.backgroundColor = UIColor.whiteColor;
    sheet.layer.cornerRadius = 24;
    sheet.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
    sheet.translatesAutoresizingMaskIntoConstraints = NO;

    UIView *header = [[UIView alloc] init];
    header.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:header];

    UILabel *title = [[UILabel alloc] init];
    title.text = @"Switch Account";
    title.font = [UIFont systemFontOfSize:20 weight:UIFontWeightBold];
    title.translatesAutoresizingMaskIntoConstraints = NO;

//    UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    [closeButton setImage:[UIImage systemImageNamed:@"xmark"] forState:UIControlStateNormal];
//    closeButton.tintColor = UIColor.systemGrayColor;
//    [closeButton addTarget:self action:@selector(dismissAddLinkSheetButtonTapped:)
//          forControlEvents:UIControlEventTouchUpInside];
//    closeButton.translatesAutoresizingMaskIntoConstraints = NO;

    [header addSubview:title];
//    [header addSubview:closeButton];

    UILabel *subtitle = [[UILabel alloc] init];
    subtitle.text = @"Select an account you want to switch to.";
    subtitle.font = [UIFont systemFontOfSize:14];
    subtitle.textAlignment = NSTextAlignmentLeft;
    subtitle.numberOfLines = 0;
    subtitle.textColor = UIColor.darkGrayColor;
    subtitle.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:subtitle];

    // --- Account Table ---
    self.accountTable = [[UITableView alloc] init];
    self.accountTable.translatesAutoresizingMaskIntoConstraints = NO;
    self.accountTable.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.accountTable.delegate = self;
    self.accountTable.dataSource = self;
    self.accountTable.rowHeight = 72;
    self.accountTable.tableFooterView = [UIView new];
    self.accountTable.alwaysBounceVertical = YES;

    [sheet addSubview:self.accountTable];

    //Ok Button
    UIButton *manageButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [manageButton setTitle:@"Manage Accounts" forState:UIControlStateNormal];
    manageButton.titleLabel.font = [UIFont systemFontOfSize:14];
    manageButton.backgroundColor = [UIColor whiteColor];
    manageButton.layer.cornerRadius = 18;
    manageButton.layer.borderWidth = 0.5;
    manageButton.layer.borderColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0].CGColor;
    [manageButton setTitleColor:[UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0] forState:UIControlStateNormal];
    [manageButton addTarget:self action:@selector(manageAccountsTapped)
       forControlEvents:UIControlEventTouchUpInside];
    manageButton.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:manageButton];

    UIButton *accountButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [accountButton setTitle:@"Add Account" forState:UIControlStateNormal];
    accountButton.titleLabel.font = [UIFont systemFontOfSize:14];
    accountButton.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    accountButton.layer.cornerRadius = 18;
    [accountButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [accountButton addTarget:self action:@selector(addAccountsTapped)
       forControlEvents:UIControlEventTouchUpInside];
    accountButton.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:accountButton];

    [NSLayoutConstraint activateConstraints:@[
        [header.topAnchor constraintEqualToAnchor:sheet.topAnchor constant:24],
        [header.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:20],
        [header.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-20],

        [title.leadingAnchor constraintEqualToAnchor:header.leadingAnchor],
        [title.centerYAnchor constraintEqualToAnchor:header.centerYAnchor],

//        [closeButton.trailingAnchor constraintEqualToAnchor:header.trailingAnchor],
//        [closeButton.centerYAnchor constraintEqualToAnchor:header.centerYAnchor],
//        [closeButton.heightAnchor constraintEqualToConstant:24],
//        [closeButton.widthAnchor constraintEqualToConstant:24],

        [subtitle.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:12],
        [subtitle.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:20],
        [subtitle.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-20],
        
        [self.accountTable.topAnchor constraintEqualToAnchor:subtitle.bottomAnchor constant:16],
        [self.accountTable.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor],
        [self.accountTable.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor],
        [self.accountTable.bottomAnchor constraintEqualToAnchor:manageButton.topAnchor constant:-24],

        [manageButton.topAnchor constraintEqualToAnchor:self.accountTable.bottomAnchor constant:32],
        [manageButton.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:16],
        [manageButton.trailingAnchor constraintEqualToAnchor:sheet.centerXAnchor constant:-8],
        [manageButton.heightAnchor constraintEqualToConstant:48],
        [manageButton.bottomAnchor constraintEqualToAnchor:sheet.safeAreaLayoutGuide.bottomAnchor constant:-16],

        [accountButton.topAnchor constraintEqualToAnchor:manageButton.topAnchor],
        [accountButton.leadingAnchor constraintEqualToAnchor:sheet.centerXAnchor constant:8],
        [accountButton.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-16],
        [accountButton.heightAnchor constraintEqualToConstant:48],
        [accountButton.bottomAnchor constraintEqualToAnchor:manageButton.bottomAnchor]
    ]];
    return sheet;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
    return self.accounts.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *cellId = @"AccountCell";
    UITableViewCell *cell =
        [tableView dequeueReusableCellWithIdentifier:cellId];

    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:cellId];
      
        // --- Profile Image Placeholder ---
        UIImageView *profileImageView = [[UIImageView alloc] init];
        profileImageView.tag = 1000;
        profileImageView.translatesAutoresizingMaskIntoConstraints = NO;
        profileImageView.backgroundColor = UIColor.systemGray4Color;
        profileImageView.layer.cornerRadius = 20; // half of width/height
        profileImageView.clipsToBounds = YES;
        [cell.contentView addSubview:profileImageView];
      
        // Name label
        UILabel *nameLabel = [[UILabel alloc] init];
        nameLabel.tag = 1001;
        nameLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
        nameLabel.translatesAutoresizingMaskIntoConstraints = NO;

        // Company code
        UILabel *companyLabel = [[UILabel alloc] init];
        companyLabel.tag = 1002;
        companyLabel.font = [UIFont systemFontOfSize:13];
        companyLabel.textColor = UIColor.systemGrayColor;
        companyLabel.translatesAutoresizingMaskIntoConstraints = NO;

        // Dot
        UILabel *dotLabel = [[UILabel alloc] init];
        dotLabel.text = @"·";
        dotLabel.tag = 1003;
        dotLabel.font = [UIFont systemFontOfSize:13];
        dotLabel.textColor = UIColor.systemGray3Color;
        dotLabel.translatesAutoresizingMaskIntoConstraints = NO;

        // Username
        UILabel *userLabel = [[UILabel alloc] init];
        userLabel.tag = 1004;
        userLabel.font = [UIFont systemFontOfSize:13];
        userLabel.textColor = UIColor.systemGrayColor;
        userLabel.translatesAutoresizingMaskIntoConstraints = NO;

        [cell.contentView addSubview:nameLabel];
        [cell.contentView addSubview:companyLabel];
        [cell.contentView addSubview:dotLabel];
        [cell.contentView addSubview:userLabel];

        // Constraints
        [NSLayoutConstraint activateConstraints:@[
            // Profile image
            [profileImageView.leadingAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor constant:16],
            [profileImageView.centerYAnchor constraintEqualToAnchor:cell.contentView.centerYAnchor],
            [profileImageView.widthAnchor constraintEqualToConstant:40],
            [profileImageView.heightAnchor constraintEqualToConstant:40],

            // Name label
            [nameLabel.topAnchor constraintEqualToAnchor:cell.contentView.topAnchor constant:12],
            [nameLabel.leadingAnchor constraintEqualToAnchor:profileImageView.trailingAnchor constant:12],
            [nameLabel.trailingAnchor constraintLessThanOrEqualToAnchor:cell.contentView.trailingAnchor constant:-16],

            // Company label
            [companyLabel.topAnchor constraintEqualToAnchor:nameLabel.bottomAnchor constant:4],
            [companyLabel.leadingAnchor constraintEqualToAnchor:nameLabel.leadingAnchor],

            // Dot
            [dotLabel.centerYAnchor constraintEqualToAnchor:companyLabel.centerYAnchor],
            [dotLabel.leadingAnchor constraintEqualToAnchor:companyLabel.trailingAnchor constant:6],

            // Username
            [userLabel.centerYAnchor constraintEqualToAnchor:companyLabel.centerYAnchor],
            [userLabel.leadingAnchor constraintEqualToAnchor:dotLabel.trailingAnchor constant:6],
            [userLabel.trailingAnchor constraintLessThanOrEqualToAnchor:cell.contentView.trailingAnchor constant:-16],
        ]];
    }

    NSDictionary *account = self.accounts[indexPath.row];

    UILabel *nameLabel = [cell.contentView viewWithTag:1001];
    UILabel *companyLabel = [cell.contentView viewWithTag:1002];
    UILabel *userLabel = [cell.contentView viewWithTag:1004];

    nameLabel.text = account[@"name"];
    companyLabel.text = account[@"company_code"];
    userLabel.text = account[@"userName"];

    // Right-side status
    BOOL loggedIn = [account[@"loggedIn"] boolValue];
    cell.accessoryView = nil;
  
    if (loggedIn) {
        UILabel *pill = [[UILabel alloc] initWithFrame:CGRectMake(0,0,88,28)];
        pill.text = @"Logged In";
        pill.font = [UIFont systemFontOfSize:12 weight:UIFontWeightSemibold];
        pill.textAlignment = NSTextAlignmentCenter;
        pill.backgroundColor = UIColor.systemGreenColor;
        pill.textColor = UIColor.whiteColor;
        pill.layer.cornerRadius = 14;
        pill.clipsToBounds = YES;
        cell.accessoryView = pill;
    } else {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        [btn setTitle:@"Switch" forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:13 weight:UIFontWeightSemibold];
        btn.layer.borderWidth = 1;
        btn.layer.borderColor = UIColor.systemGray4Color.CGColor;
        btn.layer.cornerRadius = 14;
        btn.frame = CGRectMake(0,0,88,28);
        cell.accessoryView = btn;
        [btn addTarget:self action:@selector(switchTapped:)
           forControlEvents:UIControlEventTouchUpInside];

    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)manageAccountsTapped {
  NSLog(@"Manage Accounts Tapped");
  [self dismissAddLinkSheet:^{
    ManageAccountViewController *vc = [[ManageAccountViewController alloc] init];
    vc.accounts = self.accounts;
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
  }];
}

-(void)switchTapped:(UIButton *)sender {
    // 1. Find the cell that contains this button
    UITableViewCell *cell = (UITableViewCell *)sender.superview;
    while (cell && ![cell isKindOfClass:[UITableViewCell class]]) {
        cell = (UITableViewCell *)cell.superview;
    }
    if (!cell) return;

    NSIndexPath *indexPath = [self.accountTable indexPathForCell:cell];
    if (!indexPath) return;

    // 2. Update self.accounts
    NSMutableArray *updatedAccounts = [self.accounts mutableCopy];
    
    // Set all loggedIn = NO first
    for (NSInteger i = 0; i < updatedAccounts.count; i++) {
        NSMutableDictionary *acct = [updatedAccounts[i] mutableCopy];
        acct[@"loggedIn"] = @NO;
        updatedAccounts[i] = acct;
    }

    // Set the selected account to loggedIn = YES
    NSMutableDictionary *selectedAccount = [updatedAccounts[indexPath.row] mutableCopy];
    selectedAccount[@"loggedIn"] = @YES;
    updatedAccounts[indexPath.row] = selectedAccount;

    self.accounts = [updatedAccounts copy];

    // 3. Reload the table
    [self.accountTable reloadData];
}

-(void)addAccountsTapped{
  NSLog(@"Add Accounts Tapped");
  [self dismissAddLinkSheet:^{
      // now fully dismissed, safe to show new sheet
      self.dimmedOverlay = [self buildDimmedOverlay];
      self.addLinkSheet = [self addAccountSheet];

      [self.view addSubview:self.dimmedOverlay];
      [self.view addSubview:self.addLinkSheet];

      NSLayoutConstraint *bottom = [self.addLinkSheet.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor constant:300];
      bottom.active = YES;

      [NSLayoutConstraint activateConstraints:@[
          [self.addLinkSheet.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
          [self.addLinkSheet.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
          [self.addLinkSheet.heightAnchor constraintEqualToConstant:250],
      ]];

      [self.view layoutIfNeeded];

      [UIView animateWithDuration:0.3 animations:^{
          self.dimmedOverlay.alpha = 1;
          bottom.constant = 0;
          [self.view layoutIfNeeded];
      }];
  }];

}

- (UIView *)addAccountSheet {
    UIView *sheet = [[UIView alloc] init];
    sheet.backgroundColor = UIColor.whiteColor;
    sheet.layer.cornerRadius = 24;
    sheet.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
    sheet.translatesAutoresizingMaskIntoConstraints = NO;

    UIView *header = [[UIView alloc] init];
    header.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:header];

    UILabel *title = [[UILabel alloc] init];
    title.text = @"Add Account";
    title.font = [UIFont systemFontOfSize:18 weight:UIFontWeightBold];
    title.translatesAutoresizingMaskIntoConstraints = NO;

//    UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    [closeButton setImage:[UIImage systemImageNamed:@"xmark"] forState:UIControlStateNormal];
//    closeButton.tintColor = UIColor.systemGrayColor;
//    [closeButton addTarget:self action:@selector(dismissAddLinkSheetButtonTapped:)
//          forControlEvents:UIControlEventTouchUpInside];
//    closeButton.translatesAutoresizingMaskIntoConstraints = NO;

    [header addSubview:title];
//    [header addSubview:closeButton];

    UILabel *subtitle = [[UILabel alloc] init];
    subtitle.text = @"Select an option to proceed.";
    subtitle.font = [UIFont systemFontOfSize:14];
    subtitle.textAlignment = NSTextAlignmentLeft;
    subtitle.numberOfLines = 0;
    subtitle.textColor = UIColor.darkGrayColor;
    subtitle.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:subtitle];
  
    UIView *spacer1 = [[UIView alloc] init];
    spacer1.translatesAutoresizingMaskIntoConstraints = NO;
    spacer1.layer.borderWidth = 0.5;
    spacer1.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [sheet addSubview:spacer1];

    // --- Existing Account ---
    UIView *existingAccount = [[UIView alloc] init];
    existingAccount.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:existingAccount];

    UILabel *existingTitle = [[UILabel alloc] init];
    existingTitle.text = @"Add Existing Account";
    existingTitle.font = [UIFont systemFontOfSize:16 weight:UIFontWeightBold];
    existingTitle.translatesAutoresizingMaskIntoConstraints = NO;

    UIButton *existingButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [existingButton setImage:[UIImage systemImageNamed:@"plus"] forState:UIControlStateNormal];
    existingButton.tintColor = UIColor.systemGrayColor;
    [existingButton addTarget:self action:@selector(existingButtonTapped)
          forControlEvents:UIControlEventTouchUpInside];
    existingButton.translatesAutoresizingMaskIntoConstraints = NO;

    [existingAccount addSubview:existingTitle];
    [existingAccount addSubview:existingButton];
  
    UIView *spacer2 = [[UIView alloc] init];
    spacer2.translatesAutoresizingMaskIntoConstraints = NO;
    spacer2.layer.borderWidth = 0.5;
    spacer2.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [sheet addSubview:spacer2];
  
    // --- New Account ---
    UIView *newAccount = [[UIView alloc] init];
    newAccount.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:newAccount];

    UILabel *newTitle = [[UILabel alloc] init];
    newTitle.text = @"Add New Account";
    newTitle.font = [UIFont systemFontOfSize:16 weight:UIFontWeightBold];
    newTitle.translatesAutoresizingMaskIntoConstraints = NO;

    UIButton *newButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [newButton setImage:[UIImage systemImageNamed:@"plus"] forState:UIControlStateNormal];
    newButton.tintColor = UIColor.systemGrayColor;
    [newButton addTarget:self action:@selector(newButtonTapped)
          forControlEvents:UIControlEventTouchUpInside];
    newButton.translatesAutoresizingMaskIntoConstraints = NO;

    [newAccount addSubview:newTitle];
    [newAccount addSubview:newButton];
  
    [NSLayoutConstraint activateConstraints:@[
        [header.topAnchor constraintEqualToAnchor:sheet.topAnchor constant:24],
        [header.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:20],
        [header.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-20],

        [title.leadingAnchor constraintEqualToAnchor:header.leadingAnchor],
        [title.topAnchor constraintEqualToAnchor:header.topAnchor],

//        [closeButton.trailingAnchor constraintEqualToAnchor:header.trailingAnchor],
//        [closeButton.centerYAnchor constraintEqualToAnchor:title.centerYAnchor],
//        [closeButton.heightAnchor constraintEqualToConstant:24],
//        [closeButton.widthAnchor constraintEqualToConstant:24],

        [subtitle.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:12],
        [subtitle.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:20],
        [subtitle.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-20],
        
        [spacer1.topAnchor constraintEqualToAnchor:subtitle.bottomAnchor constant:20],
        [spacer1.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor],
        [spacer1.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor],
        [spacer1.heightAnchor constraintEqualToConstant:1],
        
        [existingAccount.topAnchor constraintEqualToAnchor:spacer1.bottomAnchor constant:20],
        [existingAccount.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:16],
        [existingAccount.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-16],
        
        [existingTitle.topAnchor constraintEqualToAnchor:existingAccount.topAnchor],
        [existingTitle.leadingAnchor constraintEqualToAnchor:existingAccount.leadingAnchor],
        [existingTitle.trailingAnchor constraintEqualToAnchor:existingButton.leadingAnchor constant:-16],
        
        [existingButton.centerYAnchor constraintEqualToAnchor:existingTitle.centerYAnchor],
        [existingButton.trailingAnchor constraintEqualToAnchor:existingAccount.trailingAnchor],
        [existingButton.heightAnchor constraintEqualToConstant:24],
        [existingButton.widthAnchor constraintEqualToConstant:24],

        [spacer2.topAnchor constraintEqualToAnchor:existingButton.bottomAnchor constant:18],
        [spacer2.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:16],
        [spacer2.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-16],
        [spacer2.heightAnchor constraintEqualToConstant:1],
        
        [newAccount.topAnchor constraintEqualToAnchor:spacer2.bottomAnchor constant:18],
        [newAccount.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:16],
        [newAccount.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-16],
        
        [newTitle.topAnchor constraintEqualToAnchor:newAccount.topAnchor],
        [newTitle.leadingAnchor constraintEqualToAnchor:newAccount.leadingAnchor],
        [newTitle.trailingAnchor constraintEqualToAnchor:newButton.leadingAnchor constant:-16],
        
        [newButton.centerYAnchor constraintEqualToAnchor:newTitle.centerYAnchor],
        [newButton.trailingAnchor constraintEqualToAnchor:newAccount.trailingAnchor],
        [newButton.heightAnchor constraintEqualToConstant:24],
        [newButton.widthAnchor constraintEqualToConstant:24],
    ]];
    return sheet;
}

-(void)existingButtonTapped{
  NSLog(@"existing account button tapped");
}

-(void)newButtonTapped {
  NSLog(@"new account button tapped");
}


#pragma mark - Helpers
- (void)onBack {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
