//  AppointmentViewController.mm

#import "AppointmentViewController.h"
#import <UIKit/UIKit.h>
#import "APIClient.h"
#import <WebKit/WebKit.h>
#import "CalendarView.h"
#import "NSDate+CalendarHelpers.h"
#import "AppointmentTimeSlotViewController.h"
#import "PullToRefresh.h"
#import "AppointmentTutorialViewController.h"

@interface AppointmentViewController () <WKNavigationDelegate, WKUIDelegate, UIScrollViewDelegate, CalendarViewDelegate>

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

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

@property (nonatomic, strong) NSArray *representativeList;

// Terms & Conditions
@property (nonatomic, strong) UIView *termsOverlay;
@property (nonatomic, strong) UITextView *termsTextView;
@property (nonatomic, strong) UIButton *agreeButton;
@property (nonatomic, assign) BOOL hasAgreedToTerms;
@property (nonatomic, strong) UILabel *termsTitleLabel;
@property (nonatomic, strong) UIView *termsContainer;
@property (nonatomic, strong) NSDictionary *appointmentData;
@property (nonatomic, strong) WKWebView *termsWebView;
@property (nonatomic, strong) NSString *termsAndCondition;
@property (nonatomic, strong) NSString *appointmentType;
@property (nonatomic, assign) BOOL hasLoadedTermsHTML;

// Labels
@property (nonatomic, strong) UILabel *unitLabel;
@property (nonatomic, strong) UILabel *unitName;
@property (nonatomic, strong) UILabel *stepLabel;

// Calendar
@property (nonatomic, strong) UIView *calendarContainer;
@property (nonatomic, strong) UIStackView *legendStack;
@property (nonatomic, strong) CalendarView *calendarView;
@property (nonatomic, strong, readwrite) UICollectionView *collectionView;

// Footer buttons
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UIButton *backFooterButton;
@property (nonatomic, strong) UIButton *nextFooterButton;

@end

@implementation AppointmentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    [self requestAppointment];
    [self requestGeneralInfo];
    [self setupHeader];
    [self setupFooter];

    [self setupUI];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    if (self.termsAndCondition && !self.hasLoadedTermsHTML) {
        [self.termsWebView loadHTMLString:self.termsAndCondition baseURL:nil];
        self.hasLoadedTermsHTML = YES;
    }
}

#pragma mark - Setup UI
- (void)setupUI {
    // Scroll view
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    self.scrollView.alwaysBounceVertical = YES;
    [self.view addSubview:self.scrollView];

    self.contentView = [[UIView alloc] init];
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.scrollView addSubview:self.contentView];

    [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:self.footerView.topAnchor],

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

    // Create labels, calendar, legend
    [self setupLabels:self.contentView];
    [self setupCalendarSection:self.contentView];

    // Optional: wrap in stack if you want
    UIStackView *contentStack = [[UIStackView alloc] initWithArrangedSubviews:@[self.unitLabel, self.unitName, self.stepLabel, self.calendarContainer, self.legendStack]];
    contentStack.axis = UILayoutConstraintAxisVertical;
    contentStack.spacing = 16;
    contentStack.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:contentStack];

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

    [self setupTermsOverlay];

    // Pull-to-refresh
    __weak typeof(self) weakSelf = self;
    [self.scrollView addPullToRefresh:^(UIRefreshControl *refreshControl) {
        [weakSelf refreshAppointmentData:refreshControl];
    }];
}


#pragma mark - Navigation Bar

- (void)setupHeader {
  UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
  
  //Header
  self.headerBar = [[UIView alloc] init];
  self.headerBar.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0]; // #006D8D
  [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],
  ]];
  
  // Title
  self.titleLabel = [[UILabel alloc] init];
  self.titleLabel.text = @"Make Appointment";
  self.titleLabel.textColor = UIColor.whiteColor;
  self.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
  self.titleLabel.textAlignment = NSTextAlignmentCenter;
  
  // Back button
  self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
  [self.backButton setImage:[UIImage systemImageNamed:@"xmark"] forState:UIControlStateNormal];
  self.backButton.tintColor = UIColor.whiteColor;
  [self.backButton addTarget:self
                      action:@selector(handleBackTapped)
            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.heightAnchor constraintEqualToConstant:24],
    [self.backButton.widthAnchor constraintEqualToConstant:24],
    
    [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.headerBar.centerXAnchor],
    [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.headerBar.centerYAnchor],
  ]];
  
  self.helpButton = [UIButton buttonWithType:UIButtonTypeSystem];
  self.helpButton.translatesAutoresizingMaskIntoConstraints = NO;
  [self.helpButton setImage:[UIImage systemImageNamed:@"questionmark.circle"] forState:UIControlStateNormal];
  self.helpButton.tintColor = UIColor.whiteColor;
  [self.helpButton addTarget:self
                      action:@selector(showTutorial)
            forControlEvents:UIControlEventTouchUpInside];
  [self.headerBar addSubview:self.helpButton];
  
  [NSLayoutConstraint activateConstraints:@[
    [self.helpButton.trailingAnchor constraintEqualToAnchor:self.headerBar.trailingAnchor constant:-16],
    [self.helpButton.centerYAnchor constraintEqualToAnchor:self.backButton.centerYAnchor],
    [self.helpButton.widthAnchor constraintEqualToConstant:24],
    [self.helpButton.heightAnchor constraintEqualToConstant:24],
  ]];

}

#pragma mark = Overlay t&c
- (void)setupTermsOverlay {
    // Overlay background
    self.termsOverlay = [[UIView alloc] init];
    self.termsOverlay.backgroundColor = UIColor.whiteColor;
    self.termsOverlay.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.termsOverlay];

    [NSLayoutConstraint activateConstraints:@[
        [self.termsOverlay.topAnchor constraintEqualToAnchor:self.headerBar.bottomAnchor],
        [self.termsOverlay.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.termsOverlay.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.termsOverlay.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor]
    ]];

    // Title
    self.termsTitleLabel = [[UILabel alloc] init];
    self.termsTitleLabel.text = @"Terms & Conditions";
    self.termsTitleLabel.font = [UIFont boldSystemFontOfSize:18];
    self.termsTitleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.termsOverlay addSubview:self.termsTitleLabel];

    // WebView container
    self.termsContainer = [[UIView alloc] init];
    self.termsContainer.backgroundColor = [UIColor clearColor];
    self.termsContainer.layer.cornerRadius = 12.0;
    self.termsContainer.translatesAutoresizingMaskIntoConstraints = NO;
    self.termsContainer.layer.cornerRadius = 12.0;
    self.termsContainer.clipsToBounds = YES;
    [self.termsOverlay addSubview:self.termsContainer];

    // WKWebView
    self.termsWebView = [[WKWebView alloc] initWithFrame:CGRectZero];
    self.termsWebView.translatesAutoresizingMaskIntoConstraints = NO;
    self.termsWebView.scrollView.delegate = self;
    self.termsWebView.navigationDelegate = self;
    self.termsWebView.opaque = NO;
    self.termsWebView.backgroundColor = [UIColor clearColor];
    [self.termsContainer addSubview:self.termsWebView];

    // Agree button
    self.agreeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.agreeButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.agreeButton setTitle:@"Agree and Continue" forState:UIControlStateNormal];
    self.agreeButton.enabled = NO;
    self.agreeButton.backgroundColor = UIColor.lightGrayColor;
    self.agreeButton.tintColor = UIColor.whiteColor;
    self.agreeButton.layer.cornerRadius = 10.0;
    [self.agreeButton addTarget:self action:@selector(handleAgreeTapped)
               forControlEvents:UIControlEventTouchUpInside];
    [self.termsOverlay addSubview:self.agreeButton];

    // Layout constraints
    [NSLayoutConstraint activateConstraints:@[
        [self.termsTitleLabel.topAnchor constraintEqualToAnchor:self.termsOverlay.topAnchor constant:34],
        [self.termsTitleLabel.leadingAnchor constraintEqualToAnchor:self.termsOverlay.leadingAnchor constant:16],
        [self.termsTitleLabel.trailingAnchor constraintEqualToAnchor:self.termsOverlay.trailingAnchor constant:-20],

        [self.termsContainer.topAnchor constraintEqualToAnchor:self.termsTitleLabel.bottomAnchor constant:16],
        [self.termsContainer.leadingAnchor constraintEqualToAnchor:self.termsOverlay.leadingAnchor constant:16],
        [self.termsContainer.trailingAnchor constraintEqualToAnchor:self.termsOverlay.trailingAnchor constant:-16],
        [self.termsContainer.bottomAnchor constraintEqualToAnchor:self.agreeButton.topAnchor constant:-20],

        [self.termsWebView.topAnchor constraintEqualToAnchor:self.termsContainer.topAnchor],
        [self.termsWebView.leadingAnchor constraintEqualToAnchor:self.termsContainer.leadingAnchor],
        [self.termsWebView.trailingAnchor constraintEqualToAnchor:self.termsContainer.trailingAnchor],
        [self.termsWebView.bottomAnchor constraintEqualToAnchor:self.termsContainer.bottomAnchor],

        [self.agreeButton.leadingAnchor constraintEqualToAnchor:self.termsOverlay.leadingAnchor constant:16],
        [self.agreeButton.trailingAnchor constraintEqualToAnchor:self.termsOverlay.trailingAnchor constant:-16],
        [self.agreeButton.bottomAnchor constraintEqualToAnchor:self.termsOverlay.safeAreaLayoutGuide.bottomAnchor constant:-20],
        [self.agreeButton.heightAnchor constraintEqualToConstant:50],
    ]];
}

#pragma mark - Labels
- (void)setupLabels:(UIView *)parent {
    self.unitLabel = [[UILabel alloc] init];
    self.unitLabel.text = @"For Unit No.:";
    self.unitLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightThin];
    self.unitLabel.textColor = [UIColor grayColor];
    self.unitLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [parent addSubview:self.unitLabel];
  
    self.unitName = [[UILabel alloc] init];
    self.unitName.text = [NSString stringWithFormat:@"%@, %@", self.projectName, self.projectCode];
    self.unitName.font = [UIFont boldSystemFontOfSize:16];
    self.unitName.textColor = [UIColor blackColor];
    self.unitName.translatesAutoresizingMaskIntoConstraints = NO;
    [parent addSubview:self.unitName];

    self.stepLabel = [[UILabel alloc] init];
    self.stepLabel.text = @"Step 1/3: Select your preferred date";
    self.stepLabel.font = [UIFont systemFontOfSize:14];
    self.stepLabel.textColor = [UIColor blackColor];
    self.stepLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.stepLabel.textAlignment = NSTextAlignmentCenter;
    self.stepLabel.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
    self.stepLabel.layer.cornerRadius = 12.0;
    self.stepLabel.clipsToBounds = YES;
    [parent addSubview:self.stepLabel];

    [NSLayoutConstraint activateConstraints:@[
        [self.unitLabel.topAnchor constraintEqualToAnchor:parent.topAnchor constant:20],
        [self.unitLabel.leadingAnchor constraintEqualToAnchor:parent.leadingAnchor constant:16],
        [self.unitLabel.trailingAnchor constraintEqualToAnchor:parent.trailingAnchor constant:-16],

        [self.unitName.topAnchor constraintEqualToAnchor:self.unitLabel.bottomAnchor constant:8],
        [self.unitName.leadingAnchor constraintEqualToAnchor:parent.leadingAnchor constant:16],
        [self.unitName.trailingAnchor constraintEqualToAnchor:parent.trailingAnchor constant:-16],
        
        [self.stepLabel.topAnchor constraintEqualToAnchor:self.unitName.bottomAnchor constant:20],
        [self.stepLabel.leadingAnchor constraintEqualToAnchor:parent.leadingAnchor constant:16],
        [self.stepLabel.trailingAnchor constraintEqualToAnchor:parent.trailingAnchor constant:-16],
        [self.stepLabel.heightAnchor constraintEqualToConstant:44]
    ]];
}

#pragma mark - Calendar Section
- (void)setupCalendarSection:(UIView *)parent {
    self.calendarContainer = [[UIView alloc] init];
    self.calendarContainer.backgroundColor = [UIColor whiteColor];
    self.calendarContainer.layer.cornerRadius = 12.0;
    self.calendarContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [parent addSubview:self.calendarContainer];

    self.calendarView = [[CalendarView alloc] initWithFrame:CGRectZero];
    self.calendarView.translatesAutoresizingMaskIntoConstraints = NO;
    self.calendarView.delegate = self;
    [self.calendarContainer addSubview:self.calendarView];

    // Legend stack
    self.legendStack = [[UIStackView alloc] init];
    self.legendStack.axis = UILayoutConstraintAxisHorizontal;
    self.legendStack.alignment = UIStackViewAlignmentCenter;
    self.legendStack.distribution = UIStackViewDistributionEqualSpacing;
    self.legendStack.translatesAutoresizingMaskIntoConstraints = NO;
    self.legendStack.spacing = 5.0;
    [self.calendarContainer addSubview:self.legendStack];

    NSArray *legendData = @[
        @{@"title": @"Available", @"color": UIColor.systemGreenColor},
        @{@"title": @"Limited", @"color": UIColor.systemOrangeColor},
        @{@"title": @"Unavailable", @"color": UIColor.systemRedColor}
    ];

    for (NSDictionary *item in legendData) {
        UIView *dot = [[UIView alloc] init];
        dot.backgroundColor = item[@"color"];
        dot.layer.cornerRadius = 6;
        dot.translatesAutoresizingMaskIntoConstraints = NO;
        [dot.heightAnchor constraintEqualToConstant:12].active = YES;
        [dot.widthAnchor constraintEqualToConstant:12].active = YES;

        UILabel *label = [[UILabel alloc] init];
        label.text = item[@"title"];
        label.font = [UIFont systemFontOfSize:13];

        UIStackView *pair = [[UIStackView alloc] initWithArrangedSubviews:@[dot, label]];
        pair.axis = UILayoutConstraintAxisHorizontal;
        pair.spacing = 4.0;

        [self.legendStack addArrangedSubview:pair];
    }

    CGFloat w = UIScreen.mainScreen.bounds.size.width - 16 - 16 - 12 - 12; // container + inner padding
    CGFloat cell = floor(w / 7.0);
    CGFloat rows = 6; // max rows
    CGFloat calendarHeight = 40 + 28 + (cell * 0.9 + 12) * rows + 12 + 20;

    [NSLayoutConstraint activateConstraints:@[
        [self.calendarContainer.topAnchor constraintEqualToAnchor:self.stepLabel.bottomAnchor constant:24],
        [self.calendarContainer.leadingAnchor constraintEqualToAnchor:parent.leadingAnchor constant:16],
        [self.calendarContainer.trailingAnchor constraintEqualToAnchor:parent.trailingAnchor constant:-16],
        [self.calendarContainer.heightAnchor constraintEqualToConstant:calendarHeight],

        [self.calendarView.topAnchor constraintEqualToAnchor:self.calendarContainer.topAnchor],
        [self.calendarView.leadingAnchor constraintEqualToAnchor:self.calendarContainer.leadingAnchor constant:16],
        [self.calendarView.trailingAnchor constraintEqualToAnchor:self.calendarContainer.trailingAnchor constant:-16],
        [self.calendarView.bottomAnchor constraintEqualToAnchor:self.calendarContainer.bottomAnchor],

        [self.legendStack.topAnchor constraintEqualToAnchor:self.calendarContainer.bottomAnchor constant:30],
        [self.legendStack.leadingAnchor constraintEqualToAnchor:self.calendarContainer.leadingAnchor],
        [self.legendStack.trailingAnchor constraintEqualToAnchor:self.calendarContainer.trailingAnchor],
        [self.legendStack.centerXAnchor constraintEqualToAnchor:self.calendarContainer.centerXAnchor],
    ]];
}

#pragma mark - Footer Buttons
- (void)setupFooter {
  self.footerView = [[UIView alloc] init];
  self.footerView.backgroundColor = UIColor.whiteColor;
  self.footerView.layer.shadowOpacity = 0.1;
  self.footerView.layer.shadowOffset = CGSizeMake(0, -1);
  self.footerView.translatesAutoresizingMaskIntoConstraints = NO;
  self.footerView.userInteractionEnabled = YES;
  [self.view addSubview:self.footerView];
  
  [NSLayoutConstraint activateConstraints:@[
    [self.footerView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
    [self.footerView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
    [self.footerView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor],
    [self.footerView.heightAnchor constraintEqualToConstant:80]
  ]];
  
  self.backFooterButton = [UIButton buttonWithType:UIButtonTypeSystem];
  [self.backFooterButton setTitle:@"Back" forState:UIControlStateNormal];
  self.backFooterButton.layer.borderColor = [UIColor systemTealColor].CGColor;
  self.backFooterButton.layer.borderWidth = 1.0;
  self.backFooterButton.layer.cornerRadius = 20.0;
  [self.backFooterButton setTitleColor:[UIColor systemTealColor] forState:UIControlStateNormal];
  [self.backFooterButton addTarget:self
                            action:@selector(footerBackTapped)
                  forControlEvents:UIControlEventTouchUpInside];
  
  self.nextFooterButton = [UIButton buttonWithType:UIButtonTypeSystem];
  [self.nextFooterButton setTitle:@"Next" forState:UIControlStateNormal];
  self.nextFooterButton.backgroundColor = [UIColor systemTealColor];
  self.nextFooterButton.tintColor = UIColor.whiteColor;
  self.nextFooterButton.layer.cornerRadius = 20.0;
  [self.nextFooterButton addTarget:self
                            action:@selector(footerNextTapped)
                  forControlEvents:UIControlEventTouchUpInside];
  
  UIStackView *stack = [[UIStackView alloc] initWithArrangedSubviews:@[self.backFooterButton, self.nextFooterButton]];
  stack.axis = UILayoutConstraintAxisHorizontal;
  stack.spacing = 12.0;
  stack.distribution = UIStackViewDistributionFillEqually;
  stack.translatesAutoresizingMaskIntoConstraints = NO;
  
  [self.footerView addSubview:stack];
  [NSLayoutConstraint activateConstraints:@[
    [stack.topAnchor constraintEqualToAnchor:self.footerView.topAnchor constant:12],
    [stack.leadingAnchor constraintEqualToAnchor:self.footerView.leadingAnchor constant:16],
    [stack.trailingAnchor constraintEqualToAnchor:self.footerView.trailingAnchor constant:-16],
    [stack.bottomAnchor constraintEqualToAnchor:self.footerView.bottomAnchor constant:-12]
  ]];
}

#pragma mark - api
- (void)requestAppointment {
    [APIClient requestAppointment:^(BOOL success, NSDictionary *data, NSError *error) {
        if (error) return;
        if (!data[@"Data"]) return;
        
        NSDictionary *dataDict = data[@"Data"];
        self.appointmentData = dataDict;
        
        // --- 1️⃣ Determine Appointment Type ---
        self.appointmentType = @"joint_inspection";
        
        id handoverStatus = dataDict[@"handover_status"];
        id clearanceLetter = dataDict[@"clearance_letter"];

        if (handoverStatus && ![handoverStatus isKindOfClass:[NSNull class]] &&
            clearanceLetter && ![clearanceLetter isKindOfClass:[NSNull class]]) {
            
            if ([[NSString stringWithFormat:@"%@", clearanceLetter] isEqualToString:@"1"] &&
                [[NSString stringWithFormat:@"%@", handoverStatus] isEqualToString:@"not handed over"]) {
                self.appointmentType = @"handover";
            }
        }

        // --- 2️⃣ Select Slot Data Based on Appointment Type ---
        NSDictionary *selectedTypeDict = dataDict[self.appointmentType];
        NSArray *slots = selectedTypeDict[@"slots"] ?: @[];
        self.allSlots = slots;   // store all raw slots

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
          if (!self.termsAndCondition) {
            NSString *termsHTML = selectedTypeDict[@"terms"] ?: @"";
            NSLog(@"termsHTML: %@", termsHTML);
            NSString *styledHTML = [NSString stringWithFormat:
                @"<html>"
                 "<head>"
                 "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0\">"
                 "<style>"
                 "body { font-size: 16px; font-family: -apple-system; line-height: 1.5; padding: 12px; background-color: #F9F9F9; color: #000000; }"
                 "p, div, span, li { color: #000000 !important; }"
                 "p { margin-bottom: 12px; }"
                 "</style>"
                 "</head>"
                 "<body>%@</body>"
                 "</html>", termsHTML];

            
            self.termsAndCondition = styledHTML;
          }
          [self.termsContainer layoutIfNeeded];
          [self.termsWebView layoutIfNeeded];
          [self.termsWebView loadHTMLString:self.termsAndCondition baseURL:nil];
      });
    }];
}

-(void) requestGeneralInfo {
  [APIClient requestGeneralInfo:^(BOOL success, NSDictionary *data, NSError *error) {
      if (error) return;
    
    NSDictionary *generalInfo = data[@"Data"];
    id reps = generalInfo[@"representative"];
    
    if ([reps isKindOfClass:[NSArray class]]) {
        self.representativeList = (NSArray *)reps;
    } else {
        self.representativeList = @[]; // fallback to empty
    }
    NSLog(@"self.representativeList: %@", self.representativeList);
  }];
}

#pragma mark - WKWebView Delegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    // Ensure layout is up-to-date
    [webView layoutIfNeeded];
    
    // Get content height via JS
    [webView evaluateJavaScript:@"document.body.scrollHeight;" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        if (error) return;
        
        CGFloat contentHeight = [result doubleValue];
        CGFloat frameHeight = webView.scrollView.bounds.size.height;

        // Short content: enable button immediately
        if (contentHeight <= frameHeight) {
            [self enableAgreeButton];
        } else {
            // Long content: track scrolling
            webView.scrollView.delegate = self;
        }
    }];
}

#pragma mark - Scroll View Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView != self.termsWebView.scrollView) return;
    if (self.agreeButton.enabled) return;

    CGFloat offsetY = scrollView.contentOffset.y;
    CGFloat contentHeight = scrollView.contentSize.height;
    CGFloat frameHeight = scrollView.bounds.size.height;

    if (offsetY + frameHeight >= contentHeight - 10) {
        [self enableAgreeButton];
    }
}

#pragma mark - Helper
- (void)enableAgreeButton {
    self.agreeButton.enabled = YES;
    self.agreeButton.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
}

- (void)handleAgreeTapped {
    [UIView animateWithDuration:0.25 animations:^{
        self.termsOverlay.alpha = 0.0;
    } completion:^(BOOL finished) {
        self.termsOverlay.hidden = YES;
    }];
}

- (void)handleBackTapped {
    UIViewController *presenter = self.presentingViewController;
    if (presenter.presentingViewController) {
        [presenter.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)calendarView:(CalendarView *)calendar didSelectDate:(NSDate *)date {
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd";
    
    NSString *selectedDate = [fmt stringFromDate:date];
    self.selectedDateString = selectedDate;

    NSMutableArray *filteredSlots = [NSMutableArray array];

    for (NSDictionary *slot in self.allSlots) {
        NSString *slotDate = slot[@"start_date"];
        NSInteger remaining = [slot[@"slots"] integerValue];

        if ([slotDate isEqualToString:selectedDate] && remaining > 0) {
            NSMutableDictionary *timeObj = [NSMutableDictionary dictionary];
            timeObj[@"slot_id"] = slot[@"id"];
            timeObj[@"start_date"] = slot[@"start_date"];
            timeObj[@"start_time"] = slot[@"start_time"];
            [filteredSlots addObject:timeObj];
        }
    }

    if (filteredSlots.count == 0) {

        // Unselect the date visually AND logically
        self.selectedDateString = @"";
        self.calendarView.selectedDate = nil;
        [self.calendarView.collectionView reloadData];

        [self showNoSlotsAlert];
        self.aryTimeSlot = [NSMutableArray array];
        return;
    }

    // Sort slots by time
    NSArray *sorted = [filteredSlots sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
        return [a[@"start_time"] compare:b[@"start_time"]];
    }];

    self.aryTimeSlot = [sorted mutableCopy];

    NSLog(@"Final aryTimeSlot = %@", self.aryTimeSlot);
}

- (void)calendarViewMonthChanged:(NSDate *)monthFirstDay {
    NSLog(@"Month changed = %@", monthFirstDay);
}

- (void)showTermsOverlay {
    self.termsOverlay.hidden = NO;
    [self.view bringSubviewToFront:self.termsOverlay];
    self.termsOverlay.alpha = 0.0;

    [UIView animateWithDuration:0.25 animations:^{
        self.termsOverlay.alpha = 1.0;
    } completion:^(BOOL finished) {
        // Ensure webview loads now
        if (self.termsAndCondition) {
            [self.termsWebView loadHTMLString:self.termsAndCondition baseURL:nil];
        }
    }];
}

-(void)footerBackTapped {
  [self showTermsOverlay];
}

-(void)footerNextTapped {
  if (!self.selectedDateString || self.selectedDateString.length == 0) {
      // No date selected – show an alert
      UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Select Date"
                                                                     message:@"Please select a date before proceeding."
                                                              preferredStyle:UIAlertControllerStyleAlert];
      [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]];
      [self presentViewController:alert animated:YES completion:nil];
      return; // stop execution
  }
  NSLog(@"Navigating to AppointmentTimeSlot");
    AppointmentTimeSlotViewController *appointVC = [[AppointmentTimeSlotViewController alloc] init];
    appointVC.projectId = self.projectCode;
    appointVC.projectName = self.projectName;
    appointVC.drawingPlanId = @"135";
    appointVC.unitName = self.projectName;
    appointVC.appointmentType = self.appointmentType;
    appointVC.timeSlot = self.aryTimeSlot;
    appointVC.termsAndCondition = self.termsAndCondition;
    appointVC.representativeList = self.representativeList;
    appointVC.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:appointVC animated:YES completion:nil];
}

- (void)buildMarkedDatesFromSlots:(NSArray *)slots {
    NSMutableDictionary *marked = [NSMutableDictionary dictionary];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd";

    for (NSDictionary *slot in slots) {
        NSString *dateStr = slot[@"start_date"];
        NSInteger remaining = [slot[@"slots"] integerValue];

        NSString *status = @"available";
        if (remaining == 0) status = @"unavailable";
        else if (remaining < 5) status = @"limited";

        marked[dateStr] = @{ @"status": status };
    }

    self.markedDates = marked;
    self.calendarView.markedDates = marked;
}

- (void)showNoSlotsAlert {
    NSString *msg = [self.appointmentType isEqualToString:@"joint_inspection"]
        ? @"No available Joint Inspection slots for this date."
        : @"No available Handover slots for this date.";

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Unavailable"
                                                                   message:msg
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)refreshAppointmentData:(UIRefreshControl *)refreshControl {
    dispatch_group_t group = dispatch_group_create();

    dispatch_group_enter(group);
    [APIClient requestAppointment:^(BOOL success, NSDictionary *data, NSError *error) {
        if (data[@"Data"]) {
            NSDictionary *dataDict = data[@"Data"];
            self.appointmentData = dataDict;

            NSString *termsHTML = dataDict[self.appointmentType][@"terms"] ?: @"";
            NSString *styledHTML = [NSString stringWithFormat:
                                    @"<html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">"
                                    "<style>body { font-size:14px; font-family:-apple-system; padding:12px; }</style>"
                                    "</head><body>%@</body></html>", termsHTML];
            self.termsAndCondition = styledHTML;

            dispatch_async(dispatch_get_main_queue(), ^{
                [self.termsWebView loadHTMLString:styledHTML baseURL:nil];
            });

            NSArray *slots = dataDict[self.appointmentType][@"slots"] ?: @[];
            self.allSlots = slots;
            [self buildMarkedDatesFromSlots:slots];
            [self.calendarView.collectionView reloadData];
        }
        dispatch_group_leave(group);
    }];

    dispatch_group_enter(group);
    [APIClient requestGeneralInfo:^(BOOL success, NSDictionary *data, NSError *error) {
        id reps = data[@"Data"][@"representative"];
        self.representativeList = [reps isKindOfClass:[NSArray class]] ? reps : @[];
        dispatch_group_leave(group);
    }];

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self.scrollView endPullToRefresh];
    });
}

- (void)showTutorial {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Help"
                                                                   message:@"This would show the tutorial (e.g. step1/step2/step3)."
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
    AppointmentTutorialViewController *vc = [[AppointmentTutorialViewController alloc] init];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

@end
