//  AppointmentViewMoreViewController.mm

#import "AppointmentViewMoreViewController.h"
#import "FSCalendar.h"
#import "APIClient.h"
#import "AppointmentViewController.h"
#import "AppointmentDetailsViewController.h"

@interface ListingCell : UITableViewCell

@property (nonatomic, assign) BOOL showSidebar; // only first appointment of the day

@property (nonatomic, strong) UILabel *dayLabel;
@property (nonatomic, strong) UILabel *weekdayLabel;

@property (nonatomic, strong) UIView *infoContainer;
@property (nonatomic, strong) UILabel *statusLabel;
@property (nonatomic, strong) UILabel *timeBadge;
@property (nonatomic, strong) UILabel *unitOwnerLabel;

@end

@implementation ListingCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.backgroundColor = UIColor.clearColor;

        CGFloat sidebarWidth = 60;

        // Sidebar labels
        self.dayLabel = [[UILabel alloc] init];
        self.dayLabel.font = [UIFont boldSystemFontOfSize:16];
        self.dayLabel.textAlignment = NSTextAlignmentCenter;
        self.dayLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [self.contentView addSubview:self.dayLabel];

        self.weekdayLabel = [[UILabel alloc] init];
        self.weekdayLabel.font = [UIFont systemFontOfSize:12];
        self.weekdayLabel.textAlignment = NSTextAlignmentCenter;
        self.weekdayLabel.textColor = UIColor.darkGrayColor;
        self.weekdayLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [self.contentView addSubview:self.weekdayLabel];

        [NSLayoutConstraint activateConstraints:@[
            [self.dayLabel.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:8],
            [self.dayLabel.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor],
            [self.dayLabel.widthAnchor constraintEqualToConstant:sidebarWidth],
            
            [self.weekdayLabel.topAnchor constraintEqualToAnchor:self.dayLabel.bottomAnchor constant:2],
            [self.weekdayLabel.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor],
            [self.weekdayLabel.widthAnchor constraintEqualToConstant:sidebarWidth],
            [self.weekdayLabel.bottomAnchor constraintLessThanOrEqualToAnchor:self.contentView.bottomAnchor constant:-8]
        ]];

        // Info container
        self.infoContainer = [[UIView alloc] init];
        self.infoContainer.backgroundColor = UIColor.whiteColor;
        self.infoContainer.layer.cornerRadius = 8;
        self.infoContainer.layer.masksToBounds = YES;
        self.infoContainer.translatesAutoresizingMaskIntoConstraints = NO;

        // Optional shadow for card effect
        self.infoContainer.layer.shadowColor = UIColor.blackColor.CGColor;
        self.infoContainer.layer.shadowOpacity = 0.05;
        self.infoContainer.layer.shadowOffset = CGSizeMake(0, 2);
        self.infoContainer.layer.shadowRadius = 4;
        self.infoContainer.layer.masksToBounds = NO;

        [self.contentView addSubview:self.infoContainer];

        [NSLayoutConstraint activateConstraints:@[
            [self.infoContainer.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:4],
            [self.infoContainer.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-4],
            [self.infoContainer.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:sidebarWidth + 8],
            [self.infoContainer.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-8]
        ]];

        // Status label
        self.statusLabel = [[UILabel alloc] init];
        self.statusLabel.font = [UIFont boldSystemFontOfSize:16];
        self.statusLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [self.infoContainer addSubview:self.statusLabel];

        // Time label
        self.timeBadge = [[UILabel alloc] init];
        self.timeBadge.font = [UIFont systemFontOfSize:14];
        self.timeBadge.textColor = UIColor.darkGrayColor;
        self.timeBadge.translatesAutoresizingMaskIntoConstraints = NO;
        [self.infoContainer addSubview:self.timeBadge];

        // Unit/owner label
        self.unitOwnerLabel = [[UILabel alloc] init];
        self.unitOwnerLabel.font = [UIFont systemFontOfSize:14];
        self.unitOwnerLabel.textColor = UIColor.grayColor;
        self.unitOwnerLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [self.infoContainer addSubview:self.unitOwnerLabel];

        // Layout infoContainer contents
        [NSLayoutConstraint activateConstraints:@[
            [self.statusLabel.topAnchor constraintEqualToAnchor:self.infoContainer.topAnchor constant:8],
            [self.statusLabel.leadingAnchor constraintEqualToAnchor:self.infoContainer.leadingAnchor constant:8],
            
            [self.timeBadge.centerYAnchor constraintEqualToAnchor:self.statusLabel.centerYAnchor],
            [self.timeBadge.trailingAnchor constraintEqualToAnchor:self.infoContainer.trailingAnchor constant:-8],
            
            [self.unitOwnerLabel.topAnchor constraintEqualToAnchor:self.statusLabel.bottomAnchor constant:4],
            [self.unitOwnerLabel.leadingAnchor constraintEqualToAnchor:self.infoContainer.leadingAnchor constant:8],
            [self.unitOwnerLabel.trailingAnchor constraintEqualToAnchor:self.infoContainer.trailingAnchor constant:-8],
            [self.unitOwnerLabel.bottomAnchor constraintEqualToAnchor:self.infoContainer.bottomAnchor constant:-8]
        ]];
    }
    return self;
}

// Optional: override layoutSubviews to hide sidebar if needed
- (void)layoutSubviews {
    [super layoutSubviews];
    self.dayLabel.hidden = !self.showSidebar;
    self.weekdayLabel.hidden = !self.showSidebar;
}

// Show/hide sidebar
- (void)setShowSidebar:(BOOL)showSidebar {
    _showSidebar = showSidebar;
    self.dayLabel.hidden = !showSidebar;
    self.weekdayLabel.hidden = !showSidebar;
}

@end


@interface AppointmentViewMoreViewController () <UITableViewDelegate, UITableViewDataSource, FSCalendarDelegate, FSCalendarDataSource>

@property (nonatomic, strong) UIView *topBar;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *toggleTabButton;

@property (nonatomic, strong) UIView *filterBar;
@property (nonatomic, strong) UILabel *filterLabel;
@property (nonatomic, strong) UIButton *filterButton;

@property (nonatomic, strong) UIView *calendarContainer;
@property (nonatomic, strong) UIView *listingContainer;
@property (nonatomic, strong) UITableView *listingTable;

@property (nonatomic, strong) UIView *bottomButtonContainer;
@property (nonatomic, strong) UIButton *makeAppointmentButton;

@property (nonatomic, strong) UIView *filterOverlay;

@property (nonatomic, strong) UIActivityIndicatorView *loadingView;

@property (nonatomic, assign) BOOL showingCalendar;

@property (nonatomic, strong) NSArray *arrayAppointmentFull;
@property (nonatomic, strong) NSMutableArray *arrayListing;
@property (nonatomic, strong) NSMutableArray *arrayListingSection;
@property (nonatomic, strong) NSMutableDictionary *aryDotsByDate;

@property (nonatomic, copy) NSString *apptFilterType;
@property (nonatomic, copy) NSString *apptFilterTime;

@property (nonatomic, assign) BOOL blnLoading;
@property (nonatomic, assign) BOOL blnRefreshCalendar;

@property (nonatomic, strong) FSCalendar *calendar;
@property (nonatomic ,strong) NSLayoutConstraint *calendarHeightConstraint;
@property (nonatomic, strong) UIButton *collapseButton;
@property (nonatomic, assign) BOOL calendarCollapsed;
@property (nonatomic, strong) NSArray<NSDictionary *> *agendaSections;
@property (nonatomic, strong) NSDate *selectedAgendaStartDate;
@property (nonatomic, strong) NSDateFormatter *stringDF;
@property (nonatomic, strong) NSDate *calendarMinDate;
@property (nonatomic, strong) NSDate *calendarMaxDate;
@property (nonatomic, assign) BOOL calendarExpanded;

@end

@implementation AppointmentViewMoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
  
    self.arrayAppointmentFull = [NSMutableArray array];
    self.arrayListing = [NSMutableArray array];
    self.arrayListingSection = [NSMutableArray array];
    self.aryDotsByDate = [NSMutableDictionary dictionary];

    self.apptFilterType = @"All";
    self.apptFilterTime = @"Upcoming";

    self.showingCalendar = YES;
  
    self.stringDF = [[NSDateFormatter alloc] init];
    self.stringDF.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    self.stringDF.dateFormat = @"dd MMM yyyy";
  
    NSDate *today = [NSDate date];

    self.calendarMinDate = [self dateByAddingMonths:-24 toDate:today];
    self.calendarMaxDate = [self dateByAddingMonths:24 toDate:today];

    [self setupTopBar];
    [self setupFilterBar];
    [self setupBottomButton];
    [self setupCalendarView];
    [self setupListingView];
    [self setupFilterOverlay];
    [self setupLoadingOverlay];
    [self requestDashboardInfo];
    [self.calendar reloadData];
}

#pragma mark - Top Bar
- (void)setupTopBar {
    self.topBar = [[UIView alloc] init];
    self.topBar.backgroundColor = [UIColor colorWithRed:0 green:0.4 blue:0.55 alpha:1];
    self.topBar.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.topBar];

    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backButton addTarget:self action:@selector(onBack) forControlEvents:UIControlEventTouchUpInside];
    self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.backButton setImage:[UIImage systemImageNamed:@"chevron.left"] forState:UIControlStateNormal];
    self.backButton.tintColor = UIColor.whiteColor;
    [self.topBar addSubview:self.backButton];
  
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"Appointment";
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.topBar addSubview:self.titleLabel];

    self.toggleTabButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.toggleTabButton setImage:[UIImage systemImageNamed:@"list.bullet"] forState:UIControlStateNormal];
    [self.toggleTabButton addTarget:self action:@selector(onToggleTab) forControlEvents:UIControlEventTouchUpInside];
    self.toggleTabButton.translatesAutoresizingMaskIntoConstraints = NO;
    self.toggleTabButton.tintColor = [UIColor whiteColor];
    [self.topBar addSubview:self.toggleTabButton];

    [NSLayoutConstraint activateConstraints:@[
        [self.topBar.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
        [self.topBar.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.topBar.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.topBar.heightAnchor constraintEqualToConstant:56],

        [self.backButton.leadingAnchor constraintEqualToAnchor:self.topBar.leadingAnchor constant:12],
        [self.backButton.centerYAnchor constraintEqualToAnchor:self.topBar.centerYAnchor],
        [self.backButton.widthAnchor constraintEqualToConstant:48],
        [self.backButton.heightAnchor constraintEqualToConstant:48],

        [self.toggleTabButton.trailingAnchor constraintEqualToAnchor:self.topBar.trailingAnchor constant:-12],
        [self.toggleTabButton.centerYAnchor constraintEqualToAnchor:self.topBar.centerYAnchor],
        [self.toggleTabButton.widthAnchor constraintEqualToConstant:48],
        [self.toggleTabButton.heightAnchor constraintEqualToConstant:48],

        [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.topBar.centerXAnchor],
        [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.topBar.centerYAnchor]
    ]];
}

#pragma mark - Filter Bar
- (void)setupFilterBar {
    self.filterBar = [[UIView alloc] init];
    self.filterBar.backgroundColor = [UIColor colorWithWhite:0.6 alpha:1];
    self.filterBar.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.filterBar];

    self.filterLabel = [[UILabel alloc] init];
    self.filterLabel.text = @"Filter by All (Upcoming)";
    self.filterLabel.textColor = UIColor.whiteColor;
    self.filterLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.filterBar addSubview:self.filterLabel];

    self.filterButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.filterButton setImage:[UIImage systemImageNamed:@"slider.horizontal.3"] forState:UIControlStateNormal];
    [self.filterButton addTarget:self action:@selector(onFilterButton) forControlEvents:UIControlEventTouchUpInside];
    self.filterButton.translatesAutoresizingMaskIntoConstraints = NO;
    self.filterButton.tintColor = [UIColor whiteColor];
    [self.filterBar addSubview:self.filterButton];
    self.calendarCollapsed = YES;

    [NSLayoutConstraint activateConstraints:@[
        [self.filterBar.topAnchor constraintEqualToAnchor:self.topBar.bottomAnchor],
        [self.filterBar.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.filterBar.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.filterBar.heightAnchor constraintEqualToConstant:48],

        [self.filterLabel.leadingAnchor constraintEqualToAnchor:self.filterBar.leadingAnchor constant:16],
        [self.filterLabel.centerYAnchor constraintEqualToAnchor:self.filterBar.centerYAnchor],

        [self.filterButton.trailingAnchor constraintEqualToAnchor:self.filterBar.trailingAnchor constant:-12],
        [self.filterButton.centerYAnchor constraintEqualToAnchor:self.filterBar.centerYAnchor],
        [self.filterButton.widthAnchor constraintEqualToConstant:36],
        [self.filterButton.heightAnchor constraintEqualToConstant:36]
    ]];
}

#pragma mark - Listing Container
- (void)setupListingView {
    // Container for listing
    self.listingContainer = [[UIView alloc] init];
    self.listingContainer.backgroundColor = UIColor.whiteColor;
    self.listingContainer.translatesAutoresizingMaskIntoConstraints = NO;
    self.listingContainer.hidden = YES;
    [self.view addSubview:self.listingContainer];
  
    // Listing table
    self.listingTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.listingTable.delegate = self;
    self.listingTable.dataSource = self;
    self.listingTable.translatesAutoresizingMaskIntoConstraints = NO;
    [self.listingContainer addSubview:self.listingTable];

    // ✅ Register cell class **before any dequeuing**
    [self.listingTable registerClass:[ListingCell class] forCellReuseIdentifier:@"ListingCell"];

    // Container constraints
    [NSLayoutConstraint activateConstraints:@[
        [self.listingContainer.topAnchor constraintEqualToAnchor:self.filterBar.bottomAnchor],
        [self.listingContainer.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.listingContainer.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.listingContainer.bottomAnchor constraintEqualToAnchor:self.bottomButtonContainer.topAnchor]
    ]];

    // Table fills container
    [NSLayoutConstraint activateConstraints:@[
        [self.listingTable.topAnchor constraintEqualToAnchor:self.listingContainer.topAnchor constant:8],
        [self.listingTable.leadingAnchor constraintEqualToAnchor:self.listingContainer.leadingAnchor],
        [self.listingTable.trailingAnchor constraintEqualToAnchor:self.listingContainer.trailingAnchor],
        [self.listingTable.bottomAnchor constraintEqualToAnchor:self.listingContainer.bottomAnchor]
    ]];

    // Ensure automatic row height (optional)
    self.listingTable.estimatedRowHeight = 60;
    self.listingTable.rowHeight = UITableViewAutomaticDimension;
}

#pragma mark - Calendar
- (void)setupCalendarView {
    // --- Calendar Container ---
    self.calendarContainer = [[UIView alloc] init];
    self.calendarContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.calendarContainer];
    
    self.calendarHeightConstraint = [self.calendarContainer.heightAnchor constraintEqualToConstant:300];
    self.calendarHeightConstraint.active = YES;

    [NSLayoutConstraint activateConstraints:@[
        [self.calendarContainer.topAnchor constraintEqualToAnchor:self.filterBar.bottomAnchor constant:8],
        [self.calendarContainer.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.calendarContainer.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
    ]];

    // --- FSCalendar ---
    self.calendar = [[FSCalendar alloc] initWithFrame:CGRectZero];
    self.calendar.translatesAutoresizingMaskIntoConstraints = NO;
    self.calendar.dataSource = self;
    self.calendar.delegate = self;
    [self.calendarContainer addSubview:self.calendar];

    [NSLayoutConstraint activateConstraints:@[
        [self.calendar.topAnchor constraintEqualToAnchor:self.calendarContainer.topAnchor],
        [self.calendar.leadingAnchor constraintEqualToAnchor:self.calendarContainer.leadingAnchor],
        [self.calendar.trailingAnchor constraintEqualToAnchor:self.calendarContainer.trailingAnchor],
        [self.calendar.bottomAnchor constraintEqualToAnchor:self.calendarContainer.bottomAnchor],
    ]];

    // --- Appearance tweaks ---
    self.calendar.scope = FSCalendarScopeWeek;
    self.calendar.scrollDirection = FSCalendarScrollDirectionHorizontal;
    self.calendar.pagingEnabled = YES;
    self.calendar.headerHeight = 0;       // hides month title
    self.calendar.weekdayHeight = 24;     // keeps weekday labels visible

    self.calendarExpanded = NO;

    // --- Agenda Table ---
    self.agendaTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.agendaTable.delegate = self;
    self.agendaTable.dataSource = self;
    self.agendaTable.translatesAutoresizingMaskIntoConstraints = NO;
    self.agendaTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.agendaTable.tableFooterView = [UIView new];
    [self.view addSubview:self.agendaTable];

    [self.agendaTable registerClass:[ListingCell class] forCellReuseIdentifier:@"ListingCell"];
    self.agendaTable.estimatedRowHeight = 60;
    self.agendaTable.rowHeight = UITableViewAutomaticDimension;

    [NSLayoutConstraint activateConstraints:@[
        [self.agendaTable.topAnchor constraintEqualToAnchor:self.calendarContainer.bottomAnchor constant:8],
        [self.agendaTable.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.agendaTable.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.agendaTable.bottomAnchor constraintEqualToAnchor:self.bottomButtonContainer.topAnchor constant:-8],
    ]];
  
    // --- Expand Button ---
    self.collapseButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.collapseButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.collapseButton setTitle:@"Expand Calendar ▼" forState:UIControlStateNormal];
    self.collapseButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [self.collapseButton addTarget:self
                            action:@selector(onToggleCalendar)
                  forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.collapseButton];

    // Button constraints
    [NSLayoutConstraint activateConstraints:@[
        [self.collapseButton.topAnchor constraintEqualToAnchor:self.calendarContainer.bottomAnchor constant:8],
        [self.collapseButton.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:16],
        [self.collapseButton.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],
        [self.collapseButton.heightAnchor constraintEqualToConstant:30],
    ]];
}

#pragma mark - FSCalendar Delegate
- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date
                                      atMonthPosition:(FSCalendarMonthPosition)monthPosition {
    self.selectedAgendaStartDate = date;

    // Auto-collapse if expanded
    if (self.calendarExpanded) {
        [self collapseCalendar];
        [self.collapseButton setTitle:@"Expand Calendar ▼" forState:UIControlStateNormal];
    }

    // Reload agenda
    [self prepareAgendaSections];
    [self.agendaTable reloadData];
}

- (void)onToggleCalendar {
    if (self.calendarExpanded) {
        [self collapseCalendar];
        [self.collapseButton setTitle:@"Expand Calendar ▼" forState:UIControlStateNormal];
    } else {
        [self expandCalendar];
        [self.collapseButton setTitle:@"" forState:UIControlStateNormal];
    }
}

#pragma mark - Optional Layout Fix
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    // Ensure week mode stays in horizontal scroll
    if (!self.calendarExpanded && self.calendar.scope != FSCalendarScopeWeek) {
        [self.calendar setScope:FSCalendarScopeWeek animated:NO];
        self.calendar.scrollDirection = FSCalendarScrollDirectionHorizontal;
        self.calendar.pagingEnabled = YES;
    }
}

- (void)expandCalendar {
    if (self.calendarExpanded) return;
    self.calendarExpanded = YES;

    // Month view
    [self.calendar setScope:FSCalendarScopeMonth animated:YES];

    // Vertical scrolling & paging off
    self.calendar.scrollDirection = FSCalendarScrollDirectionVertical;
    self.calendar.pagingEnabled = NO;

    // Show full header
    self.calendar.headerHeight = 24;
    self.calendar.weekdayHeight = 24;

    // Adjust container height to fit month
    CGFloat maxHeight = self.view.bounds.size.height
        - CGRectGetMaxY(self.filterBar.frame)
        - self.bottomButtonContainer.frame.size.height
        - 16;
    self.calendarHeightConstraint.constant = maxHeight;

    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (void)collapseCalendar {
    if (!self.calendarExpanded) return;
    self.calendarExpanded = NO;

    // Keep scope as month
    [self.calendar setScope:FSCalendarScopeMonth animated:NO];

    // Show weekday row
    self.calendar.weekdayHeight = 24;

    // Hide month title
    self.calendar.headerHeight = 0;
    self.calendar.appearance.headerTitleColor = UIColor.clearColor;

    // Restrict calendar height to one week
    self.calendarHeightConstraint.constant = 100; // adjust for row size

    // Disable vertical scroll so it looks like week view
    self.calendar.scrollDirection = FSCalendarScrollDirectionHorizontal;
    self.calendar.pagingEnabled = YES;

    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (void)calendar:(FSCalendar *)calendar
boundingRectWillChange:(CGRect)bounds
animated:(BOOL)animated {

    if (!self.calendarExpanded) {
        // Collapsed → let FSCalendar decide
        self.calendarHeightConstraint.constant = bounds.size.height;
    }

    if (calendar.scope == FSCalendarScopeMonth) {
        calendar.scrollDirection = FSCalendarScrollDirectionVertical;
        calendar.pagingEnabled = NO;
    } else {
        calendar.scrollDirection = FSCalendarScrollDirectionHorizontal;
        calendar.pagingEnabled = YES;
    }

    [self.view layoutIfNeeded];
}

// If your FSCalendar supports eventColorsForDate:
- (NSArray<UIColor *> *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance eventColorsForDate:(NSDate *)date {
    NSDateFormatter *dfOut = [[NSDateFormatter alloc] init];
    dfOut.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    dfOut.dateFormat = @"yyyy-MM-dd";
    NSString *key = [dfOut stringFromDate:date];

    NSArray *dots = self.aryDotsByDate[key];
    if (!dots) return nil;
    NSMutableArray *colors = [NSMutableArray array];
    for (NSDictionary *d in dots) {
        UIColor *c = d[@"color"];
        if ([c isKindOfClass:[UIColor class]]) [colors addObject:c];
    }
    return colors;
}

- (NSInteger)calendar:(FSCalendar *)calendar numberOfEventsForDate:(NSDate *)date {
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    df.dateFormat = @"yyyy-MM-dd";
    NSString *key = [df stringFromDate:date];

    NSArray *events = self.aryDotsByDate[key];
    return events.count;   // number of dots to show
}

#pragma mark - FSCalendarDataSource
- (NSDate *)minimumDateForCalendar:(FSCalendar *)calendar {
    return self.calendarMinDate;
}

- (NSDate *)maximumDateForCalendar:(FSCalendar *)calendar {
    return self.calendarMaxDate;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == self.agendaTable) {
      return self.agendaSections.count;
    }
    return self.arrayListingSection.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.agendaTable) {
      NSDictionary *sec = self.agendaSections[section];
      NSArray *items = sec[@"items"];
      return (items.count > 0) ? items.count : 1; // always 1 for empty section
    }
    NSDictionary *sec = self.arrayListingSection[section];
    return [sec[@"data"] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ListingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ListingCell" forIndexPath:indexPath];

    NSArray *items;
    NSDictionary *item;

    if (tableView == self.agendaTable) {
        NSDictionary *sec = self.agendaSections[indexPath.section];
        items = sec[@"items"];
    } else {
        NSDictionary *sec = self.arrayListingSection[indexPath.section];
        items = sec[@"data"];
    }

    if (items.count == 0) {
        // Empty section cell
        cell.showSidebar = NO;
        cell.dayLabel.text = @"";
        cell.weekdayLabel.text = @"";

        cell.statusLabel.text = @"No Appointments";
        cell.statusLabel.textColor = UIColor.grayColor;

        cell.timeBadge.text = @"";
        cell.timeBadge.backgroundColor = UIColor.clearColor;
        cell.timeBadge.textColor = UIColor.darkGrayColor;

        cell.unitOwnerLabel.text = @"";
        return cell;
    }

    item = items[indexPath.row];

    // --- Determine if this is the first appointment of the day ---
    BOOL firstOfDay = YES;
    if (indexPath.row > 0) {
        NSDictionary *prevItem = items[indexPath.row - 1];
        NSString *prevDate = prevItem[@"start_date"] ?: @"";
        NSString *currDate = item[@"start_date"] ?: @"";
        firstOfDay = ![prevDate isEqualToString:currDate];
    }

    cell.showSidebar = firstOfDay;

    // --- Fill sidebar if first appointment ---
    if (firstOfDay) {
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        df.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
        df.dateFormat = @"dd MMM yyyy";
        NSDate *apptDate = [df dateFromString:item[@"start_date"]];

        if (apptDate) {
            NSCalendar *cal = [NSCalendar currentCalendar];
            NSInteger day = [cal component:NSCalendarUnitDay fromDate:apptDate];
            cell.dayLabel.text = [NSString stringWithFormat:@"%ld", (long)day];

            NSDateFormatter *weekdayDF = [[NSDateFormatter alloc] init];
            weekdayDF.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
            weekdayDF.dateFormat = @"EEE"; // Mon, Tue
            cell.weekdayLabel.text = [weekdayDF stringFromDate:apptDate];
        }
    } else {
        cell.dayLabel.text = @"";
        cell.weekdayLabel.text = @"";
    }

    // --- Fill appointment info ---
    NSString *status = item[@"status"] ?: @"";
    NSString *apptType = item[@"appointment_type"] ?: @"";
    NSString *startTime = item[@"start_time"] ?: @"";

    // Status label shows type/status and changes color
    cell.statusLabel.text = [status isEqualToString:@"Cancelled"] ? status : apptType;
    if ([status isEqualToString:@"Cancelled"]) {
        cell.statusLabel.textColor = UIColor.grayColor;
    } else if ([apptType isEqualToString:@"Handover"]) {
        cell.statusLabel.textColor = [self colorFromHex:@"#047C74"];
    } else if ([apptType isEqualToString:@"Joint Inspection"]) {
        cell.statusLabel.textColor = [self colorFromHex:@"#C84132"];
    } else if ([apptType isEqualToString:@"Rectification"]) {
        cell.statusLabel.textColor = [self colorFromHex:@"#FFA500"]; // example orange
    } else {
        cell.statusLabel.textColor = UIColor.blackColor;
    }

    // Time badge is now plain text
    cell.timeBadge.text = startTime;
    cell.timeBadge.backgroundColor = UIColor.clearColor;
    cell.timeBadge.textColor = UIColor.darkGrayColor;

    // Owner info
    NSArray *primary = item[@"primary_buyer"];
    NSArray *joint = item[@"joint_buyer"];
    NSString *owner = (primary.count > 0) ? primary[0][@"name"]
                    : (joint.count > 0 ? joint[0][@"name"] : @"");
    cell.unitOwnerLabel.text = [NSString stringWithFormat:@"%@ (%@)", item[@"unit_no"], owner];
    cell.backgroundColor = UIColor.clearColor;

    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.agendaTable) {
        NSDictionary *sec = self.agendaSections[indexPath.section];
        NSArray *items = sec[@"items"];
        if (items.count == 0) return 0.1; // empty cell height
        return 60; // normal cell height
    }
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView == self.agendaTable) {
        NSDictionary *sec = self.agendaSections[section];
        NSArray *items = sec[@"items"];

        if (items.count > 0) {
            return 0.1; // hide header for days with appointments
        }
        return 30; // normal height for empty days
    }

    return 30; // normal listing table
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
  
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
  if (tableView == self.agendaTable) {
    NSDictionary *sec = self.agendaSections[section];
    return sec[@"date"];
  }
    return @"1";
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (tableView != self.agendaTable) return nil;

    NSDictionary *sec = self.agendaSections[section];
    NSArray *items = sec[@"items"];

    if (items.count > 0) {
        // Section has appointments → no header needed
        return [[UIView alloc] initWithFrame:CGRectZero];
    }

    // --- Days with no appointments, keep your existing layout ---
    NSString *dateStr = sec[@"date"];

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    df.dateFormat = @"dd MMM yyyy";
    NSDate *date = [df dateFromString:dateStr];
    if (!date) return nil;

    NSCalendar *cal = [NSCalendar currentCalendar];
    NSInteger day = [cal component:NSCalendarUnitDay fromDate:date];

    NSDateFormatter *weekdayDF = [[NSDateFormatter alloc] init];
    weekdayDF.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    weekdayDF.dateFormat = @"EEE";
    NSString *weekday = [weekdayDF stringFromDate:date];

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 60)];
    headerView.backgroundColor = UIColor.whiteColor;

    CGFloat sidebarWidth = 60;

    UILabel *dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, sidebarWidth, 24)];
    dayLabel.text = [NSString stringWithFormat:@"%ld", (long)day];
    dayLabel.font = [UIFont boldSystemFontOfSize:16];
    dayLabel.textAlignment = NSTextAlignmentCenter;
    dayLabel.textColor = UIColor.blackColor;
    [headerView addSubview:dayLabel];

    UILabel *weekdayLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 28, sidebarWidth, 20)];
    weekdayLabel.text = weekday;
    weekdayLabel.font = [UIFont systemFontOfSize:12];
    weekdayLabel.textAlignment = NSTextAlignmentCenter;
    weekdayLabel.textColor = UIColor.darkGrayColor;
    [headerView addSubview:weekdayLabel];

    return headerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *item;
    if (tableView == self.agendaTable) {
        NSDictionary *sec = self.agendaSections[indexPath.section];
        NSArray *items = sec[@"items"];
        if (items.count == 0) return; // nothing to select
        item = items[indexPath.row];
    } else {
        NSDictionary *sec = self.arrayListingSection[indexPath.section];
        item = sec[@"data"][indexPath.row];
    }
    [self clickListingItemWithItem:item];
}

- (void)clickListingItemWithItem:(NSDictionary *)item {
    AppointmentDetailsViewController *vc = [[AppointmentDetailsViewController alloc] initWithNibName:nil bundle:nil];
    vc.appointmentData = item;
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView != self.agendaTable) return;

    // Get visible rows
    NSArray<NSIndexPath *> *visible = [self.agendaTable indexPathsForVisibleRows];
    if (visible.count == 0) return;

    // Find the *topmost* row (smallest section + row)
    NSIndexPath *topIndex = visible.firstObject;
    for (NSIndexPath *ip in visible) {
        if (ip.section < topIndex.section ||
           (ip.section == topIndex.section && ip.row < topIndex.row)) {
            topIndex = ip;
        }
    }

    // Get date from section
    NSDictionary *sectionInfo = self.agendaSections[topIndex.section];
    NSString *dateStr = sectionInfo[@"date"];
    if (!dateStr) return;

    // Convert to NSDate
    NSDate *date = [self.stringDF dateFromString:dateStr];
    if (!date) return;

    // Avoid infinite loop when we update calendar from user taps
    if ([self.calendar.selectedDate isEqualToDate:date]) return;

    // Update calendar selection
    [self.calendar selectDate:date scrollToDate:YES];
}

- (void)prepareAgendaSections {

    if (!self.arrayListing || self.arrayListing.count == 0) {
        // still show at least today
        NSDate *today = [[NSCalendar currentCalendar] startOfDayForDate:[NSDate date]];
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        df.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
        df.dateFormat = @"dd MMM yyyy";

        NSString *todayStr = [df stringFromDate:today];
        self.agendaSections = @[ @{ @"date": todayStr, @"items": @[] } ];
        [self.agendaTable reloadData];
        return;
    }

    // 1️⃣ Map: date string -> appointments
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    df.dateFormat = @"dd MMM yyyy";

    for (NSDictionary *item in self.arrayListing) {
        NSString *dateStr = item[@"start_date"];
        if (!dateStr) continue;

        if (!dict[dateStr]) dict[dateStr] = [NSMutableArray array];
        [dict[dateStr] addObject:item];
    }

    // 2️⃣ Sort all appointment dates
    NSArray *allDates = [[dict allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *a, NSString *b) {
        NSDate *da = [df dateFromString:a];
        NSDate *db = [df dateFromString:b];
        return [da compare:db];
    }];

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *today = [calendar startOfDayForDate:[NSDate date]];

    // If no appointment dates exist (edge case)
    NSDate *firstAppt = (allDates.count > 0) ? [df dateFromString:allDates.firstObject] : today;
    NSDate *lastAppt  = (allDates.count > 0) ? [df dateFromString:allDates.lastObject]  : today;

    // 3️⃣ Expand date range like RN Agenda
    // Start at the earlier of today or first appointment
    NSDate *startDate;

    // If user selected a date, start from there
    if (self.selectedAgendaStartDate) {
        startDate = self.selectedAgendaStartDate;
    } else {
        // default behavior (today or firstAppt)
        startDate = [firstAppt compare:today] == NSOrderedAscending ? firstAppt : today;
    }
  
    // Add a forward buffer (e.g. 60 days)
    NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:60 toDate:lastAppt options:0];

    // 4️⃣ Build all sections
    NSMutableArray *sections = [NSMutableArray array];
    NSDate *currentDate = startDate;

    while ([currentDate compare:endDate] != NSOrderedDescending) {

        NSString *dateStr = [df stringFromDate:currentDate];
        NSArray *itemsForDate = dict[dateStr] ?: @[];

        [sections addObject:@{
            @"date": dateStr,
            @"items": itemsForDate
        }];

        currentDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1
                                          toDate:currentDate
                                         options:0];
    }

    self.agendaSections = sections;
    [self.agendaTable reloadData];
}

- (void)onRefresh {
    [self requestDashboardInfo];
}

#pragma mark - Bottom Button
- (void)setupBottomButton {
    self.bottomButtonContainer = [[UIView alloc] init];
    self.bottomButtonContainer.backgroundColor = [UIColor colorWithRed:0 green:0.4 blue:0.55 alpha:1];
    self.bottomButtonContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.bottomButtonContainer];
    
    self.makeAppointmentButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.makeAppointmentButton setTitle:@"Make Appointment" forState:UIControlStateNormal];
    [self.makeAppointmentButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.makeAppointmentButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.makeAppointmentButton addTarget:self action:@selector(onMakeAppointment) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomButtonContainer addSubview:self.makeAppointmentButton];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.bottomButtonContainer.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor],
        [self.bottomButtonContainer.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.bottomButtonContainer.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.bottomButtonContainer.heightAnchor constraintEqualToConstant:56],
        
        [self.makeAppointmentButton.topAnchor constraintEqualToAnchor:self.bottomButtonContainer.topAnchor],
        [self.makeAppointmentButton.bottomAnchor constraintEqualToAnchor:self.bottomButtonContainer.bottomAnchor],
        [self.makeAppointmentButton.leadingAnchor constraintEqualToAnchor:self.bottomButtonContainer.leadingAnchor],
        [self.makeAppointmentButton.trailingAnchor constraintEqualToAnchor:self.bottomButtonContainer.trailingAnchor]
    ]];
}


#pragma mark - Filter Overlay
- (void)setupFilterOverlay {
    self.filterOverlay = [[UIView alloc] initWithFrame:self.view.bounds];
    self.filterOverlay.hidden = YES;
    self.filterOverlay.userInteractionEnabled = NO;

    // 1️⃣ Dim background
    UIView *dimView = [[UIView alloc] initWithFrame:self.filterOverlay.bounds];
    dimView.backgroundColor = [UIColor whiteColor];
    [self.filterOverlay addSubview:dimView];

    // Tap anywhere to close
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                           action:@selector(hideFilterOverlay)];
    [dimView addGestureRecognizer:tap];

    // 2️⃣ Content container (MUST BE ABOVE dimView)
    UIView *contentView = [[UIView alloc] initWithFrame:self.filterOverlay.bounds];
    contentView.backgroundColor = UIColor.clearColor; // content is transparent
    [self.filterOverlay addSubview:contentView];

    // -----------------------------
    // ADD YOUR FILTER BUTTONS HERE
    // -----------------------------
    CGFloat y = 100;

    // 1️⃣ Appointment Type Header
    [self createFilterHeaderWithText:@"Appointment Type" y:y parent:contentView];
    y += 40;

    // 2️⃣ Type options
    NSArray *typeTitles = @[@"All", @"Handover", @"Joint Inspection", @"Rectification"];
    for (int i = 0; i < typeTitles.count; i++) {

        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, y, contentView.bounds.size.width, 50)];
        btn.tag = i;
        [btn addTarget:self action:@selector(onFilterTypeTap:) forControlEvents:UIControlEventTouchUpInside];

        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, btn.bounds.size.width - 60, 50)];
        label.text = typeTitles[i];
        label.font = [UIFont systemFontOfSize:16];
        label.textColor = [UIColor blackColor];
        [btn addSubview:label];

        UIImageView *radio = [[UIImageView alloc] initWithFrame:CGRectMake(btn.bounds.size.width - 40, 13, 24, 24)];
        radio.tag = 100 + i;   // so you can update later in refreshFilterOverlay
        radio.image = [self.apptFilterType isEqualToString:typeTitles[i]] ? [UIImage imageNamed:@"radio_check"] : [UIImage imageNamed:@"radio_uncheck"];
        [btn addSubview:radio];

        [contentView addSubview:btn];

        y += 50;
    }

    // Space before next header
    y += 20;

    // 3️⃣ Appointment State Header
    [self createFilterHeaderWithText:@"Appointment State" y:y parent:contentView];
    y += 40;

    // 4️⃣ State Options
    NSArray *timeTitles = @[@"Upcoming", @"History"];
    for (int i = 0; i < timeTitles.count; i++) {

        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, y, contentView.bounds.size.width, 50)];
        btn.tag = 200 + i;
        [btn addTarget:self action:@selector(onFilterTimeTap:) forControlEvents:UIControlEventTouchUpInside];

        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, btn.bounds.size.width - 60, 50)];
        label.text = timeTitles[i];
        label.font = [UIFont systemFontOfSize:16];
        label.textColor = [UIColor blackColor];
        [btn addSubview:label];

        UIImageView *radio = [[UIImageView alloc] initWithFrame:CGRectMake(btn.bounds.size.width - 40, 13, 24, 24)];
        radio.tag = 300 + i;
        radio.image = [self.apptFilterTime isEqualToString:timeTitles[i]] ? [UIImage imageNamed:@"radio_check"] : [UIImage imageNamed:@"radio_uncheck"];
        [btn addSubview:radio];

        [contentView addSubview:btn];

        y += 50;
    }
    // finally add to main view
    [self.view addSubview:self.filterOverlay];
}

- (void)onFilterTypeTap:(UIButton *)sender {
  [self refreshFilterOverlay];
    NSArray *typeTitles = @[@"All", @"Handover", @"Joint Inspection", @"Rectification"];
    NSString *selected = typeTitles[sender.tag];
    self.apptFilterType = selected;
    self.filterOverlay.hidden = YES;
    self.filterOverlay.userInteractionEnabled = NO;
    self.blnLoading = YES;
    [self.loadingView startAnimating];
    // process
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self processAppointmentData:self.arrayAppointmentFull];
        [self.loadingView stopAnimating];
    });
}

- (void)onFilterTimeTap:(UIButton *)sender {
  [self refreshFilterOverlay];
    NSArray *timeTitles = @[@"Upcoming", @"History"];
    NSString *selected = timeTitles[sender.tag - 200];
    self.apptFilterTime = selected;

    self.filterOverlay.hidden = YES;
    self.filterOverlay.userInteractionEnabled = NO;
    self.blnLoading = YES;
    [self.loadingView startAnimating];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)),
                   dispatch_get_main_queue(), ^{
        [self processAppointmentData:self.arrayAppointmentFull];
        [self.loadingView stopAnimating];
    });
}

- (void)hideFilterOverlay {
    self.filterOverlay.hidden = YES;
    self.filterOverlay.userInteractionEnabled = NO;
  
    [self.view bringSubviewToFront:self.topBar];

    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
}

- (void)refreshFilterOverlay {
    NSArray *typeTitles = @[@"All", @"Handover", @"Joint Inspection", @"Rectification"];
    for (int i = 0; i < typeTitles.count; i++) {
        UIImageView *radio = [self.filterOverlay viewWithTag:100 + i];
        radio.image = [self.apptFilterType isEqualToString:typeTitles[i]]
                      ? [UIImage imageNamed:@"radio_check"]
                      : [UIImage imageNamed:@"radio_uncheck"];
    }

    NSArray *timeTitles = @[@"Upcoming", @"History"];
    for (int i = 0; i < timeTitles.count; i++) {
        UIImageView *radio = [self.filterOverlay viewWithTag:300 + i];
        radio.image = [self.apptFilterTime isEqualToString:timeTitles[i]]
                      ? [UIImage imageNamed:@"radio_check"]
                      : [UIImage imageNamed:@"radio_uncheck"];
    }
}

- (UILabel *)createFilterHeaderWithText:(NSString *)text y:(CGFloat)y parent:(UIView *)parent {
    UILabel *header = [[UILabel alloc] initWithFrame:CGRectMake(16, y, parent.bounds.size.width - 32, 24)];
    header.text = text;
    header.font = [UIFont boldSystemFontOfSize:16];
    header.textColor = [UIColor darkGrayColor];
    [parent addSubview:header];

    // underline
    UIView *underline = [[UIView alloc] initWithFrame:CGRectMake(16, y + 26, parent.bounds.size.width - 32, 1)];
    underline.backgroundColor = [UIColor lightGrayColor];
    [parent addSubview:underline];

    return header;
}

#pragma mark - Loading Overlay
- (void)setupLoadingOverlay {
    self.loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleLarge];
    self.loadingView.center = self.view.center;
    self.loadingView.hidesWhenStopped = YES;
    [self.view addSubview:self.loadingView];
}

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

- (void)onToggleTab {
    if (self.blnLoading) return;
    self.blnLoading = YES;
    [self.loadingView startAnimating];

    [UIView animateWithDuration:0.3 animations:^{
        self.showingCalendar = !self.showingCalendar;
        self.calendarContainer.alpha = self.showingCalendar ? 1 : 0;
        self.listingContainer.alpha = self.showingCalendar ? 0 : 1;
    } completion:^(BOOL finished) {
        self.calendarContainer.hidden = !self.showingCalendar;
        self.listingContainer.hidden = self.showingCalendar;

        NSString *imgName = self.showingCalendar ? @"listing_icon_white" : @"calendar_icon_white";
        [self.toggleTabButton setImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];

        self.blnLoading = NO;
        [self.loadingView stopAnimating];
    }];
}

- (void)onFilterButton {
    self.filterOverlay.hidden = !self.filterOverlay.hidden;
    self.filterOverlay.userInteractionEnabled = !self.filterOverlay.userInteractionEnabled;
}

- (void)onMakeAppointment {
    AppointmentViewController *vc = [[AppointmentViewController alloc] initWithNibName:nil bundle:nil];
    vc.projectCode = @"PTD197656";
    vc.projectName = @"Ara E`Residence Dev";
    vc.projectId = @"8";
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - api
- (void)requestDashboardInfo {
        [self.loadingView startAnimating];

      [APIClient requestDashboardInfo:^(BOOL success, NSDictionary *data, NSError *error) {
        
        [self.loadingView stopAnimating];
        
        if (error) {
          NSLog(@"❌ Failed to load dashboard info: %@", error);
          [self showError:@"Unable to load appointment data."];
          return;
        }
        
        if (![data isKindOfClass:[NSDictionary class]]) {
          [self showError:@"Invalid response from server."];
          return;
        }
        
        NSLog(@"✅ Dashboard Info Loaded!");
        
        // 🔥 Extract appointment array based on your API response shape
        NSArray *appointments = data[@"Data"][@"appointment"];
        if (![appointments isKindOfClass:[NSArray class]]) {
          appointments = @[];
        }

        // Save it for later use
        self.arrayAppointmentFull = appointments;
        
        NSLog(@"📦 Received Appointment Data: %@", self.arrayAppointmentFull);
        NSString *text = [NSString stringWithFormat:@"%@", self.arrayAppointmentFull];
        NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        NSString *filePath = [docsPath stringByAppendingPathComponent:@"appointFull.txt"];
        
        // Convert issueData to a readable string
        NSString *plainText = [NSString stringWithFormat:@"%@", self.arrayAppointmentFull];

        // Write as plain UTF-8 text
        [plainText writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

        // Log the path so you can find it
        NSLog(@"📁 appointData saved as plain text to: %@", filePath);

        // 🔧 Process filters + convert to sectionized data + refresh UI
        [self processAppointmentData:self.arrayAppointmentFull];
    }];
}

- (void)endRefreshWithNoData {
    self.blnRefreshCalendar = NO;
    [self.listingTable reloadData];
}

- (void)processAppointmentData:(NSArray *)data {
  if (!data) {
    [self.arrayListing removeAllObjects];
    [self.arrayListingSection removeAllObjects];
    [self.listingTable reloadData];
    return;
  }
  
  // 1. Filter by type and time
  NSMutableArray *filtered = [NSMutableArray array];
  NSDateFormatter *df = [[NSDateFormatter alloc] init];
  df.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  df.dateFormat = @"dd MMM yyyy hh:mm a"; // matches RN format 'DD MMM YYYY hh:mm a'
  
  for (NSDictionary *item in data) {
    NSString *apptType = item[@"appointment_type"] ?: @"";
    NSString *startDate = item[@"start_date"] ?: @""; // 'DD MMM YYYY'
    NSString *startTime = item[@"start_time"] ?: @""; // 'hh:mm a'
    
    // combine and parse
    NSString *combined = [NSString stringWithFormat:@"%@ %@", startDate, startTime];
    NSDate *startDateTime = [df dateFromString:combined];
    if (!startDateTime) continue;
    
    // determine upcoming vs history
    BOOL isHistory = [startDateTime timeIntervalSinceNow] < 0;
    
    // time filter
    BOOL timePass = YES;
    if ([self.apptFilterTime isEqualToString:@"History"]) {
      timePass = isHistory;
    } else if ([self.apptFilterTime isEqualToString:@"Upcoming"]) {
      timePass = !isHistory;
    }
    
    // type filter
    BOOL typePass = YES;
    if (![self.apptFilterType isEqualToString:@"All"]) {
      typePass = [apptType isEqualToString:self.apptFilterType];
    }
    
    if (timePass && typePass) {
      [filtered addObject:item];
    }
  }
  
  // 2. Sort
  [filtered sortUsingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
    NSString *aCombined = [NSString stringWithFormat:@"%@ %@", a[@"start_date"], a[@"start_time"]];
    NSString *bCombined = [NSString stringWithFormat:@"%@ %@", b[@"start_date"], b[@"start_time"]];
    NSDate *aDate = [df dateFromString:aCombined];
    NSDate *bDate = [df dateFromString:bCombined];
    if (!aDate || !bDate) return NSOrderedSame;
    if ([self.apptFilterTime isEqualToString:@"Upcoming"]) {
      return [aDate compare:bDate];
    } else {
      return [bDate compare:aDate];
    }
  }];
  
  // 3. Build sections grouped by start_date
  [self.arrayListing removeAllObjects];
  [self.arrayListing addObjectsFromArray:filtered];
  
  [self.arrayListingSection removeAllObjects];
  NSMutableDictionary *sectionsDict = [NSMutableDictionary dictionary];
  for (NSDictionary *item in filtered) {
    NSString *dateKey = item[@"start_date"] ?: @"";
    if (!dateKey) continue;
    if (!sectionsDict[dateKey]) sectionsDict[dateKey] = [NSMutableArray array];
    [sectionsDict[dateKey] addObject:item];
  }
  // convert to array preserving order of filtered array
  NSMutableSet *seenDates = [NSMutableSet set];
  for (NSDictionary *item in filtered) {
    NSString *dateKey = item[@"start_date"];
    if (![seenDates containsObject:dateKey]) {
      [seenDates addObject:dateKey];
      NSArray *itemsForDate = sectionsDict[dateKey];
      NSDictionary *section = @{@"title": dateKey, @"data": itemsForDate ?: @[]};
      [self.arrayListingSection addObject:section];
    }
  }
  
  // 4. Build dots map (date -> array of {type,color})
  [self.aryDotsByDate removeAllObjects];
  for (NSDictionary *item in self.arrayListing) {
    NSString *strConvertDate = item[@"start_date"]; // 'DD MMM YYYY'
    // convert to yyyy-MM-dd key
    NSDateFormatter *dfIn = [[NSDateFormatter alloc] init];
    dfIn.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    dfIn.dateFormat = @"dd MMM yyyy";
    NSDate *d = [dfIn dateFromString:strConvertDate];
    NSDateFormatter *dfOut = [[NSDateFormatter alloc] init];
    dfOut.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    dfOut.dateFormat = @"yyyy-MM-dd";
    NSString *key = [dfOut stringFromDate:d] ?: strConvertDate;
    
    NSString *type = item[@"appointment_type"] ?: @"";
    UIColor *color = [type isEqualToString:@"Handover"] ? [self colorFromHex:@"#047C74"] : [self colorFromHex:@"#C84132"];
    
    NSMutableArray *dots = self.aryDotsByDate[key];
    if (!dots) {
      dots = [NSMutableArray array];
      self.aryDotsByDate[key] = dots;
    }
    [dots addObject:@{@"type": type, @"color": color}];
  }
  
  // 5. refresh table + calendar
  [self.listingTable reloadData];
  
  NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  
  NSDateFormatter *dfIn = [[NSDateFormatter alloc] init];
  dfIn.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  dfIn.dateFormat = @"dd MMM yyyy";
  
  NSDateFormatter *dfOut = [[NSDateFormatter alloc] init];
  dfOut.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  dfOut.dateFormat = @"yyyy-MM-dd";
  
  for (NSDictionary *item in self.arrayListing) {
    
    NSString *startDateStr = item[@"start_date"]; // "27 Nov 2025"
    NSDate *d = [dfIn dateFromString:startDateStr];
    if (!d) continue;
    
    NSString *key = [dfOut stringFromDate:d];
    
    // Status color logic
    NSString *apptType = item[@"appointment_type"];
    UIColor *c = [apptType isEqualToString:@"Handover"]
    ? [self colorFromHex:@"#047C74"]
    : [self colorFromHex:@"#C84132"];
    
    if (!dict[key]) dict[key] = [NSMutableArray array];
    [dict[key] addObject:@{ @"color": c }];
  }
  
  self.aryDotsByDate = dict;
  [self.calendar reloadData];
  
  self.blnRefreshCalendar = YES;
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    self.blnRefreshCalendar = NO;
  });
  
  self.filterLabel.text = [NSString stringWithFormat:@"Filter by %@ (%@)",
                           self.apptFilterType,
                           self.apptFilterTime];
  
  // Auto-select today or first date that has appointments
  NSDateFormatter *dfToday = [[NSDateFormatter alloc] init];
  dfToday.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  dfToday.dateFormat = @"dd MMM yyyy";
  NSString *todayString = [dfToday stringFromDate:[NSDate date]];
  
  df.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  df.dateFormat = @"dd MMM yyyy";
  
  NSMutableArray *todayList = [NSMutableArray array];
  
  for (NSDictionary *item in self.arrayListing) {
    if ([item[@"start_date"] isEqualToString:todayString]) {
      [todayList addObject:item];
    }
  }
  
  if (todayList.count > 0) {
    [self.calendar selectDate:[NSDate date] scrollToDate:YES];
    self.agendaList = todayList;
  } else if (self.arrayListing.count > 0) {
    NSDictionary *firstItem = self.arrayListing[0];
    NSDate *firstDate = [df dateFromString:firstItem[@"start_date"]];
    if (firstDate) {
      [self.calendar selectDate:firstDate scrollToDate:YES];
      // populate agendaList for firstDate
      NSMutableArray *firstDateList = [NSMutableArray array];
      for (NSDictionary *item in self.arrayListing) {
        if ([item[@"start_date"] isEqualToString:firstItem[@"start_date"]]) {
          [firstDateList addObject:item];
        }
      }
      self.agendaList = firstDateList;
    }
  }
    [self.agendaTable reloadData];
    [self prepareAgendaSections];
}

- (UIColor *)colorFromHex:(NSString *)hex {
    unsigned rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:hex];
    [scanner setScanLocation:1]; // bypass '#'
    [scanner scanHexInt:&rgbValue];
    return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0
                           green:((rgbValue & 0xFF00) >> 8)/255.0
                            blue:(rgbValue & 0xFF)/255.0 alpha:1.0];
}

- (void)showError:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error"
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (NSDate *)dateByAddingMonths:(NSInteger)months toDate:(NSDate *)date {
    NSCalendar *cal = [NSCalendar currentCalendar];
    return [cal dateByAddingUnit:NSCalendarUnitMonth
                           value:months
                          toDate:date
                         options:0];
}

@end
