//  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"

@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;

// 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;

// Tutorial overlay
@property (nonatomic, strong) UIView *tutorialOverlay;
@property (nonatomic, strong) UIImageView *tutorialImageView;
@property (nonatomic, strong) UIButton *skipButton;

@end

@implementation AppointmentViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  self.view.backgroundColor = UIColor.whiteColor;
  [self setupUI];
  [self setupTermsOverlay];
  [self fetchAppointment];
  [self fetchGeneralInfo];
}

#pragma mark - Setup UI
- (void)setupUI {
  [self setupHeader];
  [self setupLabels];
  [self setupCalendarSection];
  [self setupFooter];
  [self setupTutorialOverlay];
}

#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:48],
  ]];
  
  // 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.titleLabel.centerXAnchor constraintEqualToAnchor:self.headerBar.centerXAnchor],
    [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.headerBar.centerYAnchor],
  ]];
}

#pragma mark = Overlay t&c
- (void)setupTermsOverlay {
    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],
    ]];
    
    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];
    
    self.termsContainer = [[UIView alloc] init];
    self.termsContainer.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
    self.termsContainer.layer.cornerRadius = 12.0;
    self.termsContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [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.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
    [NSLayoutConstraint activateConstraints:@[
        [self.termsTitleLabel.topAnchor constraintEqualToAnchor:self.termsOverlay.topAnchor constant:40],
        [self.termsTitleLabel.leadingAnchor constraintEqualToAnchor:self.termsOverlay.leadingAnchor constant:20],
        [self.termsTitleLabel.trailingAnchor constraintEqualToAnchor:self.termsOverlay.trailingAnchor constant:-20],
        
        [self.termsContainer.topAnchor constraintEqualToAnchor:self.termsTitleLabel.bottomAnchor constant:12],
        [self.termsContainer.leadingAnchor constraintEqualToAnchor:self.termsOverlay.leadingAnchor constant:20],
        [self.termsContainer.trailingAnchor constraintEqualToAnchor:self.termsOverlay.trailingAnchor constant:-20],
        [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:40],
        [self.agreeButton.trailingAnchor constraintEqualToAnchor:self.termsOverlay.trailingAnchor constant:-40],
        [self.agreeButton.bottomAnchor constraintEqualToAnchor:self.termsOverlay.safeAreaLayoutGuide.bottomAnchor constant:-20],
        [self.agreeButton.heightAnchor constraintEqualToConstant:50],
    ]];
}


#pragma mark - Labels
- (void)setupLabels {
    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;

    self.unitLabel = [[UILabel alloc] init];
    self.unitLabel.text = @"For Unit No.:";
    self.unitLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightThin];
    self.unitLabel.textColor = [UIColor grayColor];
    self.unitLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.unitLabel];
  
    self.unitName = [[UILabel alloc] init];
    self.unitName.text = [NSString stringWithFormat:@"%@, %@", self.projectName, self.projectCode];
    self.unitName.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    self.unitName.textColor = [UIColor blackColor];
    self.unitName.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view 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 = 6.0;
    self.stepLabel.clipsToBounds = YES;
    [self.view addSubview:self.stepLabel];

    [NSLayoutConstraint activateConstraints:@[
        [self.unitLabel.topAnchor constraintEqualToAnchor:self.headerBar.bottomAnchor constant:16],
        [self.unitLabel.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:16],
        [self.unitLabel.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],

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

#pragma mark - Calendar Section
- (void)setupCalendarSection {
    self.calendarContainer = [[UIView alloc] init];
    self.calendarContainer.backgroundColor = [UIColor whiteColor];
    self.calendarContainer.layer.cornerRadius = 12.0;
    self.calendarContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view 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.spacing = 16.0;
    self.legendStack.alignment = UIStackViewAlignmentCenter;
    self.legendStack.distribution = UIStackViewDistributionEqualSpacing;
    self.legendStack.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view 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 calendar ever needs
    CGFloat calendarHeight = 40 + 28 + (cell * 0.9 + 12) * rows + 12 + 20;

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

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

        [self.legendStack.topAnchor constraintEqualToAnchor:self.calendarContainer.bottomAnchor constant:16],
        [self.legendStack.centerXAnchor constraintEqualToAnchor:self.view.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 - Tutorial Overlay
- (void)setupTutorialOverlay {
  self.tutorialOverlay = [[UIView alloc] init];
  self.tutorialOverlay.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
  self.tutorialOverlay.hidden = YES;
  self.tutorialOverlay.translatesAutoresizingMaskIntoConstraints = NO;
  [self.view addSubview:self.tutorialOverlay];
  
  [NSLayoutConstraint activateConstraints:@[
    [self.tutorialOverlay.topAnchor constraintEqualToAnchor:self.view.topAnchor],
    [self.tutorialOverlay.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
    [self.tutorialOverlay.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
    [self.tutorialOverlay.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor]
  ]];
  
  self.tutorialImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tutorial_step1"]];
  self.tutorialImageView.contentMode = UIViewContentModeScaleAspectFit;
  self.tutorialImageView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.tutorialOverlay addSubview:self.tutorialImageView];
  
  self.skipButton = [UIButton buttonWithType:UIButtonTypeSystem];
  [self.skipButton setTitle:@"Skip" forState:UIControlStateNormal];
  self.skipButton.tintColor = UIColor.whiteColor;
  self.skipButton.layer.borderColor = UIColor.whiteColor.CGColor;
  self.skipButton.layer.borderWidth = 1.0;
  self.skipButton.layer.cornerRadius = 6.0;
  self.skipButton.translatesAutoresizingMaskIntoConstraints = NO;
  [self.tutorialOverlay addSubview:self.skipButton];
  
  [NSLayoutConstraint activateConstraints:@[
    [self.tutorialImageView.centerXAnchor constraintEqualToAnchor:self.tutorialOverlay.centerXAnchor],
    [self.tutorialImageView.centerYAnchor constraintEqualToAnchor:self.tutorialOverlay.centerYAnchor],
    [self.tutorialImageView.widthAnchor constraintEqualToAnchor:self.tutorialOverlay.widthAnchor multiplier:0.9],
    [self.tutorialImageView.heightAnchor constraintEqualToAnchor:self.tutorialOverlay.heightAnchor multiplier:0.7],
    
    [self.skipButton.topAnchor constraintEqualToAnchor:self.tutorialOverlay.safeAreaLayoutGuide.topAnchor constant:16],
    [self.skipButton.trailingAnchor constraintEqualToAnchor:self.tutorialOverlay.trailingAnchor constant:-16],
    [self.skipButton.widthAnchor constraintEqualToConstant:70],
    [self.skipButton.heightAnchor constraintEqualToConstant:32]
  ]];
}

#pragma mark - api
- (void)fetchAppointment {
    [APIClient fetchAppointment:^(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

        // --- 3️⃣ Load Terms HTML ---
        NSString *termsHTML = selectedTypeDict[@"terms"] ?: @"";
        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: 14px; font-family: -apple-system; line-height: 1.5; padding: 12px; background-color: #F9F9F9; }"
            "p { margin-bottom: 12px; }"
            "</style>"
            "</head>"
            "<body>%@</body>"
            "</html>", termsHTML];
        
        self.termsAndCondition = styledHTML;

        dispatch_async(dispatch_get_main_queue(), ^{
            [self.termsWebView loadHTMLString:styledHTML baseURL:nil];
            [self buildMarkedDatesFromSlots:slots];
            [self.calendarView.collectionView reloadData];
        });
    }];
}

-(void) fetchGeneralInfo {
  [APIClient fetchGeneralInfo:^(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.termsOverlay.alpha = 0.0;

    [UIView animateWithDuration:0.25 animations:^{
        self.termsOverlay.alpha = 1.0;
    }];
}

-(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];
}


@end
