//  SurveyViewController.mm
#import "APIClient.h"
#import "SurveyViewController.h"

@interface SurveyViewController ()

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

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIButton *submitButton;

// Survey Components
@property (nonatomic, assign) NSInteger surveyId;
@property (nonatomic, copy) NSString *question;
@property (nonatomic, copy) NSString *type;
@property (nonatomic, copy) NSString *style;
@property (nonatomic, assign) NSInteger numberOfRates;
@property (nonatomic, assign) BOOL mandatory;
@property (nonatomic, strong) NSArray<NSDictionary *> *ratesChecklist;
@property (nonatomic, strong) NSMutableDictionary<NSNumber *, id> *answers;
@property (nonatomic, assign) NSInteger selectedNPS;
@property (nonatomic, strong) NSDictionary *surveyData;

@end

@implementation SurveyViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;

    self.answers = [NSMutableDictionary dictionary];
    self.selectedNPS = -1;
    [self setupHeader];
    [self setupScrollView];
    [self requestSurvey];
}

#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.headerBar.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.headerBar];
    
    [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 = @"Handover Survey";
    self.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    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];
    
    for (UIView *sub in @[self.titleLabel, self.backButton]) {
        sub.translatesAutoresizingMaskIntoConstraints = NO;
        [self.headerBar addSubview:sub];
    }
    
    [NSLayoutConstraint activateConstraints:@[
        [self.backButton.leadingAnchor constraintEqualToAnchor:self.headerBar.leadingAnchor constant:16],
        [self.backButton.centerYAnchor constraintEqualToAnchor:self.headerBar.centerYAnchor],
        [self.backButton.widthAnchor constraintEqualToConstant:24],
        [self.backButton.heightAnchor constraintEqualToConstant:24],
        
        [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.headerBar.centerXAnchor],
        [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.headerBar.centerYAnchor],
    ]];
}

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

#pragma mark - Scroll View
- (void)setupScrollView {
    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;

    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.scrollView];

    [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],
    ]];
}

- (void)renderSurvey:(NSDictionary *)surveyData {
    NSArray *sections = surveyData[@"section"];
    UIView *previous = nil;

    for (NSDictionary *sectionDict in sections) {
        NSString *sectionName = sectionDict[@"name"];

        // Section Label
        UIView *sectionHeader = [[UIView alloc] init];
        sectionHeader.backgroundColor = UIColor.blackColor;
        sectionHeader.translatesAutoresizingMaskIntoConstraints = NO;

        UILabel *sectionLabel = [[UILabel alloc] init];
        sectionLabel.text = sectionName;
        sectionLabel.textColor = UIColor.whiteColor;
        sectionLabel.font = [UIFont systemFontOfSize:16];
        sectionLabel.numberOfLines = 0;
        sectionLabel.translatesAutoresizingMaskIntoConstraints = NO;

        [sectionHeader addSubview:sectionLabel];
        [self.contentView addSubview:sectionHeader];

        [NSLayoutConstraint activateConstraints:@[
            [sectionHeader.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
            [sectionHeader.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
            previous ?
              [sectionHeader.topAnchor constraintEqualToAnchor:previous.bottomAnchor constant:24] :
              [sectionHeader.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:24],

            [sectionLabel.topAnchor constraintEqualToAnchor:sectionHeader.topAnchor constant:12],
            [sectionLabel.bottomAnchor constraintEqualToAnchor:sectionHeader.bottomAnchor constant:-12],
            [sectionLabel.leadingAnchor constraintEqualToAnchor:sectionHeader.leadingAnchor constant:12],
            [sectionLabel.trailingAnchor constraintEqualToAnchor:sectionHeader.trailingAnchor constant:-12],
        ]];

        previous = sectionLabel;

        // Questions
        NSArray *surveys = sectionDict[@"survey"];
        for (NSDictionary *surveyItem in surveys) {
            UIView *questionView = [self buildQuestionView:surveyItem];
            [self.contentView addSubview:questionView];

            [NSLayoutConstraint activateConstraints:@[
                [questionView.topAnchor constraintEqualToAnchor:previous.bottomAnchor constant:16],
                [questionView.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
                [questionView.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
            ]];

            previous = questionView;
        }
    }

    self.submitButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.submitButton setTitle:@"Submit" forState:UIControlStateNormal];
    self.submitButton.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    [self.submitButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    self.submitButton.layer.cornerRadius = 12;
    self.submitButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.submitButton addTarget:self action:@selector(onSubmit) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.submitButton];
  
    [NSLayoutConstraint activateConstraints:@[
        [self.submitButton.topAnchor constraintEqualToAnchor:previous.bottomAnchor constant:32],
        [self.submitButton.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.submitButton.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
        [self.submitButton.heightAnchor constraintEqualToConstant:48],
        [self.submitButton.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-32],
    ]];
}

- (UIView *)buildQuestionView:(NSDictionary *)item {
    NSString *type = item[@"type"];
    NSString *style = item[@"style"];

    if ([type isEqualToString:@"rate"]) {
        if ([style isEqualToString:@"number"]) {
            return [self buildNumberRating:item];
        } else if ([style isEqualToString:@"star"]) {
            return [self buildStarRating:item];
        }
    } else if ([type isEqualToString:@"comment"]) {
        return [self buildCommentField:item];
    } else if ([type isEqualToString:@"rateNps"]) {
        return [self buildNPSRating:item];
    } else {
      return [self buildQuestionPlaceholder:item];
  }

  return [self buildQuestionPlaceholder:item];

}

- (UIView *)buildStarRating:(NSDictionary *)item {
    UIView *container = [[UIView alloc] init];
    container.translatesAutoresizingMaskIntoConstraints = NO;
    container.tag = [item[@"id"] integerValue];

    // Question
    UILabel *label = [self buildQuestionLabel:item];
    [container addSubview:label];

    // Helper
    UILabel *helper = [[UILabel alloc] init];
    helper.font = [UIFont systemFontOfSize:12];
    helper.textColor = UIColor.grayColor;
    helper.numberOfLines = 0;
    helper.translatesAutoresizingMaskIntoConstraints = NO;
    helper.text = [self buildRatesHelperText:item[@"rates_checklist_label"]];
    helper.hidden = (helper.text.length == 0);
    [container addSubview:helper];

    // Stars container
    UIView *starsContainer = [[UIView alloc] init];
    starsContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [container addSubview:starsContainer];

    NSInteger count = [item[@"number_of_rates"] integerValue];
    count = MAX(1, count);

    CGFloat spacing = 8;
    CGFloat size = [self buttonSizeForCount:count spacing:spacing];

    NSMutableArray *stars = [NSMutableArray array];
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];

    for (int i = 1; i <= count; i++) {
        UIButton *star = [UIButton buttonWithType:UIButtonTypeCustom];
        star.tag = i;

        [star setImage:[UIImage imageNamed:@"star_empty"
                                  inBundle:bundle
             compatibleWithTraitCollection:nil]
              forState:UIControlStateNormal];

        [star addTarget:self
                 action:@selector(onStarTapped:)
       forControlEvents:UIControlEventTouchUpInside];

        [stars addObject:star];
    }

    CGFloat height = [self layoutButtons:stars
                             inContainer:starsContainer
                               maxPerRow:count
                                spacing:spacing
                              buttonSize:size];
  
    CGFloat totalWidth = (size * count) + (spacing * (count - 1));
    [starsContainer.widthAnchor constraintEqualToConstant:totalWidth].active = YES;
    [starsContainer.heightAnchor constraintEqualToConstant:height].active = YES;

    // Constraints
    [NSLayoutConstraint activateConstraints:@[
        [label.topAnchor constraintEqualToAnchor:container.topAnchor],
        [label.leadingAnchor constraintEqualToAnchor:container.leadingAnchor],
        [label.trailingAnchor constraintEqualToAnchor:container.trailingAnchor],

        helper.hidden ?
        [starsContainer.topAnchor constraintEqualToAnchor:label.bottomAnchor constant:12] :
        [helper.topAnchor constraintEqualToAnchor:label.bottomAnchor constant:12],

        [helper.leadingAnchor constraintEqualToAnchor:container.leadingAnchor],
        [helper.trailingAnchor constraintEqualToAnchor:container.trailingAnchor],

        [starsContainer.topAnchor constraintEqualToAnchor:helper.bottomAnchor constant:8],
        [starsContainer.leadingAnchor constraintEqualToAnchor:container.leadingAnchor],
        [starsContainer.bottomAnchor constraintEqualToAnchor:container.bottomAnchor],
    ]];

    return container;
}

- (void)onStarTapped:(UIButton *)sender {
    UIView *starsContainer = sender.superview;
    UIView *questionContainer = starsContainer.superview;
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSInteger selected = sender.tag;

    for (UIButton *star in starsContainer.subviews) {
        if (star.tag <= selected) {
            [star setImage:[UIImage imageNamed:@"star_full" inBundle:bundle compatibleWithTraitCollection:nil]
                  forState:UIControlStateNormal];
        } else {
            [star setImage:[UIImage imageNamed:@"star_empty" inBundle:bundle compatibleWithTraitCollection:nil]
                  forState:UIControlStateNormal];
        }
    }

    NSNumber *questionId = @(questionContainer.tag);
    self.answers[questionId] = @(selected);

    NSLog(@"⭐ Saved Q%@ = %@", questionId, self.answers[questionId]);
}

- (UIView *)buildCommentField:(NSDictionary *)item {
    UIView *container = [[UIView alloc] init];
    container.translatesAutoresizingMaskIntoConstraints = NO;

    UILabel *label = [self buildQuestionLabel:item];
    [container addSubview:label];

    UITextField *textField = [[UITextField alloc] init];
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.translatesAutoresizingMaskIntoConstraints = NO;
    [container addSubview:textField];
    textField.tag = [item[@"id"] integerValue];
    [textField addTarget:self
                   action:@selector(onCommentChanged:)
         forControlEvents:UIControlEventEditingChanged];


    [NSLayoutConstraint activateConstraints:@[
        [label.topAnchor constraintEqualToAnchor:container.topAnchor],
        [label.leadingAnchor constraintEqualToAnchor:container.leadingAnchor],
        [label.trailingAnchor constraintEqualToAnchor:container.trailingAnchor],

        [textField.topAnchor constraintEqualToAnchor:label.bottomAnchor constant:8],
        [textField.leadingAnchor constraintEqualToAnchor:container.leadingAnchor],
        [textField.trailingAnchor constraintEqualToAnchor:container.trailingAnchor],
        [textField.heightAnchor constraintEqualToConstant:32],
        [textField.bottomAnchor constraintEqualToAnchor:container.bottomAnchor],
    ]];
    container.tag = [item[@"id"] integerValue];
    return container;
}

- (void)onCommentChanged:(UITextField *)field {
    self.answers[@(field.tag)] = field.text ?: @"";
}

- (UIView *)buildNPSRating:(NSDictionary *)item {
    UIView *container = [[UIView alloc] init];
    container.translatesAutoresizingMaskIntoConstraints = NO;
    container.tag = [item[@"id"] integerValue];

    // Question
    UILabel *label = [self buildQuestionLabel:item];
    [container addSubview:label];

    // Helper
    UILabel *helper = [[UILabel alloc] init];
    helper.font = [UIFont systemFontOfSize:12];
    helper.textColor = UIColor.grayColor;
    helper.numberOfLines = 0;
    helper.translatesAutoresizingMaskIntoConstraints = NO;
    helper.text = [self buildRatesHelperText:item[@"rates_checklist_label"]];
    helper.hidden = (helper.text.length == 0);
    [container addSubview:helper];

    // Buttons container
    UIView *buttonsContainer = [[UIView alloc] init];
    buttonsContainer.translatesAutoresizingMaskIntoConstraints = NO;
  
    [container addSubview:buttonsContainer];

      NSInteger count = [item[@"number_of_rates"] integerValue];
      CGFloat spacing = 6;
      CGFloat size = [self buttonSizeForCount:MIN(count, 8) spacing:spacing];

      NSMutableArray *buttons = [NSMutableArray array];

      for (int i = 0; i < count; i++) {
          UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
          btn.tag = i;

          btn.layer.cornerRadius = 6;
          btn.layer.borderWidth = 1;
          btn.layer.borderColor = UIColor.lightGrayColor.CGColor;

          [btn setTitle:[NSString stringWithFormat:@"%d", i]
                forState:UIControlStateNormal];
          [btn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];

          [btn addTarget:self
                  action:@selector(onNPSTapped:)
        forControlEvents:UIControlEventTouchUpInside];

          [buttons addObject:btn];
      }

      CGFloat height = [self layoutButtons:buttons
                               inContainer:buttonsContainer
                                 maxPerRow:8
                                  spacing:spacing
                                buttonSize:size];

      [buttonsContainer.heightAnchor constraintEqualToConstant:height].active = YES;

    // Constraints
    [NSLayoutConstraint activateConstraints:@[
        [label.topAnchor constraintEqualToAnchor:container.topAnchor],
        [label.leadingAnchor constraintEqualToAnchor:container.leadingAnchor],
        [label.trailingAnchor constraintEqualToAnchor:container.trailingAnchor],

        helper.hidden ?
        [buttonsContainer.topAnchor constraintEqualToAnchor:label.bottomAnchor constant:8] :
        [helper.topAnchor constraintEqualToAnchor:label.bottomAnchor constant:12],

        [helper.leadingAnchor constraintEqualToAnchor:container.leadingAnchor],
        [helper.trailingAnchor constraintEqualToAnchor:container.trailingAnchor],

        [buttonsContainer.topAnchor constraintEqualToAnchor:helper.bottomAnchor constant:8],
        [buttonsContainer.leadingAnchor constraintEqualToAnchor:container.leadingAnchor],
        [buttonsContainer.trailingAnchor constraintEqualToAnchor:container.trailingAnchor],
        [buttonsContainer.bottomAnchor constraintEqualToAnchor:container.bottomAnchor],
    ]];

    return container;
}

- (void)onNPSTapped:(UIButton *)sender {
    UIView *buttonsContainer = sender.superview;
    UIView *questionContainer = buttonsContainer.superview;

    self.selectedNPS = sender.tag;

    for (UIButton *btn in buttonsContainer.subviews) {
        if (btn.tag <= self.selectedNPS) {
            btn.backgroundColor = [self npsColorForValue:btn.tag];
            btn.layer.borderColor = UIColor.clearColor.CGColor;
            [btn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        } else {
            btn.backgroundColor = UIColor.clearColor;
            btn.layer.borderColor = UIColor.lightGrayColor.CGColor;
            [btn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        }
    }

    NSNumber *questionId = @(questionContainer.tag);
    self.answers[questionId] = @(self.selectedNPS);

    NSLog(@"📊 Saved NPS Q%@ = %@", questionId, self.answers[questionId]);
}

- (UIColor *)npsColorForValue:(NSInteger)value {
    if (value <= 1) {
        return [UIColor colorWithRed:0.86 green:0.23 blue:0.23 alpha:1.0]; // red
    } else if (value <= 6) {
        return [UIColor colorWithRed:0.96 green:0.58 blue:0.11 alpha:1.0]; // orange
    } else if (value <= 8) {
        return [UIColor colorWithRed:0.96 green:0.79 blue:0.11 alpha:1.0]; // yellow
    } else {
        return [UIColor colorWithRed:0.24 green:0.70 blue:0.44 alpha:1.0]; // green
    }
}

- (UIView *)buildNumberRating:(NSDictionary *)item {
    UIView *container = [[UIView alloc] init];
    container.translatesAutoresizingMaskIntoConstraints = NO;
    container.tag = [item[@"id"] integerValue];

    // Question
    UILabel *label = [self buildQuestionLabel:item];
    [container addSubview:label];

    // Helper
    UILabel *helper = [[UILabel alloc] init];
    helper.font = [UIFont systemFontOfSize:12];
    helper.textColor = UIColor.grayColor;
    helper.numberOfLines = 0;
    helper.translatesAutoresizingMaskIntoConstraints = NO;
    helper.text = [self buildRatesHelperText:item[@"rates_checklist_label"]];
    helper.hidden = (helper.text.length == 0);
    [container addSubview:helper];

    // Buttons container (wrap layout)
    UIView *buttonsContainer = [[UIView alloc] init];
    buttonsContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [container addSubview:buttonsContainer];

    NSInteger count = [item[@"number_of_rates"] integerValue];
    CGFloat spacing = 8;
    CGFloat size = [self buttonSizeForCount:MIN(count, 8) spacing:spacing];

    NSMutableArray *buttons = [NSMutableArray array];

    for (int i = 1; i <= count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        btn.tag = i;

        btn.layer.cornerRadius = 6;
        btn.layer.borderWidth = 1;
        btn.layer.borderColor = UIColor.lightGrayColor.CGColor;

        [btn setTitle:[NSString stringWithFormat:@"%d", i]
              forState:UIControlStateNormal];
        [btn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        [btn addTarget:self
                action:@selector(onNumberTapped:)
      forControlEvents:UIControlEventTouchUpInside];

        [buttons addObject:btn];
    }

    CGFloat height = [self layoutButtons:buttons
                             inContainer:buttonsContainer
                               maxPerRow:8
                                spacing:spacing
                              buttonSize:size];

    [buttonsContainer.heightAnchor constraintEqualToConstant:height].active = YES;

    // Constraints
    [NSLayoutConstraint activateConstraints:@[
        [label.topAnchor constraintEqualToAnchor:container.topAnchor],
        [label.leadingAnchor constraintEqualToAnchor:container.leadingAnchor],
        [label.trailingAnchor constraintEqualToAnchor:container.trailingAnchor],

        helper.hidden ?
        [buttonsContainer.topAnchor constraintEqualToAnchor:label.bottomAnchor constant:8] :
        [helper.topAnchor constraintEqualToAnchor:label.bottomAnchor constant:12],

        [helper.leadingAnchor constraintEqualToAnchor:container.leadingAnchor],
        [helper.trailingAnchor constraintEqualToAnchor:container.trailingAnchor],

        [buttonsContainer.topAnchor constraintEqualToAnchor:helper.bottomAnchor constant:8],
        [buttonsContainer.leadingAnchor constraintEqualToAnchor:container.leadingAnchor],
        [buttonsContainer.trailingAnchor constraintEqualToAnchor:container.trailingAnchor],
        [buttonsContainer.bottomAnchor constraintEqualToAnchor:container.bottomAnchor],
    ]];

    return container;
}

- (void)onNumberTapped:(UIButton *)sender {
    UIView *buttonsContainer = sender.superview;
    UIView *questionContainer = buttonsContainer.superview;

    // Reset all buttons
    for (UIButton *btn in buttonsContainer.subviews) {
        btn.backgroundColor = UIColor.whiteColor;
        btn.layer.borderColor = UIColor.lightGrayColor.CGColor;
        [btn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
    }

    // Highlight selected
    sender.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    sender.layer.borderColor = UIColor.clearColor.CGColor;
    [sender setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];

    NSNumber *questionId = @(questionContainer.tag);
    self.answers[questionId] = @(sender.tag);

    NSLog(@"🔢 Saved Q%@ = %@", questionId, self.answers[questionId]);
}

- (void)onSubmit {
    NSLog(@"submit pressed");

    // 1️⃣ Validate mandatory questions
    for (NSDictionary *section in self.surveyData[@"section"]) {
        for (NSDictionary *question in section[@"survey"]) {
            NSInteger qId = [question[@"id"] integerValue];
            BOOL mandatory = [question[@"mandatory"] boolValue];

            if (mandatory) {
                id answer = self.answers[@(qId)];

                // Check empty or nil
                BOOL emptyAnswer = NO;
                if (!answer) {
                    emptyAnswer = YES;
                } else if ([answer isKindOfClass:[NSString class]] && [(NSString *)answer length] == 0) {
                    emptyAnswer = YES;
                }

                if (emptyAnswer) {
                    NSString *msg = [NSString stringWithFormat:@"Please answer mandatory question:\n%@", question[@"question"]];
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Incomplete"
                                                                                   message:msg
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    [alert addAction:[UIAlertAction actionWithTitle:@"OK"
                                                              style:UIAlertActionStyleDefault
                                                            handler:nil]];
                    [self presentViewController:alert animated:YES completion:nil];
                    return; // stop submission
                }
            }
        }
    }

    // 2️⃣ All mandatory answered, proceed to submit
    [self requestSubmitSurvey];
}

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

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

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

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

    NSArray *surveyArray = data[@"Data"];
    if (![surveyArray isKindOfClass:[NSArray class]] || surveyArray.count == 0) {
        NSLog(@"❌ Invalid notification format");
        return;
    }

    NSDictionary *survey = surveyArray[0]; // First survey object
    if (![survey isKindOfClass:[NSDictionary class]]) {
        NSLog(@"❌ Invalid survey format");
        return;
    }

    dispatch_async(dispatch_get_main_queue(), ^{
        self.surveyData = survey;
        self.surveyId = [survey[@"id"] integerValue];
        self.question = survey[@"question"];
        self.type = survey[@"type"];
        self.style = survey[@"style"];
        self.numberOfRates = [survey[@"number_of_rates"] integerValue];
        self.mandatory = [survey[@"mandatory"] boolValue];
        self.ratesChecklist = survey[@"rates_checklist_label"];
      
        [self renderSurvey:survey];
    });
  }];
}

- (UIView *)buildQuestionPlaceholder:(NSDictionary *)item {
    UIView *container = [[UIView alloc] init];
    container.translatesAutoresizingMaskIntoConstraints = NO;

    UILabel *label = [self buildQuestionLabel:item];
    [container addSubview:label];

    UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:@[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10"]];
    seg.translatesAutoresizingMaskIntoConstraints = NO;
    [container addSubview:seg];

    [NSLayoutConstraint activateConstraints:@[
        [label.topAnchor constraintEqualToAnchor:container.topAnchor],
        [label.leadingAnchor constraintEqualToAnchor:container.leadingAnchor],
        [label.trailingAnchor constraintEqualToAnchor:container.trailingAnchor],

        [seg.topAnchor constraintEqualToAnchor:label.bottomAnchor constant:8],
        [seg.leadingAnchor constraintEqualToAnchor:container.leadingAnchor],
        [seg.trailingAnchor constraintEqualToAnchor:container.trailingAnchor],
        [seg.bottomAnchor constraintEqualToAnchor:container.bottomAnchor],
    ]];

    return container;
}

- (void)requestSubmitSurvey {

    if (self.answers.count == 0) {
        NSLog(@"❌ No answers to submit");
        return;
    }

    NSMutableDictionary<NSNumber *, NSDictionary *> *formattedAnswers =
        [NSMutableDictionary dictionary];

    [self.answers enumerateKeysAndObjectsUsingBlock:^(NSNumber *questionId,
                                                      id value,
                                                      BOOL *stop) {

        NSString *valueString = @"";
        NSString *commentString = @"";

        if ([value isKindOfClass:[NSString class]]) {
            // Comment-only question
            commentString = value;
        } else {
            // Rating / NPS / star
            valueString = [value description];
        }

        formattedAnswers[questionId] = @{
            @"value": valueString,
            @"comment": commentString
        };
    }];

    NSLog(@"📦 Submitting survey answers: %@", formattedAnswers);

    [APIClient requestSubmitSurveyWithFormId:[NSString stringWithFormat:@"%ld",
                                              (long)self.surveyId]
                              surveyAnswers:formattedAnswers
                                  completion:^(BOOL success,
                                               NSDictionary *response,
                                               NSError *error) {

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

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

        NSLog(@"✅ Survey submitted successfully");

        dispatch_async(dispatch_get_main_queue(), ^{
            [self onBack];
        });
    }];
}

- (NSString *)buildRatesHelperText:(NSArray *)labels {
    if (![labels isKindOfClass:[NSArray class]] || labels.count == 0) {
        return nil;
    }

    NSMutableArray *parts = [NSMutableArray array];

    for (NSDictionary *item in labels) {
        NSNumber *value = item[@"value"];
        NSString *label = item[@"label"];

        if (value && label && ![label isKindOfClass:[NSNull class]]) {
            [parts addObject:[NSString stringWithFormat:@"%@ = %@", value, label]];
        }
    }

    return parts.count > 0 ? [parts componentsJoinedByString:@"   "] : nil;
}

- (CGFloat)buttonSizeForCount:(NSInteger)count spacing:(CGFloat)spacing {
    CGFloat horizontalPadding = 32; // match your container padding
    CGFloat availableWidth = UIScreen.mainScreen.bounds.size.width - horizontalPadding;

    CGFloat rawSize = (availableWidth - (spacing * (count - 1))) / count;
    return MIN(36, floor(rawSize));
}

- (CGFloat)layoutButtons:(NSArray<UIButton *> *)buttons
             inContainer:(UIView *)container
               maxPerRow:(NSInteger)maxPerRow
                spacing:(CGFloat)spacing
              buttonSize:(CGFloat)buttonSize {

    CGFloat x = 0;
    CGFloat y = 0;
    NSInteger index = 0;

    for (UIButton *btn in buttons) {
        if (index > 0 && index % maxPerRow == 0) {
            x = 0;
            y += buttonSize + spacing;
        }

        btn.frame = CGRectMake(x, y, buttonSize, buttonSize);
        [container addSubview:btn];

        x += buttonSize + spacing;
        index++;
    }

    return y + buttonSize;
}

- (UILabel *)buildQuestionLabel:(NSDictionary *)item {
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:15 weight:UIFontWeightBold];
    label.numberOfLines = 0;
    label.translatesAutoresizingMaskIntoConstraints = NO;

    NSString *question = item[@"question"] ?: @"";
    BOOL mandatory = [item[@"mandatory"] boolValue];

    if (mandatory) {
        NSMutableAttributedString *attr =
        [[NSMutableAttributedString alloc] initWithString:
         [NSString stringWithFormat:@"* %@", question]];

        [attr addAttribute:NSForegroundColorAttributeName
                     value:UIColor.redColor
                     range:NSMakeRange(0, 1)];

        [attr addAttribute:NSForegroundColorAttributeName
                     value:UIColor.blackColor
                     range:NSMakeRange(2, attr.length - 2)];

        label.attributedText = attr;
    } else {
        label.text = question;
    }

    return label;
}

- (void)appendFormField:(NSMutableData *)body
               boundary:(NSString *)boundary
                   key:(NSString *)key
                 value:(NSString *)value {

    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary]
                     dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:
                       @"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key]
                     dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:@"%@\r\n", value ?: @""]
                     dataUsingEncoding:NSUTF8StringEncoding]];
}


@end
